@bitkyc08/opencodex 2.36.0-preview.20260830 → 2.37.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.
@@ -76,7 +76,7 @@ v2'de ChatGPT v1'de kalsın, Sol/Terra'yı v1'de bırakır; böylece Grok veya C
76
76
 
77
77
  Değişiklikler yeni oturumlara uygulanır.`,"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":`Varsayılan {value}`,"models.contextSettings":`Özel pencereler`,"models.contextSettingsTitle":`Özel pencereler — {provider}`,"models.contextDefault":`Sağlayıcı varsayılanı`,"models.contextModel":`Model`,"models.contextModelOverride":`Model geçersiz kılma`,"models.contextHint":`Pencereyi biliyorsanız gerçek Codex penceresini buraya yazın. Üst akış değer yoksa bu kullanılır; daha büyük bildirilen pencere düşürülür, daha küçük olan korunur. Boş bırakırsanız sağlayıcının «Varsayılan pencere / sınır» değeri kullanılır; o sınır kapalıysa 128k olur.`,"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":`Her yönlendirilen sağlayıcıda {value} varsayılan pencereyi açar. Röle context_window / context_length vermezse bu değer gerçek Codex penceresi olur. Tek bir modeli elle yazmak için aynı satırdaki «Özel pencereler»i kullanı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.interceptedHelpersOnly":`Yalnizca yakalanan yardimcilar`,"logs.badge.interceptedHelper":`I · {model}`,"logs.badge.interceptedHelperTitle":`Yakalanan yardimci istegi`,"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.cost.approximate":`yaklaşık {amount}`,"logs.cost.lowerBound":`en az {amount}`,"logs.cost.unavailable":`kullanılamıyor`,"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.detail.estimate.priority_lower_bound":`Doğrulanan Priority fiyatı kullanılamıyor; gösterilen tahmin bilinen bir alt sınırdır.`,"logs.col.error":`Hata`,"logs.col.upstreamReason":`Yukarı akış nedeni`,"logs.col.duration":`Süre`,"logs.modelTooltip.model":`model`,"logs.modelTooltip.resolvedModel":`çözümlenen model`,"logs.modelTooltip.requestedTier":`istenen katman`,"logs.modelTooltip.configuredTier":`yapılandırılan katman`,"logs.modelTooltip.responseTier":`yanıt katmanı`,"logs.modelTooltip.supportsTier":`katman desteği`,"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}).`,"storage.policy.metadataSaveWarning":`Politika çalışması tamamlandı ancak zamanlama meta verileri kaydedilemedi.`,"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.creditsBalance":`Kredi bakiyesi`,"quota.creditsPeriodEnds":`Faturalandırma dönemi {date} tarihinde sona erer`,"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.xaiResponsesOptIn":`Grok 4.5 ve 4.6 için Responses API kullan`,"pws.xaiResponsesOptInDesc":`İki modeli de openai-responses üzerinden yönlendirir. Diğer Grok modelleri ve katman davranışı değişmez.`,"pws.xaiResponsesOptInMixed":`Kısmen etkin.`,"pws.cursorTransport":`Cursor aktarımı`,"pws.cursorTransportHttp2":`HTTP/2 (varsayılan)`,"pws.cursorTransportHttp1":`HTTP/1.1 (proxy uyumluluğu)`,"pws.cursorTransportDesc":`Proxy'niz Cursor'ın HTTP/2 akışını güvenilir biçimde taşıyamıyorsa HTTP/1.1 kullanın.`,"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.codexSet":`Codex Ayarları`,"codexSet.tab.multiauth":`Çoklu kimlik doğrulama`,"codexSet.tab.prompt":`İstem`,"codexSet.prompt.title":`İstem katmanları`,"codexSet.prompt.timing":`Yeni başlatılan oturumlara uygulanır. Çalışan oturumlar mevcut istem ayarlarını korur.`,"codexSet.prompt.staleRevision":`Yapılandırma başka bir yerde değişti. Liste yeniden yüklendi.`,"codexSet.prompt.writeFailed":`Değişiklik kaydedilemedi.`,"codexSet.prompt.loadFailed":`İstem katmanları yüklenemedi.`,"codexSet.prompt.repair":`Onar`,"codexSet.prompt.repairFailed":`Onarım tamamlanamadı.`,"codexSet.drift.journalPresent":`Önceki yazma işlemi tamamlanmadı. Kurtarma bir sonraki yazma sırasında otomatik olarak çalışır.`,"codexSet.drift.projectionStale":`Kaydedilen katmanlar ile config.toml içindeki değer uyuşmuyor. Onarım, değeri katmanlarınıza göre yeniden yazar.`,"codexSet.drift.storeMissing":`Katman dosyası yok ancak config.toml içinde talimatlar duruyor. Onarım önce yedek alır ve metni tek bir katman olarak saklar.`,"codexSet.drift.ownedMalformed":`config.toml içinde oluşturulan satır elle değiştirilmiş, bu yüzden yeniden yazmak artık güvenli değil.`,"codexSet.custom.adoptUnsupported":`{path} dosyasının {line}. satırındaki değer tek satırlık bir dizge olmadığından içe aktarılamaz. Burada yönetmek için elle taşıyın.`,"codexSet.prompt.unreadable":`Codex yapılandırma dosyası var ancak okunamadı, bu yüzden değişiklikler reddedildi.`,"codexSet.layer.permissions":`İzinler`,"codexSet.layer.collaboration":`İş birliği modu`,"codexSet.layer.environment":`Ortam bağlamı`,"codexSet.layer.apps":`Uygulamalar`,"codexSet.layer.skills":`Beceriler`,"codexSet.prompt.extensionsUnknown":`Uzantılar kendi katmanlarını ekleyebilir. Codex bunları göstermediği için burada listelenemez.`,"codexSet.group.transition":`Geçiş bildirimleri`,"codexSet.group.transitionDesc":`Durumu anlatmak yerine bir değişikliği bildirirler; bu yüzden yalnızca oturum gerçek zamanlıya geçtiğinde veya model değiştiğinde görünürler.`,"codexSet.custom.slotNote":`Özel katmanlar bu sırayla birleştirilip tek bir bölüm olur.`,"codexSet.row.alwaysOn":`Her zaman açık`,"codexSet.row.onChange":`Değişimde gönderilir`,"codexSet.row.featureGated":`[features] altında yapılandırılır`,"codexSet.row.openFeatures":`Ayarları aç`,"codexSet.dialog.setValue":`{value} (varsayılan {fallback})`,"codexSet.dialog.copyKey":`Anahtarı kopyala`,"codexSet.dialog.unknownLayer":`Bu derlemede bu katman için açıklama yok. Panelden daha yeni bir Codex çalışma zamanından geliyor.`,"codexSet.custom.heading":`Özel katmanlar`,"codexSet.custom.add":`+ Katman ekle`,"codexSet.custom.newTitle":`Yeni katman`,"codexSet.custom.editTitle":`Katmanı düzenle`,"codexSet.custom.titleLabel":`Başlık`,"codexSet.custom.bodyLabel":`Talimatlar`,"codexSet.custom.bodySize":`{max} baytın {bytes} baytı`,"codexSet.custom.normalized":`Sekmeler dört boşluğa, satır sonları LF biçimine dönüştürüldü.`,"codexSet.custom.titleRequired":`Bir başlık girin.`,"codexSet.custom.titleTooLong":`Başlık {count} karakter; sınır {max}.`,"codexSet.custom.titleMultiline":`Başlık tek satır olmalıdır.`,"codexSet.custom.bodyTooLarge":`Bu katman {bytes} bayt; sınır {max}.`,"codexSet.custom.composedTooLarge":`Etkin katmanların toplamı {bytes} bayt olacak ve sınırı aşacak.`,"codexSet.custom.invalidCharacter":`{position} konumundaki denetim karakteri kaydedilemez.`,"codexSet.custom.discardPrompt":`Değişiklikler silinsin mi?`,"codexSet.custom.keepEditing":`Düzenlemeye devam et`,"codexSet.custom.delete":`{title} katmanını sil`,"codexSet.custom.deleteConfirm":`Bu katman silinsin mi? Bu işlem geri alınamaz.`,"codexSet.custom.layerGone":`Bu katman başka bir yerde silindiği için düzenleyici kapatıldı.`,"codexSet.custom.deleteConfirmNamed":`“{title}” silinsin mi? Bu işlem geri alınamaz.`,"codexSet.custom.moveUp":`{title} katmanını yukarı taşı`,"codexSet.custom.prevLayer":`Önceki katman`,"codexSet.custom.nextLayer":`Sonraki katman`,"codexSet.custom.navPosition":`{position} / {total}`,"codexSet.custom.moveDown":`{title} katmanını aşağı taşı`,"codexSet.custom.limitReached":`En fazla {max} özel katman saklayabilirsiniz.`,"codexSet.custom.notOwned":`developer_instructions opencodex dışında yazıldığı için buradan düzenlenemez. Katman olarak yönetmek için içe aktarın.`,"codexSet.custom.adopt":`Mevcut talimatları içe aktar`,"codexSet.custom.adoptConfirm":`Katman olarak içe aktar`,"codexSet.custom.adoptRefused":`Mevcut değer içe aktarılamadı.`,"codexSet.custom.baseReplaced":`model_instructions_file {path} olarak ayarlandığından, opencodex dışındaki bir öğe temel istemi değiştirmiş.`,"codexSet.lint.identity":`Bu, Codex tarafından belirlenenden farklı bir kimlik iddia ediyor.`,"codexSet.lint.foreignTool":`Araçlar kayıt defterinden gelir; burada bir aracın adını belirtmek onu oluşturmaz.`,"codexSet.lint.placeholder":`Talimatlar bir şablon motorundan geçmez, bu nedenle bu metin olduğu gibi gönderilir.`,"codexSet.lint.applyPatch":`apply_patch talimatlar tarafından değil, araç kayıt defteri tarafından tanımlanır.`,"codexSet.lint.approvalVocab":`Codex kendi onay terimlerini ekler; bu metin onlarla çelişebilir.`,"codexSet.lint.environment":`Ortam bilgileri daha sonra oluşturulur ve bu metinle çelişebilir.`,"codexSet.lint.size":`Bu katman 8 KB sınırını aşıyor. Yine de kaydedilir, ancak her istekte belirteç harcar.`,"codexSet.preset.blank":`Boş katman`,"codexSet.preset.concise.name":`Kısa çıktı`,"codexSet.preset.concise.description":`Kısa yanıtlar, giriş yok, en az biçimlendirme.`,"codexSet.preset.concise.provenance":`Claude Code'un kısa yanıt talimatlarından uyarlandı. İfade bize aittir, kopya değildir.`,"codexSet.preset.planFirst.name":`Düzenlemeden önce planla`,"codexSet.preset.planFirst.description":`Önce planı belirt, ardından değişikliği yap.`,"codexSet.preset.planFirst.provenance":`Claude Code'un planlama yaklaşımından uyarlandı. İfade bize aittir, kopya değildir.`,"codexSet.preset.explainWhy.name":`Gerekçeyi açıkla`,"codexSet.preset.explainWhy.description":`Yalnızca ne olduğunu değil, nedenini de belirt.`,"codexSet.preset.explainWhy.provenance":`Grok Build'in onaylama tarzından uyarlandı. İfade bize aittir, kopya değildir.`,"codexSet.preset.testFirst.name":`Önce test`,"codexSet.preset.testFirst.description":`Düzeltmeden önce başarısız olan testi yaz.`,"codexSet.preset.testFirst.provenance":`Yaygın ajan uygulamalarından uyarlandı. İfade bize aittir, kopya değildir.`,"codexSet.preset.korean.name":`Korece yanıtlar`,"codexSet.preset.korean.description":`İstek hangi dilde olursa olsun Korece yanıt ver.`,"codexSet.preset.korean.provenance":`Sık istenen bir ihtiyaçtan yola çıkarak opencodex için yazıldı. İfade bize aittir, kopya değildir.`,"codexSet.dialog.class":`Tür`,"codexSet.dialog.key":`Yapılandırma anahtarı`,"codexSet.dialog.fileValue":`Bu dosyadaki değer`,"codexSet.dialog.absentDefault":`ayarlanmamış (varsayılan: {value})`,"codexSet.dialog.noRenderedText":`Codex yerleşik bir katmanın birleştirilmiş metnini göstermez. Bu nedenle bu iletişim kutusu içeriği göstermek yerine katmanı açıklar ve anahtarını belirtir.`,"codexSet.dialog.sourceText":`Modele gönderilen metin`,"codexSet.dialog.sourceBytes":`{bytes} bayt`,"codexSet.dialog.notRendered":`Okuduğumuz turda bu katman hiçbir şey göndermedi. Bölümler yalnızca değiştiklerinde yeniden gönderilir, bu yüzden tek bir örnekte görünmeyebilir.`,"codexSet.dialog.emptySource":`{path} konumundaki dosya var ancak boş, bu yüzden bu katman hiçbir şey göndermiyor.`,"codexSet.dialog.notExposed":`Temel istem, Codex'in yazdırabildiği mesaj listesinin dışından geçtiği için burada gösterilemez. model_instructions_file ile değiştirilebilir.`,"codexSet.dialog.textUnavailable":`Bu makinede Codex istemi okunamadı, bu yüzden metin kullanılamıyor.`,"codexSet.class.base":`Temel talimatlar`,"codexSet.class.config-toggle":`Buradan değiştirilebilir`,"codexSet.class.feature-gated":`Özellik bayraklı`,"codexSet.class.runtime-conditional":`Çalışma zamanına bağlı`,"codexSet.class.extension-unknown":`Uzantı katmanı`,"codexSet.layer.base-instructions":`Temel talimatlar`,"codexSet.layer.model-switch":`Model değişikliği bildirimi`,"codexSet.layer.personality":`Kişilik`,"codexSet.layer.context-window-guidance":`Bağlam penceresi yönlendirmesi`,"codexSet.layer.realtime":`Gerçek zamanlı`,"codexSet.layer.agents-md":`AGENTS.md`,"codexSet.layer.environments-instructions":`Yürütme ortamları`,"codexSet.layer.plugins":`Eklentiler`,"codexSet.layer.tools":`Araçlar`,"codexSet.layer.multi-agent-mode":`Çoklu ajan modu`,"codexSet.layer.git-attribution":`Commit atıfları`,"codexSet.about.base-instructions":`Codex'in kendi talimatlarıdır. İstekle birlikte gönderilir ve kapatılamaz.`,"codexSet.about.model-switch":`Oturum sırasında model değiştiğinde eklenir.`,"codexSet.about.personality":`Bir özellik bayrağının yönettiği ton ve anlatım yönlendirmesi.`,"codexSet.about.context-window-guidance":`Bir özellik bayrağının yönettiği kalan bağlam bütçesi önerileri.`,"codexSet.about.realtime":`Gerçek zamanlı oturumlarda eklenir.`,"codexSet.about.agents-md":`Projenizin AGENTS.md dosyalarıdır. Bu sayfa katmanı gösterir, proje belgelerinizi değiştirmez.`,"codexSet.about.permissions":`Geçerli korumalı alan ve onay ayarlarını açıklar.`,"codexSet.about.collaboration":`Etkin iş birliği modunu açıklar.`,"codexSet.about.environment":`Çalışma dizini, platform ve diğer ortam bilgileri.`,"codexSet.about.environments-instructions":`Bir özellik bayrağının yönettiği ertelenmiş yürütme ortamı talimatları.`,"codexSet.about.apps":`Bağlı uygulamaların nasıl kullanılacağını açıklar.`,"codexSet.about.plugins":`Bir eklenti seçildiğinde veya herhangi bir eklenti bir yetenek bildirdiğinde eklenir.`,"codexSet.about.tools":`Bir özellik bayrağının yönettiği ertelenmiş araç açıklamaları.`,"codexSet.about.skills":`Kullanılabilir becerilerin listesi.`,"codexSet.about.multi-agent-mode":`Bir özellik bayrağının yönettiği alt ajan talimatları.`,"codexSet.about.git-attribution":`Modelin yazdığı commit’lere Co-authored-by: Codex trailer’ını, açtığı pull request’lere de Generated with Codex. satırını eklemesini söyler. Codex bunu hesabınızdan okur; ne burada ne de [features] altında değiştirilebilir. Hesabınız kapattığında Codex hiçbir şey göndermek yerine tersi yönde talimat gönderir.`,"codexSet.condition.model-switch":`Yalnızca oturum sırasında model değiştikten sonra eklenir.`,"codexSet.condition.realtime":`Yalnızca gerçek zamanlı oturumlarda eklenir.`,"codexSet.condition.agents-md":`Çalışma dizini için bir proje belgesi bulunduğunda eklenir.`,"codexSet.condition.plugins":`Bir eklenti seçildiğinde veya herhangi bir eklenti bir yetenek bildirdiğinde eklenir.`,"codexSet.condition.git-attribution":`Hesabınızın atıf politikası belirler.`,"codexSet.base.title":`Temel istem`,"codexSet.base.prev":`Önceki seçenek`,"codexSet.base.next":`Sonraki seçenek`,"codexSet.base.position":`{position} / {total}`,"codexSet.base.swipeHint":`Yana kaydırın, yön tuşlarını ya da ok düğmelerini kullanarak seçenekler arasında geçin. Yeni başlatılan oturumlarda geçerlidir.`,"codexSet.base.defaultTitle":`Codex’in kendi temel istemi`,"codexSet.base.defaultBody":`Varsayılan burada saklanmaz, dolayısıyla düzenlenecek veya silinecek bir şey yoktur: seçmek yapılandırmadan model_instructions_file satırını kaldırır ve Codex kendi istemini kullanır.`,"codexSet.base.variantTitle":`Ad`,"codexSet.base.variantBody":`İstem`,"codexSet.base.replacesWarning":`Bu, Codex’in temel istemine eklemek yerine onun YERİNE geçer. Buraya kısa yazarsanız modelin talimatları da o kadar kısa olur.`,"codexSet.base.use":`Bunu kullan`,"codexSet.base.inUse":`Kullanımda`,"codexSet.base.externalBlocked":`model_instructions_file zaten {path} yolunu gösteriyor ve bunu opencodex yazmadı. Buradan seçim yapmadan önce kendiniz temizleyin.`,"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.tab.zcode":`ZCode`,"integrations.tab.prime":`Prime Agent`,"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.desktopDesiredOffCleanupPending":`Claude Desktop hâlâ ağ geçidini kullanıyor; temizlik bekleniyor`,"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.zcode":`Yalnızca ~/.zcode/v2/config.json içindeki provider.opencodex bölümünü yönetir. Z.ai oturumu ve diğer sağlayıcılar değişmez. Değişikliklerden sonra ZCode'u yeniden başlatın.`,"integrations.semantics.prime":`Yalnızca Prime Agent'ın models.json dosyasındaki providers.opencodex bölümünü yönetir — PRIME_AGENT_CODING_AGENT_DIR ayarlı değilse ~/.prime/agent. Diğer sağlayıcılar ve model geçersiz kılmaları değişmez. Yeni oturumlarda geçerli olur.`,"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.sparkQuota":`Codex Spark kotası`,"codexAuth.sparkQuotaHint":`Hesap kartlarında GPT-5.3-Codex-Spark haftalık penceresini gösterir. Yalnızca tek bir modeli kapsadığı için varsayılan olarak gizlidir.`,"codexAuth.sparkQuotaShown":`Codex Spark kotası gösteriliyor`,"codexAuth.sparkQuotaHidden":`Codex Spark kotası gizlendi`,"codexAuth.sparkQuotaFailed":`Codex Spark kotası ayarı değiştirilemedi`,"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":`429 alındığında hesabı bekletir ve başka bir hesaba geçer. Yeni oturumlar {window} değerine göre %{threshold} altında kullanıma sahip hesapları tercih eder.`,"anthropicPool.enabledNoProactiveDesc":`429 alındığında hesabı bekletir ve başka bir hesaba geçer. Eşik 0 iken kullanıma dayalı öngörülü geçiş kapalıdır, ancak yeni oturum seçimi ve 429 kurtarma hâlâ {window} penceresini kullanır.`,"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.quotaWindow":`Kota penceresi`,"accountPool.quotaWindowDesc":`Kotaya dayalı yeni oturum seçimi, İlk doldurma eşik kontrolleri ve uygun 429 yedekleri için hangi önbelleğe alınmış kullanım çubuğunun kullanılacağını belirler.`,"accountPool.quotaWindowFiveHour":`5 saatlik çubuk`,"accountPool.quotaWindowWeekly":`Haftalık çubuk`,"accountPool.quotaWindowMaxUtilization":`Daha yüksek çubuk`,"accountPool.quotaWindowHint":`Haftalık çubuk, başka uygun hesap kaldığı sürece 5 saatlik çubuğu tükenmiş hesapları atlar; hiçbiri kalmazsa bu hesaplara geri döner. Eşitlikte 5 saatlik kullanımı daha düşük olan seçilir; hesap başına haftalık çubuklar ancak Sağlayıcılar sayfası sorguladıktan sonra bilinir.`,"accountPool.quotaWindowInert":`Kullanım çubuğunu yalnızca Kota ya da eşiği 0'ın üzerinde olan İlk doldurma puanlar; bu yüzden geçerli rotasyon stratejisi için bu ayar hiçbir şeyi değiştirmez.`,"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.clientZcode":`ZCode`,"api.clientConfig.clientPrime":`Prime Agent`,"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: penceresi sıkıştırma eşiğini barındırabilen her model 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":`{value} (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.group.other":`Diğer stratejiler`,"cws.targetCount":`{count} hedef`,"cws.targetCountOne":`1 hedef`,"cws.overviewTitle":`Kombolar`,"cws.overviewBlurb":`Sağlayıcı/model hedefleri arasında failover, round-robin, ağırlıklı rastgele, en az kullanılan veya en yakın kota sıfırlamasıyla yönlendiren sanal modeller.`,"cws.count.total":`Toplam`,"cws.count.failover":`Failover`,"cws.count.roundRobin":`Round-robin`,"cws.count.other":`Diğer`,"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.attention.allTargetsExhausted":`Etkin hedeflerin tüm kotaları tükendi`,"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.random":`Rastgele`,"cws.strategy.leastUsed":`En az kullanılan`,"cws.strategy.resetWindow":`Sıfırlama penceresi`,"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.strategy.randomHint":`Her istek için ağırlığa orantılı olasılıkla bir uygun hedef çekilir. İstekler arasında yapışkanlık yoktur.`,"cws.strategy.leastUsedHint":`Her isteği, kayıtlı başarısı en az olan uygun hedefe yönlendirir. Sayaçlar proxy ile yeniden başlar.`,"cws.strategy.resetWindowHint":`Kota penceresi en yakında sıfırlanacak uygun hedefi tercih eder. Kota verisi yoksa yapılandırma sırasına döner.`,"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.targets.randomHint":`Ağırlıklar her çekilişin olasılığını kontrol eder; sıralamanın önemi yoktur.`,"cws.targets.leastUsedHint":`Sıralama yalnızca eşit kullanımlı hedefler arasındaki eşitliği bozar.`,"cws.targets.resetWindowHint":`Kota verisi eksik veya eşitse sıralama uygulanır.`,"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.quota.available":`Kullanılabilir`,"cws.quota.exhausted":`Kota tükendi`,"cws.quota.unknown":`Kota bilinmiyor`,"cws.quota.allExhausted":`Etkin hedeflerin tüm kotaları tükendi. Başka bir hedef seçin veya kotanın yenilenmesini bekleyin.`,"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ı`,"models.newPolicyGlobal":`Yeni modeller devre dışı başlasın`,"models.newPolicyProvider":`Yeni model ilkesi`,"models.newPolicy_inherit":`Devral`,"models.newPolicy_off":`Kapalı`,"models.newPolicy_on":`Açık`,"models.newBadge":`YENİ`,"models.newCount":`{count} yeni, kapalı`,"models.aliases":`Takma adlar`,"models.aliasesTable":`Takma ad tablosu`,"models.aliasPrompt":`Sağlayıcı takma adı (temizlemek için boş bırakın)`,"models.modelAliasPrompt":`Model takma adı (temizlemek için boş bırakın)`,"models.aliasSaved":`Takma ad kaydedildi`,"models.aliasConflict":`Bu takma ad mevcut bir adla çakışıyor`,"models.editProviderAlias":`Sağlayıcı takma adını düzenle`,"models.editModelAlias":`Model takma adını düzenle`,"models.useDefaultAliases":`Varsayılan takma adları kullan`,"models.useDefaultAliasesGlobal":`Varsayılan takma adları her yerde kullan`,"models.aliasAuto":`otomatik`,"models.aliasUser":`kullanıcı`,"models.aliasStale":`eski`},qe={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`},fr:{"lab.title":`Laboratoire de compatibilité`,"lab.subtitle":`Matrice en lecture seule des verdicts de compatibilité fondée sur les preuves de la projection du laboratoire.`,"lab.loadFailed":`Impossible de charger les données du laboratoire de compatibilité`,"lab.projectionUnavailable":`La projection du laboratoire n’est pas disponible. Exécutez d’abord les sondes de conformité ou en conditions réelles.`,"lab.projectionIncompatible":`Le schéma de la projection du laboratoire est incompatible. Reconstruisez la projection.`,"lab.statusTitle":`État de la projection`,"lab.matrixTitle":`Matrice de compatibilité`,"lab.verdictsTitle":`Enregistrements des verdicts`,"lab.filter.layer":`Couche de preuves`,"lab.filter.verdict":`Verdict`,"lab.filter.subject":`ID du sujet`,"lab.filter.all":`Tous`,"lab.col.subject":`Sujet`,"lab.col.layer":`Couche`,"lab.col.suite":`Suite`,"lab.col.verdict":`Verdict`,"lab.col.asOf":`Établi le`,"lab.col.protocol":`Conformité au protocole`,"lab.col.live":`Compatibilité du routage en conditions réelles`,"lab.col.task":`Efficacité des tâches`,"lab.empty":`La projection ne contient encore aucun verdict de compatibilité.`,"lab.subjectKind":`Type`,"lab.observationCount":`Observations`,"lab.eventCount":`Événements`,"lab.verdictCount":`Verdicts`,"lab.subjectCount":`Sujets`,"lab.builtAt":`Générée le`,"lab.loading":`Chargement des preuves de compatibilité…`,"lab.loadMore":`Charger plus`,"lab.detailTitle":`Détails du verdict`,"lab.detailClose":`Fermer`,"lab.detailSubject":`Sujet`,"lab.detailObservations":`Observations`,"lab.detailEvents":`Événements probants`,"lab.detailArtifacts":`Métadonnées des artefacts`,"lab.detailLoadFailed":`Impossible de charger les détails du verdict`,"lab.refresh":`Actualiser`,"lab.verdict.UNKNOWN":`Inconnu`,"lab.verdict.CLAIMED":`Déclaré`,"lab.verdict.PROBED":`Sondé`,"lab.verdict.VERIFIED":`Vérifié`,"lab.verdict.DEGRADED":`Dégradé`,"lab.verdict.BLOCKED":`Bloqué`,"lab.verdict.UNSUPPORTED":`Non pris en charge`,"lab.layer.protocol_conformance":`Conformité au protocole`,"lab.layer.live_route_compatibility":`Compatibilité du routage en conditions réelles`,"lab.layer.task_effectiveness":`Efficacité des tâches`},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`}},Je={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`},fr:{subjectKindUnknown:`Inconnu`,"artifact.present":`Présent`,"artifact.corrupt":`Corrompu`,"artifact.purged_unavailable":`Purgé / indisponible`,selectVerdict:`Afficher le verdict pour {subject}`,"community.title":`Données de la communauté`,"community.notLocalVerdict":`Contexte non fiable en lecture seule. Non inclus dans ce verdict local.`,"community.bundles":`Lots`,"community.activeRecords":`Enregistrements actifs`,"community.revokedRecords":`Enregistrements révoqués`},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 Ye(e,t,n){let r=Je[e][t];if(n)for(let[e,t]of Object.entries(n))r=r.split(`{${e}}`).join(String(t));return r}function Xe(e,t){return{...t,...qe[e]}}var Ze={en:Xe(`en`,Re),de:Xe(`de`,ze),fr:Xe(`fr`,Be),ko:Xe(`ko`,Ve),zh:Xe(`zh`,He),"zh-TW":Xe(`zh-TW`,Ue),ru:Xe(`ru`,We),ja:Xe(`ja`,Ge),tr:Xe(`tr`,Ke)};function Qe(e){return Ze[e][`lang.nativeName`]}function $e(e,t){return Ze[e][t]}var et=[{code:`en`,htmlLang:`en`},{code:`de`,htmlLang:`de`},{code:`fr`,htmlLang:`fr`},{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`}],tt=`ocx-lang`,nt=null;function rt(){try{let e=localStorage.getItem(tt);if(e===`en`||e===`de`||e===`fr`||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(`fr`)?`fr`: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 it(){return nt??rt()}function at(e){nt=e}var ot=(0,_.createContext)(null);function st(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 ct(){let e=(0,_.useContext)(ot);if(!e)throw Error(`useI18n must be used within LanguageProvider`);return e}function Q(){return ct().t}function lt({children:e}){let[t,n]=(0,_.useState)(()=>{let e=rt();return at(e),e}),r=(0,_.useCallback)(e=>{at(e),n(e)},[]);(0,_.useEffect)(()=>{let e=et.find(e=>e.code===t)??et[0];document.documentElement.lang=e.htmlLang;try{localStorage.setItem(`ocx-lang`,t)}catch{}},[t]);let i=(0,_.useCallback)((e,n)=>st(Ze[t][e]??Re[e]??e,n),[t]),a=(0,_.useMemo)(()=>({locale:t,setLocale:r,t:i}),[t,i]);return(0,J.jsx)(ot.Provider,{value:a,children:e})}function ut({k:e,cmd:t,vars:n}){let{t:r}=ct(),[i,a=``]=r(e,n).split(`{cmd}`);return(0,J.jsxs)(J.Fragment,{children:[i,(0,J.jsx)(`code`,{className:`chip`,children:t}),a]})}function dt(e){return e.replace(/^#\/?/,``)}function ft(e,t=window){let n=dt(e);if(dt(t.location.hash)===n)return;let r=`${t.location.pathname}${t.location.search}#${n}`;t.history.replaceState(t.history.state,``,r)}function pt(e,t=window){let n=dt(e);dt(t.location.hash)!==n&&(t.location.hash=n)}var mt=m(),ht=4,gt=8,_t=8,vt=280,yt=120,bt=160,xt=12;function St(){return typeof window<`u`?window.innerHeight:800}function Ct(){return typeof window<`u`?window.innerWidth:1024}function wt(e,{align:t,placement:n=`below`,menuHeight:r=vt}={}){let i=Math.min(Math.max(r,yt),vt),a=St(),o=Ct();if(n===`right`){let t=a-e.top-_t,n=e.top-_t,r=i+gt>t&&n>t,s=Math.max(_t,Math.min(e.right+xt,o-bt-_t));return r?{position:`fixed`,left:s,bottom:a-e.top+gt,minWidth:bt,maxHeight:Math.max(yt,Math.min(vt,e.top-_t-ht))}:{position:`fixed`,top:e.top,left:s,minWidth:bt,maxHeight:Math.max(yt,Math.min(vt,a-e.top-_t))}}let s=t??(e.right>o/2?`right`:`left`),c=Math.max(e.width,0),l=a-e.bottom-_t,u=e.top-_t;if(i+ht>l&&u>l){let t={position:`fixed`,bottom:a-e.top+gt,minWidth:c,maxHeight:Math.max(0,Math.min(vt,u-ht))};return s===`right`?t.right=Math.max(_t,o-e.right):t.left=Math.max(_t,Math.min(e.left,o-_t-c)),t}let d={position:`fixed`,top:e.bottom+ht,minWidth:c,maxHeight:Math.max(0,Math.min(vt,l-ht))};return s===`right`?d.right=Math.max(_t,o-e.right):d.left=Math.max(_t,Math.min(e.left,o-_t-c)),d}function Tt({on:e,mixed:t=!1,onClick:n,disabled:r,label:i}){return(0,J.jsx)(`button`,{type:`button`,className:`switch${e?` on`:``}${t?` mixed`:``}`,onClick:n,disabled:r,"aria-pressed":t?`mixed`:e,"aria-label":i??(e?`enabled`:`disabled`),children:(0,J.jsx)(`span`,{className:`knob`})})}function $({tone:e,children:t}){return(0,J.jsxs)(`div`,{className:`notice ${e===`ok`?`notice-ok`:e===`warn`?`notice-warn`:`notice-err`}`,role:`status`,children:[e===`ok`?(0,J.jsx)(le,{}):(0,J.jsx)(_e,{}),(0,J.jsx)(`span`,{children:t})]})}function Et({tone:e,children:t,onDismiss:n,dismissLabel:r}){return(0,mt.createPortal)((0,J.jsx)(`div`,{className:`toast-notice-host`,role:`presentation`,children:(0,J.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,J.jsx)(le,{}):(0,J.jsx)(_e,{}),(0,J.jsx)(`span`,{className:`toast-notice-copy`,children:t}),n&&(0,J.jsx)(`button`,{type:`button`,className:`toast-notice-dismiss`,onClick:n,"aria-label":r,children:`×`})]})}),document.body)}function Dt({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(wt(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=wt(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,J.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,J.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,J.jsxs)(`div`,{ref:x,className:`custom-select`,style:{position:`relative`,display:`inline-block`,...c},children:[(0,J.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,J.jsx)(`span`,{children:T?.label??e}),(0,J.jsx)(Se,{style:{width:12,height:12,color:`var(--muted)`,transform:m?`rotate(90deg)`:`none`,transition:`transform .12s`}})]}),f?P&&(0,mt.createPortal)(P,document.body):P]})}function Ot({icon:e,title:t,children:n,className:r,style:i}){return(0,J.jsxs)(`div`,{className:r?`empty ${r}`:`empty`,style:i,children:[e,(0,J.jsx)(`div`,{className:`title`,children:t}),n&&(0,J.jsx)(`div`,{className:`text-control`,children:n})]})}function kt({content:e,children:t,side:n=`top`,maxWidth:r=280}){let[i,a]=(0,_.useState)(!1),o=(0,_.useId)(),s=(0,_.useRef)(null),c=()=>{s.current!==null&&window.clearTimeout(s.current),s.current=window.setTimeout(()=>a(!0),150)},l=()=>{s.current!==null&&(window.clearTimeout(s.current),s.current=null),a(!1)};return(0,_.useEffect)(()=>()=>{s.current!==null&&window.clearTimeout(s.current)},[]),(0,J.jsxs)(`button`,{type:`button`,className:`ocx-tooltip`,onMouseEnter:c,onMouseLeave:l,onFocus:c,onBlur:l,onKeyDown:e=>{e.key===`Escape`&&l()},"aria-describedby":i?o:void 0,style:{display:`inline`,border:0,background:`transparent`,padding:0,margin:0,color:`inherit`,font:`inherit`,cursor:`inherit`},children:[t,i&&(0,J.jsx)(`span`,{id:o,className:`ocx-tooltip-bubble ocx-tooltip-bubble--${n}`,role:`tooltip`,style:{maxWidth:r},children:e})]})}var At=45e3,jt=2147483647;async function Mt(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 Nt(e,t){return typeof e.error==`string`&&e.error?e.error:typeof e.message==`string`&&e.message?e.message:t}async function Pt(e,t=`HTTP ${e.status}`){if(!e.ok){let n=t;try{n=Nt(await e.json(),t)}catch{}throw Error(n)}return Mt(e)}async function Ft(e){if(!e.ok)return null;try{return await Mt(e)}catch{return null}}var It=[`gpt-5.6-luna`];function Lt(e){let t=Array.isArray(e)?e.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>e.trim()):[];return t.length>0?t:It}function Rt(e){return Lt(e).join(`, `)}function zt(e){return Lt(e).map(e=>e.replace(/^gpt-/,``)).join(`, `)}var Bt=`dashboard/update`;function Vt(){let e=window.location.hash.replace(/^#\/?/,``);return e===`dashboard/providers`?`providers`:e===`dashboard/models`?`models`:`overview`}function Ht(){return window.location.hash.replace(/^#\/?/,``)===Bt}function Ut(e){return e===`overview`?`dashboard`:`dashboard/${e}`}async function Wt(e,t){let n=await Pt(e,t);if(n===void 0)throw Error(t??`empty response`);return n}var Gt=[`low`,`medium`,`high`,`xhigh`];function Kt(e){return e?.includes(`-preview.`)?`preview`:`latest`}function qt(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 Jt(e,t){switch(e){case`running`:return t(`dash.updateStatus.running`);case`restarting`:return t(`dash.updateStatus.restarting`);case`succeeded`:return t(`dash.updateStatus.succeeded`);case`failed`:return t(`dash.updateStatus.failed`)}}function Yt(e,t){let n={...e};return t?.model!==void 0&&(n.model=t.model),t?.backend===null?delete n.backend:t?.backend!==void 0&&(n.backend=t.backend),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 Xt(e){return{vision:{reasoning:e}}}function Zt(e){return{vision:{enabled:e}}}function Qt(e){return{vision:{maxDescriptionsPerTurn:e}}}function $t(e){return{vision:{timeoutMs:e}}}var en=At,tn=jt,nn=1;function rn(e){let t=e.trim();if(!/^[0-9]+$/.test(t))return;let n=Number(t);if(!(!Number.isSafeInteger(n)||n<=0))return n}function an(e){let t=rn(e);if(!(t===void 0||t<nn||t>tn))return t}var on=[`low`,`medium`,`high`,`xhigh`,`max`];function sn(e,t){let n=e.find(e=>e.id===t)?.reasoningEfforts;if(!n||n.length===0)return[...on];let r=on.filter(e=>n.includes(e));return r.length>0?r:[...on]}function cn(e,t){let n=ln(e,t);return e.includes(n)?e:[n,...e]}function ln(e,t){if(e.length===0||e.includes(t))return t;let n=on.indexOf(t),r=e[0],i=on.indexOf(r);for(let t of e){let e=on.indexOf(t);e<=n&&e>=i&&(r=t,i=e)}return r}function un(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 dn(e,t,n,r){if(e===void 0){let e=un(t);return n&&!e.some(e=>e.value===n)&&e.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),e}let i=e.map(e=>({value:e.value,label:e.label,backend:e.backend,model:e.model}));return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{},model:n}),i}function fn(e,t,n,r){let i=e?e.map(e=>({value:e.value,label:e.label,backend:e.backend})):un(t);return n&&!i.some(e=>e.value===n)&&i.unshift({value:n,label:n,...r?{backend:r}:{}}),i}function pn(e,t,n){let r=Lt(n),i=r.flatMap(t=>{let n=e.find(e=>e.namespaced.startsWith(t))??e.find(e=>e.id.startsWith(t));return n?[{provider:n.provider,modelId:t}]:[]}),a=e.filter(e=>i.some(t=>e.provider===t.provider&&e.id.startsWith(t.modelId))),o=new Set([...r.flatMap(e=>[e,`openai/${e}`]),...a.flatMap(e=>[e.namespaced,`${e.provider}/${e.id}`])]),s=[{value:``,label:`—`},...e.filter(e=>!o.has(e.namespaced)).map(e=>({value:e.namespaced,label:e.namespaced}))];return t&&!o.has(t)&&!s.some(e=>e.value===t)&&s.push({value:t,label:t}),s}function mn(e,t){return e.find(e=>e.id===t)?.provider===`anthropic`?`anthropic`:`openai`}function hn(e,t,n){let r=t.find(e=>e.value===n);return{backend:r?.backend??mn(e,n),model:r?.model??n}}function gn(e,t,n){return t.find(e=>e.value===n)?.backend||(n.includes(`/`)?`routed`:mn(e,n))}var _n=!1;typeof window<`u`&&typeof window.addEventListener==`function`&&(window.addEventListener(`keydown`,()=>{_n=!0},{capture:!0,passive:!0}),window.addEventListener(`pointerdown`,()=>{_n=!1},{capture:!0,passive:!0}));function vn(e){if(e){if(_n){e.focus({preventScroll:!0});return}try{e.focus({preventScroll:!0,focusVisible:!1})}catch{e.focus({preventScroll:!0})}}}function yn(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(),vn(t.current)}},[e,t]),(0,_.useEffect)(()=>()=>{let e=n.current;e?.open&&e.close(),vn(t.current)},[t]),n}function bn(e){let{t,updateOpen:n,closeUpdateDialog:r,updateDialogRef:i,updateChannel:a,changeUpdateChannel:o,updateLoading:s,updateError:c,updateCheck:l,fetchUpdateCheck:u,updateRestart:d,setUpdateRestart:f,runUpdate:p,maHelpOpen:m,setMaHelpOpen:h,maHelpDialogRef:g,effortCapHelpOpen:_,setEffortCapHelpOpen:v,effortCapHelpDialogRef:y,shadowCallHelpOpen:b,setShadowCallHelpOpen:x,shadowCallHelpDialogRef:S,shadowCall:C}=e;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`dialog`,{ref:i,id:`dashboard-update-dialog`,className:`modal-overlay`,style:{display:n?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`update-title`,onCancel:e=>{e.preventDefault(),r()},children:(0,J.jsxs)(`div`,{className:`modal-card`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`update-title`,children:t(`dash.updateTitle`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:r,"aria-label":t(`common.cancel`),children:(0,J.jsx)(ue,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc`,children:t(`dash.updateDesc`)}),(0,J.jsxs)(`div`,{className:`update-row`,children:[(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`update-channel`,children:t(`dash.updateChannel`)}),(0,J.jsx)(Dt,{value:a,options:[{value:`latest`,label:`latest`},{value:`preview`,label:`preview`}],onChange:e=>o(e),disabled:s,label:t(`dash.updateChannel`),portal:!1})]}),s&&(0,J.jsx)(Ot,{className:`update-empty`,icon:(0,J.jsx)(`span`,{className:`spin`}),title:t(`dash.updateChecking`)}),c&&(0,J.jsxs)(`div`,{className:`notice notice-err`,role:`status`,children:[(0,J.jsx)(_e,{}),(0,J.jsx)(`span`,{children:c})]}),l&&!s&&(0,J.jsxs)(`div`,{className:`update-box`,children:[(0,J.jsxs)(`div`,{className:`spread`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateInstalled`)}),(0,J.jsx)(`div`,{className:`mono`,children:l.currentVersion})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateLatest`)}),(0,J.jsx)(`div`,{className:`mono`,children:l.latestVersion??`—`})]}),(0,J.jsx)(`span`,{className:`badge ${l.updateAvailable?`badge-green`:`badge-muted`}`,children:l.updateAvailable?t(`dash.updateAvailable`):t(`dash.updateCurrent`)})]}),(0,J.jsxs)(`div`,{className:`muted update-command`,children:[t(`dash.updateCommand`),` `,(0,J.jsx)(`code`,{className:`chip`,children:l.command})]}),l.reason===`source_checkout`&&(0,J.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,J.jsx)(_e,{}),` `,t(`dash.updateSource`)]}),l.reason===`latest_unavailable`&&(0,J.jsxs)(`div`,{className:`notice-warn`,role:`status`,children:[(0,J.jsx)(_e,{}),` `,t(`dash.updateUnavailable`),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},style:{marginLeft:12},children:[(0,J.jsx)(fe,{}),` `,t(`dash.updateRetry`)]})]}),!l.canUpdate&&l.reason!==`latest_unavailable`&&l.reason!==`source_checkout`&&(0,J.jsxs)(`div`,{className:`update-recheck`,children:[(0,J.jsx)(`span`,{className:`muted update-recheck-reason`,children:t(`dash.updateCannotAuto`,{reason:qt(l.reason,t)})}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s,onClick:()=>{u(a,!0)},children:[(0,J.jsx)(fe,{}),` `,t(s?`dash.updateChecking`:`dash.updateRecheck`)]})]}),l.canUpdate&&(0,J.jsxs)(`div`,{className:`spread update-restart`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.updateRestart`)}),(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`dash.updateRestartHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${d?`on`:``}`,onClick:()=>f(e=>!e),"aria-label":t(`dash.updateRestart`),"aria-pressed":d,children:(0,J.jsx)(`span`,{className:`knob`})})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:t(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:p,disabled:!l?.canUpdate||s,children:t(`dash.runUpdate`)})]})]})}),(0,J.jsxs)(`dialog`,{ref:g,id:`multi-agent-help-dialog`,className:`modal-overlay`,style:{display:m?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`multi-agent-help-title`,onCancel:e=>{e.preventDefault(),h(!1)},children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>h(!1)}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`multi-agent-help-title`,children:t(`dash.multiAgent`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>h(!1),"aria-label":t(`common.close`),children:(0,J.jsx)(ue,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`models.v2Help`)}),(0,J.jsx)(`div`,{style:{marginTop:12},children:(0,J.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:t(`models.v2DocsLink`)})}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>h(!1),children:t(`common.ok`)})})]})]}),(0,J.jsxs)(`dialog`,{ref:y,id:`effort-cap-help-dialog`,className:`modal-overlay`,style:{display:_?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`effort-cap-help-title`,onCancel:e=>{e.preventDefault(),v(!1)},children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>v(!1)}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`effort-cap-help-title`,children:t(`dash.effortCapLabel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>v(!1),"aria-label":t(`common.close`),children:(0,J.jsx)(ue,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.effortCapHelp`)}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>v(!1),children:t(`common.ok`)})})]})]}),(0,J.jsxs)(`dialog`,{ref:S,id:`shadow-call-help-dialog`,className:`modal-overlay`,style:{display:b?`flex`:`none`,border:`none`,margin:0,maxWidth:`none`,maxHeight:`none`,width:`100%`,height:`100%`},"aria-labelledby":`shadow-call-help-title`,onCancel:e=>{e.preventDefault(),x(!1)},children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":t(`common.close`),tabIndex:-1,onClick:()=>x(!1)}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:`shadow-call-help-title`,children:t(`dash.shadowCallIntercept`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,onClick:()=>x(!1),"aria-label":t(`common.close`),children:(0,J.jsx)(ue,{})})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:t(`dash.shadowCallTooltip`,{models:Rt(C?.sourceModels)})}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>x(!1),children:t(`common.ok`)})})]})]})]})}var xn={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`},Sn={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`},Cn={"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`},wn=new Set([...Object.keys(Sn),...Object.keys(Cn)]);function Tn(e){let t=e.toLowerCase();return Object.hasOwn(xn,t)?xn[t]:void 0}function En(e,t){let n=Tn(e);return n?`/provider-icons/${n}`:void 0}function Dn(e,t){let n=e.toLowerCase(),r=Object.hasOwn(Cn,n)?Cn[n]:void 0;return r?t(r):(Object.hasOwn(Sn,n)?Sn[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 On(e){return wn.has(e.toLowerCase())}function kn(e){return e===`command-code`?`commandcode-auth`:e===`commandcode`?`commandcode-api`:e}function An(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 jn({t:e,models:t,modelsLoading:n,modelQuery:r,setModelQuery:i,filteredGroups:a,expandedProviders:o,setExpandedProviders:s}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`h-section`,children:[e(`dash.availableModels`),` `,(0,J.jsx)(`span`,{className:`count`,children:t.length}),n&&(0,J.jsx)(`span`,{className:`spin`,style:{marginLeft:4}})]}),t.length===0&&!n?(0,J.jsx)(Ot,{title:e(`dash.noModels`)}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,J.jsx)(ye,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:e(`models.search`),value:r,onChange:e=>i(e.target.value),"aria-label":e(`models.search`)})]}),a.length===0?(0,J.jsx)(`p`,{className:`muted text-control`,style:{margin:`4px 0`},children:e(`dash.modelsNoResults`)}):(0,J.jsx)(`div`,{className:`dash-model-acc`,children:a.map(([t,n])=>{let i=r.trim().toLowerCase()!==``||o.has(t);return(0,J.jsxs)(`div`,{className:`dash-model-group`,children:[(0,J.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,J.jsx)(Se,{width:12,height:12,style:{transform:i?`rotate(90deg)`:`none`,transition:`transform .12s`,color:`var(--muted)`},"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`font-semibold`,children:Dn(t,e)}),(0,J.jsx)(`span`,{className:`count`,children:n.length})]}),i&&(0,J.jsx)(`div`,{className:`dash-model-chips`,children:n.map(e=>(0,J.jsx)(`code`,{className:`dash-model-chip`,children:e.id},`${e.provider}/${e.id}`))})]},t)})})]})]})}var Mn={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 Nn(e){return e.replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function Pn(e,t){let n=Mn[t];if(n){for(let t of n)if(e>=t.v)return`${Nn((e/t.v).toFixed(1))}${t.s}`;return String(e)}return e<1e4?String(e):e<1e6?`${Nn((e/1e3).toFixed(1))}K`:e<1e9?`${Nn((e/1e6).toFixed(1))}M`:e<0xe8d4a51000?`${Nn((e/1e9).toFixed(1))}B`:`${Nn((e/0xe8d4a51000).toFixed(1))}T`}function Fn(e,t){let n=Math.max(0,Math.floor(e)),r=$e(t,`uptime.day`),i=$e(t,`uptime.hour`),a=$e(t,`uptime.minute`),o=$e(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 In({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=Q(),g=t?.status===`ok`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`dash-overview-head`,children:[(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsxs)(`div`,{className:`label`,style:{display:`flex`,alignItems:`center`,gap:6},children:[h(`dash.multiAgent`),(0,J.jsx)(`button`,{ref:u,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>f(!0),"aria-label":h(`dash.multiAgent`),"aria-haspopup":`dialog`,"aria-controls":`multi-agent-help-dialog`,"aria-expanded":d,children:(0,J.jsx)(ve,{width:14,height:14,"aria-hidden":`true`})})]}),(0,J.jsx)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,justifyContent:`center`},children:(0,J.jsx)(`div`,{role:`radiogroup`,"aria-label":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,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":c===e,className:`btn btn-sm text-caption${c===e?` btn-primary`:` btn-ghost`}`,style:{borderRadius:`var(--radius-pill)`,minWidth:36,padding:`5px 10px`,border:`none`,background:c===e?void 0:`transparent`,color:c===e?void 0:`var(--muted)`},disabled:l,onClick:()=>void p(e),children:h(`models.v2Mode_${e}`)},e))})}),m&&(0,J.jsx)(`div`,{role:`alert`,className:`text-caption`,style:{color:`var(--red)`,marginTop:4,textAlign:`center`,maxWidth:280,wordBreak:`break-word`},children:m})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:h(`dash.status`)}),(0,J.jsxs)(`div`,{className:`value`,style:{display:`flex`,alignItems:`center`,gap:9,color:g?`var(--green)`:`var(--red)`},children:[(0,J.jsx)(`span`,{className:`dot ${g?`dot-green`:`dot-red`}`}),h(g?`dash.online`:`dash.offline`)]})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:h(`dash.version`)}),(0,J.jsx)(`div`,{className:`value mono`,children:t?.version??`—`})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:h(`dash.uptime`)}),(0,J.jsx)(`div`,{className:`value mono`,children:t?Fn(t.uptime,e):`—`})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":a||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:h(`dash.providers`)}),(0,J.jsx)(`div`,{className:`value`,children:n.length})]}),(0,J.jsxs)(`div`,{className:`stat`,"aria-busy":i||void 0,children:[(0,J.jsx)(`div`,{className:`label`,children:h(`dash.tokens30d`)}),(0,J.jsx)(`div`,{className:`value mono`,children:r&&r.summary.requests>0?Pn(r.summary.totalTokens,e):`—`}),(0,J.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,J.jsx)(`div`,{className:`startup-health-slot`,"aria-live":`polite`,children:o?(0,J.jsxs)(`button`,{type:`button`,className:`startup-health-bar`,onClick:()=>pt(`startup`),children:[(0,J.jsx)(`span`,{className:`dot ${o===`error`?`dot-red`:o===`at-risk`?`dot-amber`:`dot-green`}`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`startup-health-bar__summary`,children:h(o===`error`?`startup.error`:o===`at-risk`?`startup.summary.atRisk`:o===`protected`?`startup.summary.protected`:`startup.summary.native`)})]}):(0,J.jsxs)(`div`,{className:`startup-health-bar startup-health-bar--pending`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`dot dot-amber`}),(0,J.jsx)(`span`,{className:`startup-health-bar__summary`,children:`\xA0`})]})})]}),s.length>0&&(0,J.jsxs)(`div`,{className:`notice notice-err maintenance-notice`,role:`alert`,children:[(0,J.jsx)(_e,{}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:h(`dash.projectConfigTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginTop:4},children:h(`dash.projectConfigHint`)}),(0,J.jsx)(`ul`,{className:`text-control`,style:{margin:`10px 0 0`,paddingLeft:18},children:s.map(e=>(0,J.jsxs)(`li`,{style:{marginBottom:8},children:[(0,J.jsx)(`code`,{children:e.path}),` — `,e.issues.join(`, `),(0,J.jsx)(`div`,{className:`muted`,style:{marginTop:2},children:e.bypass})]},e.path))})]})]})]})}function Ln(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)}}function Rn(){return typeof document<`u`&&document.visibilityState===`hidden`}function zn(e,t){return typeof window<`u`&&typeof window.setInterval==`function`?window.setInterval(e,t):setInterval(e,t)}function Bn(e){if(typeof window<`u`&&typeof window.clearInterval==`function`){window.clearInterval(e);return}clearInterval(e)}function Vn(e,t,n){let r=n?.pauseWhenHidden!==!1,i=null,a=!1,o=()=>{try{e()}catch(e){console.error(`[visibility-poll]`,e)}},s=()=>{i!==null||a||(i=zn(o,t))},c=()=>{i!==null&&(Bn(i),i=null)},l=()=>{if(r){if(Rn()){c();return}o(),s()}};return r&&Rn()||s(),r&&typeof document<`u`&&document.addEventListener(`visibilitychange`,l),n?.immediate&&o(),()=>{a=!0,c(),r&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,l)}}var Hn=new Map;function Un(e,t){let n=`${e}:${t}`,r=Hn.get(n);return r||(r=new Intl.NumberFormat(e,{minimumFractionDigits:t,maximumFractionDigits:t}),Hn.set(n,r)),r}var Wn=new Map;function Gn(e){let t=Wn.get(e);return t||(t=new Intl.NumberFormat(e),Wn.set(e,t)),t}function Kn(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`${Un(t,r===0?0:1).format(i)} ${n[r]}`}function qn(e,t){return!Number.isFinite(e)||e<0?`—`:Fn(e/1e3,t)}function Jn(e){return typeof e.observedBytes==`number`?e.observedBytes:Math.max(e.rss,e.external??0,e.arrayBuffers??0)}function Yn(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 Xn(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:(Jn(n)-Jn(t))/r*36e5}function Zn({label:e,value:t,sub:n,tone:r}){return(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:e}),(0,J.jsx)(`div`,{className:`value mono${r?` value--${r}`:``}`,children:t}),n&&(0,J.jsx)(`div`,{className:`stat-sub mono`,children:n})]})}function Qn({observedBytes:e,thresholdBytes:t,metric:n,locale:r,t:i}){let a=e!==null&&t!==null&&t>0?e/t:null,o=a===null?`unknown`:a>=1?`over`:a>=.75?`warn`:`ok`,s=a===null?null:Math.round(a*100);return(0,J.jsxs)(`div`,{className:`mem-pressure mem-pressure--${o}`,children:[(0,J.jsxs)(`div`,{className:`mem-pressure-head`,children:[(0,J.jsxs)(`span`,{className:`mem-pressure-label`,children:[i(`dash.mem.pressure`),n?(0,J.jsx)(`span`,{className:`mem-pressure-metric mono`,children:n}):null]}),(0,J.jsxs)(`span`,{className:`mem-pressure-figure mono`,children:[e===null?`—`:Kn(e,r),t!==null&&(0,J.jsxs)(`span`,{className:`mem-pressure-limit`,children:[` / `,Kn(t,r)]})]})]}),(0,J.jsx)(`div`,{className:`mem-pressure-track`,role:`presentation`,children:(0,J.jsx)(`span`,{className:`mem-pressure-fill`,style:{"--mem-scale":String(a===null?0:Math.min(1,Math.max(.01,a)))}})}),(0,J.jsx)(`div`,{className:`mem-pressure-foot`,children:s===null?i(`dash.mem.pressureUnknown`):i(`dash.mem.pressureOf`,{pct:s})})]})}var $n=60,er=1500,tr=12e4;function nr({apiBase:e}){let{locale:t,t:n}=ct(),[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=Ln(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=Vn(()=>void a(),5e3);return()=>{t=!0,r?.controller.abort(),r?.clear(),l()}},[e,s,h]),(0,_.useEffect)(()=>{if(s!==`reconnecting`)return;let t=!1,r=!1,i=null,a=Date.now(),o=()=>{if(r||t)return;r=!0;let o=Ln(5e3);i=o,fetch(`${e}/healthz`,{cache:`no-store`,signal:o.signal}).then(async e=>{if(t)return;if(!e.ok){Date.now()-a>=tr&&(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>=tr&&(c(`error`),u(n(`dash.mem.restartFailed`)))}}).catch(()=>{t||Date.now()-a>=tr&&(c(`error`),u(n(`dash.mem.restartFailed`)))}).finally(()=>{o.clear(),i===o&&(i=null),r=!1})};o();let l=setInterval(o,er);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:$n})];d&&i.push(n(`dash.mem.restartNoSupervisor`)),window.confirm(i.join(`
78
78
 
79
- `))&&(async()=>{u(null),g(typeof r?.pid==`number`?r.pid:null),c(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{c(`error`),g(null),u(n(`dash.mem.restartFailed`))}})()};if(a&&!r&&s===`idle`)return(0,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(se,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=r?.watchdog?Xn(r.watchdog.samples):null,b=r?r.observedBytes??r.watchdog?.observedBytes??Jn(r):null,x=r?Yn(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,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`mem-head`,children:[(0,J.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,J.jsx)(se,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,J.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,J.jsxs)(`span`,{className:`mem-inflight`,children:[(0,J.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,J.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?Gn(t).format(w):`—`})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,J.jsx)(Qn,{observedBytes:b,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,J.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,J.jsx)(Zn,{label:n(`dash.mem.rss`),value:r?Kn(r.rss,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.jsHeap`),value:r?Kn(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:Kn(r.heapTotal,t)}):void 0}),(0,J.jsx)(Zn,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?Kn(r.jscHeap.heapSize,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${Kn(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,J.jsxs)(`details`,{style:{marginTop:10},children:[(0,J.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(Zn,{label:n(`dash.mem.observed`),value:b===null?`—`:`${Kn(b,t)} (${x})`}),(0,J.jsx)(Zn,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:Kn(r.external,t)}),(0,J.jsx)(Zn,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:Kn(r.arrayBuffers,t)})]}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(Zn,{label:n(`dash.mem.storeEntries`),value:C?Gn(t).format(C.count):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.storeTotal`),value:C?Kn(C.totalBytes,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.storeLargest`),value:C?Kn(C.largestBytes,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:qn(C.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,J.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,J.jsx)(Zn,{label:n(`dash.mem.threshold`),value:Kn(r.watchdog.warnThresholdBytes,t)}),(0,J.jsx)(Zn,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,J.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),s===`reconnecting`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,J.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function rr({apiBase:e,d:t}){let{t:n,maMode:r,maModeResolved:i,effortCapHelpTriggerRef:a,effortCapHelpOpen:o,setEffortCapHelpOpen:s,effortCap:c,subagentEffortCap:l,effortCapSaving:u,setEffortCap:d,setSubagentEffortCap:f,setEffortCapSaving:p}=t;return!i||r===`v1`?null:(0,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`injection-head`,children:[(0,J.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,J.jsx)(`button`,{ref:a,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>s(e=>!e),"aria-label":n(`dash.effortCapLabel`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`effort-cap-help-dialog`,children:(0,J.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})]}),(0,J.jsx)(Dt,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...Gt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Wt(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,J.jsx)(Dt,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...Gt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Wt(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 ir({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsx)(Dt,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:An(`${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,J.jsx)(Dt,{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,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>pt(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function ar({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,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,J.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,J.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:r,children:[(0,J.jsx)(fe,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,J.jsx)(`button`,{ref:i,type:`button`,className:`maintenance-update-anchor`,onClick:a,disabled:o,"aria-haspopup":`dialog`,"aria-controls":`dashboard-update-dialog`,"aria-expanded":s,"aria-label":t(`dash.checkUpdate`),tabIndex:-1})]})]}),u&&(0,J.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,J.jsx)(_e,{}):(0,J.jsx)(fe,{}),(0,J.jsxs)(`span`,{children:[Jt(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,J.jsxs)(`div`,{className:`action-toast notice ${p?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[p?(0,J.jsx)(_e,{}):(0,J.jsx)(le,{}),(0,J.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,J.jsxs)(J.Fragment,{children:[` `,(0,J.jsx)(ut,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,J.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,J.jsx)(ue,{width:13,height:13,"aria-hidden":`true`})})]}),!m&&l&&(0,J.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(_e,{}),(0,J.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})}),(0,J.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,J.jsx)(ue,{width:13,height:13,"aria-hidden":`true`})})]})]})}function or({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(wt(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,J.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,J.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,J.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,J.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,J.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,J.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,J.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,J.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,J.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:nn,max:tn,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,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,J.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:nn,max:tn})})]})]}):null}function sr({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=sn(l,y),S=ln(x,b),C=String(a?.vision.maxDescriptionsPerTurn??8),w=String(a?.vision.timeoutMs??en),[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=rn(e);if(t===void 0){E(e),A(!0);return}A(!1),E(null),t!==(a?.vision.maxDescriptionsPerTurn??8)&&u(Qt(t))},z=(e=L)=>{let t=an(e);if(t===void 0){O(e),M(!0);return}M(!1),O(null),t!==(a?.vision.timeoutMs??en)&&u($t(t))};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`spread`,children:[(0,J.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${n?.codexAutoStart??!0?`on`:``}`,onClick:i,disabled:!n||r,"aria-label":t(`dash.codexAutoStart`),"aria-pressed":n?.codexAutoStart??!0,children:(0,J.jsx)(`span`,{className:`knob`})})]})}),(0,J.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsx)(Dt,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{u({webSearch:hn(l,s,e)})},disabled:!a||o,label:t(`dash.sidecarModel`),align:`right`}),(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},title:t(`dash.webSearchStreamHint`),children:[(0,J.jsx)(`span`,{className:`muted setting-hint`,children:t(`dash.webSearchStream`)}),(0,J.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,J.jsx)(`span`,{className:`knob`})})]})]})]}),(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsxs)(`div`,{className:`dash-vision-select-row`,children:[(0,J.jsx)(Dt,{value:y,options:[{value:``,label:t(`dash.visionOff`)},...c],onChange:e=>{if(e===``){u(Zt(!1));return}let t=ln(sn(l,e),S),n={vision:{model:e,backend:gn(l,c,e),reasoning:t}};v||(n.vision={...n.vision,enabled:!0}),u(n)},disabled:!a||o,label:t(`dash.sidecarModel`)}),(0,J.jsx)(Dt,{value:S,options:cn(x,S).map(e=>({value:e,label:e})),onChange:e=>{u(Xt(e))},disabled:!v||!a||o,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),(0,J.jsx)(`div`,{className:`dash-vision-advanced-row`,children:(0,J.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,J.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`,style:{transform:N?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,mt.createPortal)((0,J.jsx)(or,{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:z}),document.body)]})]}),(0,J.jsx)(`div`,{className:`panel`,"aria-busy":!d||void 0,children:(0,J.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,J.jsx)(`button`,{ref: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,J.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})}),(0,J.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${zt(d?.sourceModels)}`})]}),(0,J.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,J.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,J.jsx)(`span`,{className:`knob`})}),(0,J.jsx)(Dt,{value:d?.model??``,options:pn(l,d?.model,d?.sourceModels).map(e=>e.value===``?e:{...e,label:An(e.value,t)}),onChange:e=>{g({model:e})},disabled:!d||f||!d?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function cr(e){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(rr,{apiBase:e.apiBase,d:e}),(0,J.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,J.jsx)(ir,{apiBase:e.apiBase,d:e}),(0,J.jsx)(ar,{d:e})]}),(0,J.jsx)(sr,{d:e}),(0,J.jsx)(nr,{apiBase:e.apiBase})]})}function lr(e){return(0,J.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,J.jsx)(In,{...e}),(0,J.jsx)(cr,{...e})]})}function ur({t:e,providers:t}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,J.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,J.jsx)(Ot,{title:(0,J.jsx)(ut,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:e(`dash.col.name`)}),(0,J.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,J.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,J.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,J.jsx)(`tbody`,{children:t.map(t=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`font-semibold`,children:Dn(t.name,e)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,J.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,J.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}var dr=`__ocxCachedAt`;function fr(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return pr(n)?n.data:n}catch{return null}}function pr(e){return typeof e==`object`&&!!e&&typeof e[dr]==`number`&&`data`in e}function mr(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return pr(n)?{data:n.data,cachedAt:n[dr]}:{data:n,cachedAt:null}}catch{return null}}function hr(e,t){try{sessionStorage.setItem(e,JSON.stringify({[dr]:Date.now(),data:t}))}catch{}}function gr(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function _r(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function vr(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function yr(e,t){return{request:++e.current,mutation:t.current}}var br=2e3;function xr(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function Sr(e){return e?e.stale&&e.status!==`error`:!1}function Cr(e,t){return!t||e!==null&&e!==`error`?e:t.status}var wr=3e4;function Tr(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function Er(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function Dr(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=xr(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(Er(e,t))throw e;return{status:`error`,stale:!1}}}async function Or(e,t){try{return(await Ft(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function kr(e,t){return Wt(await fetch(`${e}/api/models`,{signal:t}))}async function Ar(e,t){return Wt(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function jr(e,t,n){let{request:r,mutation:i}=yr(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 Wt(a),c;try{if(o.ok){let e=await o.json();vr({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else vr({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{vr({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 Mr(e,t,n){let{request:r,mutation:i}=yr(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await Wt(await fetch(`${e}/api/settings`,{signal:t})),o,s;return vr({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 Nr(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(Er(e,t))throw e;return{maMode:`default`}}}async function Pr(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await Wt(n),providers:await Wt(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function Fr(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={...Tr(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 Ir(e,t=`all`){return t===`codex`?[`usage-summary-30d`,e,`codex`].join(`:`):[`usage-summary-30d`,e,`all`].join(`:`)}var Lr=`ocx.dash.controls.v1:`,Rr=`ocx.dash.overview.v1:`,zr=`ocx.dash.usage30d.v1:`,Br=`ocx.dash.startup.v1:`,Vr=`ocx.dash.maMode.v1:`;function Hr(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 Ur(e){return`${Lr}${e}`}function Wr(e){let{locale:t,t:n}=ct(),[r,i]=(0,_.useState)(Vt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>fr(Ur(e)),[e]),u=(0,_.useMemo)(()=>fr(`${Rr}${e}`),[e]),d=(0,_.useMemo)(()=>fr(`${zr}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=fr(`${Br}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>fr(`${Vr}${e}`),[e]),[m,h]=(0,_.useState)(()=>u?.health??null),[g,v]=(0,_.useState)(()=>f),[y,b]=(0,_.useState)(()=>u?.providers??[]),[x,S]=(0,_.useState)([]),[C,w]=(0,_.useState)(()=>l?.settings??null),[T,E]=(0,_.useState)(()=>l?.sidecar??null),[D,O]=(0,_.useState)(()=>l?.shadowCall??null),[k,A]=(0,_.useState)(()=>d),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),[F,I]=(0,_.useState)(!1),[L,R]=(0,_.useState)(!1),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(()=>p??`default`),[U,W]=(0,_.useState)(!1),[ee,K]=(0,_.useState)(null),[q,J]=(0,_.useState)(!1),[Y,te]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)(``),[oe,X]=(0,_.useState)(``),[se,ce]=(0,_.useState)([]),[le,ue]=(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,Z]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)(null),[Ee,De]=(0,_.useState)([]),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)(`latest`),[Me,Ne]=(0,_.useState)(!0),[Pe,Fe]=(0,_.useState)(!1),Ie=(0,_.useRef)(0),Le=(0,_.useRef)(null),Re=(0,_.useRef)(0),ze=(0,_.useRef)(0),Be=(0,_.useRef)(0),Ve=(0,_.useRef)(!1),He=(0,_.useRef)(0),Ue=(0,_.useRef)(0),We=(0,_.useRef)(!1),[Ge,Ke]=(0,_.useState)(null),[qe,Je]=(0,_.useState)(null),[Ye,Xe]=(0,_.useState)(null),[Ze,Qe]=(0,_.useState)(!1),[$e,et]=(0,_.useState)(!1),tt=(0,_.useRef)(null),nt=(0,_.useRef)(null),rt=(0,_.useRef)(null),it=(0,_.useRef)(null),at=yn(Y,tt),ot=yn(Oe,nt),st=yn(q,rt),Q=yn(ne,it);(0,_.useEffect)(()=>{let e=()=>i(Vt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)},[]);let lt=(0,_.useRef)(f),ut=(0,_.useRef)(0),dt=(0,_.useRef)({settingsRequestEpochRef:ze,settingsMutationEpochRef:Be,settingsMutationInFlightRef:Ve,shadowCallRequestEpochRef:He,shadowCallMutationEpochRef:Ue,shadowCallMutationInFlightRef:We}).current,pt=G(`dashboard-startup-health:${e}`,[e],t=>Dr(e,t),{pollMs:3e4}),mt=Sr(pt.data),ht=pt.refresh;(0,_.useEffect)(()=>{if(!mt)return;let e=window.setTimeout(()=>{ht()},br);return()=>window.clearTimeout(e)},[mt,ht]);let gt=G(`dashboard-overview:${e}`,[e],t=>Pr(e,t),{pollMs:5e3}),_t=m!==null||gt.data!==void 0,vt=G(`dashboard-ma-mode:${e}`,[e],t=>Nr(e,t),{pollMs:5e3}),yt=G(`dashboard-sidecars:${e}`,[e],async t=>{let n=ut.current;return{...await jr(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),bt=G(`dashboard-settings:${e}`,[e],async t=>{let n=ut.current;return{...await Mr(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),xt=G(`dashboard-multi-agent:${e}`,[e],t=>Fr(e,t),{pollMs:5e3,enabled:_t}),St=G(Ir(e),[e],t=>Ar(e,t),{enabled:_t,deadlineMs:6e4}),Ct=G(`dashboard-diagnostics:${e}`,[e],t=>Or(e,t),{pollMs:wr,enabled:_t}),wt=G(`dashboard-models:${e}`,[e,$e],t=>kr(e,t),{enabled:_t&&!$e});(0,_.useEffect)(()=>{if(pt.data!==void 0){let t=pt.data;ut.current+=1,v(t.status),lt.current=t.status,t.status!==`error`&&!t.stale&&gr(`${Br}${e}`,t.status)}},[pt.data,e]),(0,_.useEffect)(()=>{let t=gt.data;t&&(t.health&&(h(t.health),b(t.providers),gr(`${Rr}${e}`,{health:t.health,providers:t.providers})),et(t.error))},[gt.data,e]),(0,_.useEffect)(()=>{vt.data!==void 0&&(H(vt.data.maMode),gr(`${Vr}${e}`,vt.data.maMode))},[vt.data,e]);let Tt=vt.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=xt.data;e&&(e.injection&&(me(e.injection.multiAgentGuidanceEnabled),ge(e.injection.syncCodexSubagentDefaults),ae(e.injection.injectionModel),X(e.injection.injectionEffort),ce(e.injection.injectionEfforts),ue(e.injection.injectionAvailable)),e.effortCaps&&(ve(e.effortCaps.effortCap),be(e.effortCaps.subagentEffortCap)))},[xt.data]),(0,_.useEffect)(()=>{let t=yt.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=fr(Ur(e))??{};gr(Ur(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[yt.data,e]),(0,_.useEffect)(()=>{let t=bt.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===ut.current){let n=Cr(lt.current,t.startupHealthSeed);v(n),lt.current=n,n&&gr(`${Br}${e}`,n)}if(t.settings!==void 0){let n=fr(Ur(e))??{};gr(Ur(e),{...n,settings:t.settings})}}},[bt.data,e]),(0,_.useEffect)(()=>{St.data!==void 0&&(A(St.data),gr(`${zr}${e}`,St.data))},[St.data,e]),(0,_.useEffect)(()=>{Ct.data&&De(Ct.data)},[Ct.data]),(0,_.useEffect)(()=>{wt.data&&S(wt.data),I(wt.loading)},[wt.data,wt.loading]),(0,_.useEffect)(()=>()=>{ze.current+=1,He.current+=1},[]);let $=G(Ye?.id&&Ye.restart?`update-job:${e}:${Ye.id}`:`update-job:idle:${e}`,[e,Ye?.id,Ye?.restart,Ye?.latestVersion],async t=>{if(!Ye?.id||!Ye.restart)return{reconnecting:!1};let n=Ye.latestVersion;try{let r=await Wt(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Ye.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await Wt(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:!!(Ye?.id&&Ye.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=$.data;e&&(`job`in e&&e.job&&Xe(e.job),Qe(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[$.data]);let Et=(0,_.useMemo)(()=>Hr(x),[x]),Dt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return Et;let t=[];for(let[n,r]of Et){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Et,a]),Ot=(0,_.useMemo)(()=>{let e=T?.webSearch.backend;return dn(T?.webSearchModels,x,T?.webSearch.model,e===`routed`?void 0:e)},[x,T?.webSearchModels,T?.webSearch]),kt=(0,_.useMemo)(()=>fn(T?.visionModels,x,T?.vision?.model,T?.vision?.backend),[T?.visionModels,x,T?.vision]),At=async t=>{if(!T||j)return;let n=T,r={webSearch:Yt(T.webSearch,t.webSearch),vision:Yt(T.vision,t.vision),...T.visionModels?{visionModels:T.visionModels}:{},...T.webSearchModels?{webSearchModels:T.webSearchModels}:{}};M(!0),E(r);try{let n=await Wt(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}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}});let r=fr(Ur(e))??{};gr(Ur(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}}})}catch{E(n)}finally{M(!1)}};async function jt(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),We.current=!0,O(r);try{if(!(await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`shadow-call save failed`);Ue.current+=1}catch{O(n)}finally{We.current=!1,P(!1)}}let Mt=async t=>{if(!(U||V===t)){W(!0),K(null);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})});if(r.ok)H(t),gr(`${Vr}${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{}K(e)}}catch(e){K(e instanceof Error?e.message:n(`dash.maNetworkError`))}finally{W(!1)}}},Nt=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 Wt(await fetch(`${e}/api/injection-model`)),r=Tr(n);me(r.multiAgentGuidanceEnabled),ge(r.syncCodexSubagentDefaults),ae(r.injectionModel),X(r.injectionEffort),Array.isArray(n.efforts)&&ce(n.efforts),Array.isArray(n.available)&&ue(n.available)}catch{}finally{fe(!1)}}},Pt=async()=>{if(!C||L)return;let t=!C.codexAutoStart;R(!0),Ve.current=!0,w({...C,codexAutoStart:t});try{let n=await Wt(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Be.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),et(!0)}finally{Ve.current=!1,R(!1)}},Ft=(0,_.useCallback)(()=>{Ce(null),Te(null)},[]),It=async()=>{if(!z){B(!0),Ce(null),Te(null);try{let t=await Wt(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Ce(t),t.projectConfigGrouped&&De(t.projectConfigGrouped)}catch(e){Te(e instanceof Error?e.message:String(e))}finally{B(!1)}}},Lt=async(t,n=!1)=>{n&&(Ie.current=0),Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);let r=++Re.current;Fe(!0),Je(null),Ke(null);try{let n=await Wt(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==Re.current)return;if(Ke(n),n.reason===`latest_unavailable`&&Ie.current<2){let e=++Ie.current;Le.current=window.setTimeout(()=>{r===Re.current&&(Le.current=null,Lt(t))},800*e);return}n.reason!==`latest_unavailable`&&(Ie.current=0),Fe(!1)}catch(e){if(r!==Re.current)return;Je(e instanceof Error?e.message:String(e)),Fe(!1)}},Rt=()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null),Fe(!1),ke(!1)},zt=()=>{let e=Kt(m?.version);je(e),Ne(!0),ke(!0),Lt(e,!0)},Bt=e=>{je(e),Lt(e,!0)},Ut=(0,_.useRef)(zt);return(0,_.useEffect)(()=>{Ut.current=zt}),(0,_.useEffect)(()=>{let e=()=>{Ht()&&(ft(`dashboard`),Ut.current())},t=Ht()?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:St.loading&&!k,healthLoading:gt.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:F,settingsSaving:L,syncing:z,maMode:V,maModeResolved:Tt,maBusy:U,setMaHelpOpen:J,maHelpOpen:q,maError:ee,effortCapHelpOpen:Y,setEffortCapHelpOpen:te,shadowCallHelpOpen:ne,setShadowCallHelpOpen:re,injectionModel:ie,injectionEffort:oe,injectionEfforts:se,injectionAvailable:le,injectionSaving:de,multiAgentGuidanceEnabled:pe,syncCodexSubagentDefaults:he,saveInjection:Nt,effortCap:_e,subagentEffortCap:ye,effortCapSaving:xe,setEffortCap:ve,setSubagentEffortCap:be,setEffortCapSaving:Z,syncResult:Se,syncError:we,projectConfigWarnings:Ee,updateOpen:Oe,updateChannel:Ae,setUpdateRestart:Ne,updateRestart:Me,updateLoading:Pe,updateCheck:Ge,updateError:qe,updateJob:Ye,reconnecting:Ze,error:$e,effortCapHelpTriggerRef:tt,updateTriggerRef:nt,maHelpTriggerRef:rt,shadowCallHelpTriggerRef:it,effortCapHelpDialogRef:at,updateDialogRef:ot,maHelpDialogRef:st,shadowCallHelpDialogRef:Q,filteredGroups:Dt,sidecarModels:Ot,visionModels:kt,saveSidecar:At,saveShadowCall:jt,switchMaMode:Mt,toggleCodexAutoStart:Pt,runSync:It,clearSyncFeedback:Ft,fetchUpdateCheck:Lt,closeUpdateDialog:Rt,openUpdateDialog:zt,changeUpdateChannel:Bt,runUpdate:async()=>{if(Ge?.canUpdate){Je(null);try{let t=await Wt(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Ae,restart:Me})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);Xe(t.job),Qe(!1),Rt()}catch(e){Je(e instanceof Error?e.message:String(e))}}}}}function Gr(e){pt(Ut(e))}function Kr({apiBase:e}){let t=Wr(e),{t:n,error:r,selectedSection:i,providers:a,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}=t;if(r)return(0,J.jsx)(Ot,{style:{marginTop:40},icon:(0,J.jsx)(_e,{}),title:(0,J.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,J.jsx)(ut,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,J.jsx)(lr,{...t}),m=(0,J.jsx)(ur,{t:n,providers:a}),h=(0,J.jsx)(jn,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,J.jsx)(bn,{...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=Gr,b=e=>{let t=_.findIndex(e=>e.id===i),n=-1;if(e.key===`ArrowRight`?n=(t+1)%_.length:e.key===`ArrowLeft`?n=(t-1+_.length)%_.length:e.key===`Home`?n=0:e.key===`End`&&(n=_.length-1),n<0)return;e.preventDefault();let r=_[n];y(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,J.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":i===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>y(e.id),onKeyDown:b,children:e.label},e.id))}),(0,J.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${v.id}`,"aria-labelledby":`dashboard-tab-${v.id}`,tabIndex:0,children:v.body}),g]})}var qr=`https://chatgpt.com/backend-api/codex`,Jr=`openai`;function Yr(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 Xr=new URL(qr).protocol;function Zr(e,...t){return`${Xr}//${e}/${t.join(`/`)}`}var Qr={"cline-pass":{adapter:`openai-chat`,baseUrl:Zr(`api.cline.bot`,`api`,`v1`)},"mimo-free":{adapter:`mimo-free`,baseUrl:Zr(`api.xiaomimimo.com`,`api`,`free-ai`,`openai`,`chat`)}};function $r(e,t){let n=Qr[e];return!n||t.adapter!==n.adapter||Yr(t.baseUrl)!==Yr(n.baseUrl)}function ei(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 ti(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||ei(e.baseUrl)||e.hasApiKey===!0}function ni(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Yr(e.baseUrl)===qr}function ri(e,t){return e===Jr&&ni(t)}function ii(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||ei(e.baseUrl)}function ai(e,t){return ri(e,t)?`accounts`:ii(t)?`free`:`paid`}function oi(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??ai(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 si(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}ti(a)?t.push({name:i,...a,tier:ai(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function ci(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 li(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:ti(e)?`ready`:`needs-setup`}function ui(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!ri(`openai`,t)||!ni(n))return e;let r={...e};return delete r.chatgpt,r}function di(e){return e.authMode===`local`||ei(e.baseUrl)}var fi=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function pi(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(di(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return fi.some(e=>n.includes(e))?`selfHosted`:`cloud`}function mi(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 hi(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 gi(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 _i(e){let t={};for(let[n,r]of Object.entries(mi(e)))t[n]=r.length;return t}function vi(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 yi={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function bi(e,t,n){let r=typeof t==`object`&&t?t:yi,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 xi(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 Si(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 Ci(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function wi(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 Ti(e,t=`en`){return wi(e,t)}function Ei(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function Di(e,t){let n=li(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 ki(e){let t=li(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 Ai({name:e,adapter:t,baseUrl:n,cls:r}){let i=Q(),a=En(e,{adapter:t,baseUrl:n});return(0,J.jsx)(`span`,{className:r,children:a?(0,J.jsx)(`img`,{src:a,alt:``,"aria-hidden":`true`}):(0,J.jsx)(ji,{name:e,label:Dn(e,i)})})}function ji({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,J.jsx)(`span`,{className:`provider-icon-fallback`,style:{background:`hsl(${n} 55% 90%)`,color:`hsl(${n} 65% 32%)`},"aria-hidden":`true`,children:r})}function Mi({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=Q(),l=ii(e),u=di(e),d=Di(e,c),f=Dn(e.name,c),p=a?`${f} (${e.name})`:f,m=`${i?c(`pws.rail.suffixDefault`):``}${u?c(`pws.rail.suffixLocal`):l?c(`pws.rail.suffixFree`):``}`,h=r!==void 0&&r>0?r===1?c(`pws.modelCountOne`):c(`pws.modelCount`,{count:r}):``,g=[a?e.name:``,h].filter(Boolean).join(` · `);return(0,J.jsxs)(`button`,{type:`button`,className:`providers-workspace-rail-row${t?` providers-workspace-rail-row--selected`:``}`,onClick:o,role:`option`,"aria-selected":t,tabIndex:n?0:-1,"aria-label":c(`pws.rail.selectAria`,{name:p,status:d,suffix:m}),title:p,onFocus:s,children:[(0,J.jsx)(Ai,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,J.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,J.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,J.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,J.jsx)(Ie,{width:17,height:17,"aria-hidden":`true`})}),(0,J.jsx)(`span`,{className:ki(e),title:d,"aria-hidden":`true`})]})]})}var Ni=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Pi=e=>{let t=Ni(e);if(t===void 0)return;let n=t>1e10?t:t*1e3;return Number.isFinite(new Date(n).getTime())?t: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`||Ni(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...Ni(t.resetAt)===void 0?{}:{resetAt:t.resetAt}}]}):[],i=n.creditsUsd&&typeof n.creditsUsd==`object`&&!Array.isArray(n.creditsUsd)?n.creditsUsd:null,a=Ni(i?.used),o=Ni(i?.limit),s=Ni(i?.remaining),c=Ni(i?.percent),l=Pi(i?.expiresAt),u=a!==void 0&&o!==void 0&&s!==void 0&&c!==void 0?{used:a,limit:o,remaining:s,percent:c,...l===void 0?{}:{expiresAt:l},...typeof i?.unlimited==`boolean`?{unlimited:i.unlimited}:{}}:void 0,d={...Ni(n.fiveHourPercent)===void 0?{}:{fiveHourPercent:n.fiveHourPercent},...Ni(n.fiveHourResetAt)===void 0?{}:{fiveHourResetAt:n.fiveHourResetAt},...Ni(n.weeklyPercent)===void 0?{}:{weeklyPercent:n.weeklyPercent},...Ni(n.weeklyResetAt)===void 0?{}:{weeklyResetAt:n.weeklyResetAt},...Ni(n.monthlyPercent)===void 0?{}:{monthlyPercent:n.monthlyPercent},...Ni(n.monthlyResetAt)===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...r.length>0?{customWindows:r}:{},...u?{creditsUsd:u}:{},updatedAt:Ni(n.updatedAt)??t??Date.now()};return d.fiveHourPercent!==void 0||d.weeklyPercent!==void 0||d.monthlyPercent!==void 0||(d.customWindows?.length??0)>0||d.creditsUsd!==void 0?d:null}function Ii(e){return Fi(e?.quota,e?.updatedAt)}function Li(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=Ni(t.usedPercent);if(n!==void 0)return{usedPercent:n,...typeof t.incomplete==`boolean`?{incomplete:t.incomplete}:{},...Ni(t.excludedAccounts)===void 0?{}:{excludedAccounts:t.excludedAccounts},...Ni(t.nextRecoveryAt)===void 0?{}:{nextRecoveryAt:t.nextRecoveryAt},...Ni(t.nextRecoveryPercent)===void 0?{}:{nextRecoveryPercent:t.nextRecoveryPercent}}}function Ri(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=Ni(n.excludedAccounts),i=Ni(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=Li(t);return typeof t.label==`string`&&n?[{label:t.label,...n}]:[]}):[],s=Li(n.fiveHour),c=Li(n.weekly),l=Li(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:Ni(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 zi(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function Bi(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 Hi(e,t){if(!e)return null;let n=e.shortPercent===void 0&&e.shortResetAt===void 0?e:{...e,fiveHourPercent:e.fiveHourPercent??e.shortPercent,fiveHourResetAt:e.fiveHourResetAt??e.shortResetAt};return Vi(t)?{...n.monthlyPercent===void 0?{}:{monthlyPercent:n.monthlyPercent},...n.monthlyResetAt===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...n.creditsUsd===void 0?{}:{creditsUsd:n.creditsUsd},...n.resetCredits===void 0?{}:{resetCredits:n.resetCredits},updatedAt:n.updatedAt}:n}function Ui(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function Wi(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 Gi(e,t,n){let r=Hi(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=Wi(e.label,n);i.push({rank:Ui(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 Ki(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 qi(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function Ji(e){return e>=99.5}function Yi(e,t){return t>0&&e>=t}function Xi(e,t){return Yi(e,t)||Ji(e)?`bar-warn`:`bar-green`}function Zi(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function Qi(e){return{"--bar-scale":String(Zi(e)/100)}}function $i({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1,incompleteWindowKeys:s,incompleteCustomWindowLabels:c}){let{locale:l}=ct(),u=Gi(e,t,r);return u.length===0?o?a===`stacked`?(0,J.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,J.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,J.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,J.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:u.map(e=>(0,J.jsx)(ta,{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,J.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:u.map(e=>(0,J.jsx)(ea,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:l},e.label))})}function ea({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Ji(t),s=Yi(t,r),c=Xi(t,r),l=ra(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,J.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,J.jsx)(`span`,{className:`quota-label`,title:u,children:e}),(0,J.jsx)(`span`,{className:`quota-reset-label`,children:d?i(`codexAuth.resets`):``}),(0,J.jsx)(`span`,{className:`quota-reset-day`,children:l.day}),(0,J.jsx)(`span`,{className:`quota-reset-time`,children:l.time}),(0,J.jsx)(`div`,{className:`bar`,title:u,children:(0,J.jsx)(`div`,{className:`bar-fill ${c}`,style:Qi(t)})}),(0,J.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):u,"aria-label":u,children:[s&&(0,J.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function ta({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=Ji(e.percent),o=Yi(e.percent,t),s=Xi(e.percent,t),c=ia(e.resetAt,n,r);return(0,J.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,J.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,J.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${s}`,style:Qi(e.percent)})}),(0,J.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,J.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,J.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function na(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=e<1e10?e*1e3:e,n=new Date(t);return Number.isFinite(n.getTime())?{date:n,ms:t}:null}function ra(e,t,n){let r=na(e);if(!r)return{day:``,time:``};let{date:i}=r,a=new Date,o=qi(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 ia(e,t,n=`en`,r=Date.now()){let i=na(e);if(!i)return``;let{date:a,ms:o}=i,s=qi(n),c=new Intl.DateTimeFormat(s,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(a),l=new Date(r),u=new Date(l.getFullYear(),l.getMonth(),l.getDate()).getTime(),d=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),f=Math.round((d-u)/864e5);if(f===1)return t(`quota.resetsTomorrow`,{time:c});let p=a.getFullYear()!==l.getFullYear(),m=new Intl.DateTimeFormat(s,{day:`numeric`,month:`short`,...p?{year:`numeric`}:{}}).format(a);if(o<=r)return t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`});let h=Math.round((o-r)/6e4);if(h<60)return t(`quota.resetsRelativeMinutes`,{n:Math.max(1,h)});let g=Math.round(h/60);return g<12&&f===0?t(`quota.resetsRelativeHours`,{n:Math.max(1,g)}):f===0?t(`quota.resetsToday`,{time:c}):t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`})}function aa(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function oa(e){let t=new Date(e>1e10?e:e*1e3);return Number.isFinite(t.getTime())?t:null}function sa({report:e,pending:t}){let n=Q(),{locale:r}=ct(),i=Ri(e),a=Ii(e),o=a?.creditsUsd,s=i?.presentation===`aggregate`,c=new Set,l=new Set;if(s&&i){i.fiveHour?.incomplete&&c.add(`fiveHour`),i.weekly?.incomplete&&c.add(`weekly`),i.monthly?.incomplete&&c.add(`monthly`);for(let e of i.customWindows??[])e.incomplete&&l.add(e.label)}let u=s&&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}))]:[],d=e=>new Intl.NumberFormat(r,{maximumFractionDigits:1}).format(e),f=e=>{let t=oa(e);return t===null?null:new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(t)},p=aa(r),m=e=>new Intl.NumberFormat(p,{style:`currency`,currency:`USD`}).format(e),h=o?.expiresAt===void 0?null:(e=>{let t=oa(e);return t===null?null:new Intl.DateTimeFormat(p,{dateStyle:`medium`}).format(t)})(o.expiresAt);return(0,J.jsxs)(J.Fragment,{children:[s&&(0,J.jsx)(`div`,{className:`pws-capacity-label`,children:n(`pws.capacity.estimate`)}),(a||t)&&(0,J.jsx)($i,{quota:a,threshold:80,t:n,layout:`stacked`,pending:t,incompleteWindowKeys:s?c:void 0,incompleteCustomWindowLabels:s?l:void 0}),(o||i)&&(0,J.jsxs)(`div`,{className:`pws-capacity-details`,children:[o&&(0,J.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,J.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,J.jsx)(`strong`,{children:m(o.remaining)})]}),h!==null&&(0,J.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,J.jsx)(`span`,{children:n(`quota.creditsPeriodEnds`,{date:h})})}),u.flatMap(({key:e,label:t,window:r})=>{let i=r.nextRecoveryAt===void 0?null:f(r.nextRecoveryAt);return i!==null&&r.nextRecoveryPercent!==void 0?[(0,J.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,J.jsxs)(`span`,{children:[n(`pws.capacity.nextRecovery`),` · `,t,` · `,i]}),(0,J.jsx)(`strong`,{children:n(`pws.capacity.recoveryShare`,{percent:d(r.nextRecoveryPercent)})})]},e)]:[]}),s&&i&&i.currentAccount?.quota&&(0,J.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,J.jsxs)(`span`,{className:`pws-capacity-label`,children:[n(`pws.capacity.currentAccount`),i.currentAccount.plan?` · ${i.currentAccount.plan}`:``]}),(0,J.jsx)($i,{quota:i.currentAccount.quota,threshold:80,t:n,layout:`stacked`})]}),i&&i.incomplete&&i.excludedAccounts>0&&(0,J.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.incomplete`,{excluded:i.excludedAccounts,unknown:i.unknownPlanAccounts})}),i&&i.partialWindowAccounts>0&&(0,J.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.partial`,{count:i.partialWindowAccounts})})]})]})}function ca({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=Q(),{locale:c}=ct(),l=xi(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)(()=>Si(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?Ii(r):null,a=r?Ri(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?Ki(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 vi(e).slice(0,4)},[n,d]),b=e=>{let t=Ci(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,J.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,J.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,J.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,J.jsx)(la,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,J.jsx)(la,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,J.jsx)(la,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,J.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,J.jsx)(_e,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,J.jsx)(Ai,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Dn(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,J.jsx)(Se,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Ai,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Dn(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:s(`pws.dashboard.checkedAgo`,{time:bi(t.updatedAt,l)})})]}),(0,J.jsx)(Se,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)(sa,{report:t,pending:i&&!t.quota})})]},e.name))}):i?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)($i,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Ai,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Dn(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:wi(e.requests,c)})}),(0,J.jsx)(Se,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function la({count:e,label:t,tone:n}){return(0,J.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,J.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function ua({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=Q(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,J.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,J.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,J.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,J.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,J.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,J.jsx)(`textarea`,{ref:o,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":a(`pws.jsonEditorDesc`)}),i&&(0,J.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var da=[{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`}],fa=18e5;function pa(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>=fa||!(`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 ma(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=pa(i,t);r.trim()&&e&&(n[r]=e)}return n}function ha(e){return ma(fr(e))}function ga(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=pa(r,t);typeof e==`string`&&e.trim()&&i&&(n[e]=i)}return n}function _a({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=Q(),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)({ready:!0,needsSetup:!0,disabled:!0}),[x,S]=(0,_.useState)({free:!0,paid:!0}),[C,w]=(0,_.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[T,E]=(0,_.useState)(`az`),[D,O]=(0,_.useState)(!1),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)({}),[N,P]=(0,_.useState)({}),[F,I]=(0,_.useState)({}),[L,R]=(0,_.useState)({}),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(!1),U=`ocx.providers.quotas.v1:${t}`,W=`ocx.providers.usage.v1:${t}`,[ee,K]=(0,_.useState)(()=>fr(W)?.totals??{}),[q,Y]=(0,_.useState)(()=>fr(W)?.models??{}),[te,ne]=(0,_.useState)(()=>ha(U)??{}),[re,ie]=(0,_.useState)(()=>!fr(W)),[ae,oe]=(0,_.useState)(()=>{let e=ha(U);return!e||Object.keys(e).length===0}),[X,se]=(0,_.useState)(0),ce=(0,_.useRef)(null),le=G(Ir(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()},{deadlineMs:6e4}),ue=(0,_.useMemo)(()=>ci(si(ui(e)),d??{}),[e,d]),de=(0,_.useCallback)(()=>{se(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{B(!0),(async()=>{try{let n=await Pt(await fetch(`${t}/api/selected-models`));if(e)return;M(_i(n)),P(mi(n)),I(hi(n)),R(gi(n)),H(!1)}catch{if(e)return;H(!0)}finally{e||B(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,X]),(0,_.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=le.data;if(e)return;if(!t){le.loading&&ie(!fr(W));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}})}Y(r),gr(W,{totals:n,models:r}),ie(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,W,le.data,le.loading]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=ha(U);(!n||Object.keys(n).length===0)&&oe(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>Ft(e)).then(t=>{if(e||!t)return;let n=ga(t.reports);ne(n),gr(U,n)}).catch(()=>{e||ne(e=>{let t=ma(e)??{};return gr(U,t),t})}).finally(()=>{e||oe(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,U]),(0,_.useEffect)(()=>{if(!D)return;let e=e=>{ce.current&&!ce.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 fe=(0,_.useMemo)(()=>[...ue.ready,...ue.needsSetup,...ue.disabled],[ue]),pe=(0,_.useMemo)(()=>fe.filter(ii).length,[fe]),me=fe.length-pe,ge=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of fe)e[pi(t)]+=1;return e},[fe]),_e=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>oi(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=ii(t);return!(n&&!x.free||!n&&!x.paid||!C[pi(t)])}),T);return{ready:y.ready?t(ue.ready):[],needsSetup:y.needsSetup?t(ue.needsSetup):[],disabled:y.disabled?t(ue.disabled):[]}},[ue,g,y,x,C,T]),ve=!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?fe.find(e=>e.name===r)??null:null,[r,fe]),Z=(0,_.useMemo)(()=>{let e=new Map;for(let t of fe){let n=Dn(t.name,h);e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e.entries())r>1&&t.add(n);return t},[fe,h]);if(fe.length===0)return(0,J.jsx)(va,{onAddProvider:o});let Se=[{key:`ready`,label:h(`pws.status.ready`),count:ue.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:ue.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:ue.disabled.length}],Ce=[{id:`ready`,label:h(`pws.status.ready`),count:_e.ready.length,ariaLabel:h(`pws.groupReady`,{count:_e.ready.length}),items:_e.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:_e.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:_e.needsSetup.length}),items:_e.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:_e.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:_e.disabled.length}),items:_e.disabled}],we=Ce.flatMap(e=>e.items.map(e=>e.name)),Te=k&&we.includes(k)?k:r&&we.includes(r)?r:we[0]??null;return(0,J.jsx)(`div`,{className:`pws-shell-container`,children:(0,J.jsxs)(`div`,{className:`pws-root`,children:[(0,J.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,J.jsxs)(`div`,{className:`pws-search-row`,children:[(0,J.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,J.jsx)(ye,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:h(`pws.searchPlaceholder`),value:g,onChange:e=>v(e.target.value),"aria-label":h(`pws.searchPlaceholder`)})]}),(0,J.jsxs)(`div`,{className:`pws-filter-wrap`,ref:ce,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${ve||D?` pws-filter-btn--active`:``}`,onClick:()=>O(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":D,"aria-controls":`pws-provider-filters`,children:[(0,J.jsx)(Le,{width:18,height:18,"aria-hidden":`true`}),ve&&(0,J.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),D&&(0,J.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,J.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),Se.map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:y[e],onChange:()=>b(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:x.free,onChange:()=>S(e=>({...e,free:!e.free}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:pe})]}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:x.paid,onChange:()=>S(e=>({...e,paid:!e.paid}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:me})]}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:ge.cloud},{key:`local`,label:h(`pws.type.local`),count:ge.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:ge.selfHosted},{key:`login`,label:h(`pws.type.login`),count:ge.login}].map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:C[e],onChange:()=>w(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,J.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:da.map(e=>(0,J.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,J.jsx)(`div`,{className:`pws-filter-footer`,children:(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:be,disabled:!ve,children:h(`pws.resetAll`)})})]})]})]}),(0,J.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":h(`pws.providersAria`),onKeyDown:e=>{let t=Array.from(e.currentTarget.querySelectorAll(`[role="option"]`));if(t.length===0)return;let n=document.activeElement,r=t.findIndex(e=>e===n||e.contains(n));if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let n=e.key===`ArrowDown`?1:-1;t[r<0?n>0?0:t.length-1:(r+n+t.length)%t.length]?.focus();return}if(e.key===`Home`){e.preventDefault(),t[0]?.focus();return}e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus())},children:[Object.values(_e).every(e=>e.length===0)&&(0,J.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:ve?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Ce.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,J.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,J.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,J.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,J.jsx)(Mi,{item:e,selected:r===e.name,tabbable:Te===e.name,modelCount:j[e.name],isDefault:n===e.name,showConfigId:Z.has(Dn(e.name,h)),onClick:()=>i(e.name),onFocus:()=>A(e.name)}),a&&(0,J.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),a(e.name)},title:h(`pws.removeConfirmTitle`),children:(0,J.jsx)(he,{width:14,height:14})})]},e.name))]},e))]})]}),(0,J.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,J.jsx)(ua,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):xe?m?.(xe,{usageTotals:ee[xe.name],modelUsage:q[xe.name],quotaReport:te[xe.name],availableModels:N[xe.name]??[],hasLiveModels:(F[xe.name]??0)>0,selectedModels:L[xe.name]??[],modelsLoading:z,modelsLoadFailed:V,onRetryModels:de})??(0,J.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,J.jsx)(`h3`,{children:Dn(xe.name,h)}),(0,J.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,J.jsx)(ca,{sections:ue,quotaReports:te,usageTotals:ee,usageLoading:re,quotasLoading:ae,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function va({onAddProvider:e}){let t=Q();return(0,J.jsx)(`div`,{className:`pws-empty-root`,children:(0,J.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,J.jsx)(`div`,{"aria-hidden":`true`,children:(0,J.jsx)(re,{style:{width:64,height:64}})}),(0,J.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,J.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Ne,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(De,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Ee,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function ya(e){if(ri(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||di(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 ba(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 xa({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=Q(),{locale:m}=ct(),h=xi(p),g=li(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=Ii(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 Pt(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,J.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,J.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.connection`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.connection`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`dash.status`)}),(0,J.jsxs)(`dd`,{className:g===`ready`?`pws-status-ok`:`pws-status-warn`,children:[g===`ready`?(0,J.jsx)(le,{style:{width:13,height:13},"aria-hidden":`true`}):(0,J.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`}),y]})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.baseUrl`)}),(0,J.jsx)(`dd`,{children:(0,J.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.auth`)}),(0,J.jsx)(`dd`,{children:r?`${Oi(e,p)} · ${r}`:Oi(e,p)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.defaultModel`)}),(0,J.jsx)(`dd`,{children:e.defaultModel??(0,J.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.note`)}),(0,J.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),a&&(0,J.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:D,onClick:()=>void k(),children:p(D?`pws.testing`:`pws.testConnection`)}),O&&(0,J.jsx)(`span`,{role:`status`,className:A===`ok`?`pws-status-ok`:A===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":A,children:j})]}),s&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:s,children:p(`pws.editSettings`)})]}),n&&(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.rateLimits`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.rateLimits`)}),(0,J.jsx)(sa,{report:n,pending:!1})]}),(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.authSummary`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.authSummary`)}),v?(0,J.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,J.jsx)(_e,{style:{width:14,height:14},"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:p(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?p(`pws.attention.reauthForward`):p(`pws.attention.reauth`)]}),u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:f,onClick:()=>u(),children:p(f?`prov.waitingBrowser`:`pws.reauthenticate`)}),f&&d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d(),children:p(`common.cancel`)})]})]}):(0,J.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,J.jsx)(`span`,{className:`pws-auth-dot`}),(0,J.jsx)(`span`,{children:e.authMode===`forward`?p(`pws.passthrough`):e.authMode===`oauth`?r?p(`pws.loggedInAs`,{email:r}):i?.loggedIn?p(`pws.loggedInTitle`):p(`pws.notLoggedIn`):e.hasApiKey?p(`pws.apiKeyConfigured`):Oi(e,p)})]})]})]}),(0,J.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.statsAria`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.statsTitle`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[typeof b==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalRequests`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:wi(b,m)})]}),typeof x==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalTokens`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:Ti(x,m)})]}),n&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?zi(n.source):void 0,children:bi(n.updatedAt,h)})]}),typeof b!=`number`&&typeof x!=`number`&&!n&&(0,J.jsx)(`div`,{className:`muted`,children:p(`pws.usageUnavailable`)})]}),c&&(0,J.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:c,children:[p(`pws.viewUsage`),` →`]}),S&&(0,J.jsx)(`div`,{className:`muted pws-stats-note`,children:p(`pws.stats.quotaTracked`)})]}),(0,J.jsx)(Sa,{item:e,onUpdateProvider:l})]})]})}function Sa({item:e,onUpdateProvider:t}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,_.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``)){i(!1),u(``);return}c(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){u(a.error||n(`prov.saveFailed`));return}u(``),i(!1)}finally{c(!1)}},[a,e.name,e.note,t,s,n]);return r?(0,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.jsx)(`textarea`,{ref:d,className:`pws-notes-textarea`,value:a,onChange:e=>o(e.target.value),onBlur:()=>void f(),onKeyDown:t=>{t.key===`Escape`&&(o(e.note??``),u(``),i(!1))},placeholder:n(`pws.notePlaceholder`),rows:3,disabled:s}),l?(0,J.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,J.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function Ca(e){return e.includes(`/`)?e.replaceAll(`/`,`-`):e}function wa(e,t){let n=Ca(e);for(let r of t)if(r!==e&&Ca(r)===n)return!0;return!1}function Ta({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=Q(),[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=[...n,...S,...P,...e.defaultModel?[e.defaultModel]:[]],L=!w||!F||n.includes(F)||S.includes(F)||P.includes(F)||e.defaultModel===F||wa(F,I),R=(0,_.useMemo)(()=>Bi(n,e.defaultModel,d,P,S,r),[n,e.defaultModel,d,P,S,r]);(0,_.useEffect)(()=>{let n=!0;return(async()=>{try{let r=await fetch(`${t}/api/custom-models`);if(!r.ok)throw Error();let i=await r.json();if(!Array.isArray(i))throw Error(`Invalid custom model list`);if(!n)return;C(i.flatMap(t=>{if(!t||typeof t!=`object`)return[];let n=t;return n.provider===e.name&&typeof n.modelId==`string`?[n.modelId]:[]})),D(!1),y(``),T(!0)}catch{if(!n)return;C([]),T(!1),D(!0),y(u(`models.networkError`))}})(),()=>{n=!1}},[t,e.name,u,O]);let z=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let B=async e=>{try{await navigator.clipboard.writeText(e),j(e),M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{j(t=>t===e?null:t),M.current=null},1200)}catch{}},V=async()=>{if(!(L||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=R.length>300,ee=W?R.slice(0,300):R;return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-section-head`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),R.length>0&&(0,J.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:R.length})})]}),s&&(0,J.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),U&&!s&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,J.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,J.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,J.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&V()},placeholder:u(`models.customFieldModelIdPlaceholder`),"aria-label":u(`models.customAdd`),disabled:h}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{V()},disabled:h||L,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,J.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,J.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:z,style:{marginLeft:8},children:u(`common.retry`)})]}),!H&&(0,J.jsx)(`input`,{type:`search`,className:`input pws-model-search`,placeholder:u(`pws.modelSearchPlaceholder`),value:d,onChange:e=>f(e.target.value),"aria-label":u(`pws.modelSearchPlaceholder`)}),a&&H?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&H?(0,J.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):H?(0,J.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):R.length===0?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,J.jsx)(`ul`,{className:`pws-model-list`,children:ee.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,J.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,J.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:()=>{B(t)},title:t,"aria-label":u(A===t?`pws.modelCopied`:`pws.copyModelId`),children:(0,J.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,J.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,J.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),W&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(R.length)})})]})}function Ea({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=Q(),{locale:a}=ct(),o=xi(i),s=t?.requests!==void 0,c=Ii(n),[l,u]=(0,_.useState)(null),d=(0,_.useMemo)(()=>r?.length?r.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[r]),f=(0,_.useMemo)(()=>{if(!d.length)return;let e=0,t=!1;for(let n of d)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[d]);return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:Ei(f,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:wi(t?.requests,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:Ti(t?.totalTokens,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,J.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`pws-model-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`pws.col.model`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,J.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,J.jsxs)(_.Fragment,{children:[(0,J.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,J.jsx)(`td`,{className:`mono`,children:(0,J.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,J.jsx)(`td`,{className:`num mono`,children:Ei(e.estimatedCostUsd,a)}),(0,J.jsx)(`td`,{className:`num mono`,children:Ti(e.totalTokens,a)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`pws-share-bar`,children:(0,J.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,J.jsx)(`tr`,{className:`pws-model-detail`,children:(0,J.jsx)(`td`,{colSpan:5,children:(0,J.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Ti(e.inputTokens,a)]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Ti(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($i,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,J.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,J.jsx)(`dd`,{children:zi(n.source)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{children:bi(n?.updatedAt,o)})]})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function Da(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function Oa(e){return Da(e)??`account-…`}function ka(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function Aa(e){let t=ka(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function ja(e){return e===`reauth_required`}function Ma(e){return!!e?.needsReauth||ja(e?.health?.status)}function Na(e){return e===`cooldown`}function Pa(e){return e===`warning`||e===`reauth_required`}function Fa(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 Ia(e,t){let n=Fa(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`):Oa(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 Ra(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return za(e)}function za(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 Ba(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}var Va=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function Ha(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 Ua({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=Q();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,J.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:a(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>n(e.target.value),style:{marginBottom:12}}),(0,J.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,J.jsx)(Ne,{width:20}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,J.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var Wa=2500;function Ga(){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;Ra(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)},Wa))})},[i])}}function Ka({url:e}){let t=Q(),{outcomeFor:n,copy:r}=Ga();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,J.jsxs)(`div`,{className:`login-url-block`,children:[(0,J.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,J.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,J.jsx)(ke,{style:{width:13,height:13},"aria-hidden":`true`}),(0,J.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,J.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,J.jsx)(Te,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function qa({hint:e,paste:t}){let n=Q(),r=Ga(),i=e.deviceCode??``,a=e.url??``;if(!i&&!a&&!e.instructions&&!t)return null;let o=r.outcomeFor(i),s=n(o===`copied`?`prov.codeCopied`:o===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`);return(0,J.jsxs)(`div`,{className:`login-hint`,children:[i&&(0,J.jsxs)(`div`,{className:`login-hint-device pwi-device-code-wrap`,children:[(0,J.jsx)(`span`,{className:`text-label`,children:n(`prov.deviceCode`)}),(0,J.jsx)(`code`,{className:`login-hint-device-code pwi-device-code`,children:i}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>r.copy(i,i),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:s})})]}),(0,J.jsx)(Ka,{url:a}),e.instructions&&(0,J.jsx)(`div`,{className:`muted text-label`,children:e.instructions}),t&&(0,J.jsxs)(`div`,{className:`login-hint-paste`,children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:n(`prov.pasteRedirectHint`)}),(0,J.jsxs)(`div`,{className:`login-hint-paste-row`,children:[(0,J.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:t.value,onChange:e=>t.onChange(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),t.onSubmit())},placeholder:n(`prov.pasteRedirect`),"aria-label":n(`prov.pasteRedirect`),disabled:t.busy,className:`input text-label login-hint-paste-input`}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:t.busy||t.disabled===!0||!t.value.trim(),onClick:t.onSubmit,children:t.busy?t.submittingLabel??n(`prov.pasteSubmitting`):n(`prov.pasteSubmit`)})]}),t.message&&(0,J.jsx)(`div`,{className:`text-label`,"aria-live":`polite`,style:{color:t.ok?`var(--accent-hover)`:`var(--amber)`},children:t.message})]})]})}function Ja({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=Q();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,J.jsx)(qa,{hint:{url:t},paste:{value:n,busy:r,disabled:r||i||!n.trim()||!s,submittingLabel:f(`codexAuth.oauthSubmittingCode`),message:``,ok:!0,onChange:l,onSubmit:u}}),a&&(0,J.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,J.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,J.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}var Ya=`ocx.oauth.openBrowser`;function Xa(){try{let e=window.localStorage.getItem(Ya);return e===`0`?!1:e===`1`||void 0}catch{return}}function Za(){let e=Xa();return e===void 0?{}:{openBrowser:e}}function Qa(e){try{window.localStorage.setItem(Ya,e?`1`:`0`)}catch{}}function $a(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 eo({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&&=(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({...Za(),...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 Pt(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=Vn(async()=>{if(s.current||v.signal.aborted)return;s.current=!0;let e=AbortSignal.any([v.signal,AbortSignal.timeout(1e4)]);try{let n=await Ft(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($a(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 to({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=Q(),[a,o]=(0,_.useReducer)(Ha,r,Va),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=eo({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,J.jsx)(`dialog`,{ref:c,"aria-label":g,className:`modal-overlay`,onCancel:h,children:(0,J.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,J.jsx)(Ua,{id:a.id,error:a.error,onIdChange:e=>o({type:`set-id`,id:e}),onStartOAuth:()=>{p(a.id)},onClose:f}),a.step===`oauth-waiting`&&(0,J.jsx)(Ja,{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 no=[2,1,0,-1,-2],ro=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function io(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function ao(e){let t=io(e);return t>0?`+${t}`:String(t)}function oo(e){return ro.has(e)}function so(e){return ro.get(e)??null}function co(e,t){let n=io(t);return e(`accountPool.priorityOption`,{name:e(so(n)??`accountPool.priorityCustom`),value:ao(n)})}var lo=1e4;function uo(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function fo(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function po(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function mo(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function ho(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function go(e,t,n){if(e<=0){let t=po(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:fo(t)??po(0,n)}}async function _o(e,t,n=(e,t)=>fetch(e,t),r=lo){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 vo=3e4,yo=new Map;function bo(e,t=!0){let n=yo.get(e),[r,i]=(0,_.useState)(()=>n?.accounts??[]),a=G(Ir(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),I=(0,_.useRef)(null),L=(0,_.useRef)(null),R=(0,_.useCallback)(e=>(j.current.add(e),()=>{j.current.delete(e)}),[]),z=(0,_.useCallback)(()=>ho(M.current?.value),[]),B=(0,_.useCallback)(()=>M.current?.value,[]),V=(0,_.useCallback)(async(t=!1)=>{let n=++k.current,r=Ln(2e4);S(e=>e+1);try{let a=[...j.current],o=new Map;for(let e of a)o.set(e,e.beginActiveRead());!t&&!F.current&&l(`loading`);let c=null,u,d=(async()=>{try{let a=await fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`,{signal:r.signal});if(!a.ok)throw Error(`account load failed`);let o=await a.json();return k.current===n&&(c=(o.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel;return{...e,...t?{logLabel:t}:{},priority:io(e.priority)}}),i(c),P.current=c.length>0,F.current=!0,l(`ready`)),!0}catch{return!1}})(),f=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`,{signal:r.signal});if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(k.current===n){let e=i.activeCodexAccountId??null,t=A.current;t&&e!==t.id||(A.current=null,u=e,s(e)),M.current={value:i},b(typeof i.pinnedAccountId==`string`?i.pinnedAccountId:null);for(let e of a)e.acceptActiveRead(i,o.get(e))}return!0}catch{if(k.current===n)for(let e of a)e.rejectActiveRead();return!1}})(),[p,m]=await Promise.all([d,f]);if(k.current!==n)return!1;if(p){l(`ready`),F.current=!0;let t=yo.get(e);return yo.set(e,{accounts:c??t?.accounts??[],activeId:u===void 0?t?.activeId??null:u}),m}return F.current||l(`error`),!1}finally{r.clear(),S(e=>Math.max(0,e-1)),w(!0)}},[e]);(0,_.useEffect)(()=>{t&&O.current!==e&&(O.current=e,Promise.resolve().then(()=>{V()}))},[e,t,V]);let H=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!H||T>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{V(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,H,T,V]),(0,_.useEffect)(()=>{if(!(!t||T>0))return Vn(()=>{V()},vo)},[t,V,T]);let U=(0,_.useCallback)(()=>{let e={};return D.current.add(e),E(D.current.size),e},[]),W=(0,_.useCallback)(e=>{D.current.delete(e)&&E(D.current.size)},[]),ee=(0,_.useCallback)(async t=>{if(N.current||L.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__`),V(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{N.current=null,d(null)}},[e,V]),K=(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 V(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,V]),q=(0,_.useCallback)(async(t,n)=>{if(I.current)return{ok:!1,reason:`busy`};I.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),V(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{I.current=null,p(null)}},[e,V]),J=(0,_.useCallback)(async(t,n)=>{if(L.current||N.current)return{ok:!1,reason:`busy`};L.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=io((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,V(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{L.current=null,h(null)}},[e,V]),Y=(0,_.useCallback)(async()=>{if(I.current)return{ok:!1,reason:`busy`};I.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),V(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{I.current=null,v(!1)}},[e,V]),te=(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=$a(await n.json().catch(()=>({})));return await V(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[e,V]),ne=(0,_.useCallback)(async()=>await V()?{ok:!0}:{ok:!1,reason:`reload`},[V]),re=o&&o!==`__main__`?r.find(e=>e.id===o):null,ie=r.find(e=>e.isMain),ae=re??ie,oe=!ae?.paused&&Ma(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:V,switchAccount:ee,setAccountPaused:q,setAccountPriority:J,pauseExhaustedAccounts:Y,saveAlias:K,removeAccount:te,syncAfterAccountAdded:ne,pauseRefresh:U,resumeRefresh:W,subscribeLoadObserver:R,readLastThreshold:z,readLastActive:B}}function xo(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 So({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,J.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,J.jsx)(be,{width:10,height:10,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,J.jsx)(xe,{width:10,height:10,"aria-hidden":`true`})})]})}var Co={quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function wo({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=Q(),m=(0,_.useRef)(!1),h=e>0,g=Co[n][h?`on`:`off`],v=i||!r,y=i?p(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,J.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,J.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,J.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,J.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?p(`codexAuth.autoSwitchLoadFailed`):p(g,{threshold:e})}),(0,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,J.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(c(!1),m.current){m.current=!1;return}h&&!v&&l()}},children:[a&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,J.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(So,{disabled:v,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s(xo(t,1,1,100))},onDecrement:()=>{c(!0),s(xo(t,-1,1,100))}})]})]}),(0,J.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,J.jsx)(`button`,{type:`button`,className:`toggle ${h?`on`:``}`,onPointerDownCapture:()=>{m.current=!0},onPointerUp:()=>{m.current=!1},onPointerCancel:()=>{m.current=!1},onClick:()=>{m.current=!1,d()},disabled:v,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,J.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,J.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}var To=[`quota`,`round-robin`,`fill-first`],Eo=[`five-hour`,`weekly`,`max-utilization`],Do=`quota`,Oo=`five-hour`,ko=new Set(To),Ao=new Set(Eo);function jo(e){return typeof e==`string`&&ko.has(e)?e:Do}function Mo(e){return typeof e==`string`&&Ao.has(e)?e:Oo}function No(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Po(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function Fo(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:jo(i.accountPoolStrategy??t.strategy),stickyLimit:No(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var Io={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},Lo={quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function Ro({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=Q(),l=To.map(e=>({value:e,label:c(Io[e])}));return(0,J.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(Lo[e])}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.unboundDefinition`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(Dt,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,J.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{id:i,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,disabled:n,"aria-label":c(`accountPool.stickyLimitAria`),onChange:e=>o(e.target.value),onBlur:()=>s(),onKeyDown:e=>{e.nativeEvent.isComposing||n||e.key===`Enter`&&(e.preventDefault(),s())}}),(0,J.jsx)(So,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=xo(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=xo(t,-1,1,100);o(e),s(e)}})]})})]})]})}function zo(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:jo(t.accountPoolStrategy),stickyLimit:No(t.accountPoolStickyLimit)}}function Bo({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r}){let i=Q(),[a,o]=(0,_.useState)(Do),[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=jo(e.accountPoolStrategy),n=No(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=zo(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 Fo(e,t);y.current+=1,d.ok?(o(d.strategy),r?.(d.strategy),c(d.stickyLimit),u(String(d.stickyLimit)),p.current=!0,f(!0)):(C(i(`accountPool.strategyUpdateFailed`)),o(n),r?.(n),c(l),u(String(l))),g.current=!1,h(!1),D()},[e,r,D,s,a,i]),k=m||b||!d;return(0,J.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":m||!d&&!b,children:[b&&(0,J.jsx)(`div`,{className:`card-sub`,role:`alert`,children:i(`accountPool.strategyLoadFailed`)}),b&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{E()},children:i(`common.retry`)}),!b&&(0,J.jsx)(Ro,{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=Po(e??l);if(t===null){u(String(s)),C(i(`accountPool.stickyLimitInvalid`));return}if(t===s){u(String(t));return}O({stickyLimit:t})}}),S&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:S})]})}function Vo({t:e,open:t,onToggle:n,children:r}){return(0,J.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,J.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,J.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function Ho(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=ho(e),r=mo(v.current,y.current,t,x.current);r===`defer`?S.current=uo(n):r===`apply`&&T(uo(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(uo(ho(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 _o(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=fo(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=go(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 Uo({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=Q(),a=io(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,c=no.map(e=>({value:String(e),label:co(i,e)})),l=oo(a)?c:[{value:String(a),label:co(i,a)},...c];return(0,J.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,J.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,J.jsx)(Dt,{id:n,value:String(a),options:l,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(io(Number.parseInt(e,10)))}),(0,J.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function Wo({value:e}){let t=Q(),n=io(e);return n===0?null:(0,J.jsx)(`span`,{className:`badge badge-muted`,children:co(t,n)})}var Go=new Map;function Ko(e,t){return`${e??``}\0${JSON.stringify(t)}`}function qo(e,t){let n=Ko(e,t??{}),r=Go.get(n);return r||(r=new Intl.NumberFormat(e,t),Go.set(n,r)),r}var Jo={month:`short`,day:`numeric`,year:`numeric`},Yo={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},Xo=new Map;function Zo(e,t){let n=Ko(e,t),r=Xo.get(n);return r||(r=new Intl.DateTimeFormat(e,t),Xo.set(n,r)),r}function Qo(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Zo(t,Jo).format(n)}function $o(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Zo(t,Yo).format(n)}function es(e,t){return!Number.isFinite(e)||e<0?`—`:`~${qo(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function ts(e,t){return Qo(e,t)}function ns(e,t){return $o(e,t)}function rs(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function is({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=rs(n),s=o<=7;return(0,J.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,J.jsxs)(`div`,{className:`credit-item-head`,children:[(0,J.jsx)(Oe,{width:13}),(0,J.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,J.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,J.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,J.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:ts(t,i)})}),(0,J.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:ns(n,i),days:String(o)})})]})]})}function as({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Oe,{width:12}),`0`]}):r===void 0?null:(0,J.jsxs)(`button`,{type:`button`,className:`badge ${typeof r==`number`&&r>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":n(`codexAuth.resetCreditsAria`,{count:String(r)}),children:[(0,J.jsx)(Oe,{width:12}),r]})}function os({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,J.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function ss({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=Q(),b=e=>!e.paused&&t===e.id;return(0,J.jsx)(J.Fragment,{children:e.map(e=>{let t=e.health?.status,x=!!e.needsReauth||ja(t),S=Na(t),C=Ia(y,e.health),w=La(y,`codex`,e.id,e.health);return(0,J.jsxs)(`div`,{className:`card ${b(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${x?`dot-amber`:b(e)?`dot-blue`:`dot-muted`}`}),(0,J.jsx)(`strong`,{children:e.alias??e.email}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:y(`codexAuth.pausedHint`),children:y(`codexAuth.paused`)}),(0,J.jsx)(Wo,{value:e.priority}),e.id===p&&!e.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:y(`codexAuth.pinned`)}),(0,J.jsx)(as,{t:y,account:e,onClick:()=>a(e)}),C&&(0,J.jsx)(`span`,{className:Aa(t),children:C}),x&&!C&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:y(`codexAuth.needsReauth`)}),b(e)&&!x&&!S&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:y(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&(!b(e)||p!==e.id)&&!x&&!S&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),x&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>m(e.id),children:y(`codexAuth.reauthenticate`)}),_&&Pa(t)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>_(e.id),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Ba(y,v?.(e.id))})}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(e),disabled:l,title:e.paused?y(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${y(`codexAuth.resume`)}. ${y(`codexAuth.pausedHint`)}`:y(`codexAuth.pause`),children:[e.paused?(0,J.jsx)(me,{width:14}):(0,J.jsx)(pe,{width:14}),(0,J.jsx)(os,{t:y,paused:e.paused,saving:c===e.id})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void h(e),children:y(`prov.editAlias`)}),(0,J.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,J.jsx)(ue,{width:14})})]}),(0,J.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,J.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,y(`prov.accountId`),`: `,Oa(e.id)]}),(0,J.jsx)(Uo,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:d!==null||f!==null,onChange:t=>u(e,t)})]}),w&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:w}),S&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:y(`pws.healthCooldownHint`)}),x?(0,J.jsx)(`div`,{className:`card-sub faint`,children:y(`codexAuth.tokenExpired`)}):!S&&(0,J.jsx)($i,{quota:e.quota,plan:e.plan,threshold:i,t:y,pending:e.quota==null})]},e.id)})})}function cs({onReauth:e}){let t=Q();return(0,J.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(_e,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function ls({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,onCancel:a,onConfirm:o}){let s=Q(),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,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:l,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?s(`codexAuth.preparePoolTitle`):e.id===`__main__`?s(`codexAuth.switchBack`):s(`codexAuth.switchTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?s(`codexAuth.preparePoolDesc`):e.id===`__main__`?s(`codexAuth.switchBackDesc`):s(`codexAuth.switchDesc`)}),(0,J.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,J.jsx)(`strong`,{children:e.id===`__main__`?t||s(`codexAuth.codexApp`):e.email}),e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,J.jsxs)(`div`,{className:`notice-warn`,children:[(0,J.jsx)(_e,{width:14}),` `,s(`codexAuth.cacheWarning`)]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`codexAuth.cancel`)}),(0,J.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 us({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=ct(),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,J.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:f,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,J.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,J.jsx)(`div`,{className:`confirm-icon`,children:(0,J.jsx)(_e,{width:22})}),(0,J.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:ts(n[0].granted_at,l)})}),(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,J.jsx)(Oe,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,J.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,J.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,J.jsx)(is,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,J.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function ds({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||ja(t?.health?.status),x=Na(t?.health?.status),S=Ia(e,t?.health),C=t?La(e,`codex`,v,t.health):null;return(0,J.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${b?`dot-amber`:`dot-green`}`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,J.jsx)(as,{t:e,account:{...t,id:`__main__`},onClick:()=>m({...t,id:`__main__`})}),t?.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,J.jsx)(Wo,{value:y.priority}),p===`__main__`&&!t?.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:e(`codexAuth.pinned`)}),S&&(0,J.jsx)(`span`,{className:Aa(t?.health?.status),children:S}),b&&!S&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,J.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&(!n||p!==`__main__`)&&!b&&!x&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(y),children:a}),h&&Pa(t?.health?.status)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>h(v),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Ba(e,g?.(v))})}),t&&(0,J.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,J.jsx)(me,{width:14}):(0,J.jsx)(pe,{width:14}),(0,J.jsx)(os,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(De,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,J.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),t&&(0,J.jsx)(Uo,{value:y.priority,selectId:`codex-account-priority-${y.id}`,disabled:d!==null||f!==null,onChange:e=>u(y,e)})]}),C&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:C}),x&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),b?(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!x&&(0,J.jsx)($i,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function fs({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c,sparkVisible:l,sparkBusy:u,onToggleSpark:d}){return(0,J.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,J.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,J.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,J.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`warn`?` is-warn`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),l!==void 0&&d&&(0,J.jsxs)(`span`,{className:`codex-auth-spark-toggle`,children:[(0,J.jsx)(`span`,{className:`codex-auth-spark-toggle__label`,children:e(`codexAuth.sparkQuota`)}),(0,J.jsx)(`button`,{type:`button`,className:`toggle ${l?`on`:``}`,onClick:d,disabled:!!u,"aria-pressed":l,"aria-label":e(`codexAuth.sparkQuota`),title:e(`codexAuth.sparkQuotaHint`),children:(0,J.jsx)(`span`,{className:`toggle-knob`})})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,J.jsx)(pe,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,J.jsx)(fe,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function ps({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,J.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,J.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot dot-muted`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Oe,{width:12}),`0`]}),(0,J.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(pe,{width:14}),` `,e(`codexAuth.pause`)]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(De,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,J.jsx)($i,{quota:null,threshold:0,t:e,pending:!0})]}),(0,J.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(de,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,J.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,J.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,J.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function ms(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function hs(e,t,n,r){try{let i=await Ft(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:ms(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 gs=`ocx doctor`;function _s({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a,advancedExtras:o=null}){let s=Q(),c=Ho(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=bo(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),z=(0,_.useRef)(null),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(void 0),[W,ee]=(0,_.useState)(!1),[G,K]=(0,_.useState)(null),[q,Y]=(0,_.useState)(!1),[te,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(null),[ae,oe]=(0,_.useState)(!1),X=Ga(),se=(0,_.useCallback)((e,t=`ok`)=>{z.current&&clearTimeout(z.current),I(e),R(t),z.current=setTimeout(()=>{I(null),R(null),z.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{z.current&&clearTimeout(z.current)},[]);let ce=(0,_.useCallback)(e=>{X.copy(gs,e)},[X]),{subscribeLoadObserver:le,readLastThreshold:ue}=g;(0,_.useEffect)(()=>le({beginActiveRead:d,acceptActiveRead:f,rejectActiveRead:p}),[le,d,f,p]),(0,_.useEffect)(()=>{let e=ue();e!==void 0&&m(e)},[ue,m]),(0,_.useEffect)(()=>{if(!k)return;let e=g.pauseRefresh();return()=>g.resumeRefresh(e)},[g,k]);let fe=y&&y!==`__main__`?v.find(e=>e.id===y):null,pe=!fe?.paused&&Ma(fe);(0,_.useEffect)(()=>{i?.(pe)},[pe,i]);let me=(0,_.useCallback)(e=>{P(e),A(!0)},[]),he=(0,_.useCallback)(()=>{A(!1),P(null)},[]),ge=(0,_.useCallback)(e=>{g.syncAfterAccountAdded(),se(s(e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.catalogRefreshPending?`warn`:`ok`),he()},[he,g,se,s]),_e=async e=>{let n=await g.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;se(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`);se(s(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},ve=async e=>{let t=window.prompt(s(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await g.saveAlias(e.id,t);se(s(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},ye=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),se(s(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},be=async(e,t)=>{if(t===e.priority)return;let n=await g.setAccountPriority(e.id,t);!n.ok&&n.reason===`busy`||se(s(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},xe=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&&se(s(`codexAuth.catalogRefreshPending`),`warn`):se(s(`codexAuth.removeFailed`),`err`)},Z=async()=>{V(!0);try{let e=await E(!0);se(s(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{V(!1)}};(0,_.useEffect)(()=>{let t=new AbortController;return fetch(`${e}/api/settings`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(e=>{t.signal.aborted||typeof e?.showCodexSparkQuota!=`boolean`||U(e.showCodexSparkQuota)}).catch(()=>{}),()=>{t.abort()}},[e]);let Se=async()=>{if(W||H===void 0)return;let t=!H;ee(!0),U(t);try{let n=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({showCodexSparkQuota:t})});if(!n.ok)throw Error(`save`);let r=await n.json(),i=typeof r.showCodexSparkQuota==`boolean`?r.showCodexSparkQuota:t;U(i),se(s(i?`codexAuth.sparkQuotaShown`:`codexAuth.sparkQuotaHidden`),`ok`),await E(!0)}catch{U(!t),se(s(`codexAuth.sparkQuotaFailed`),`err`)}finally{ee(!1)}},Ce=async()=>{let e=await g.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||se(e.ok?e.pausedCount>0?s(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):s(`codexAuth.pauseExhaustedNone`):s(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},we=async t=>{K(t),Y(!1),ie(null),oe(!0);try{let n=await Ft(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());ie(e)}}catch{}finally{oe(!1)}},Te=async t=>{ne(!0);try{let n=await hs(e,t,s,E);n.close&&(K(null),Y(!1)),n.toast&&se(n.toast,n.ok?`ok`:`err`)}finally{ne(!1)}},Ee=v.find(e=>e.isMain),De=v.filter(e=>!e.isMain),Oe=!Ee?.paused&&(!y||y===`__main__`),ke=s(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),Ae=S!==null||w,je=c.threshold??0,Me=!r;return(0,J.jsxs)(`div`,{children:[(0,J.jsx)(fs,{t:s,embedded:r,refreshingQuota:B,actionFeedback:F,actionFeedbackTone:L,pausingExhausted:w,pauseBusy:Ae,onRefresh:()=>{Z()},onPauseExhausted:()=>{Ce()},sparkVisible:H,sparkBusy:W,onToggleSpark:()=>{Se()}}),n,(0,J.jsx)(ps,{t:s,loadState:b,accountsCount:v.length,onRetry:()=>{E()}}),(b!==`loading`||v.length!==0)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(ds,{t:s,main:Ee,isMainActive:Oe,accountModeState:t,threshold:je,switchActionLabel:ke,onSwitch:O,onTogglePause:ye,pauseUpdatingId:S,pauseBusy:Ae,onPriorityChange:(e,t)=>{be(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onOpenReset:we,onCopyDoctor:Me?ce:void 0,doctorCopyOutcomeFor:Me?X.outcomeFor:void 0}),(0,J.jsxs)(`div`,{className:`section-sep`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:s(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>A(!0),children:[(0,J.jsx)(de,{width:14}),` `,s(`codexAuth.add`)]})]}),pe&&fe&&(0,J.jsx)(cs,{onReauth:()=>me(fe.id)}),De.length===0&&(0,J.jsx)(Ot,{title:s(`codexAuth.noPool`)}),(0,J.jsx)(ss,{pool:De,activeId:y,accountModeState:t,switchActionLabel:ke,threshold:je,onOpenReset:we,onSwitch:O,onTogglePause:ye,pauseUpdatingId:S,pauseBusy:Ae,onPriorityChange:(e,t)=>{be(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onReauth:me,onEditAlias:ve,onRemove:xe,onCopyDoctor:Me?ce:void 0,doctorCopyOutcomeFor:Me?X.outcomeFor:void 0})]}),(0,J.jsx)(Bo,{apiBase:e,subscribeLoadObserver:g.subscribeLoadObserver,readLastActive:g.readLastActive,onStrategyResolved:u}),(0,J.jsxs)(Vo,{t:s,open:j,onToggle:()=>M(e=>!e),children:[l!==null&&(0,J.jsx)(wo,{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,J.jsx)(ls,{confirm:D,mainEmail:Ee?.email,accountModeState:t,switchingId:x,orderBusy:C!==null,onCancel:()=>O(null),onConfirm:()=>{_e(D.id===`__main__`?`__main__`:D.id)}}),G&&(0,J.jsx)(us,{resetPopup:G,resetConfirm:q,creditDetails:re,creditDetailsLoading:ae,redeeming:te,onClose:()=>{K(null),Y(!1),ie(null)},onShowConfirm:()=>Y(!0),onCancelConfirm:()=>Y(!1),onRedeem:()=>{Te(G.id)}}),k&&(0,J.jsx)(to,{apiBase:e,reauthAccountId:N??void 0,onClose:he,onAdded:ge})]})}var vs={"five-hour":`accountPool.quotaWindowFiveHour`,weekly:`accountPool.quotaWindowWeekly`,"max-utilization":`accountPool.quotaWindowMaxUtilization`};function ys({apiBase:e,accountCount:t}){let n=Q(),[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=No(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:jo(e.strategy),stickyLimit:r,quotaWindow:Mo(e.quotaWindow)}),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,quotaWindow:t.quotaWindow}),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,quotaWindow:t.quotaWindow})});if(!n.ok)throw Error(`save`);let r=await n.json().catch(()=>null),a=jo(r?.strategy??t.strategy),s=No(r?.stickyLimit??t.stickyLimit),l=Mo(r?.quotaWindow??t.quotaWindow);i({enabled:t.enabled,threshold:t.threshold,strategy:a,stickyLimit:s,quotaWindow:l}),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?.quotaWindow??`five-hour`,S=y===`round-robin`,C=r===null&&!p,w=C||l||p||!g&&t<2;return(0,J.jsxs)(`div`,{className:`card anthropic-pool-card`,"aria-busy":C||l,children:[(0,J.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,J.jsxs)(`div`,{style:{flex:1},children:[(0,J.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:p?n(`anthropicPool.loadFailed`):C?n(`common.loading`):g?v===0?n(`anthropicPool.enabledNoProactiveDesc`,{window:n(vs[x])}):n(`anthropicPool.enabledDesc`,{threshold:v,window:n(vs[x])}):n(`anthropicPool.disabledDesc`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`toggle ${g?`on`:``}`,disabled:w,"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,quotaWindow:x})},children:(0,J.jsx)(`span`,{className:`toggle-knob`})})]}),(0,J.jsx)(`div`,{role:`alert`,className:`card-sub anthropic-pool-card__notice`,children:n(`anthropicPool.experimentalWarning`)}),t<2&&(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`field anthropic-pool-card__field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:a,disabled:l,"aria-label":n(`anthropicPool.thresholdAria`),onChange:e=>o(e.target.value),onBlur:()=>{let e=Number(a);if(!Number.isInteger(e)||e<0||e>100){o(String(v)),f(n(`anthropicPool.thresholdInvalid`));return}e!==v&&h({enabled:!0,threshold:e,strategy:y,stickyLimit:b,quotaWindow:x})}}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,J.jsx)(Ro,{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,quotaWindow:x})},onStickyDraftChange:c,onStickyCommit:e=>{let t=Po(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,quotaWindow:x})}}),(0,J.jsxs)(`div`,{className:`field anthropic-pool-card__field anthropic-pool-card__field--quota-window`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`accountPool.quotaWindow`)}),(0,J.jsx)(Dt,{id:`anthropic-pool-quota-window`,value:x,options:Eo.map(e=>({value:e,label:n(vs[e])})),disabled:l||S,label:n(`accountPool.quotaWindow`),onChange:e=>{let t=Mo(e);t!==x&&h({enabled:!0,threshold:v,strategy:y,stickyLimit:b,quotaWindow:t})}}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`accountPool.quotaWindowDesc`)}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(S?`accountPool.quotaWindowInert`:`accountPool.quotaWindowHint`)})]})]}),d&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}function bs({serverDefault:e=!0}){let t=Q(),[n,r]=(0,_.useState)(Xa);return(0,J.jsxs)(`label`,{className:`open-browser-pref`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:!(n??e),onChange:e=>{let t=!e.target.checked;r(t),Qa(t)}}),(0,J.jsxs)(`span`,{className:`open-browser-pref-copy`,children:[(0,J.jsx)(`span`,{className:`text-label`,children:t(`prov.dontOpenBrowser`)}),(0,J.jsx)(`span`,{className:`muted text-label`,children:t(`prov.dontOpenBrowserHint`)})]})]})}var xs=4e3,Ss=262144,Cs=[],ws=[];function Ts({initialState:e,onUpdateProvider:t}){let n=Q(),[r,i]=(0,_.useState)(e),[a,o]=(0,_.useState)(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``);e!==a&&(o(e),i(e));let d=r===`mixed`,f=async()=>{if(!t||s)return;let e=r!==!0;c(!0),u(``);try{let r=await t(`xai`,{xaiResponsesOptIn:e});if(!r.ok){u(r.error??n(`prov.updateFail`));return}i(r.xaiResponsesOptInState??e)}catch{u(n(`prov.networkError`))}finally{c(!1)}};return(0,J.jsxs)(`div`,{className:`pwi-auth-optin-row`,children:[(0,J.jsxs)(`div`,{className:`pwi-auth-optin-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-optin-label`,children:n(`pws.xaiResponsesOptIn`)}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-secondary`,children:[n(`pws.xaiResponsesOptInDesc`),d&&(0,J.jsxs)(`span`,{className:`pwi-auth-optin-mixed`,children:[` `,n(`pws.xaiResponsesOptInMixed`)]})]}),l&&(0,J.jsx)(`span`,{className:`pwi-auth-optin-error`,role:`alert`,children:l})]}),(0,J.jsx)(Tt,{on:r===!0,mixed:d,onClick:()=>{f()},disabled:!t||s,label:n(`pws.xaiResponsesOptIn`)})]})}var Es=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),Ds=new Set([`imported`,`updated`,`failed`,`unsupported`]),Os={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 ks(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function As(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function js(e){if(!ks(e)||Object.keys(e).some(e=>!Es.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!As(t)||!As(n)||!As(r)||!As(i)||!As(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(!ks(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||!Ds.has(n)||!Os[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 Ms({item:e,apiBase:t,oauth:n,accounts:r=Cs,keys:i=ws,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d,onUpdateProvider:f}){let p=Q(),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(!1),[C,w]=(0,_.useState)(`idle`),[T,E]=(0,_.useState)(null),[D,O]=(0,_.useState)(!1),k=(0,_.useRef)(null),[A,j]=(0,_.useState)(``),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(``),[I,L]=(0,_.useState)(!0);(0,_.useEffect)(()=>{if(r.length===0){O(!1);return}if(!r.some(e=>e.quota==null&&!e.quotaUnavailable)){O(!1);return}O(!0);let e=window.setTimeout(()=>O(!1),xs);return()=>window.clearTimeout(e)},[r]);let R=ya({...e,hasApiKey:e.hasApiKey||i.length>0}),z=R===`oauth-accounts`,B=R===`api-keys`;if(R===`codex-accounts`)return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":p(`pws.availableAccounts`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:p(`pws.availableAccounts`)}),(0,J.jsx)(`div`,{className:`pwi-auth-body`,children:(0,J.jsx)(_s,{apiBase:t,embedded:!0,controller:d,onActiveNeedsReauthChange:u})})]});if(!R||!l)return null;let V=c?.provider===e.name?c:null,H=async()=>{let n=A.trim();if(!(!n||M)){N(!0),F(``);try{let r=await fetch(`${t}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,input:n})});if(!r.ok){let e=await r.json().catch(()=>({}));L(!1),F(p(`prov.pasteFail`,{error:e.error||r.statusText}));return}j(``),L(!0),F(p(`prov.pasteOk`))}catch{L(!1),F(p(`modal.networkError`))}finally{N(!1)}}},U=r.length>0||n?.loggedIn===!0,W=r.find(e=>e.active&&e.needsReauth),ee=!!W,G=async()=>{let t=g.trim();if(t){b(!0);try{await l.onAddApiKey(e.name,t)&&(v(``),h(!1))}finally{b(!1)}}},K=async n=>{if(!(!n||x)){S(!0),w(`idle`),E(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>Ss){w(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{w(`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){w(`failed`);return}let a=js(await i.json().catch(()=>null));if(!a){w(`failed`);return}E(a),w(`complete`);try{await l.onRetryAccounts?.(e.name)}catch{}}catch{w(`failed`)}finally{k.current&&(k.current.value=``),S(!1)}}};return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":p(z?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:p(z?`pws.availableAccounts`:`pws.apiKeys`)}),(0,J.jsxs)(`div`,{className:`pwi-auth-body`,children:[e.name===`xai`&&(0,J.jsx)(Ts,{initialState:e.xaiResponsesOptInState??!1,onUpdateProvider:f}),z&&(0,J.jsxs)(J.Fragment,{children:[e.name===`anthropic`&&(0,J.jsx)(ys,{apiBase:t,accountCount:r.length}),e.name===`google-antigravity`&&(0,J.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:p(`pws.cockpitImportDescription`)}),(0,J.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:p(`pws.cockpitImportFileLabel`)}),(0,J.jsx)(`input`,{ref:k,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:x,onChange:e=>{K(e.currentTarget.files?.[0])}})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:x,onClick:()=>k.current?.click(),children:p(x?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,J.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[C===`invalid`&&p(`pws.cockpitImportInvalid`),C===`failed`&&p(`pws.cockpitImportFailed`),C===`complete`&&T&&p(`pws.cockpitImportComplete`,{imported:T.importedCount,updated:T.updatedCount,failed:T.failedCount,unsupported:T.unsupportedCount})]})]}),(0,J.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${ee?`pwi-auth-dot--warn`:U?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`pwi-auth-status-text`,children:U?r.length>0?p(`pws.loggedInTitle`):n?.email??p(`pws.loggedInTitle`):n?.error||p(`pws.notLoggedInTitle`)}),(0,J.jsxs)(`span`,{className:`pwi-auth-actions`,children:[W&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onReauth(e.name,W.id),children:p(`pws.reauthenticate`)}),U?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:p(`prov.logout`)}):(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,J.jsx)(De,{style:{width:13,height:13},"aria-hidden":`true`}),p(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),!s&&(0,J.jsx)(bs,{}),s&&V&&(0,J.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,J.jsx)(`div`,{className:`pwi-auth-wait-title`,children:p(`prov.waitingBrowser`)}),(0,J.jsx)(qa,{hint:{url:V.url,deviceCode:V.deviceCode,instructions:V.instructions},paste:{value:A,busy:M,message:P,ok:I,onChange:j,onSubmit:()=>{H()}}}),l.onCancelLogin&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onCancelLogin?.(e.name),children:p(`common.cancel`)})]})]}),a===`loading`&&r.length===0&&(0,J.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),p(`pws.accountsLoading`)]}),a===`error`&&(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:p(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:p(`pws.retryAccounts`)})]}),r.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=ba(r,t,p),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||ja(a),u=Na(a),d=Oa(t.id),f=Ia(p,t.health),m=La(p,e.name,t.id,t.health);return(0,J.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,J.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!c&&!u&&!o&&l.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${p(`pws.accountCurrent`)}`:``}`,disabled:!!(c||u||o&&!i),children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${c?`pwi-auth-dot--warn`:t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${p(`prov.accountId`)}: ${d}`].filter(Boolean).join(` · `)}),m&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:m}),u&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:p(`pws.healthCooldownHint`)})]}),f&&(0,J.jsx)(`span`,{className:Aa(a),children:f}),c&&!f&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:p(`pws.reauth`)}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:p(`prov.accountActive`)}),i&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:p(`pws.accountSwitching`)})]}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s||!!o,onClick:()=>void l.onReauth(e.name,t.id),children:p(`pws.reauthenticate`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`oauth`,t.id,t.alias),children:p(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${p(`common.remove`)} — ${n}`,title:`${p(`common.remove`)} — ${n}`,disabled:!!o,onClick:()=>void l.onRemoveAccount(e.name,t),children:(0,J.jsx)(he,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||D&&t.quota==null)&&(0,J.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,J.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:p(`pws.accountQuotaUnavailable`)}):(0,J.jsx)($i,{quota:t.quota??null,plan:null,threshold:80,t:p,layout:`stacked`,pending:t.quota==null})})]},t.id)})}),a===`ready`&&U&&r.length===0&&(0,J.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:p(`pws.noAccounts`)}),U&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>void l.onLogin(e.name,!0),disabled:s||!!o,children:p(`pws.addAccount`)})]}),B&&(0,J.jsxs)(J.Fragment,{children:[i.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,J.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,J.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,p(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:p(`prov.accountActive`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`api-key`,t.id,t.label),children:p(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${p(`common.remove`)} — ${t.label??t.masked}`,title:`${p(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void l.onRemoveApiKey(e.name,t),children:(0,J.jsx)(he,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),m?(0,J.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,J.jsx)(`input`,{className:`input`,type:`password`,value:g,onChange:e=>v(e.target.value),placeholder:p(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:y}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void G(),disabled:y||!g.trim(),children:p(y?`pws.saving`:`pws.addKey`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h(!1),v(``)},children:p(`common.cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>h(!0),children:p(`pws.addKey`)})]})]})]})}function Ns(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 Ps(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 Fs(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Is=`https://chatgpt.com/backend-api/codex`;function Ls(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 Rs(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 zs(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Ls(e.baseUrl)!==Is?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function Bs(e){return e.id===`openai`}function Vs(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function Hs(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 Us(e,t){return Bs(e)?Ws(e):{name:t.name.trim(),provider:Hs(t)}}function Ws(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Gs=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function Ks(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 Gs(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Gs(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Gs(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Ws(i))})).ok)throw new Gs(`codexAuth.enableOpenaiFailed`)}var qs=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],Js=[];function Ys(e){return e===`http1.1`||e===`h1`?`http1.1`:`http2`}function Xs(e){return e===void 0?``:String(e)}function Zs(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function Qs(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function $s(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 ec({item:e,availableModels:t=Js,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=Q(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),c=$r(e.name,e),l=c?e.liveModels!==!1:!1,u=Ys(e.upstreamHttpVersion),[d,f]=(0,_.useState)(e.adapter),[p,m]=(0,_.useState)(e.baseUrl),[h,g]=(0,_.useState)(e.defaultModel??``),[v,y]=(0,_.useState)(s),[b,x]=(0,_.useState)(e.apiKeyTransport??`x-api-key`),[S,C]=(0,_.useState)(e.note??``),[w,T]=(0,_.useState)(e.allowPrivateNetwork??!1),[E,D]=(0,_.useState)(l),[O,k]=(0,_.useState)(u),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(null),[P,F]=(0,_.useState)(e.codexAccountMode??`pool`),[I,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(null),[B,V]=(0,_.useState)(),[H,U]=(0,_.useState)(n?`loading`:`idle`),[W,ee]=(0,_.useState)(()=>`custom`),[G,K]=(0,_.useState)(e.requestPacing?.enabled===!0),[q,Y]=(0,_.useState)(()=>Xs(e.requestPacing?.requestsPerMinute)),[te,ne]=(0,_.useState)(()=>Xs(e.requestPacing?.minIntervalMs)),[re,ie]=(0,_.useState)(()=>({...e.requestPacing?.models??{}})),[ae,oe]=(0,_.useState)(``),[X,se]=(0,_.useState)(``),[ce,le]=(0,_.useState)(``),[ue,de]=(0,_.useState)(null);(0,_.useEffect)(()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),y(String(e.authMode??(e.keyOptional?`local`:`key`))),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),D(l),k(u),K(e.requestPacing?.enabled===!0),Y(Xs(e.requestPacing?.requestsPerMinute)),ne(Xs(e.requestPacing?.minIntervalMs)),ie({...e.requestPacing?.models??{}}),N(null),z(null),queueMicrotask(()=>ee(Ps(B,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,l,u,e.requestPacing,B]),(0,_.useEffect)(()=>{F(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=>Ft(e)).then(e=>{if(t)return;if(!e){V(void 0),U(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;V(n),U(`ready`),ee(Ps(n,i))}).catch(()=>{t||(V(void 0),U(`error`))}),()=>{t=!0}},[n,e.name]),(0,_.useEffect)(()=>{if(!n)return;let t=!0,r=!1,i=()=>{if(r)return;r=!0;let i=Ln(1e4);fetch(`${n}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`,{signal:i.signal}).then(e=>Ft(e)).then(e=>{t&&e&&de(e)}).catch(()=>void 0).finally(()=>{i.clear(),r=!1})};i();let a=Vn(i,2e3);return()=>{t=!1,a()}},[n,e.name]);let fe=(0,_.useMemo)(()=>({enabled:G,...Zs(q)===void 0?{}:{requestsPerMinute:Zs(q)},...Qs(te)===void 0?{}:{minIntervalMs:Qs(te)},...Object.keys(re).length>0?{models:re}:{}}),[te,G,re,q]),pe=d.trim()!==e.adapter||p.trim()!==e.baseUrl||h.trim()!==(e.defaultModel??``)||v!==String(e.authMode??(e.keyOptional?`local`:`key`))||d.trim()===`anthropic`&&v===`key`&&b!==(e.apiKeyTransport??`x-api-key`)||S.trim()!==(e.note??``)||w!==(e.allowPrivateNetwork??!1)||E!==l||d.trim()===`cursor`&&O!==u,me=$s(fe)!==$s(e.requestPacing),he=pe||me;(0,_.useEffect)(()=>(i?.(he),()=>i?.(!1)),[he,i]);let ge=(0,_.useMemo)(()=>{let n=new Set(t);return h.trim()&&n.add(h.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,h,e.defaultModel]),_e=(0,_.useMemo)(()=>{let e=[...qs];return d&&!e.includes(d)&&e.unshift(d),e},[d]),ve=On(e.name),ye=H===`ready`&&!!(B&&B.length>0),be=d.trim()===`anthropic`&&v===`key`,xe=e.name===`openai`?zs(e):`invalid`,Z=xe===`ready`||xe===`disabled`,Se=ve&&H!==`error`,Ce=async()=>{if(!r)return N({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;if(I)return!1;let t=ye?Fs(B,W,p):p.trim();if(!d.trim()||!t)return N({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;j(!0),N(null);try{if(G&&!fe.requestsPerMinute&&!fe.minIntervalMs&&!fe.models)return N({ok:!1,text:o(`pws.pacingRuleRequired`)}),!1;let n=me&&!pe,i=n?{requestPacing:fe}:{adapter:d.trim(),baseUrl:t,defaultModel:h.trim(),authMode:v,note:S.trim(),allowPrivateNetwork:w,...me?{requestPacing:fe}:{}};n||(c&&E!==(e.liveModels!==!1)&&(i.liveModels=E),d.trim()===`cursor`&&O!==u&&(i.upstreamHttpVersion=O===`http1.1`?`http1.1`:null),be?i.apiKeyTransport=b:e.apiKeyTransport!==void 0&&(i.apiKeyTransport=``));let a=await r(e.name,i);return N(a.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:a.error||o(`prov.saveFailed`)}),a.ok}finally{j(!1)}},we=(0,_.useRef)(Ce);(0,_.useEffect)(()=>{we.current=Ce}),(0,_.useEffect)(()=>{if(a)return a(()=>we.current()),()=>a(null)},[a]);let Te=async e=>{if(!(I||A||e===P)){if(!r){z({ok:!1,text:o(`pws.updatesUnavailable`)});return}L(!0),z(null);try{let t=await r(`openai`,{codexAccountMode:e});t.ok?(F(e),z({ok:!0,text:o(`pws.accountModeSaved`)})):z({ok:!1,text:t.error||o(`pws.accountModeFailed`)})}catch{z({ok:!1,text:o(`pws.accountModeFailed`)})}finally{L(!1)}}},Ee=()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),y(s),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),D(l),k(u),N(null),K(e.requestPacing?.enabled===!0),Y(Xs(e.requestPacing?.requestsPerMinute)),ne(Xs(e.requestPacing?.minIntervalMs)),ie({...e.requestPacing?.models??{}}),ee(Ps(B,e.baseUrl))},Oe=(e,t)=>{switch(e){case`token-plan`:return o(`modal.endpoint.tokenPlan`);case`payg`:return o(`modal.endpoint.payAsYouGo`);case`custom`:return o(`modal.endpoint.custom`);default:return t}};return(0,J.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,J.jsx)(De,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,J.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),ve?(0,J.jsx)(`input`,{className:`input`,value:d,readOnly:!0,disabled:!0}):(0,J.jsx)(`select`,{className:`input`,value:d,onChange:e=>f(e.target.value),children:_e.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})]}),ye?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,J.jsx)(`select`,{className:`input`,value:W,onChange:e=>{let t=e.target.value;ee(t),m(Ns(B,t,p))},children:B.map(e=>(0,J.jsx)(`option`,{value:e.id,children:Oe(e.id,e.label)},e.id))})]}),W===`custom`&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),readOnly:Se,disabled:Se})]}),d.trim()===`cursor`&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cursorTransport`)}),(0,J.jsxs)(`select`,{className:`input`,value:O,onChange:e=>k(e.target.value),children:[(0,J.jsx)(`option`,{value:`http2`,children:o(`pws.cursorTransportHttp2`)}),(0,J.jsx)(`option`,{value:`http1.1`,children:o(`pws.cursorTransportHttp1`)})]}),(0,J.jsx)(`span`,{className:`pwi-settings-hint`,children:o(`pws.cursorTransportDesc`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),ge.length>0?(0,J.jsxs)(`select`,{className:`input`,value:h,onChange:e=>g(e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),ge.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}):(0,J.jsx)(`input`,{className:`input`,value:h,onChange:e=>g(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),ve?(0,J.jsx)(`input`,{className:`input`,value:Oi(e,o),readOnly:!0,disabled:!0}):(0,J.jsxs)(`select`,{className:`input`,value:v,onChange:e=>y(e.target.value),children:[(0,J.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,J.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,J.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,J.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),Z&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`codexAuth.accountModeTitle`)}),(0,J.jsxs)(`select`,{className:`input`,value:P,disabled:I||A,onChange:e=>{let t=e.target.value;if(t!==P){if(!window.confirm(o(`pws.accountModeConfirm`))){e.target.value=P;return}Te(t)}},children:[(0,J.jsx)(`option`,{value:`pool`,children:o(`codexAuth.accountModePool`)}),(0,J.jsx)(`option`,{value:`direct`,children:o(`codexAuth.accountModeDirect`)})]}),(0,J.jsx)(`span`,{className:`pwi-settings-hint`,children:o(P===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),I&&(0,J.jsx)(`span`,{className:`muted text-label`,children:o(`pws.accountSwitching`)}),R&&(0,J.jsx)(`span`,{role:R.ok?`status`:`alert`,className:R.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:R.text})]}),be&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,J.jsxs)(`select`,{className:`input`,value:b,onChange:e=>x(e.target.value),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,J.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:S,onChange:e=>C(e.target.value),rows:2})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:w,onChange:e=>T(e.target.checked)}),(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:E,disabled:!c,onChange:e=>D(e.target.checked)}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,J.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),(0,J.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,J.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h3`,{id:`pwi-pacing-title`,children:o(`pws.pacingTitle`)}),(0,J.jsx)(`p`,{children:o(`pws.pacingDesc`)})]}),(0,J.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:G,onChange:e=>K(e.target.checked)}),` `,o(`pws.pacingEnabled`)]})]}),(0,J.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:q,onChange:e=>Y(e.target.value),placeholder:`38`})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:te,onChange:e=>ne(e.target.value),placeholder:`1600`})]})]}),(0,J.jsx)(`p`,{className:`pwi-settings-hint`,children:o(`pws.pacingSlowerWins`)}),(0,J.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:ue?.queued??0}),` `,o(`pws.pacingQueued`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsxs)(`strong`,{children:[ue?.nextSlotInMs??0,` ms`]}),` `,o(`pws.pacingNextSlot`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:ue?.lastModelId??o(`pws.pacingNone`)}),` `,o(`pws.pacingLastModel`)]})]}),(0,J.jsx)(`h4`,{children:o(`pws.pacingModelOverrides`)}),(0,J.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingModel`)}),(0,J.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:ae,onChange:e=>oe(e.target.value)}),(0,J.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,J.jsx)(`option`,{value:e},e))})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:X,onChange:e=>se(e.target.value)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ce,onChange:e=>le(e.target.value)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{let e=ae.trim(),t=Zs(X),n=Qs(ce);!e||t===void 0&&n===void 0||(ie(r=>({...r,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n}}})),oe(``),se(``),le(``))},children:o(`pws.pacingAdd`)})]}),Object.entries(re).length>0&&(0,J.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(re).map(([e,t])=>(0,J.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.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,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ie(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":o(`pws.pacingRemoveModel`,{model:e}),children:o(`pws.pacingRemove`)})]},e))})]}),he&&(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,J.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ee,disabled:A,children:o(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Ce(),disabled:A||I,children:o(A?`pws.saving`:`pws.saveSettings`)})]})]}),M&&(0,J.jsx)(`div`,{role:M.ok?`status`:`alert`,className:M.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:M.text})]})}function tc({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=Q();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,J.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function nc({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=Q();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,J.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function rc({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=Q(),[M,N]=(0,_.useState)(`overview`),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[R,z]=(0,_.useState)(!1),B=(0,_.useRef)(null),[V,H]=(0,_.useState)(0),U=(0,_.useCallback)(e=>{B.current=e},[]),W=e.disabled===!0,ee=(0,_.useMemo)(()=>ii(e),[e]),G=(0,_.useMemo)(()=>di(e),[e]),K=(0,_.useMemo)(()=>ya(e),[e]),q=v===e.name?g:0,Y=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??``]),te=(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!==V&&!(q&&!K)&&(H(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)%te.length;else if(e.key===`ArrowLeft`)n=(t-1+te.length)%te.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=te.length-1;else return;e.preventDefault(),ne(te[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ne,te]),ae=`pws-tab-${M}`,oe=`pws-panel-${M}`;return(0,J.jsxs)(`div`,{className:`pws-detail`,children:[(0,J.jsx)(`div`,{className:`pws-detail-head`,children:(0,J.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:re,children:[(0,J.jsx)(Se,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),j(`pws.allProviders`)]})}),(0,J.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,J.jsx)(Ai,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,J.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,J.jsxs)(`h2`,{className:`pws-detail-title`,children:[Dn(e.name,j),G&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:j(`modal.badge.local`)}),!G&&ee&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:j(`modal.badge.free`)})]})}),(0,J.jsxs)(`div`,{className:`pws-detail-actions`,children:[!D&&!W&&A&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(e.name),children:j(`prov.setDefault`)}),O&&(0,J.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,J.jsx)(he,{style:{width:15,height:15},"aria-hidden":`true`})}),k&&(0,J.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,J.jsx)(`span`,{className:`pws-detail-toggle-label`,children:j(`pws.enabledLabel`)}),(0,J.jsx)(Tt,{on:!W,onClick:()=>k(e.name,!W),disabled:D,label:j(`pws.enabledLabel`)})]})]})]}),(0,J.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:te.map((e,t)=>(0,J.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,J.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:oe,"aria-labelledby":ae,tabIndex:0,children:[M===`overview`&&(0,J.jsx)(xa,{item:e,apiBase:f,connectionIdentity:Y,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,J.jsx)(Ta,{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,J.jsx)(Ea,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),M===`accounts`&&(0,J.jsx)(Ms,{item:e,apiBase:f,oauth:p,accounts:m,keys:b,accountLoadState:h,switchingAccountId:y,busy:x===e.name,loginHint:S,authHandlers:C,onUpdateProvider:E,onCodexActiveNeedsReauthChange:w,codexController:T}),M===`settings`&&(0,J.jsx)(ec,{item:e,apiBase:f,availableModels:i,onUpdateProvider:E,onDirtyChange:F,onRegisterSave:U},e.name)]}),I&&(0,J.jsx)(nc,{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){z(!0);try{if(!(await B.current?.()??!1))return;let e=I;L(null),F(!1),e===`deselect`?d():e&&N(e)}finally{z(!1)}}})()}})]})}var ic=new Set([`anthropic`,`google-antigravity`]),ac=new Set([`github-copilot`,`cursor`]);function oc(e){let t=e.trim().toLowerCase();return ic.has(t)?`high`:ac.has(t)?`elevated`:null}function sc(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function cc(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function lc(e,t=!1){let n={};for(let[t,r]of Object.entries(e))Ma(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function uc(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)}&quota=1`);if(!r.ok)return;let o=await r.json();if(!i.current||T.current[e]!==n)return;d(t=>({...t,[e]:{activeAccountId:o.activeAccountId??a.activeAccountId??null,accounts:o.accounts??a.accounts??[]}}))}catch{}})(),!0)}catch{return!i.current||T.current[e]!==n||(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=ba(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=ba(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)(()=>lc(u,l),[u,l])}}function dc(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 fc={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},pc=e=>fc[e]??e;function mc({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:pc(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,...Za(),..._||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:pc(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 Ft(a)??null:null;if(!o)continue;if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:pc(d)}):t(`prov.loginError`,{provider:pc(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:pc(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),y=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:pc(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:pc(d)}),!1):l(t(`prov.loginOk`,{provider:pc(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:pc(d)}),!1),s(null))}catch{g.current.get(d)===b&&l(t(`prov.loginRequestFail`,{provider:pc(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:pc(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:pc(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:pc(n)}),!1)}}}}async function hc(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function gc(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 _c({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(gc(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 hc(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 hc(i,t(`prov.updateFail`))};let a=await i.json().catch(()=>({}));if(await s(),Object.hasOwn(r,`codexAccountMode`)){let e=[l(!0)];u&&e.push(Promise.resolve(u())),await Promise.all(e)}let o=a.xaiResponsesOptInState;return{ok:!0,...o===!0||o===!1||o===`mixed`?{xaiResponsesOptInState:o}:{}}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,l,u,t]);return{removeProvider:d,confirmRemoveProvider:f,setProviderDisabled:p,setDefaultProvider:(0,_.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(gc(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 vc({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await Pt(await fetch(`${e}/api/config`));n(t??null),s&&t&&gr(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await Pt(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 Ft(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function yc({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=Q(),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=oc(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`:cc(p),v=h===`anthropic`||h===`google-antigravity`;return(0,J.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,J.jsx)(`h3`,{id:a,children:i(sc(p),{provider:t})}),(0,J.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,J.jsx)(_e,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,J.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,J.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,J.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!l||d,onClick:()=>{!l||c.current||(c.current=!0,f(!0),r())},children:i(`oauthTos.continue`)})]})]})]})}function bc(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function xc(e){return ai(e.id,bc(e))}function Sc(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[xc(n)].push(n);return t}function Cc(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}function wc(e,t,n){return!n||e.kind!==`oauth`||t!==e.id?!1:n.provider===e.id}var Tc={},Ec=[],Dc={};function Oc({presets:e,usageRank:t=Tc,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=Ec,accountStatus:s=Dc,busyProvider:c=null,loginHint:l=null,paste:u,onLogin:d,onCancelLogin:f,onLogout:p,onManage:m}){let h=Q(),[g,v]=(0,_.useState)(r),[y,b]=(0,_.useState)(``),x=(0,_.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),S=(0,_.useMemo)(()=>{let e=Object.keys(t).length>0;return x.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)})},[x,t]),C=(0,_.useMemo)(()=>Sc(S),[S])[g],w=(0,_.useMemo)(()=>Cc(C,y),[C,y]),T=e=>{let t=e.codexAccountMode===`direct`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:h(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:h(`modal.badge.pool`)}):e.auth===`oauth`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:h(`modal.badge.oauth`)}):e.auth===`forward`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:h(`modal.badge.codexLogin`)}):e.auth===`local`?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:h(`modal.badge.local`)}):e.keyOptional?null:(0,J.jsx)(`span`,{className:`badge badge-muted`,children:h(`modal.badge.apiKey`)}),n=(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:h(`modal.badge.free`)}):null;return(0,J.jsxs)(J.Fragment,{children:[n,t]})};return(0,J.jsxs)(`div`,{className:`provider-catalog`,children:[(0,J.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":g===e,className:`provider-catalog-tab${g===e?` active`:``}`,onClick:()=>{v(e),b(``)},children:h(e===`accounts`?`modal.tab.accounts`:e===`free`?`modal.tab.free`:`modal.tab.paid`)},e))}),g===`accounts`&&(0,J.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:h(`modal.accountsHint`)}),(0,J.jsx)(`input`,{className:`input provider-catalog-search`,value:y,onChange:e=>b(e.target.value),placeholder:h(`modal.search`)}),(0,J.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&w.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:h(`modal.catalogLoading`)}),g!==`accounts`&&w.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsxs)(`div`,{className:`sub`,children:[(0,J.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:T(e)})]},e.id)),g!==`accounts`&&!n&&w.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:h(`modal.noMatch`)}),g===`accounts`&&o.map(e=>{let t=s[e.id],n=c===e.id,r=!!t?.loggedIn,i=r?t?.email??e.statusLabel??h(`modal.accountLoggedIn`):t?.error??e.statusLabel??h(`modal.accountLoggedOut`),a=wc(e,c,l);return(0,J.jsxs)(`div`,{className:`list-row provider-catalog-account-row${a?` provider-catalog-account-row--waiting`:``}`,children:[(0,J.jsxs)(`div`,{className:`provider-catalog-account-row-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsx)(`div`,{className:`sub`,children:i})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,J.jsxs)(J.Fragment,{children:[r&&(0,J.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-set`,children:h(`modal.accountManage`)}),d&&(0,J.jsx)(`button`,{type:`button`,className:r?`btn btn-ghost`:`btn btn-primary`,disabled:n,onClick:()=>{n||d(e.id)},children:h(n?`codexAuth.enablingOpenai`:r?`modal.accountAdd`:`modal.accountLogin`)})]}):r?(0,J.jsxs)(J.Fragment,{children:[m&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>m(e.id),children:h(`modal.accountManage`)}),d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:n,onClick:()=>{n||d(e.id,!0)},children:h(n?`prov.waitingBrowser`:`modal.accountAdd`)}),n&&f&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>f(e.id),children:h(`common.cancel`)}),p&&!n&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>p(e.id),children:h(`modal.accountLogout`)})]}):n?f&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>f(e.id),children:h(`common.cancel`)}):d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>d(e.id),children:h(`modal.accountLogin`)})})]}),a&&l&&(0,J.jsx)(qa,{hint:{url:l.url,deviceCode:l.deviceCode,instructions:l.instructions},...u?{paste:{value:u.value,busy:u.busy,message:u.message,ok:u.ok,onChange:u.onChange,onSubmit:()=>u.onSubmit(e.id)}}:{}})]},e.id)}),g===`accounts`&&o.length===0&&!n&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:h(`modal.noMatch`)})]}),(0,J.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,J.jsx)(`div`,{style:{flex:1}}),g!==`accounts`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:h(`modal.notListed`)})]})]})}function kc({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,oauthDeviceCode:o,oauthInstructions:s,manualCode:c,manualCodeBusy:l,manualCodeMsg:u,manualCodeOk:d,onRequestLogin:f,onUseApiKeyInstead:p,onManualCodeChange:m,onSubmitManualCode:h,onBack:g}){let _=Q();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,J.jsx)(`div`,{className:`muted text-control`,children:e.note??_(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>f(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,J.jsx)(De,{}),n?_(`modal.waitingBrowser`):_(`modal.logInWith`,{label:e.label})]}),!n&&(0,J.jsx)(bs,{})]}):(0,J.jsx)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:_(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,J.jsx)(qa,{hint:{url:a,deviceCode:o,instructions:s},paste:{value:c,busy:l,disabled:!e.oauthProvider,message:u,ok:d,onChange:m,onSubmit:()=>{e.oauthProvider&&h(e.oauthProvider)}}}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:_(`modal.useApiKeyInstead`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:g,children:_(`modal.back`)})]})]})}function Ac({label:e,children:t}){return(0,J.jsxs)(`label`,{style:{display:`block`},children:[(0,J.jsx)(`span`,{className:`field-label`,children:e}),t]})}function jc({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=Q();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,J.jsxs)(`details`,{className:`setup-guide`,children:[(0,J.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,J.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,J.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,J.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,J.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,J.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,J.jsx)(Ac,{label:h(`modal.providerName`),children:(0,J.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Ac,{label:h(`modal.adapter`),children:(0,J.jsx)(`select`,{className:`input`,value:t.adapter,onChange:e=>u({...t,adapter:e.target.value}),children:[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`].map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Ac,{label:h(`modal.endpoint`),children:(0,J.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:Ns(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,J.jsx)(`option`,{value:e.id,children:e.id===`token-plan`?h(`modal.endpoint.tokenPlan`):e.id===`payg`?h(`modal.endpoint.payAsYouGo`):e.id===`custom`?h(`modal.endpoint.custom`):e.label},e.id))})}),n===`custom`&&(0,J.jsx)(Ac,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,J.jsx)(Ac,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,J.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,J.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,J.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:l(e)}):t.authMode===`local`?(0,J.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:h(`modal.localHint`)}):e.keyOptional?(0,J.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,J.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,J.jsxs)(J.Fragment,{children:[e.dashboardUrl&&(0,J.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,J.jsx)(Ee,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,J.jsx)(Te,{style:{width:13,height:13}})]}),(0,J.jsx)(Ac,{label:h(`modal.apiKey`),children:(0,J.jsx)(`input`,{className:`input`,type:`password`,value:t.apiKey,onChange:e=>u({...t,apiKey:e.target.value}),placeholder:h(`modal.apiKeyPlaceholder`)})}),t.adapter===`anthropic`&&t.authMode===`key`&&(0,J.jsx)(Ac,{label:h(`modal.apiKeyTransport`),children:(0,J.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,J.jsx)(Ac,{label:h(`modal.defaultModel`),children:(0,J.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,J.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Mc=2e3;function Nc({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,...Za()})});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();l(o.url??``,i,o.deviceCode,o.instructions),o.url||o.deviceCode?s(t(`modal.waitingLogin`)):s(o.instructions||t(`modal.loggingIn`));for(let a=0;a<100;a++){if(await new Promise(e=>setTimeout(e,Mc)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await Ft(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 Pc(e,t){return{preset:e?{id:`custom`,label:t,adapter:`openai-chat`,baseUrl:``,auth:`key`}:null,form:e?{name:``,adapter:`openai-chat`,baseUrl:``,authMode:`key`,apiKey:``,apiKeyTransport:void 0,defaultModel:``,allowPrivateNetwork:!1}:null,saving:!1,error:``,oauthBusy:!1,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,manualCode:``,manualCodeBusy:!1,manualCodeMsg:``,manualCodeOk:!0,endpointChoice:`custom`,oauthTosPending:null}}function Fc(e,t){switch(t.type){case`choose-preset`:return{...e,preset:t.preset,form:t.form,endpointChoice:t.endpointChoice,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`back`:return{...e,preset:null,form:null,endpointChoice:`custom`,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`set-form`:return{...e,form:t.form};case`set-endpoint-choice`:return{...e,endpointChoice:t.choice};case`set-saving`:return{...e,saving:t.saving};case`set-error`:return{...e,error:t.error};case`set-oauth-busy`:return{...e,oauthBusy:t.busy};case`set-oauth-msg`:return{...e,oauthMsg:t.msg,oauthMsgTone:t.tone??e.oauthMsgTone};case`set-oauth-tone`:return{...e,oauthMsgTone:t.tone};case`set-oauth-url`:return e.preset?.oauthProvider===t.providerId?{...e,oauthUrl:t.url,oauthDeviceCode:t.deviceCode??``,oauthInstructions:t.instructions??``,oauthUrlProvider:t.providerId}:e;case`set-manual-code`:return{...e,manualCode:t.code};case`set-manual-code-busy`:return{...e,manualCodeBusy:t.busy};case`set-manual-code-msg`:return{...e,manualCodeMsg:t.msg,manualCodeOk:t.ok??e.manualCodeOk};case`set-oauth-tos-pending`:return{...e,oauthTosPending:t.providerId};case`use-oauth-login`:return{...e,form:t.form,error:``,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null};case`use-api-key-instead`:return{...e,form:t.form,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``};default:return e}}function Ic({apiBase:e,existingNames:t,onClose:n,onAdded:r,initialTier:i,initialCustom:a=!1,accountRows:o,accountStatus:s,accountBusy:c,accountLoginHint:l=null,onAccountLogin:u,onAccountCancelLogin:d,onAccountLogout:f,onAccountManage:p,onOpen:m}){let h=Q(),g=(0,_.useMemo)(()=>[{id:`custom`,label:h(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[h]),[v,y]=(0,_.useReducer)(Fc,a,e=>Pc(e,h(`modal.customProvider`))),b=(0,_.useRef)(!0),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=G(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),w=G(`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}),T=G(Ir(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()},{deadlineMs:6e4}),E=C.data??[],D=w.data??g,O=w.loading,k=Object.fromEntries((T.data?.providers??[]).map(e=>[e.provider,e.requests])),{preset:A,form:j,saving:M,error:N,oauthBusy:P,oauthMsg:F,oauthMsgTone:I,oauthUrl:L,oauthUrlProvider:R,oauthDeviceCode:z,oauthInstructions:B,manualCode:V,manualCodeBusy:H,manualCodeMsg:U,manualCodeOk:W,endpointChoice:ee,oauthTosPending:K}=v;(0,_.useEffect)(()=>{b.current=!0,x.current=document.activeElement,m?.();let e=S.current;if(e){let t=e.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);t&&t.focus()}return()=>{b.current=!1,x.current?.focus()}},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!K&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,K]);let q=e=>{let t=Vs(e);return t?h(t):e.note},Y=e=>{let t=Ps(e.baseUrlChoices,e.baseUrl);y({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?Ns(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},te=async()=>{if(!j)return;let t=A?Bs(A):!1,n=A?.baseUrlChoices?.length?Fs(A.baseUrlChoices,ee,j.baseUrl):j.baseUrl.trim();if(!t&&!j.name.trim()){y({type:`set-error`,error:h(`modal.nameRequired`)});return}if(!t&&!n){y({type:`set-error`,error:h(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){y({type:`set-error`,error:h(`modal.baseUrlPlaceholderError`)});return}let i={...j,baseUrl:n},a;try{a=Us(A??{id:`custom`},i)}catch{y({type:`set-error`,error:h(`modal.invalidPreset`)});return}y({type:`set-saving`,saving:!0}),y({type:`set-error`,error:``});try{let t=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(!t.ok){let e=await t.json().catch(()=>({}));y({type:`set-error`,error:e.error||h(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{y({type:`set-error`,error:h(`modal.networkError`)})}finally{y({type:`set-saving`,saving:!1})}},{loginOAuth:ne,submitManualCode:re}=Nc({apiBase:e,t:h,aliveRef:b,onAdded:r}),ie={setOauthBusy:e=>y({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>y({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>y({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t,n,r)=>y({type:`set-oauth-url`,url:e,providerId:t,deviceCode:n,instructions:r}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:U,ok:e})},ae=j?t.includes(j.name.trim())&&j.name.trim()!==``:!1,oe=e=>{if(!P){if(oc(e)){y({type:`set-oauth-tos-pending`,providerId:e});return}ne(e,ie)}},X=e=>{re(e,V,H,{setManualCodeBusy:e=>y({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:U,ok:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e})})},se=A?.id===`custom`,ce=j?.authMode===`local`,le=A?Bs(A):!1;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":h(`modal.add`),className:`modal-overlay`,children:(0,J.jsxs)(`div`,{ref:S,className:`modal-card`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:A?h(`modal.addNamed`,{label:A.label}):h(`modal.add`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":h(`common.close`),onClick:n,children:(0,J.jsx)(ue,{})})]}),A?j&&(A.auth===`oauth`&&j.authMode===`oauth`?(0,J.jsx)(kc,{preset:A,oauthSupported:E,oauthBusy:P,oauthMsg:F,oauthMsgTone:I,oauthUrl:R===A.oauthProvider?L:``,oauthDeviceCode:R===A.oauthProvider?z:``,oauthInstructions:R===A.oauthProvider?B:``,manualCode:V,manualCodeBusy:H,manualCodeMsg:U,manualCodeOk:W,onRequestLogin:oe,onUseApiKeyInstead:()=>{y({type:`use-api-key-instead`,form:{...j,authMode:`key`}})},onManualCodeChange:e=>y({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{X(e)},onBack:()=>y({type:`back`})}):(0,J.jsx)(jc,{preset:A,form:j,endpointChoice:ee,error:N,saving:M,dup:ae,isCustom:se,isLocal:ce,isReservedForward:le,presetDescription:q,onFormChange:e=>y({type:`set-form`,form:e}),onEndpointChoiceChange:e=>y({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{te()},onUseOauthLogin:()=>y({type:`use-oauth-login`,form:{...j,authMode:`oauth`}}),onBack:()=>y({type:`back`})})):(0,J.jsx)(Oc,{presets:D,usageRank:k,presetsLoading:O,initialTier:i,onSelectPreset:e=>Y(e),onSelectCustom:()=>Y(g[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:u,onCancelLogin:d,onLogout:f,onManage:p,loginHint:l,paste:{value:V,busy:H,message:U,ok:W,onChange:e=>y({type:`set-manual-code`,code:e}),onSubmit:e=>{X(e)}}})]})}),K&&(0,J.jsx)(yc,{providerId:K,providerLabel:A?.label??K,onCancel:()=>y({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=K;e&&(y({type:`set-oauth-tos-pending`,providerId:null}),ne(e,ie))}},K)]})}function Lc({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,accountLoginHint:s,removeConfirmName:c,removeDefaultProvider:l,codexLoginOpen:u,jsonLeaveOpen:d,jsonSaving:f,oauthTosPending:p,onCloseAdd:m,onAdded:h,onAccountLogin:g,onAccountCancelLogin:_,onAccountLogout:v,onAccountManage:y,onOpenAdd:b,onCloseCodexLogin:x,onCodexAdded:S,onCancelRemove:C,onConfirmRemove:w,onCancelJsonLeave:T,onDiscardJson:E,onSaveJson:D,onCancelOauthTos:O,onContinueOauthTos:k}){return(0,J.jsxs)(J.Fragment,{children:[n&&(0,J.jsx)(Ic,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:m,onAdded:h,accountRows:a,accountStatus:o,accountBusy:i,accountLoginHint:s??null,onAccountLogin:g,onAccountCancelLogin:_,onAccountLogout:v,onAccountManage:y,onOpen:b}),u&&(0,J.jsx)(to,{apiBase:e,onClose:x,onAdded:S}),c&&(0,J.jsx)(tc,{providerName:c,defaultProviderName:l,onCancel:C,onConfirm:w}),d&&T&&E&&D&&(0,J.jsx)(nc,{saving:f??!1,onCancel:T,onDiscard:E,onSave:D}),p&&(0,J.jsx)(yc,{providerId:p.provider,providerLabel:pc(p.provider),onCancel:O,onContinue:k},`${p.provider}:${p.addAccount?`add`:`login`}`)]})}function Rc(e,t,n){return[...Rs(e.providers).map(e=>({id:e,label:Dn(e,n),kind:`codex`,href:`#codex-set`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:pc(e),kind:`oauth`}))]}function zc(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 Bc({apiBase:e}){let t=Q(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>fr(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),[I,L]=(0,_.useState)({token:0,provider:null}),R=(0,_.useRef)(!0),z=(0,_.useRef)(null),B=(0,_.useRef)(!1),V=(0,_.useCallback)((e,t=!0)=>{c(e),u(t),f(t?`ok`:`err`),m(e=>e+1)},[]),H=(0,_.useCallback)(()=>{c(``),u(!1),f(`err`)},[]),U=(0,_.useCallback)(e=>{if(e.catalogRefreshPending){c(t(`codexAuth.catalogRefreshPending`)),u(!1),f(`warn`),m(e=>e+1);return}V(t(`codexAuth.accountAdded`),!0)},[V,t]);(0,_.useEffect)(()=>(R.current=!0,()=>{R.current=!1}),[]),(0,_.useEffect)(()=>{if(!s||!l)return;let e=window.setTimeout(H,4500);return()=>window.clearTimeout(e)},[s,l,p,H]);let W=(0,_.useCallback)(e=>{o(!1),D(null),T(e),L(t=>({token:t.token+1,provider:e}))},[]);G(`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}),G(Ir(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()},{deadlineMs:6e4});let[ee,K]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:q,fetchOauth:Y,fetchProviderQuotas:te}=vc({apiBase:e,t,setConfig:i,setOauthProviders:g,setOauthStatus:y,notify:V,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{K(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),ne=bo(e),re=ne.activeNeedsReauth,ie=(0,_.useMemo)(()=>{let e=ne.accounts;if(e.length===0&&ne.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}:{},...re?{needsReauth:!0}:{}}}},[v,ne.accounts,ne.loadState,re]),{accountSets:ae,setAccountSets:oe,accountLoadStates:X,switchingAccount:se,keyPools:ce,fetchAccountSets:le,switchAccount:ue,switchApiKey:fe,removeApiKey:pe,addApiKeyValue:me,editCredentialAlias:he,removeAccount:ge,activeAccountNeedsReauth:_e}=uc({apiBase:e,t,config:r,oauthStatus:ie,aliveRef:R,notify:V,fetchConfig:q,fetchOauth:Y,fetchProviderQuotas:te,codexActiveNeedsReauth:re}),{draft:ve,setDraft:ye,jsonEditorOpen:be,jsonSaving:xe,jsonLeaveOpen:Z,saveConfig:Se,openJsonEditor:Ce,discardJsonEditor:we,requestCloseJsonEditor:Te,restoreJsonEditor:Ee,jsonIsDirty:De,setJsonLeaveOpen:Oe}=dc({apiBase:e,config:r,notify:V,fetchConfig:q,fetchProviderQuotas:te,onSaved:()=>N(e=>e+1),t});(0,_.useEffect)(()=>{z.current!==e&&(z.current=e,Promise.resolve().then(()=>{q(),Y()}))},[e,q,Y]);let ke=()=>N(e=>e+1),{cancelLoginOAuth:Ae,loginOAuth:je,logoutOAuth:Me}=mc({apiBase:e,t,aliveRef:R,accountSets:ae,setAccountSets:oe,setBusy:x,setStatus:c,setLoginInfo:C,setOauthStatus:y,notify:V,fetchConfig:q,fetchOauth:Y,fetchAccountSets:le,fetchProviderQuotas:te,bumpModelsRefresh:ke,onLoginSettled:W}),{removeProvider:Ne,confirmRemoveProvider:Pe,setProviderDisabled:Fe,setDefaultProvider:Ie,updateProvider:Le}=_c({apiBase:e,t,removeBusyRef:B,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:V,fetchConfig:q,fetchOauth:Y,fetchProviderQuotas:te,refreshCodexAccount:()=>ne.load(!0)}),Re=(e,t=!1)=>{if(b!==e){if(oc(e)){F({provider:e,addAccount:t});return}je(e,t)}};if(!r)return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,J.jsx)(Et,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}):(0,J.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,J.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`providers-workspace-main`,children:(0,J.jsxs)(`p`,{className:`muted`,children:[(0,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let ze=Rc(r,h,t),Be=zc(r,ie),Ve=e=>r.providers[e]?.authMode===`forward`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.providers`)}),(0,J.jsx)(`div`,{className:`row`,children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,J.jsx)(de,{}),t(`prov.add`)]})})]}),s&&(0,J.jsx)(Et,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}),(0,J.jsx)(_a,{onRemoveProvider:Ne,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),o(!0)},onEditConfig:Ce,jsonEditor:{open:be,draft:ve,isDirty:De,onDraftChange:ye,onSave:()=>Se(),onClose:Te,onRestore:Ee},jsonSaving:xe,modelsRefreshToken:M,activeAccountNeedsReauth:_e,quotaRefreshEpoch:ee.epoch,quotaForceRefresh:ee.force,detail:(t,n)=>{let i=Be[t.name]??v[t.name];return(0,J.jsx)(rc,{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:ae[t.name]?.accounts??[],keys:ce[t.name]??[],accountLoadState:X[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:I.token,accountsFocusProvider:I.provider,switchingAccountId:se?.provider===t.name?se.accountId:null,busyProvider:b,loginHint:S,authHandlers:{onLogin:Re,onCancelLogin:Ae,onLogout:Me,onReauth:(e,t)=>je(e,!0,t),onSwitchAccount:ue,onRemoveAccount:ge,onRetryAccounts:async e=>{await le([e])},onAddApiKey:me,onSwitchApiKey:fe,onRemoveApiKey:pe,onEditAlias:he},isDefault:t.name===r.defaultProvider,onRemoveProvider:Ne,onSetDisabled:Fe,onSetDefault:e=>{Ie(e)},onUpdateProvider:Le,codexController:ne},t.name)}}),(0,J.jsx)(Lc,{apiBase:e,config:r,adding:a,addIntent:E,busy:b,addModalAccountRows:ze,accountLoginStatus:Be,accountLoginHint:S,removeConfirmName:O,removeDefaultProvider:O===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Z,jsonSaving:xe,oauthTosPending:P,onCloseAdd:()=>{b&&Ae(b),o(!1),D(null)},onAdded:e=>{o(!1),D(null),V(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),q(),Y(),te(!0),ke()},onAccountLogin:async(n,i=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=r.providers.openai,i=zs(n);if(i===`invalid`){V(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){x(`openai`);try{await Ks(e,i),await q()}catch(e){e instanceof Gs?V(t(e.i18nKey),!1):V(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{R.current&&x(e=>e===`openai`?null:e)}}j(!0);return}if(Ve(n)){j(!0);return}(r.providers[n]?.authMode===`oauth`||h.includes(n))&&Re(n,i)},onAccountCancelLogin:e=>{Ae(e)},onAccountLogout:e=>{Me(e)},onAccountManage:e=>{W(e)},onOpenAdd:Y,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),U(e),q(),Y(),te(!0),ke()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{Pe(O)},onCancelJsonLeave:()=>{xe||Oe(!1)},onDiscardJson:we,onSaveJson:()=>{Se()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),je(e.provider,e.addAccount))}})]})}function Vc(e){let{t}=ct();return e.state===`stale`?(0,J.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,J.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,J.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 Hc=[`fresh`,`stale`,`not_running`,`unknown`],Uc=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function Wc(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function Gc(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&Hc.includes(t.stateBefore)&&typeof t.code==`string`&&Uc.includes(t.code)&&Wc(t.requested)&&Wc(t.stopped)&&Wc(t.surviving)&&Wc(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 Kc(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&Hc.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var qc={state:null,runningCount:0};async function Jc(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 qc;let i=await r.json().catch(()=>null);return Kc(i)?{state:i.state,runningCount:i.runningCount}:qc}catch{return qc}}var Yc=3e4;function Xc(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function Zc(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=Yc,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:Xc(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:Xc(e)?s():o()}}return Gc(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function Qc(e){return e===`stopped`||e===`nothing_running`}function $c(e,t={}){let{t:n}=ct(),[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 Zc(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&&Qc(r.code)&&o.current?.(r.code),r.code},[e,n])}}var el={"gpt-5.6-sol":Ae,"gpt-5.6-terra":Ne,"gpt-5.6-luna":je,"gpt-daybreak-blue-latest":Ae,"daybreak-blue-latest":Ae,"daybreak-red-latest":De},tl={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function nl(e){return e.slice(e.lastIndexOf(`/`)+1)}function rl(e){return el[e]??el[nl(e)]??null}function il(e){let t=rl(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:tl,"aria-hidden":!0}),e):e}function al(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 ol(e,t,n,r){let{isEmpty:i,sessionCacheKey:a,...o}=r,s=(0,_.useMemo)(()=>a?mr(a):null,[a]),c=G(e,t,(0,_.useCallback)(async e=>{let t=await n(e);return a&&hr(a,t),t},[n,a]),{...o,...a?{initialData:o.initialData??s?.data,initialDataCachedAt:o.initialDataCachedAt??s?.cachedAt??null}:{}});return{...c,state:al(c,i,r.enabled!==!1)}}function sl({className:e,style:t}){return(0,J.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function cl({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,J.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,J.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,J.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,J.jsx)(sl,{})},t))]})}function ll({children:e,busy:t=!0,live:n=!0,className:r}){return(0,J.jsxs)(`div`,{className:r?`data-surface-status ${r}`:`data-surface-status`,role:n?`status`:void 0,"aria-live":n?`polite`:void 0,"aria-atomic":n?`true`:void 0,"aria-busy":t||void 0,children:[t&&(0,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:e})]})}var ul=class extends _.Component{state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:Error(String(e))}}reload=()=>{this.setState({error:null})};render(){return this.state.error?(0,J.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,J.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,J.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,J.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},dl=`gpt-daybreak-blue-latest`,fl=Object.freeze({[dl]:`gpt-5.6-sol`});Object.freeze(Object.keys(fl));var pl=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`,dl]),ml=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],hl=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`],gl={failover:`cws.strategy.failover`,"round-robin":`cws.strategy.roundRobin`,random:`cws.strategy.random`,"least-used":`cws.strategy.leastUsed`,"reset-window":`cws.strategy.resetWindow`},_l={failover:`cws.strategy.failoverHint`,"round-robin":`cws.strategy.roundRobinHint`,random:`cws.strategy.randomHint`,"least-used":`cws.strategy.leastUsedHint`,"reset-window":`cws.strategy.resetWindowHint`},vl={failover:`cws.targets.failoverHint`,"round-robin":`cws.targets.roundRobinHint`,random:`cws.targets.randomHint`,"least-used":`cws.targets.leastUsedHint`,"reset-window":`cws.targets.resetWindowHint`},yl=new Set(hl);function bl(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...ml];let r=new Set(ml),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[...ml];let a=new Set(i);return ml.filter(e=>a.has(e))}var xl=0;function Sl(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++xl}`}}function Cl(e){return e===`disabled`?`disabled`:`auto`}var wl=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Tl=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,El=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Dl(e){return wl.test(e.trim())}function Ol(e){return`combo/${e.trim()}`}function kl(e,t){return(typeof t==`string`?t.trim():``)||Ol(e)}function Al(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!El.test(n));return{...e,alias:n?t:null,model:kl(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function jl(e){return typeof e==`string`&&e.trim()?e.trim():null}function Ml(e){return typeof e==`string`&&yl.has(e)?e:`failover`}function Nl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Pl(e){return typeof e==`string`&&ml.includes(e)?e:null}function Fl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Il(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=Fl(t.weight);a.push(Sl(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():kl(r,jl(t.alias)),alias:jl(t.alias),nativeAlias:t.nativeAlias===!0,displayName:jl(t.displayName),strategy:Ml(t.strategy),stickyLimit:Nl(t.stickyLimit),defaultEffort:Pl(t.defaultEffort),imageInput:Cl(t.imageInput),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function Ll(e){let t=[],n=[],r=[];for(let i of e)i.strategy===`failover`?t.push(i):i.strategy===`round-robin`?n.push(i):r.push(i);return{failover:t,roundRobin:n,other:r}}function Rl(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 zl(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Bl(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Vl(e,t){let n=Bl(e);return n!==null&&t-n<18e5}function Hl(e){let t=Bl(e);return t!==null&&Number.isInteger(t)&&t>=0?t:null}function Ul(e,t){let n=zl(e),r=Bl(n?.usedPercent);return!!n&&r!==null&&r>=0&&Hl(n.includedAccounts)!==null&&(Hl(n.includedAccounts)??0)>0&&Hl(n.excludedAccounts)===0&&n.incomplete===!1&&Vl(n.updatedAt,t)}function Wl(e,t){let n=zl(e);if(!n||n.kind!==`capacity-weighted-v1`||n.scope!==`routable-known`||n.presentation!==`aggregate`||n.incomplete!==!1)return!1;for(let e of[`includedAccounts`,`excludedAccounts`,`unknownPlanAccounts`,`missingQuotaAccounts`,`pausedAccounts`,`reauthAccounts`,`staleQuotaAccounts`,`partialWindowAccounts`])if(Hl(n[e])===null)return!1;if((Hl(n.includedAccounts)??0)===0)return!1;for(let e of[`excludedAccounts`,`unknownPlanAccounts`,`missingQuotaAccounts`,`pausedAccounts`,`reauthAccounts`,`staleQuotaAccounts`,`partialWindowAccounts`])if(n[e]!==0)return!1;let r=!1;for(let e of[`fiveHour`,`weekly`,`monthly`])if(Object.hasOwn(n,e)){if(!Ul(n[e],t))return!1;r=!0}if(Object.hasOwn(n,`customWindows`)){if(!Array.isArray(n.customWindows))return!1;for(let e of n.customWindows){let n=zl(e);if(!n||typeof n.label!=`string`||!n.label.trim()||!Ul(n,t))return!1;r=!0}}return r}function Gl(e,t){if(!Vl(e.updatedAt,t))return`unknown`;let n=zl(e.quota);if(!n||!Vl(n.updatedAt,t)||e.aggregation!==void 0&&!Wl(e.aggregation,t))return`unknown`;let r=!1,i=!1;for(let e of[`fiveHourPercent`,`weeklyPercent`,`monthlyPercent`]){if(!Object.hasOwn(n,e))continue;let t=Bl(n[e]);if(t===null||t<0)return`unknown`;r=!0,t>=100&&(i=!0)}for(let e of[`fiveHourResetAt`,`weeklyResetAt`,`monthlyResetAt`])if(Object.hasOwn(n,e)&&Bl(n[e])===null)return`unknown`;if(Object.hasOwn(n,`customWindows`)){if(!Array.isArray(n.customWindows))return`unknown`;for(let e of n.customWindows){let t=zl(e),n=Bl(t?.percent);if(!t||typeof t.label!=`string`||!t.label.trim()||n===null||n<0||Object.hasOwn(t,`resetAt`)&&Bl(t.resetAt)===null)return`unknown`;r=!0,n>=100&&(i=!0)}}if(Object.hasOwn(n,`creditsUsd`)){let e=zl(n.creditsUsd);if(!e)return`unknown`;let t=Bl(e.used),a=Bl(e.limit),o=Bl(e.remaining),s=Bl(e.percent);if(t===null||t<0||a===null||a<0||o===null||s===null||s<0||e.unlimited!==void 0&&typeof e.unlimited!=`boolean`||Object.hasOwn(e,`expiresAt`)&&Bl(e.expiresAt)===null)return`unknown`;r=!0,e.unlimited!==!0&&o<=0&&(i=!0)}return r?i?`exhausted`:`available`:`unknown`}function Kl(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=zl(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=Gl(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function ql(e,t,n){let r=e.flatMap(e=>{let t=e.provider.trim();return!t||!e.model.trim()||!Object.hasOwn(n,t)||n[t]?.disabled===!0?[]:[t]});if(r.length===0)return`unknown`;let i=!1;for(let e of r){let n=t[e]??`unknown`;if(n===`available`)return`available`;n===`unknown`&&(i=!0)}return i?`unknown`:`exhausted`}function Jl(e,t={}){let n=[],r=t.cataloguedComboIds;for(let i of e)i.targets.length===0?n.push({id:i.id,model:i.model,reason:`empty-targets`}):i.targets.length<2&&n.push({id:i.id,model:i.model,reason:`few-targets`}),r&&i.targets.length>0&&!r.has(i.id)&&n.push({id:i.id,model:i.model,reason:`catalog-omitted`}),t.providerQuotaStates&&t.providers&&ql(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function Yl(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 Xl(e,t={}){let n=e.strategy===`round-robin`||e.strategy===`random`;return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},combo:{targets:e.targets.map(e=>n?{provider:e.provider.trim(),model:e.model.trim(),weight:e.weight??1}:{provider:e.provider.trim(),model:e.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 Zl(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Dl(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(!Tl.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&El.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&&!pl.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`&&(!Number.isInteger(e.stickyLimit)||e.stickyLimit<1||e.stickyLimit>100))return`invalidStickyLimit`;if(e.strategy===`round-robin`||e.strategy===`random`)for(let t of e.targets){let e=t.weight??1;if(!Number.isInteger(e)||e<1||e>1e4)return`invalidWeight`}return e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function Ql(e=``){return{id:e,model:e?Ol(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,targets:[Sl()]}}function $l(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 eu(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function tu(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function nu(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 ru(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||nu(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 iu({value:e,onChange:t,disabled:n}){let r=Q();return(0,J.jsxs)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:[[[`failover`,`cws.strategy.failover`],[`round-robin`,`cws.strategy.roundRobin`]].map(([i,a])=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===i,className:`btn btn-sm${e===i?` btn-primary`:` btn-ghost`}`,disabled:n,onClick:()=>t(i),children:r(a)},i)),e!==`failover`&&e!==`round-robin`?(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:r(gl[e])}):null]})}function au({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=Q(),o=i??ml,s=t!==null&&!o.includes(t);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`select`,{id:e,className:`input`,value:t??``,disabled:r,"aria-label":a(`cws.field.defaultEffort`),onChange:e=>n(e.target.value===``?null:e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,J.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),s?(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function ou({targets:e,models:t,imageInput:n,disabled:r,onChange:i}){let a=Q(),o=$l(e,t),s=o&&n!==`disabled`;return(0,J.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":a(`cws.capabilities`),children:[(0,J.jsx)(`span`,{className:`field-label`,children:a(`cws.capabilities`)}),(0,J.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`cwi-capability-label`,children:a(`cws.capability.imageInput`)}),(0,J.jsx)(`p`,{className:`muted cwi-capability-hint`,children:a(o?`cws.capability.imageInputHint`:`cws.capability.imageInputUnavailable`)})]}),(0,J.jsx)(Tt,{on:s,onClick:()=>{o&&i({imageInput:n===`auto`?`disabled`:`auto`})},disabled:r||!o,label:a(`cws.capability.imageInput`)})]})]})}function su({targets:e,strategy:t,providers:n,models:r,providerQuotaStates:i,onChange:a}){let o=Q(),s=eu(n),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),f=(t,n)=>{a(e.map((e,r)=>r===t?{...e,...n}:e))},p=(t,n)=>{if(t===n||t<0||n<0||t>=e.length||n>=e.length)return;let r=[...e],[i]=r.splice(t,1);r.splice(n,0,i),a(r)};return(0,J.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((m,h)=>{let g=n.find(e=>e.name===m.provider),_=g&&!s.some(e=>e.name===m.provider)?[...s,g]:s,v=ru(r,m.provider,n),y=m.model&&!v.includes(m.model)?[m.model,...v]:v,b=!m.provider,x=c===h,S=u===h&&c!==null&&c!==h,C=i[m.provider.trim()]??`unknown`;return(0,J.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`?`cwi-target-row--failover`:``,x?`cwi-target-row--dragging`:``,S?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{c!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,u!==h&&d(h))},onDrop:e=>{e.preventDefault(),c!==null&&p(c,h),l(null),d(null)},onDragEnd:()=>{l(null),d(null)},children:[(0,J.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":o(`cws.target.drag`),title:o(`cws.target.drag`),onDragStart:e=>{l(h),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(h))},children:(0,J.jsx)(Fe,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:h===0,"aria-label":o(`cws.target.moveUp`),onClick:()=>p(h,h-1),children:(0,J.jsx)(be,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:h===e.length-1,"aria-label":o(`cws.target.moveDown`),onClick:()=>p(h,h+1),children:(0,J.jsx)(xe,{width:14,height:14,"aria-hidden":`true`})})]}),(0,J.jsxs)(`select`,{className:`input`,value:m.provider,"aria-label":o(`cws.target.provider`),onChange:e=>{let t=e.target.value,i=ru(r,t,n)[0]??``;f(h,{provider:t,model:i})},children:[(0,J.jsx)(`option`,{value:``,children:o(`cws.target.pickProvider`)}),_.map(e=>(0,J.jsx)(`option`,{value:e.name,children:e.disabled?o(`cws.target.disabled`,{name:Dn(e.name,o)}):Dn(e.name,o)},e.name))]}),(0,J.jsxs)(`select`,{className:`input`,value:m.model,disabled:b,"aria-label":o(`cws.target.model`),onChange:e=>f(h,{model:e.target.value}),children:[(0,J.jsx)(`option`,{value:``,children:b?o(`cws.target.pickProviderFirst`):y.length===0?o(`cws.target.noModels`):o(`cws.target.pickModel`)}),y.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),(t===`round-robin`||t===`random`)&&(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:m.weight??1,"aria-label":o(`cws.target.weight`),onChange:e=>{let t=tu(e.target.value,1,1e4);t!==void 0&&f(h,{weight:t})}}),(0,J.jsx)(`span`,{className:`cwi-quota-badge cwi-quota-badge--${C}`,"aria-label":o(`cws.quota.${C}`),children:o(`cws.quota.${C}`)}),(0,J.jsx)(`div`,{className:`cwi-target-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>a(e.filter((e,t)=>t!==h)),"aria-label":o(`common.remove`),children:(0,J.jsx)(he,{width:14,height:14})})})]},m.clientKey??`${m.provider}:${m.model}`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>a([...e,Sl()]),children:[(0,J.jsx)(de,{width:14,height:14}),` `,o(`cws.target.add`)]})]})}function cu({existingIds:e,existingAliases:t,providerMap:n,providerQuotaStates:r,providers:i,models:a,onClose:o,onSubmit:s}){let c=Q(),l=(0,_.useRef)(null),[u,d]=(0,_.useState)(()=>Ql()),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),g=(0,_.useMemo)(()=>{let e=new Map;for(let t of a)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[a]),v=(0,_.useMemo)(()=>bl(u.targets,g),[u.targets,g]),y=ql(u.targets,r,n)===`exhausted`;(0,_.useEffect)(()=>{let e=l.current;e&&!e.open&&e.showModal()},[]);let b=(0,_.useCallback)(()=>{f||o()},[f,o]),x=(0,_.useCallback)(e=>{e.preventDefault(),b()},[b]),S=async()=>{let r=Zl(u,{existingIds:e,existingAliases:t,isCreate:!0,providers:n});if(r){h(c(`cws.err.${r}`));return}p(!0),h(``);let i=u.id.trim(),a=u.alias?.trim()||null;try{let e=await s({...u,id:i,alias:a,model:kl(i,a)});if(!e.ok){h(e.error||c(`cws.saveFailed`));return}}finally{p(!1)}};return(0,J.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:x,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":c(`common.close`),tabIndex:-1,onClick:b}),(0,J.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,J.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:c(`cws.addTitle`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:b,disabled:f,"aria-label":c(`common.close`),children:(0,J.jsx)(ue,{width:16,height:16})})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:c(`cws.addSubtitle`)}),m&&(0,J.jsx)($,{tone:`err`,children:m}),y&&(0,J.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:c(`cws.quota.allExhausted`)}),(0,J.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-id`,children:c(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:u.id,disabled:f,onChange:e=>d(t=>({...t,id:e.target.value,model:kl(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.idInternalHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:c(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:u.alias??``,placeholder:c(`cws.field.aliasPlaceholder`),disabled:f,onChange:e=>d(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:kl(t.id,e.target.value)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.aliasHint`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.idHint`,{model:u.id.trim()?kl(u.id,u.alias):`…`})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:c(`cws.strategy`)}),(0,J.jsx)(iu,{value:u.strategy,disabled:f,onChange:e=>d(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(_l[u.strategy])})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:c(`cws.field.defaultEffort`)}),(0,J.jsx)(au,{id:`cwi-new-effort`,value:u.defaultEffort,disabled:f,allowedEfforts:v,onChange:e=>d(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.defaultEffortHint`)})]}),u.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:c(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:u.stickyLimit,disabled:f,onChange:e=>{let t=tu(e.target.value,1,100);t!==void 0&&d(e=>({...e,stickyLimit:t}))}}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.stickyLimitHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:c(`cws.targets`)}),(0,J.jsx)(su,{targets:u.targets,strategy:u.strategy,providers:i,models:a,providerQuotaStates:r,onChange:e=>d(t=>({...t,targets:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(vl[u.strategy])})]}),(0,J.jsx)(ou,{targets:u.targets,models:a,imageInput:u.imageInput??`auto`,disabled:f,onChange:e=>d(t=>({...t,...e}))})]}),(0,J.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:b,disabled:f,children:c(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{S()},disabled:f||y,children:c(f?`common.saving`:`cws.create`)})]})]})]})}var lu=[`config`,`about`],uu=e=>`cws-detail-tab-${e}`,du=e=>`cws-detail-panel-${e}`;function fu({baseline:e,isCreate:t=!1,otherIds:n,otherAliases:r,providerMap:i,providerQuotaStates:a,providers:o,models:s,onBack:c,onSaved:l,onRequestRemove:u,onSave:d,onDirtyChange:f}){let p=Q(),[m,h]=(0,_.useState)(`config`),g=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%lu.length;else if(e.key===`ArrowLeft`)n=(t-1+lu.length)%lu.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=lu.length-1;else return;e.preventDefault(),h(lu[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[]),[v,y]=(0,_.useState)(e),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(!1),E=!Yl(v,e),D=ql(v.targets,a,i)===`exhausted`,O=`${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(`,`)}`,k=(0,_.useMemo)(()=>{let e=new Map;for(let t of s)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[s]),A=(0,_.useMemo)(()=>bl(v.targets,k),[v.targets,k]),j=(0,_.useCallback)(t=>{let n=t(v);y(n),f(!Yl(n,e))},[v,e,f]);(0,_.useEffect)(()=>{let t=window.setTimeout(()=>{y(e),C(null),h(`config`),f(!1)},0);return()=>window.clearTimeout(t)},[O]);let M=async()=>{try{await navigator.clipboard.writeText(e.model),T(!0),window.setTimeout(()=>T(!1),1200)}catch{}},N=async()=>{let a=Zl(v,{existingIds:n,existingAliases:r,isCreate:t,providers:i});if(a){C({ok:!1,text:p(`cws.err.${a}`)});return}x(!0);let o=v.id.trim(),s=v.alias?.trim()||null,c=v.displayName?.trim()||null,u={...v,id:o,alias:s,displayName:c,model:kl(o,s)},f=!t&&o!==e.id?e.id:void 0;try{let e=await d(u,t,f);if(!e.ok){C({ok:!1,text:e.error||p(`cws.saveFailed`)});return}C({ok:!0,text:t?p(`cws.created`,{model:u.model}):p(`cws.saved`)}),l(u)}finally{x(!1)}},P=t?v.id.trim()?kl(v.id,v.alias):p(`cws.addTitle`):e.model;return(0,J.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[c&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:c,"aria-label":p(`cws.backToAll`),children:[(0,J.jsx)(Se,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),p(`cws.allCombos`)]}),(0,J.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:P}),!t&&(0,J.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{M()},title:p(`cws.copyModel`),children:p(w?`cws.copied`:`cws.copyModel`)}),(0,J.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&u&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:u,children:[(0,J.jsx)(he,{width:14,height:14}),` `,p(`common.remove`)]}),(0,J.jsx)(`button`,{id:t?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!t&&!E||b||D,onClick:()=>{N()},children:p(b?`common.saving`:t?`cws.create`:`common.save`)})]})]}),S&&(0,J.jsx)($,{tone:S.ok?`ok`:`err`,children:S.text}),D&&(0,J.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:p(`cws.quota.allExhausted`)}),(0,J.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":p(`cws.tabsLabel`),children:lu.map((e,t)=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:uu(e),"aria-selected":m===e,"aria-controls":du(e),tabIndex:m===e?0:-1,className:`btn btn-sm ${m===e?`btn-primary`:`btn-ghost`}`,onClick:()=>h(e),onKeyDown:e=>g(e,t),children:p(e===`config`?`cws.tab.config`:`cws.tab.about`)},e))}),(0,J.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:du(`config`),"aria-labelledby":uu(`config`),hidden:m!==`config`,children:(0,J.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:p(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:v.id,disabled:b,onChange:e=>j(t=>({...t,id:e.target.value,model:kl(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:t?p(`cws.field.idInternalHint`):p(`cws.field.idHintEdit`,{model:kl(v.id,v.alias)})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:p(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:v.alias??``,placeholder:Ol(v.id.trim()||`…`),disabled:b,onChange:e=>j(t=>Al(t,e.target.value))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.aliasHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,J.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:v.nativeAlias,disabled:b,onChange:e=>j(t=>({...t,nativeAlias:e.target.checked}))}),` `,p(`cws.field.nativeAlias`)]}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.nativeAliasHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:p(`cws.field.displayName`)}),(0,J.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:v.displayName??``,maxLength:128,disabled:b,onChange:e=>j(t=>({...t,displayName:e.target.value||null}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.displayNameHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`cws.strategy`)}),(0,J.jsx)(iu,{value:v.strategy,disabled:b,onChange:e=>j(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(_l[v.strategy])})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-effort`,children:p(`cws.field.defaultEffort`)}),(0,J.jsx)(au,{id:`cwi-effort`,value:v.defaultEffort,disabled:b,allowedEfforts:A,onChange:e=>j(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.defaultEffortHint`)})]}),v.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-sticky`,children:p(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:v.stickyLimit,disabled:b,onChange:e=>{let t=tu(e.target.value,1,100);t!==void 0&&j(e=>({...e,stickyLimit:t}))}})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`cws.targets`)}),(0,J.jsx)(su,{targets:v.targets,strategy:v.strategy,providers:o,models:s,providerQuotaStates:a,onChange:e=>j(t=>({...t,targets:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(vl[v.strategy])})]}),(0,J.jsx)(ou,{targets:v.targets,models:s,imageInput:v.imageInput??`auto`,disabled:b,onChange:e=>j(t=>({...t,...e}))})]})}),(0,J.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:du(`about`),"aria-labelledby":uu(`about`),hidden:m!==`about`,tabIndex:0,children:(0,J.jsxs)(`section`,{className:`pwi-section`,children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:p(`cws.aboutTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:p(`cws.aboutBody`)})]})})]})}function pu({model:e,onCancel:t,onConfirm:n}){let r=Q(),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,J.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,J.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,J.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function mu({onKeep:e,onDiscard:t}){let n=Q(),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,J.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,J.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,J.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function hu(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:e===`all-targets-exhausted`?`cws.attention.allTargetsExhausted`:`cws.attention.few`)}function gu({combos:e,cataloguedComboIds:t,providerMap:n,providerQuotaStates:r,onSelect:i,onAdd:a}){let o=Q(),s=Ll(e),c=Jl(e,{cataloguedComboIds:t,providers:n,providerQuotaStates:r});return(0,J.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,J.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:o(`cws.overviewTitle`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:[(0,J.jsx)(de,{width:14,height:14}),` `,o(`cws.add`)]})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:o(`cws.overviewBlurb`)}),(0,J.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:e.length}),(0,J.jsx)(`span`,{children:o(`cws.count.total`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:s.failover.length}),(0,J.jsx)(`span`,{children:o(`cws.count.failover`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:s.roundRobin.length}),(0,J.jsx)(`span`,{children:o(`cws.count.roundRobin`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:s.other.length}),(0,J.jsx)(`span`,{children:o(`cws.count.other`)})]})]}),(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":o(`cws.howTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:o(`cws.howTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0},children:o(`cws.howBody`)})]}),c.length>0&&(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":o(`cws.attentionTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:o(`cws.attentionTitle`)}),(0,J.jsx)(`div`,{className:`cwi-attention-list`,children:c.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>i(e.id),children:[(0,J.jsx)(_e,{width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`code`,{className:`chip`,children:e.model}),(0,J.jsx)(`span`,{className:`muted`,children:hu(e.reason,o)}),(0,J.jsx)(Se,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function _u({combos:e,providerQuotaStates:t,providers:n,models:r,cataloguedComboIds:i,loading:a,onRefresh:o,onSave:s,onRemove:c,onAdd:l,adding:u,onCloseAdd:d,onCreated:f}){let p=Q(),m=(0,_.useMemo)(()=>Object.fromEntries(n.map(e=>[e.name,{disabled:e.disabled}])),[n]),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(void 0),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),E=(0,_.useMemo)(()=>Ql(),[]),D=(0,_.useMemo)(()=>Rl(e,h),[e,h]),O=(0,_.useMemo)(()=>Ll(D),[D]),k=(0,_.useMemo)(()=>e.flatMap(e=>e.alias?[e.alias]:[]),[e]),A=v&&e.some(e=>e.id===v)?v:null,j=e.find(e=>e.id===A)??null,M=j&&w?.id===j.id?w:j,[N,P]=(0,_.useState)(!1),F=[],I=[];if(M)for(let t of e)t.id!==M.id&&(F.push(t.id),t.alias&&I.push(t.alias));let L=(0,_.useCallback)(e=>{if(e!==A){if(!N){y(e),T(null);return}x(e)}},[A,N]),R=()=>{b!==void 0&&(y(b),T(null),P(!1),x(void 0))},z=()=>x(void 0),B=b!==void 0&&N,V=!a&&e.length===0;return(0,J.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":p(`cws.railAria`),children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`combos-workspace-rail-title`,children:p(`nav.combos`)}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(V){document.getElementById(`cwi-edit-id`)?.focus();return}l()},"aria-label":p(`cws.add`),children:[(0,J.jsx)(de,{width:14,height:14}),` `,p(`cws.add`)]})]}),(0,J.jsx)(`div`,{className:`cwi-search-row`,children:(0,J.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,J.jsx)(ye,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,J.jsx)(`input`,{className:`input cwi-search-input`,value:h,onChange:e=>g(e.target.value),placeholder:p(`cws.searchPlaceholder`),"aria-label":p(`cws.searchPlaceholder`)})]})}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-list`,children:D.length===0&&e.length>0?(0,J.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:p(`cws.noSearchResults`)}):(0,J.jsx)(J.Fragment,{children:[[`failover`,O.failover,`cws.group.failover`],[`round-robin`,O.roundRobin,`cws.group.roundRobin`],[`other`,O.other,`cws.group.other`]].map(([e,t,n])=>t.length>0?(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,J.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),p(n),(0,J.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${A===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>L(e.id),"aria-current":A===e.id?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,J.jsx)(Pe,{width:16,height:16})}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?p(`cws.targetCountOne`):p(`cws.targetCount`,{count:e.targets.length})}),(0,J.jsx)(Se,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,J.jsx)(`div`,{className:`combos-workspace-main`,children:M?(0,J.jsx)(fu,{baseline:M,otherIds:F,otherAliases:I,providerMap:m,providerQuotaStates:t,providers:n,models:r,onBack:()=>L(null),onSaved:e=>{P(!1),e.id===M.id?T(e):(y(e.id),T(null)),o()},onRequestRemove:()=>C(M.id),onSave:s,onDirtyChange:P},M.id):V?(0,J.jsx)(fu,{baseline:E,isCreate:!0,otherIds:[],otherAliases:[],providerMap:m,providerQuotaStates:t,providers:n,models:r,onSaved:e=>{P(!1),y(e.id),T(e),f(e.id)},onSave:s,onDirtyChange:P},`first-combo`):(0,J.jsx)(gu,{combos:e,cataloguedComboIds:i,providerMap:m,providerQuotaStates:t,onSelect:e=>L(e),onAdd:l})}),u&&!V&&(0,J.jsx)(cu,{existingIds:e.map(e=>e.id),existingAliases:k,providerMap:m,providerQuotaStates:t,providers:n,models:r,onClose:d,onSubmit:async e=>{let t=await s(e,!0);return t.ok&&(d(),f(e.id),y(e.id),T(null)),t}}),S&&(0,J.jsx)(pu,{model:e.find(e=>e.id===S)?.model??Ol(S),onCancel:()=>C(null),onConfirm:()=>{(async()=>{let e=await c(S);C(null),e.ok&&(A===S&&(y(null),T(null)),o())})()}}),B&&(0,J.jsx)(mu,{onKeep:z,onDiscard:R})]})}function vu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function yu(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function bu(e){return mr(e)?.data??null}function xu(e){return mr(e)?.cachedAt??null}function Su({apiBase:e,active:t=!0,onCountChange:n}){let r=Q(),i=`ocx.combos.workspace.v1:${e}`,a=(0,_.useMemo)(()=>bu(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=Il(o),f=c.providers??{},p=ui(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 hr(i,_),s(_),_},[e,i]),g=ol(i,[e],h,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:xu(i),staleAfterMs:6e4,enabled:t}),{state:v}=g,y=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`combo quota load failed`);let r=await n.json();return r&&typeof r==`object`&&!Array.isArray(r)?r:{}},[e]),b=ol(`ocx.combos.provider-quotas.v1:${e}`,[e],y,{isEmpty:()=>!1,pollMs:6e4,pauseWhenHidden:!0,enabled:t}),x=(0,_.useMemo)(()=>b.lastAttemptOk?Kl(b.data?.reports):{},[b.data,b.lastAttemptOk]),S=v.data??o??void 0,C=S?.combos??[];(0,_.useEffect)(()=>{S&&n?.(C.length)},[C.length,S,n]);let w=S?.providers??[],T=S?.models??[],E=new Set(S?.cataloguedComboIds??[]),D=async(t,n,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(Xl(t,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=vu(o);if(!a.ok||s||!yu(o)){let e=s||r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(i?r(`cws.renamed`,{from:Ol(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}}},O=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=vu(i);if(!n.ok||a||!yu(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&&!S)return(0,J.jsx)(cl,{label:r(`cws.loading`),rows:5});if(v.kind===`failed-cold`&&!S){let e=v.error instanceof Error?v.error.message:r(`cws.loadFailed`);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($,{tone:`err`,children:e}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g.refresh(),children:r(`common.retry`)})]})}return(0,J.jsxs)(`div`,{className:`combos-workspace-shell`,children:[c&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)($,{tone:u?`ok`:`err`,children:c})}),v.showError&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)($,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,J.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":v.refreshing,children:[(0,J.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:v.refreshing?r(`common.loading`):``}),(0,J.jsx)(_u,{combos:C,providerQuotaStates:x,providers:w,models:T,cataloguedComboIds:E,loading:!1,onRefresh:()=>g.refresh(),onSave:D,onRemove:O,onAdd:()=>p(!0),adding:f,onCloseAdd:()=>p(!1),onCreated:()=>g.refresh()})]})]})}var Cu=0;function wu(){return Cu+=1,`candidate-${Cu}`}function Tu(e,t){return{provider:e,model:t,key:wu()}}function Eu(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 Du(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:Eu(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 Ou={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},ku={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function Au(e){return e===!0?`true`:e===!1?`false`:``}function ju(e){return e===void 0?``:String(e)}function Mu(e=``,t=``){return{id:``,alias:``,candidates:[Tu(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...Ou},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...ku},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function Nu(e){let t=Du(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:wu()})),require:{minContextWindow:ju(e.require.minContextWindow),minQuotaHeadroom:ju(e.require.minQuotaHeadroom),tools:Au(e.require.tools),imageInput:Au(e.require.imageInput),structuredOutput:Au(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:Au(e.require.localOnly),remoteAllowed:Au(e.require.remoteAllowed),encryptedCodexTasks:Au(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:ju(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:ju(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function Pu(e){let t=e.trim();return t?Number(t):void 0}function Fu(e){if(e===`true`)return!0;if(e===`false`)return!1}function Iu(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Lu(e,t,n){let r=Iu({minContextWindow:Pu(e.require.minContextWindow),minQuotaHeadroom:Pu(e.require.minQuotaHeadroom),tools:Fu(e.require.tools),imageInput:Fu(e.require.imageInput),structuredOutput:Fu(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:Fu(e.require.localOnly),remoteAllowed:Fu(e.require.remoteAllowed),encryptedCodexTasks:Fu(e.require.encryptedCodexTasks)}),i=Pu(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?Iu({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:Pu(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=Iu({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 Ru(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 zu(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Bu(e,t){return e.filter(e=>e.provider===t)}var Vu={en:{maxEvidenceAgeMs:`Maximum evidence age (ms)`,unknownEvidence:`Unknown evidence`,degradedEvidence:`Degraded evidence`},de:{maxEvidenceAgeMs:`Maximales Evidenzalter (ms)`,unknownEvidence:`Unbekannte Evidenz`,degradedEvidence:`Eingeschränkte Evidenz`},fr:{maxEvidenceAgeMs:`Âge maximal des preuves (ms)`,unknownEvidence:`Preuves inconnues`,degradedEvidence:`Preuves dégradées`},ko:{maxEvidenceAgeMs:`최대 증거 유효 기간 (ms)`,unknownEvidence:`알 수 없는 증거`,degradedEvidence:`저하된 증거`},zh:{maxEvidenceAgeMs:`证据最大有效期(毫秒)`,unknownEvidence:`未知证据`,degradedEvidence:`降级证据`},"zh-TW":{maxEvidenceAgeMs:`證據最大有效期限(毫秒)`,unknownEvidence:`未知證據`,degradedEvidence:`降級證據`},ru:{maxEvidenceAgeMs:`Максимальный возраст доказательств (мс)`,unknownEvidence:`Неизвестные доказательства`,degradedEvidence:`Ухудшенные доказательства`},ja:{maxEvidenceAgeMs:`エビデンスの最大有効期間 (ms)`,unknownEvidence:`不明なエビデンス`,degradedEvidence:`低下したエビデンス`},tr:{maxEvidenceAgeMs:`Maksimum kanıt yaşı (ms)`,unknownEvidence:`Bilinmeyen kanıt`,degradedEvidence:`Bozulmuş kanıt`}},Hu=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],Uu=[`reasoningEffort`,`serviceTier`],Wu={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},Gu=Object.keys(Wu),Ku=[`latency`,`health`,`cost`,`quota`],qu=[`capability`,`health`,`quota`,`cost`],Ju=[`allow`,`penalize`,`exclude`],Yu=[`allow`,`exclude`];function Xu(e){return`${e.evidenceLayer}:${e.suiteId}`}function Zu(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Qu(e){let t=new Set,n=[];for(let r of e){if(!Zu(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=Xu(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 $u(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function ed(e,t){return e===void 0?t:`${Math.round(e)}ms`}function td(e,t){return e==null?t:`${Math.round(e*100)}%`}function nd(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 rd(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 id(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>Zu(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&Zu(e.require)&&Zu(e.optimize)&&Zu(e.limits)&&Zu(e.unknownEvidence):!1).map(e=>{let t=Du(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function ad(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 od(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 sd({apiBase:e,active:t=!0,onCountChange:n}){let{locale:r,t:i}=ct(),a=Vu[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,z]=(0,_.useState)(``),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)([]),[W,ee]=(0,_.useState)(!1),G=(0,_.useRef)(null),K=(0,_.useRef)(0),q=(0,_.useRef)(null),Y=(0,_.useRef)(!0),te=(0,_.useCallback)(()=>{Y.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),z(``),V(!1)},[]),ae=(0,_.useCallback)(e=>{G.current=e,x(e),C(e?Nu(e):null),T(null),ie()},[ie]),oe=(0,_.useCallback)(async t=>{if(!Y.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=id(d),b=G.current,S=od(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()]));G.current=S,c(y),x(S),C(S?Nu(S):null),u(p),f(T),m(E),g(ad(_)),v&&Array.isArray(v.scenarios)?(U(Qu(v.scenarios)),ee(!1)):(U([]),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){te();return}Y.current=!0;let e=window.setTimeout(()=>void oe(),0);return()=>{window.clearTimeout(e),te()}},[t,te,oe]),(0,_.useEffect)(()=>{n?.(s.length)},[n,s.length]);let X=d[0]??``,se=p[X]??Bu(h,X)[0]?.id??``,ce=()=>{G.current=null,x(null),C(Mu(X,se)),T(null),ie()},le=()=>{if(b){C(Nu(b)),T(null);return}ae(s[0]??null)},ue=async()=>{if(!(!S||E)){D(!0),T(null);try{let t=Lu(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 Ft(n);if(!n.ok){let e=await n.json().catch(()=>null);re(Ru(e)??i(`routing.loadFailed`),!1);return}if(!zu(r)){re(Ru(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 Ft(t);if(!t.ok){let e=await t.json().catch(()=>null);re(Ru(e)??i(`routing.loadFailed`),!1);return}if(!zu(n)){re(Ru(n)??i(`routing.loadFailed`),!1);return}G.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]??Bu(h,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},pe=()=>{C(e=>e&&{...e,candidates:[...e.candidates,Tu(X,se)]})},me=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},he=async()=>{if(!b)return;let t=++ne.current;V(!0),L(null),z(``);try{let n={},r=O.trim()?Number(O.trim()):NaN;Number.isFinite(r)&&r>0&&(n.contextWindow=r),A&&(n.toolsRequired=!0),M&&(n.imageInputRequired=!0),P&&(n.structuredOutputRequired=!0);let a=await fetch(`${e}/api/routing-profiles/dry-run`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:b.id,evidence:n})});if(t!==ne.current)return;if(!a.ok){let e=await a.json().catch(()=>null);if(t!==ne.current)return;z(Ru(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;z(e instanceof Error?e.message:String(e))}finally{t===ne.current&&V(!1)}},ge=S?.candidates.map(e=>Bu(h,e.provider))??[];return(0,J.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,J.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:ce,children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.createProfile`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void oe(),children:i(`common.retry`)})]}),v?(0,J.jsxs)($,{tone:`err`,children:[i(`routing.loadFailed`),`: `,v]}):null,w?(0,J.jsx)($,{tone:w.ok?`ok`:`err`,children:w.message}):null,s.length>0?(0,J.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:s.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>ae(e),"aria-pressed":b?.id===e.id,children:(0,J.jsxs)(`div`,{className:`card-badges`,children:[(0,J.jsx)(`strong`,{children:e.id}),(0,J.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,J.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),ue()},children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsxs)(`h3`,{children:[i(`routing.detail`),`: `,b?.model??(0,J.jsx)(`code`,{children:`policy/…`})]}),b?(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,b.revision]}):null]}),(0,J.jsxs)(`div`,{className:`model-grid`,children:[(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`id`}),(0,J.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`alias`}),(0,J.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.candidates`)}),(0,J.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,J.jsxs)(`div`,{className:`model-card`,children:[(0,J.jsxs)(`div`,{className:`model-grid`,children:[(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`provider`}),(0,J.jsxs)(`select`,{className:`input`,required:!0,value:e.provider,onChange:e=>fe(t,`provider`,e.target.value),children:[(0,J.jsx)(`option`,{value:``,disabled:!0,children:i(`routing.none`)}),n.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`model`}),(0,J.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>fe(t,`model`,e.target.value)}),(0,J.jsx)(`datalist`,{id:r,children:ge[t]?.map(e=>(0,J.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,J.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,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:pe,children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.candidate`)]})]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.require`)}),(0,J.jsxs)(`div`,{className:`model-grid`,children:[Gu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:Wu[e].min,max:Wu[e].max,step:Wu[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Uu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Hu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsxs)(`select`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}}),children:[(0,J.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,J.jsx)(`option`,{value:`true`,children:i(`routing.yes`)}),(0,J.jsx)(`option`,{value:`false`,children:i(`routing.no`)})]})]},e))]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.optimize`)}),(0,J.jsx)(`div`,{className:`model-grid`,children:Ku.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.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,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.limits`)}),(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,J.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,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`onUnknownCost`}),(0,J.jsx)(`select`,{className:`input`,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e.target.value}}),children:Yu.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.unknownEvidence`)}),(0,J.jsx)(`div`,{className:`model-grid`,children:qu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsx)(`select`,{className:`input`,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t.target.value}}),children:Ju.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]},e))})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.compatibility.title`)}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.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,J.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,J.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[i(`routing.compatibility.requiredSuites`),W?(0,J.jsx)(`div`,{style:{marginTop:6},children:(0,J.jsx)($,{tone:`warn`,children:i(`routing.compatibility.catalogUnavailable`)})}):null,H.length>0?(0,J.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:H.map(e=>(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:$u(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,J.jsxs)(`span`,{children:[e.suiteId,` `,(0,J.jsxs)(`span`,{className:`muted`,children:[`(`,i(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[i(`routing.compatibility.minStatus`),(0,J.jsxs)(`select`,{className:`input`,value:S.compatibility.minStatus,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e.target.value}}),children:[(0,J.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,J.jsx)(`option`,{value:`PROBED`,children:i(`lab.verdict.PROBED`)}),(0,J.jsx)(`option`,{value:`VERIFIED`,children:i(`lab.verdict.VERIFIED`)})]})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[a.maxEvidenceAgeMs,(0,J.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,J.jsxs)(`label`,{className:`field-label`,children:[a.unknownEvidence,(0,J.jsx)(`select`,{className:`input`,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e.target.value}}),children:Ju.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[a.degradedEvidence,(0,J.jsx)(`select`,{className:`input`,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e.target.value}}),children:Ju.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}):null]}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,J.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:i(E?`common.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:le,children:i(`common.cancel`)}),b?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void de(),children:i(`common.remove`)}):null]})]}):null,(0,J.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,J.jsx)(`h3`,{children:i(`routing.dryRun`)}),(0,J.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[i(`routing.dryRunContext`),(0,J.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),ie()}})]}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),ie()}}),i(`routing.dryRunTools`)]}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),ie()}}),i(`routing.dryRunImage`)]}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),ie()}}),i(`routing.dryRunStructured`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||B,onClick:()=>void he(),children:i(`routing.dryRunRun`)}),R?(0,J.jsx)($,{tone:`err`,children:R}):null,I?(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`routing.candidate`)}),(0,J.jsx)(`th`,{children:i(`routing.eligible`)}),(0,J.jsx)(`th`,{children:i(`routing.exclusions`)}),(0,J.jsx)(`th`,{children:i(`routing.costCap`)}),(0,J.jsx)(`th`,{children:i(`routing.score`)})]})}),(0,J.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,J.jsxs)(`tr`,{children:[(0,J.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${i(`routing.selected`)})`:``]}),(0,J.jsx)(`td`,{children:e.eligible?i(`routing.yes`):i(`routing.no`)}),(0,J.jsx)(`td`,{children:e.exclusions.map(e=>rd(e.code,i)).join(`, `)||i(`routing.none`)}),(0,J.jsx)(`td`,{children:nd(e.cost?.capOutcome,i,o)}),(0,J.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):o})]},`${e.provider}/${e.model}`))})]}):null]}),(0,J.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,J.jsx)(`h3`,{children:i(`routing.analytics`)}),l?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`card-badges`,children:[(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsTotal`),`: `,l.totalRequests]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsSuccessRate`),`: `,td(l.successRate,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsFallbackRate`),`: `,td(l.fallbackRate,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP50`),`: `,ed(l.durationMs.p50,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP95`),`: `,ed(l.durationMs.p95,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP99`),`: `,ed(l.durationMs.p99,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsCooldown`),`: `,l.cooldownTriggeringFailures]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsConfidence`),`: `,l.confidence??o]}),l.historyTruncated?(0,J.jsx)(`span`,{className:`badge badge-muted`,children:i(`routing.analyticsTruncated`)}):null]}),(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`routing.candidate`)}),(0,J.jsx)(`th`,{children:i(`routing.analyticsRequests`)}),(0,J.jsx)(`th`,{children:i(`routing.analyticsSuccessRate`)}),(0,J.jsx)(`th`,{children:i(`routing.analyticsP50`)})]})}),(0,J.jsx)(`tbody`,{children:l.breakdown.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,J.jsx)(`td`,{children:e.requests}),(0,J.jsx)(`td`,{children:td(e.successRate,o)}),(0,J.jsx)(`td`,{children:ed(e.p50DurationMs,o)})]},`${e.provider}/${e.model}`))})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`routing.analyticsEmpty`)})]})]})}var cd=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],ld=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],ud=[`present`,`corrupt`,`purged_unavailable`];function dd(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function fd(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function pd(e){return e===null||typeof e==`string`}function md(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function hd(e){if(!dd(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(!md(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function gd(e){return!dd(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!cd.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`||!ld.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!fd(e.scenarioManifestDigests)||!pd(e.claimSourceDigest)||!fd(e.contributingEventIds)||!fd(e.contradictingEventIds)||!fd(e.notes)?null:e}function _d(e){return!dd(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(gd).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function vd(e){return!dd(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>dd(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function yd(e){return!dd(e)||!dd(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function bd(e){return!dd(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!cd.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`||!pd(e.exclusionReason)?null:e}function xd(e){return!dd(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(bd).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function Sd(e){if(!dd(e)||!dd(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`||!pd(t.exclusionReason)?null:t}function Cd(e){if(!dd(e)||!dd(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!ud.includes(t.status)||!pd(t.artifactClass)||!pd(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!pd(t.lastError)?null:t}function wd(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 Td(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function Ed(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:Td()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function Dd(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function Od(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function kd(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 Ad=50,jd=200,Md=6,Nd=200;async function Pd(e,t,n){return Pt(await fetch(`${e}${t}`,{signal:n}))}function Fd(e,t){let n=new URLSearchParams({limit:String(Ad)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var Id=class extends Error{};function Ld(){return new Id}function Rd(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw Ld()}function zd(e){if(!dd(e)||!Array.isArray(e.verdicts))throw Ld();let t=_d(e);if(t.verdicts.length!==e.verdicts.length)throw Ld();return Rd(e,t.hasMore,t.nextCursor),t}function Bd(e){if(!dd(e)||!Array.isArray(e.subjects))throw Ld();let t=vd(e);if(t.subjects.length!==e.subjects.length)throw Ld();return Rd(e,t.hasMore,t.nextCursor),t}function Vd(e){if(!dd(e)||!Array.isArray(e.observations))throw Ld();let t=xd(e);if(t.observations.length!==e.observations.length)throw Ld();return Rd(e,t.hasMore,t.nextCursor),t}async function Hd(e,t){let n=hd(await Pd(e,`/api/lab/status`,t));if(!n)throw Ld();return n}async function Ud(e,t,n,r){return zd(await Pd(e,`/api/lab/verdicts?${Fd({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function Wd(e,t,n){return Bd(await Pd(e,`/api/lab/subjects?${Fd({},t)}`,n))}async function Gd(e){let t=[],n=new Set,r;for(let i=0;i<jd;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 Id;n.add(a),r=a}return{rows:t,truncated:!0}}async function Kd(e,t){return Gd(async n=>{let r=await Wd(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function qd(e,t,n){let r=yd(await Pd(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw Ld();return r}async function Jd(e,t,n,r){return Vd(await Pd(e,`/api/lab/observations?${Fd({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function Yd(e,t,n){return Gd(async r=>{let i=await Jd(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function Xd(e,t,n){let r=Sd(await Pd(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw Ld();return r}async function Zd(e,t,n){let r=Cd(await Pd(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw Ld();return r}function Qd(e){if(!dd(e)||e.verificationStatus!==`not_verification`||!dd(e.summary))throw Ld();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 Ld();return{verificationStatus:`not_verification`,summary:t}}async function $d(e,t,n){return Qd(await Pd(e,`/api/lab/production-signals?${Fd({subjectId:t})}`,n))}function ef(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function tf(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function nf(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function rf(e){if(!dd(e)||!ef(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(!dd(n)||!ef(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!tf(n.bundleId)||!tf(n.publisherKeyId)||!nf(n.activeRecordCount)||!nf(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 af(e,t){let n=rf(await Pd(e,`/api/lab/public/community`,t));if(!n)throw Ld();return n}async function of(e,t,n){let[r,i]=await Promise.all([Hd(e,n),af(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([Ud(e,t,void 0,n),Kd(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function sf(e,t,n,r){return Ud(e,t,n,r)}async function cf(e,t,n,r){let i=e.slice(0,Nd),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 lf(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=kd(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([qd(e,t.subjectId,n),Yd(e,a,n),cf(r,Md,n,t=>Xd(e,t,n)),cf(i,Md,n,t=>Zd(e,t,n)),$d(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 uf={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},df={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},ff={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`},pf={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function mf(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 hf({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,J.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,J.jsx)(`span`,{children:n}),(0,J.jsx)(`span`,{className:`suite`,children:t})]}):(0,J.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,J.jsx)(`span`,{children:n}),(0,J.jsx)(`span`,{className:`suite`,children:t})]})}function gf({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,J.jsx)(`span`,{className:`muted`,children:`-`}):(0,J.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,J.jsx)(hf,{verdict:e.verdict,caption:e.suiteId,label:t(ff[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function _f({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:Od(r.builtAtMs,n)}),(0,J.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,J.jsxs)(`div`,{className:`lab-status-card`,children:[(0,J.jsx)(`span`,{className:`label`,children:e.label}),(0,J.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function vf({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,J.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,J.jsx)(`h3`,{className:`lab-matrix-title`,children:Ye(t,`community.title`)}),(0,J.jsx)(`p`,{className:`muted`,children:Ye(t,`community.notLocalVerdict`)}),(0,J.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:Ye(t,`community.bundles`)}),(0,J.jsx)(`dd`,{children:e.evidence.length})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:Ye(t,`community.activeRecords`)}),(0,J.jsx)(`dd`,{children:n})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:Ye(t,`community.revokedRecords`)}),(0,J.jsx)(`dd`,{children:r})]})]})]})}function yf({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,J.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,J.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,J.jsx)(`h3`,{children:Dd(e.subjectId)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,J.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,J.jsx)(`dd`,{children:i(uf[e.evidenceLayer])})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,J.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,J.jsx)(`dd`,{children:i(ff[e.verdict])})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,J.jsx)(`dd`,{children:Od(e.asOf,a)})]})]}),n&&(0,J.jsx)(ll,{busy:!0,children:i(`common.loading`)}),r&&(0,J.jsx)($,{tone:`err`,children:r}),t&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,J.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,J.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,J.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,J.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,J.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,J.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,J.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,J.jsx)(`dd`,{children:Od(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,J.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,J.jsx)(`span`,{children:e.outcome}),(0,J.jsx)(`span`,{className:`muted`,children:Od(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,J.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,J.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,J.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`mono`,title:e.digest,children:Dd(e.digest)}),(0,J.jsx)(`span`,{children:e.artifactClass??`-`}),(0,J.jsx)(`span`,{children:Ye(a,pf[e.status])})]},e.digest))})]})]})]})}function bf({apiBase:e,active:t=!0,onCountChange:n}){let{t:r,locale:i}=ct(),[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)(()=>wd(a),[a]),E=JSON.stringify(T),D=(0,_.useCallback)(t=>of(e,T,t),[e,T]),O=ol(`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?Ed(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 sf(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:mf(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 lf(e,n,i.signal);!i.signal.aborted&&w.current===n.projectionKey&&g(t)}catch(e){!i.signal.aborted&&w.current===n.projectionKey&&x(mf(e,r(`lab.detailLoadFailed`)))}finally{C.current===i&&(C.current=null,!i.signal.aborted&&w.current===n.projectionKey&&y(!1))}},[t,e,r]),z=O.refresh,B=(0,_.useCallback)(()=>{A(),k(),z({forceLoading:!0})},[A,z,k]),V=t?p:null,H=M?M.hasMore:O.data?.hasMore??!1,U=[{value:``,label:r(`lab.filter.all`)},...cd.map(e=>({value:e,label:r(uf[e])}))],W=[{value:``,label:r(`lab.filter.all`)},...ld.map(e=>({value:e,label:r(ff[e])}))],ee=[{value:``,label:r(`lab.filter.all`)},...(O.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${Dd(e.subjectId)} · ${e.subjectKind}`}))];if(O.state.showSkeleton)return(0,J.jsx)(cl,{label:r(`lab.loading`),rows:5});let G=O.state.showError?mf(O.error,r(`lab.loadFailed`)):null,K=O.data?.status,q=K&&!K.projectionAvailable,Y=K?.projectionIncompatible===!0;return(0,J.jsxs)(`div`,{className:`lab-page`,children:[(0,J.jsx)(`div`,{className:`lab-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:B,disabled:O.refreshing,children:[(0,J.jsx)(fe,{}),r(`lab.refresh`)]})}),O.refreshing&&!O.state.showSkeleton&&(0,J.jsx)(ll,{busy:!0,live:!G,children:r(`common.loading`)}),G&&(0,J.jsx)($,{tone:`err`,children:G}),Y&&(0,J.jsx)($,{tone:`err`,children:r(`lab.projectionIncompatible`)}),q&&!Y&&(0,J.jsx)(Ot,{title:r(`lab.projectionUnavailable`)}),O.data&&(0,J.jsx)(vf,{community:O.data.community,locale:i}),O.data&&K?.projectionAvailable&&!Y&&(0,J.jsxs)(`div`,{className:`lab-layout`,children:[(0,J.jsxs)(`div`,{className:`lab-main`,children:[(0,J.jsx)(_f,{data:O.data,t:r,locale:i}),(0,J.jsxs)(`div`,{className:`lab-filters`,children:[(0,J.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,J.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:r(`lab.filter.layer`)}),(0,J.jsx)(Dt,{id:`lab-filter-layer`,value:a.layer,options:U,onChange:e=>j(t=>({...t,layer:e})),label:r(`lab.filter.layer`),portal:!1})]}),(0,J.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,J.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:r(`lab.filter.verdict`)}),(0,J.jsx)(Dt,{id:`lab-filter-verdict`,value:a.verdict,options:W,onChange:e=>j(t=>({...t,verdict:e})),label:r(`lab.filter.verdict`),portal:!1})]}),(0,J.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,J.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:r(`lab.filter.subject`)}),(0,J.jsx)(Dt,{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,J.jsx)(Ot,{title:r(`lab.empty`)}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,J.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.matrixTitle`)}),(0,J.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,J.jsxs)(`table`,{className:`lab-matrix`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,J.jsx)(`th`,{children:r(`lab.subjectKind`)}),cd.map(e=>(0,J.jsx)(`th`,{children:r(df[e])},e))]})}),(0,J.jsx)(`tbody`,{children:I.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`subject`,title:e.subjectId,children:Dd(e.subjectId)}),(0,J.jsx)(`td`,{className:`kind`,children:e.subjectKind||Ye(i,`subjectKindUnknown`)}),cd.map(t=>(0,J.jsx)(`td`,{children:(0,J.jsx)(gf,{rows:e.byLayer[t],t:r,selectedKey:V?.projectionKey??null,onSelect:e=>{R(e)}})},t))]},e.subjectId))})]})})]}),(0,J.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,J.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.verdictsTitle`)}),(0,J.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,J.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,J.jsx)(`th`,{children:r(`lab.col.layer`)}),(0,J.jsx)(`th`,{children:r(`lab.col.suite`)}),(0,J.jsx)(`th`,{children:r(`lab.col.verdict`)}),(0,J.jsx)(`th`,{children:r(`lab.col.asOf`)})]})}),(0,J.jsx)(`tbody`,{children:F.map(e=>{let t=V?.projectionKey===e.projectionKey;return(0,J.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,J.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":Ye(i,`selectVerdict`,{subject:Dd(e.subjectId)}),onClick:()=>{R(e)},children:Dd(e.subjectId)})}),(0,J.jsx)(`td`,{children:r(uf[e.evidenceLayer])}),(0,J.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,J.jsx)(`td`,{children:(0,J.jsx)(hf,{verdict:e.verdict,caption:e.suiteId,label:r(ff[e.verdict])})}),(0,J.jsx)(`td`,{children:Od(e.asOf,i)})]},e.projectionKey)})})]})})]}),N&&(0,J.jsx)($,{tone:`err`,children:N}),H&&(0,J.jsx)(`div`,{className:`lab-load-more`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:d,onClick:()=>{L()},children:r(d?`common.loading`:`lab.loadMore`)})})]})]}),V&&(0,J.jsx)(yf,{verdict:V,detail:h,loading:v,error:b,t:r,locale:i,onClose:A})]})]})}var xf=[`catalog`,`combos`,`routing`,`compatibility`];function Sf(e){return e===`catalog`?`models`:`models/${e}`}function Cf(e=window.location.hash){let t=dt(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 wf(e){pt(Sf(e))}function Tf(e){return`models-tab-${e}`}function Ef(e){return`models-panel-${e}`}var Df={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function Of({tab:e,onSelect:t,meta:n}){let r=Q(),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=xf.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+xf.length)%xf.length:t.key===`ArrowRight`?r=(n+1)%xf.length:t.key===`Home`?r=0:t.key===`End`&&(r=xf.length-1),r!==null&&(t.preventDefault(),a(xf[r]))};return(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:xf.map(t=>{let s=t===e,c=n?.[t];return(0,J.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:Tf(t),"aria-selected":s,"aria-controls":Ef(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r(Df[t]),c?(0,J.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function kf(e,t){let n=new Map;for(let t of e){let e=n.get(t.provider);e?e.push(t):n.set(t.provider,[t])}let r=new Map(t.map(e=>[e.name,e]));for(let e of t){if(e.disabled===!0){n.delete(e.name);continue}e.authMode!==`forward`&&(n.has(e.name)||n.set(e.name,[]))}return[...n.entries()].map(([e,t])=>{let n=r.get(e);return{provider:e,rows:t,native:t.length>0&&t.every(e=>e.native===!0),nativeProviderGroup:t.some(e=>e.native===!0),liveModels:n?.liveModels!==!1,configuredModels:n?.models??[],contextWindow:n?.contextWindow,modelContextWindows:n?.modelContextWindows,discovery:n?.discovery}}).sort((e,t)=>e.nativeProviderGroup===t.nativeProviderGroup?e.provider.localeCompare(t.provider):e.nativeProviderGroup?-1:1)}function Af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jf(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Mf(e){if(!Af(e))throw Error(`invalid selected models response`);let t=e.selected;if(!Af(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,jf(t)]))}async function Nf(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 Mf(await r.json())}function Pf(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Ff(e,t,n,r,i){return Pf(e,t,n,r)&&!i}async function If(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 Lf(e,t){return e===t}function Rf(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 zf=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Bf=Array.from({length:18},(e,t)=>1e5+t*5e4),Vf=new Set(Bf),Hf=272e3,Uf=922e3,Wf=[Hf,372e3,Uf],Gf=new Set(Wf),Kf=`custom`,qf=[4,8,16,32,64,128,256,500,1e3],Jf=new Set(qf),Yf=`ocx-models-collapsed:v2`;function Xf(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?e>=1e6?Number((e/1e6).toFixed(2))+`M`:`${e/1e3}k`:e.toLocaleString()}function Zf(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Qf(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);Ff(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?An(a.namespaced,r):a.namespaced})}return i}function $f(e=localStorage){try{let t=e.getItem(Yf);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 ep(e,t=localStorage){try{t.setItem(Yf,JSON.stringify([...e]))}catch{}}function tp({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=Q(),i=e&&t?.status===`failed`?t:void 0;return(0,J.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,J.jsx)(ve,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,J.jsxs)(`span`,{children:[i&&n&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${Rf(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>pt(`providers`),children:r(`models.openProviderSettings`)})]})]})}var np={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function rp(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 ip({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=>{Jc(e,{signal:t}).then(e=>{t?.aborted||!i.current||r(e.state)})},[e]),{restarting:o,restart:s}=$c(e,{onSettled:()=>a()});(0,_.useEffect)(()=>{let e=new AbortController;return a(e.signal),()=>e.abort()},[a,t]);let[c,l]=(0,_.useState)(Cf),[u,d]=(0,_.useState)(()=>new Set([Cf()])),f=(0,_.useCallback)(e=>{l(e),d(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,_.useEffect)(()=>{let e=()=>f(Cf());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[f]);let p=(0,_.useCallback)(e=>{wf(e),f(e)},[f]),m=c===`catalog`,[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),S=Q(),C=`ocx.models.catalog.v1:${e}`,w=(0,_.useMemo)(()=>fr(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)({}),[L,R]=(0,_.useState)(()=>w?.contextCaps??{}),[z,B]=(0,_.useState)(()=>w?.contextCapValue??35e4),[V,H]=(0,_.useState)(``),[U,W]=(0,_.useState)(!1),[ee,G]=(0,_.useState)({}),[q,Y]=(0,_.useState)({}),te=$f(),[ne,ie]=(0,_.useState)(()=>te??new Set),ae=(0,_.useRef)(te===null),[oe,X]=(0,_.useState)(``),[se,ce]=(0,_.useState)(!1),[ue,de]=(0,_.useState)(0),pe=(e,t)=>{ce(e),X(t),de(e=>e+1)};(0,_.useEffect)(()=>{if(!oe)return;let e=setTimeout(()=>X(``),se?6e3:8e3);return()=>clearTimeout(e)},[oe,se,ue]);let[me,he]=(0,_.useState)(!1),ye=(0,_.useRef)(!1),be=(0,_.useRef)(0),xe=(0,_.useRef)(!1),[Z,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)({}),[Ee,De]=(0,_.useState)(null),[Oe,ke]=(0,_.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[Ae,je]=(0,_.useState)(!1),[Me,Ne]=(0,_.useState)(null),[Pe,Fe]=(0,_.useState)(!0),[Ie,Le]=(0,_.useState)(!1),[Re,ze]=(0,_.useState)(``),Be=(0,_.useRef)(!1),[Ve,He]=(0,_.useState)(``),[Ue,We]=(0,_.useState)(!1),[Ge,Ke]=(0,_.useState)(!1),[qe,Je]=(0,_.useState)(!1),Ye=(0,_.useCallback)(async t=>{let n=await Ft(await fetch(`${e}/api/aliases`,{signal:t}));n&&!t?.aborted&&ke(n)},[e]);(0,_.useEffect)(()=>{let e=new AbortController;return Ye(e.signal),()=>e.abort()},[Ye]);let Xe=async t=>{let n=window.prompt(S(`models.aliasPrompt`),Oe.providers[t]??``);if(n!==null){if(!(await fetch(`${e}/api/providers/${encodeURIComponent(t)}/alias`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:n.trim()||null})})).ok){pe(!1,S(`models.aliasConflict`));return}await Ye(),pe(!0,S(`models.aliasSaved`))}},Ze=async(t,n)=>{let r=Oe.models[t]?.[n]?.alias??``,i=window.prompt(S(`models.modelAliasPrompt`),r);if(i===null)return;let a=i.trim()?{set:{[n]:i.trim()}}:{remove:[n]};if(!(await fetch(`${e}/api/providers/${encodeURIComponent(t)}/model-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(a)})).ok){pe(!1,S(`models.aliasConflict`));return}await Ye(),pe(!0,S(`models.aliasSaved`))},Qe=async(t,n)=>{(await fetch(`${e}/api/default-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:t,...n?{provider:n}:{}})})).ok&&await Ye()},[$e,et]=(0,_.useState)(`add`),[tt,nt]=(0,_.useState)(``),[rt,it]=(0,_.useState)(``),[at,ot]=(0,_.useState)(``),[st,ct]=(0,_.useState)(``),[lt,ut]=(0,_.useState)(``),[dt,ft]=(0,_.useState)(!1),[pt,mt]=(0,_.useState)([`text`]),[ht,gt]=(0,_.useState)(!1),[_t,vt]=(0,_.useState)([]),yt=(0,_.useRef)(!1),[bt,xt]=(0,_.useState)(!1),[St,Ct]=(0,_.useState)(``),[wt,Et]=(0,_.useState)(null),[At,jt]=(0,_.useState)([]),[Mt,Nt]=(0,_.useState)(``),[It,Lt]=(0,_.useState)(``),[Bt,Vt]=(0,_.useState)({}),[Ht,Ut]=(0,_.useState)({contextWindow:null,modelContextWindows:{}}),[Wt,Gt]=(0,_.useState)(new Set),[Kt,qt]=(0,_.useState)(!1),[Jt,Yt]=(0,_.useState)(!1),[Xt,Zt]=(0,_.useState)(``),[Qt,$t]=(0,_.useState)(null),en=(0,_.useRef)(null),[tn,nn]=(0,_.useState)(null),[rn,an]=(0,_.useState)(!1),[on,sn]=(0,_.useState)(null);(0,_.useEffect)(()=>()=>{en.current&&clearTimeout(en.current)},[]);let cn=(0,_.useMemo)(()=>Qf(T,k,j??{},S),[T,k,j,S]),ln=(0,_.useMemo)(()=>{let e=new Set(cn.map(e=>e.value));return pn(T.filter(t=>e.has(t.namespaced)),tn?.model,tn?.sourceModels)},[T,tn?.model,tn?.sourceModels,cn]),un=(0,_.useCallback)(async()=>{let t=Ln(15e3);try{let n=await Ft(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&nn(n)}catch{}finally{t.clear()}},[e]),dn=(0,_.useCallback)(async()=>{if(Be.current)return;let t=Ln(15e3);try{let n=await fetch(`${e}/api/v2`,{signal:t.signal});if(!(n.headers.get(`content-type`)??``).includes(`application/json`)){Ce(null);return}let r=await Ft(n);if(!r||typeof r.enabled!=`boolean`){Ce(null);return}Ce({enabled:r.enabled,agentsMaxThreadsConflict:r.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof r.maxConcurrentThreadsPerSession==`number`?r.maxConcurrentThreadsPerSession:null,multiAgentMode:r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?r.multiAgentMode:`default`,keepNativeChatGptOnV1:r.keepNativeChatGptOnV1===!0})}catch{Ce(null)}finally{t.clear(),Fe(!1)}},[e]),fn=(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}),Nf(e,fetch,t)]),[o,s,c]=await Promise.all([Pt(n),Pt(r),Pt(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=Zf(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 gr(C,f),f},[e,C]),mn=(0,_.useCallback)(e=>{let t=kf(e.models,e.providers);sn(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),B(e.contextCapValue),R(e.contextCaps)},[]),hn=ol(C,[e],async e=>{let t=await fn(e);if(e.aborted)throw Error(`models request aborted`);return mn(t),t},{isEmpty:()=>!1,pollMs:1e4,initialData:w??void 0,enabled:m,deadlineMs:6e4}),gn=hn.state,_n=(0,_.useCallback)(async(e=!1)=>{if(xe.current&&!e)return!1;xe.current=!0;let t=++be.current;try{let e=await fn(new AbortController().signal);return Lf(t,be.current)?(mn(e),K(C,e),!0):!1}catch{return!1}finally{Lf(t,be.current)&&(xe.current=!1)}},[mn,C,fn]);(0,_.useEffect)(()=>{if(!m)return;let e=window.setTimeout(()=>{un(),dn(),Gn(),Kn()},0),t=Vn(()=>{Be.current||dn()},1e4);return()=>{window.clearTimeout(e),t()}},[m,un,dn]);let vn=(0,_.useMemo)(()=>kf(T,D),[T,D]),yn=T.length>0||gn.data!==void 0,bn=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;Et(e.provider),jt(t),Nt(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));Lt(r),Vt(i),Ut({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),Gt(new Set),qt(!1),Zt(``)},xn=e=>{Nt(e)},Sn=async()=>{if(!wt)return;let t=rp(It);if(!vn.find(e=>e.provider===wt)){Zt(S(`models.contextSaveFailed`));return}if(Kt&&t===void 0){Zt(S(`models.contextInvalid`));return}let n={};for(let e of Wt){let t=rp(Bt[e]??``);if(t===void 0){Zt(S(`models.contextInvalid`));return}t!==(Ht.modelContextWindows[e]??null)&&(n[e]=t)}let r=Kt&&t!==Ht.contextWindow;if(!r&&Object.keys(n).length===0){Et(null),pe(!0,S(`models.contextUnchanged`));return}Yt(!0),Zt(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await Pt(await fetch(`${e}/api/providers?name=${encodeURIComponent(wt)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),S(`models.contextSaveFailed`))}catch(e){Zt(e instanceof Error?e.message:S(`models.contextSaveFailed`));return}finally{Yt(!1)}Et(null),pe(!0,S(`models.contextSaved`)),await _n(!0)};(0,_.useEffect)(()=>{if(!ae.current||vn.length===0)return;ae.current=!1;let e=new Set(vn.map(e=>e.provider));ie(e),ep(e)},[vn]);let Cn=(0,_.useMemo)(()=>j?T.filter(e=>Ff(j,e.provider,e.id,e.native===!0,k.has(e.namespaced))).length:0,[k,T,j]),wn=(0,_.useMemo)(()=>({catalog:yn?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)}),[yn,h,b,Cn,T.length,v,S]),Tn=async(t,n,r,i)=>{++be.current,he(!0),ye.current=!0,X(``);let a=null;try{(await If(e,t,n,r,i)).ok||(a=`models.saveFailed`)}catch{a=`models.networkError`}finally{let e=await _n(!0);a?(ce(!1),X(S(a))):e&&(ce(!0),X(S(`models.applied`))),he(!1),ye.current=!1}},En=async(t,n=!1)=>{he(!0),ye.current=!0,X(``);let r=L[t]===void 0;try{let i=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r&&n?{provider:t,enabled:r,value:Uf}:{provider:t,enabled:r})});try{let e=await Pt(i,S(`models.capSaveFailed`));R(e?.caps??{}),ce(!0),X(S(`models.capApplied`)),await _n(!0)}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{he(!1),ye.current=!1}},On=e=>{ie(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),ep(n),n})},jn=e=>{ie(()=>{let t=e?new Set(vn.map(e=>e.provider)):new Set;return ep(t),t})},Mn=async t=>{he(!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 Pt(n,S(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&B(e.value),R(e?.caps??{}),ce(!0),X(S(`models.capApplied`)),await _n(!0)}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{he(!1),ye.current=!1}},Nn=(0,_.useMemo)(()=>{let e=vn.filter(e=>!e.native);return e.length>0&&e.every(e=>L[e.provider]===z)&&Object.keys(L).every(e=>L[e]===z)},[vn,L,z]),Pn=e=>{!Number.isSafeInteger(e)||e<=0||Mn(Nn?{value:e,setAll:!0}:{value:e})},Fn=(e,t)=>{if(t===`custom`){G(t=>({...t,[e]:!0})),Y(t=>({...t,[e]:String(L[e]??z)}));return}G(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==L[e]&&Mn({provider:e,enabled:!0,value:n})},In=e=>{let t=Number((q[e]??``).replace(/[_,\s]/g,``));if(!Number.isSafeInteger(t)||t<=0){pe(!1,S(`models.capSaveFailed`));return}G(t=>({...t,[e]:!1})),Mn({provider:e,enabled:!0,value:t})},Rn=e=>{if(e===`custom`){W(!0),H(String(z));return}W(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==z&&Pn(t)},zn=()=>{let e=Number(V.replace(/[_,\s]/g,``));if(!Number.isSafeInteger(e)||e<=0){pe(!1,S(`models.capSaveFailed`));return}W(!1),Pn(e)},Bn=()=>{Mn({setAll:!Nn})},Hn=async t=>{if(!(!tn||rn)){an(!0),nn({...tn,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{an(!1)}}},Un=async t=>{if(!(!Z||Be.current)){Le(!0),Be.current=!0,ze(``),X(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await Pt(n,S(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){ce(!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`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0}),ce(!0),X(S(`models.v2Applied`)),ze((e.warnings??[]).join(` `))}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{Le(!1),Be.current=!1}}},Wn=async e=>{!Z||Z.multiAgentMode===e||await Un({multiAgentMode:e})},Gn=async()=>{try{let t=Ln(15e3),n=await Ft(await fetch(`${e}/api/model-presets`,{signal:t.signal}));Te(n?.providers??{})}catch{Te({})}},Kn=async()=>{try{let t=await fetch(`${e}/api/model-discovery`);De(await Ft(t)??null)}catch{De(null)}},qn=async(t,n)=>{await Ft(await fetch(`${e}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:t,provider:n??null})})),await Promise.all([Kn(),_n()])},Jn=async(t,n)=>{if(!Me){Ne(t);try{let r=Ln(3e4),i=await Ft(await fetch(`${e}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t,mode:n}),signal:r.signal}))??{};i.fallback===`preset-empty`?pe(!1,S(`models.presetEmpty`,{provider:t})):pe(!0,n===`all`?S(`models.presetClearedToast`,{provider:t}):S(`models.presetAppliedToast`,{provider:t,count:String(i.selected?.length??0)})),await Promise.all([Gn(),_n()])}catch(e){pe(!1,e instanceof Error?e.message:String(e))}finally{Ne(null)}}},Yn=async e=>{!Z||Z.keepNativeChatGptOnV1===e||await Un({keepNativeChatGptOnV1:e})},Xn=async t=>{if(!(!Z||Be.current)){if(!Number.isInteger(t)||t<1){pe(!1,S(`models.v2ThreadsInvalid`));return}if(Z.maxConcurrentThreadsPerSession!==t){Le(!0),Be.current=!0,ze(``),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 Pt(n,S(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){ce(!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`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0}),ce(!0),X(S(`models.v2ThreadsApplied`)),We(!1)}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{Le(!1),Be.current=!1}}}},Zn=e=>{if(e===`custom`){We(!0),He(String(Z?.maxConcurrentThreadsPerSession??``));return}We(!1),Xn(Number(e))},Qn=(e,t)=>{en.current&&clearTimeout(en.current),en.current=setTimeout(()=>{$t({namespaced:e,rect:t.getBoundingClientRect()})},300)},$n=(e,t)=>{en.current&&clearTimeout(en.current),$t({namespaced:e,rect:t.getBoundingClientRect()})},er=()=>{en.current&&clearTimeout(en.current),en.current=setTimeout(()=>$t(null),120)},tr=()=>{en.current&&clearTimeout(en.current)},nr=async(t,n,r,i,a,o)=>{xt(!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 Pt(s,S(`models.customSaveFailed`)),Je(!1),pe(!0,S(`models.customAdded`)),await _n(!0)}catch(e){Ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{Ct(S(`models.networkError`))}finally{xt(!1)}},rr=async(t,n)=>{xt(!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 Pt(r,S(`models.customSaveFailed`)),Je(!1),pe(!0,S(`models.customUpdated`)),await _n(!0)}catch(e){Ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{Ct(S(`models.networkError`))}finally{xt(!1)}},ir=async t=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(pe(!0,S(`models.customDeleted`)),await _n(!0)):pe(!1,S(`models.customSaveFailed`))}catch{pe(!1,S(`models.networkError`))}},ar=gn.data??w,or=gn.kind===`failed-cold`?gn.error instanceof Error?gn.error.message:S(`models.loadFail`):null,sr=gn.showSkeleton&&!ar,cr=j??{},lr=e=>{let{provider:t,rows:n,nativeProviderGroup:r,liveModels:i,discovery:a}=e,o=ne.has(t),s=e=>Ff(cr,t,e.id,e.native===!0,k.has(e.namespaced)),c=n.filter(s).length,l=Ee?.recentArrivals[t]??[],u=new Set(l.map(e=>e.id)),d=L[t]!==void 0,f=L[t]??z,p=n.reduce((e,t)=>{let n=typeof t.contextWindow==`number`&&t.contextWindow>0?t.contextWindow:void 0;return n===void 0?e:e===void 0||n>e?n:e},void 0),m=d?f:r?Hf:p??f,h=e.nativeProviderGroup?Wf:Bf,g=e.nativeProviderGroup?Gf:Vf,_=i&&a?.status===`failed`?a:void 0,v=(N[t]??``).trim().toLowerCase(),y=v?n.filter(e=>e.id.toLowerCase().includes(v)):n,b=y.toSorted((e,t)=>Number(!s(e))-Number(!s(t))),x=F[t]??60,C=b.slice(0,x),w=y.length-C.length,T=n.length>0,E=!T||n.every(s),D=!T||n.every(e=>!s(e)),O=e=>{T&&Tn(`provider`,t,n.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,J.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,J.jsxs)(`div`,{className:`row group-head models-provider-head${o?``:` open`}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>On(t),"aria-expanded":!o,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,J.jsx)(Se,{style:{width:14,height:14,color:`var(--muted)`,transform:o?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,J.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:kn(t)}),Oe.providers[t]&&(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:Oe.providers[t]}),r&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.nativeGroupLabel`)}),_&&(0,J.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:Rf(S,_),children:S(`models.discoveryFailedBadge`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:S(`models.active`,{active:c,total:n.length})}),l.length>0&&(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:S(`models.newCount`,{count:l.length})})]}),(0,J.jsxs)(`div`,{className:`row models-provider-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":S(`models.editProviderAlias`),title:S(`models.editProviderAlias`),onClick:()=>void Xe(t),children:(0,J.jsx)(ge,{style:{width:14,height:14}})}),(0,J.jsx)(Tt,{on:Oe.defaults.providers[t]??Oe.defaults.global,onClick:()=>void Qe(!(Oe.defaults.providers[t]??Oe.defaults.global),t),label:S(`models.useDefaultAliases`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>bn(e),"aria-haspopup":`dialog`,children:S(`models.contextSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),et(`add`),nt(t),it(``),ot(``),ct(``),ut(``),ft(!1),mt([`text`]),gt(!1),vt([]),yt.current=!1,Ct(``),Je(!0)},"aria-label":S(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(()=>{let e=we[t];if(!e)return null;let n=Me===t,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.mode===r,className:`btn btn-sm${e.mode===r?` btn-primary`:` btn-ghost`}`,style:{background:e.mode===r?void 0:`transparent`,color:e.mode===r?void 0:`var(--muted)`},disabled:me||n,onClick:n=>{n.stopPropagation(),!(r===`preset`&&e.mode===`custom`&&!confirm(S(`models.presetConfirmReplace`,{count:String(e.presetCount)})))&&Jn(t,r)},children:S(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:S(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,J.jsx)(`span`,{className:`muted mono text-label`,children:S(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,J.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:S(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})(),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:me||E,onClick:()=>O(!0),children:S(`models.allOn`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:me||D,onClick:()=>O(!1),children:S(`models.allOff`)}),(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Tt,{on:d,onClick:()=>En(t,r),disabled:me,label:S(`models.capValue`,{value:Xf(m)})}),(d||r)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Dt,{value:ee[t]?`custom`:String(m),options:[...!g.has(m)&&!ee[t]?[{value:String(m),label:Xf(m)}]:[],...h.map(e=>({value:String(e),label:Xf(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>Fn(t,e),disabled:me||!d,label:S(`models.capValue`,{value:Xf(m)})}),ee[t]&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:q[t]??``,onChange:e=>Y(n=>({...n,[t]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&In(t)},disabled:me,"aria-label":S(`models.customPlaceholder`)}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>In(t),disabled:me,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]})]})]})]})]}),!o&&(0,J.jsxs)(`div`,{className:`models-provider-body`,children:[r&&(0,J.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:S(`models.nativeHint`)}),!r&&Ee&&(0,J.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:S(`models.newPolicyProvider`)}),(0,J.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.newPolicyProvider`),children:[`off`,`on`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Ee.providers[t]??`inherit`)===e,className:`btn btn-sm${(Ee.providers[t]??`inherit`)===e?` btn-primary`:` btn-ghost`}`,onClick:()=>void qn(e,t),children:S(`models.newPolicy_${e}`)},e))})]}),n.length===0&&(0,J.jsx)(tp,{liveModels:i,discovery:a,showFailureBadge:!1}),n.length>30&&(0,J.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`)}),C.map(e=>{let n=!s(e);return(0,J.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Qn(e.namespaced,t.currentTarget),onMouseLeave:er,onFocus:t=>$n(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||$t(null)},children:[(0,J.jsxs)(`div`,{className:`row models-model-row`,children:[(0,J.jsx)(Tt,{on:!n,onClick:()=>void Tn(`models`,t,[{id:e.id,native:e.native===!0}],n),disabled:me,label:e.native?e.id:e.namespaced}),Oe.models[t]?.[e.id]&&(0,J.jsx)(`strong`,{className:`mono text-control`,children:Oe.models[t][e.id].alias}),(0,J.jsx)(`code`,{className:`mono text-control`,style:{color:n?`var(--faint)`:`var(--text)`,textDecoration:n?`line-through`:`none`},children:e.native?il(e.id):An(e.namespaced,S)}),Oe.models[t]?.[e.id]?.source===`builtin`&&(0,J.jsx)(`span`,{className:`models-chip muted text-caption`,children:S(`models.aliasAuto`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":S(`models.editModelAlias`),title:S(`models.editModelAlias`),onClick:()=>void Ze(t,e.id),children:(0,J.jsx)(ge,{style:{width:13,height:13}})}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.customBadge`)}),!e.custom&&u.has(e.id)&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:S(`models.newBadge`)}),e.contextCapped&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.contextCappedValue`,{value:Xf(e.contextCap??z)})})]}),Qt?.namespaced===e.namespaced&&(()=>{let t=Qt.rect,r=t.bottom+4,i=r+360>window.innerHeight;return(0,J.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:tr,onMouseLeave:er,children:[(0,J.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,J.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:S(`models.customBadge`)}),(0,J.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipProvider`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:Dn(e.provider,S)}),(e.contextWindow||e.contextCap)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipContext`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:Xf(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipModalities`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipStatus`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:S(n?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,J.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{et(`edit`),nt(e.provider),it(e.customId),ot(e.id),ct(e.displayName??``),ut(e.contextWindow?String(e.contextWindow):``),ft(!1),mt(e.inputModalities??[`text`]),gt(Array.isArray(e.reasoningEfforts)),vt(e.reasoningEfforts??[]),yt.current=Array.isArray(e.reasoningEfforts),Ct(``),Je(!0),$t(null)},children:S(`models.customEdit`)}),(0,J.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}))&&ir(e.customId),$t(null)},children:S(`models.customDelete`)})]})]})})()]},e.namespaced)}),w>0&&(0,J.jsx)(`button`,{type:`button`,onClick:()=>I(e=>({...e,[t]:x+60})),className:`btn btn-ghost btn-sm models-show-more`,children:S(`models.showMore`,{n:w})})]})]},t)},ur=on?vn.filter(e=>e.provider===on):vn,dr=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`models-control-top-row`,children:[Ee&&(0,J.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,children:[(0,J.jsx)(`span`,{className:`models-shadow-label`,children:S(`models.newPolicyGlobal`)}),(0,J.jsx)(Tt,{on:Ee.policy===`off`,onClick:()=>void qn(Ee.policy===`off`?`on`:`off`),label:S(`models.newPolicyGlobal`)})]}),(0,J.jsxs)(`div`,{className:`row`,children:[(0,J.jsx)(Tt,{on:Oe.defaults.global,onClick:()=>void Qe(!Oe.defaults.global),label:S(`models.useDefaultAliasesGlobal`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>je(e=>!e),children:S(`models.aliases`)})]}),(0,J.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!tn||void 0,children:[(0,J.jsxs)(`span`,{className:`models-shadow-label`,children:[S(`models.shadowCallIntercept`),` `,(0,J.jsx)(kt,{content:S(`models.shadowCallInterceptHint`,{models:Rt(tn?.sourceModels)}),side:`top`,maxWidth:320,children:(0,J.jsx)(`span`,{style:{cursor:`help`},"aria-label":S(`models.shadowCallInterceptHint`,{models:Rt(tn?.sourceModels)}),children:`ⓘ`})})]}),(0,J.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:S(`models.shadowCallOriginal`,{models:zt(tn?.sourceModels)})}),(0,J.jsx)(Tt,{on:tn?.enabled??!1,onClick:()=>void Hn({enabled:!tn?.enabled}),disabled:!tn||rn,label:S(`models.shadowCallIntercept`)}),(0,J.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,J.jsx)(Dt,{value:tn?.model??``,options:ln,onChange:e=>{nn(t=>t&&{...t,model:e}),Hn({model:e})},disabled:!tn||rn||!tn.enabled,label:S(`models.shadowCallIntercept`)})})]}),(Pe||Z)&&(0,J.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2Label`)}),(0,J.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Z?.multiAgentMode??`default`)===e,className:`btn btn-sm${(Z?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(Z?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(Z?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!Z||Ie,onClick:()=>void Wn(e),children:S(`models.v2Mode_${e}`)},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},disabled:!Z,onClick:()=>Ke(!0),"aria-label":S(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,J.jsx)(ve,{width:14,height:14,"aria-hidden":`true`})})]}),Z&&Z.multiAgentMode===`v2`&&(0,J.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,J.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,J.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:S(`models.keepNativeOnV1`)}),(0,J.jsx)(Tt,{on:Z.keepNativeChatGptOnV1===!0,onClick:()=>void Yn(!Z.keepNativeChatGptOnV1),disabled:Ie,label:S(`models.keepNativeOnV1`)}),(0,J.jsx)(kt,{content:S(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,J.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":S(`models.keepNativeOnV1Hint`),children:(0,J.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})})]})})]}),Z&&(Z.enabled||Z.agentsMaxThreadsConflict||Re)&&(0,J.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[Z.enabled&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2ThreadsLabel`)}),(0,J.jsx)(Dt,{value:Ue?`custom`:Z.maxConcurrentThreadsPerSession!==null&&Z.maxConcurrentThreadsPerSession!==void 0?Jf.has(Z.maxConcurrentThreadsPerSession)?String(Z.maxConcurrentThreadsPerSession):`custom`:``,options:[...Z.maxConcurrentThreadsPerSession===null||Z.maxConcurrentThreadsPerSession===void 0?[{value:``,label:S(`models.v2ThreadsDefault`)}]:[],...Z.maxConcurrentThreadsPerSession!==null&&Z.maxConcurrentThreadsPerSession!==void 0&&!Jf.has(Z.maxConcurrentThreadsPerSession)&&!Ue?[{value:`custom`,label:String(Z.maxConcurrentThreadsPerSession)}]:[],...qf.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>Zn(e),disabled:Ie,label:S(`models.v2ThreadsLabel`)}),Ue&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:Ve,onChange:e=>He(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Xn(Number(Ve.replace(/[_,\s]/g,``)))},disabled:Ie,"aria-label":S(`models.v2ThreadsLabel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:Ie,onClick:()=>{Xn(Number(Ve.replace(/[_,\s]/g,``)))},children:S(`models.v2ThreadsApply`)})]})]}),Z.enabled&&Z.agentsMaxThreadsConflict&&(0,J.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:S(`models.v2Conflict`)}),Re&&(0,J.jsx)(`span`,{className:`muted text-label`,children:Re})]}),(0,J.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:S(`models.contextCapLabel`)}),(0,J.jsx)(Dt,{value:U?Kf:String(z),options:[...!Vf.has(z)&&!U?[{value:String(z),label:Xf(z)}]:[],...Bf.map(e=>({value:String(e),label:Xf(e)})),{value:Kf,label:S(`models.custom`)}],onChange:e=>Rn(e),disabled:me,label:S(`models.contextCapLabel`)}),U&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:V,onChange:e=>H(e.target.value),onKeyDown:e=>{e.key===`Enter`&&zn()},disabled:me,"aria-label":S(`models.customPlaceholder`)}),(0,J.jsx)(`button`,{type:`button`,onClick:zn,disabled:me,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]}),(0,J.jsx)(Tt,{on:Nn,onClick:Bn,disabled:me,label:S(`models.setAll`)}),(0,J.jsx)(`span`,{className:`muted text-label leading-body`,children:S(`models.setAllHint`,{value:Xf(z)})})]}),(()=>{let e=T.filter(e=>e.custom).length;return e===0?null:(0,J.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:S(`models.customSummary`,{count:e})})})})(),(0,J.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,J.jsx)(ve,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:S(`models.orderHint`)})]})]}),pr=(0,J.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>jn(!0),disabled:me,children:[(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`}),` `,S(`models.collapseAll`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>jn(!1),disabled:me,children:[(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,S(`models.expandAll`)]})]}),mr=(0,J.jsx)(J.Fragment,{children:vn.length===0&&(0,J.jsx)(Ot,{icon:(0,J.jsx)(re,{}),title:S(`models.noRouted`),children:S(`models.noRoutedHint`)})}),hr=(0,J.jsxs)(J.Fragment,{children:[Ge&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.v2Label`),onClick:()=>Ke(!1),onKeyDown:e=>{e.key===`Escape`&&Ke(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:S(`models.v2Label`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ke(!1),"aria-label":S(`common.close`),children:`×`})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:S(`models.v2Help`)}),(0,J.jsx)(`div`,{className:`models-help-link`,children:(0,J.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:S(`models.v2DocsLink`)})}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Ke(!1),children:S(`common.ok`)})})]})}),wt&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.contextSettings`),onClick:()=>{Jt||Et(null)},onKeyDown:e=>{e.key===`Escape`&&!Jt&&Et(null)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:S(`models.contextSettingsTitle`,{provider:Dn(wt,S)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Et(null),disabled:Jt,"aria-label":S(`common.close`),children:`×`})]}),Xt&&(0,J.jsx)($,{tone:`err`,children:Xt}),(0,J.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:S(`models.contextHint`)}),(0,J.jsxs)(`div`,{className:`models-context-fields`,children:[(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextDefault`),(0,J.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:It,onChange:e=>{Lt(e.target.value),qt(!0)},disabled:Jt,placeholder:S(`models.contextAutomatic`),autoFocus:!0})]}),At.length>0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.contextModel`),(0,J.jsx)(Dt,{value:Mt,options:At.map(e=>({value:e,label:e})),onChange:xn,disabled:Jt,label:S(`models.contextModel`)})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextModelOverride`),(0,J.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:Bt[Mt]??``,onChange:e=>{Vt(t=>({...t,[Mt]:e.target.value})),Gt(e=>new Set(e).add(Mt))},disabled:Jt,placeholder:S(`models.contextAutomatic`)})]})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Et(null),disabled:Jt,children:S(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void Sn(),disabled:Jt,children:S(Jt?`models.customSaving`:`models.customApply`)})]})]})}),qe&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.customAdd`),onClick:()=>{bt||Je(!1)},onKeyDown:e=>{e.key===`Escape`&&!bt&&Je(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:S($e===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:Dn(tt,S)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Je(!1),disabled:bt,"aria-label":S(`common.close`),children:`×`})]}),St&&(0,J.jsx)($,{tone:`err`,children:St}),(0,J.jsxs)(`div`,{className:`models-field-stack`,children:[(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldModelId`),(0,J.jsx)(`input`,{className:`input`,value:at,onChange:e=>ot(e.target.value),disabled:bt,placeholder:S(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldDisplayName`),(0,J.jsx)(`input`,{className:`input`,value:st,onChange:e=>ct(e.target.value),disabled:bt,placeholder:S(`models.customFieldDisplayNamePlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldContext`),(0,J.jsxs)(`div`,{className:`row models-field-row`,children:[(0,J.jsx)(Dt,{value:dt?`custom`:lt,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`){ft(!0);return}ft(!1),ut(e)},disabled:bt,label:S(`models.customFieldContext`)}),dt&&(0,J.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:lt,onChange:e=>ut(e.target.value),disabled:bt,placeholder:S(`models.customPlaceholder`),"aria-label":S(`models.customFieldContext`)})]})]}),(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldModalities`),(0,J.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:pt.includes(e),onChange:t=>{mt(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:bt}),(0,J.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldReasoning`),(0,J.jsx)(`div`,{className:`row models-field-row`,children:(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:ht,onChange:e=>{if(gt(e.target.checked),e.target.checked&&!yt.current){yt.current=!0;let e=T.find(e=>e.provider===tt&&e.id===at),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;vt(t??[...zf])}},disabled:bt}),(0,J.jsx)(`span`,{className:`text-control`,children:S(`models.customFieldReasoningOverride`)})]})}),ht&&(0,J.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:zf.map(e=>(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:_t.includes(e),onChange:t=>{vt(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:bt}),(0,J.jsx)(`span`,{className:`text-control`,children:S(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Je(!1),disabled:bt,children:S(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:bt||!at.trim(),onClick:()=>{let e=at.trim(),t=st.trim(),n=lt?Number(lt.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;if($e===`add`){let n=ht?_t:void 0;nr(tt,e,t||void 0,r,pt.length>0?pt:void 0,n)}else rr(rt,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:pt,reasoningEfforts:ht?_t:null})},children:S(bt?`models.customSaving`:$e===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),_r=(0,J.jsxs)(`div`,{className:`models-workspace-shell`,children:[oe&&(0,J.jsxs)(`div`,{className:`action-toast notice ${se?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[se?(0,J.jsx)(le,{}):(0,J.jsx)(_e,{}),(0,J.jsx)(`span`,{children:oe})]}),gn.showError&&(0,J.jsx)($,{tone:`err`,children:S(`models.loadFail`)}),(0,J.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":gn.refreshing||void 0,children:[(0,J.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":S(`nav.models`),children:[(0,J.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-title`,children:S(`models.workspace.providers`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-count`,children:vn.length})]}),(0,J.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${on===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>sn(null),"aria-current":on===null?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:S(`models.workspace.allProviders`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:Cn,total:T.length})})]}),vn.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>Ff(cr,t,e.id,e.native===!0,k.has(e.namespaced))).length;return(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${on===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>sn(t),"aria-current":on===t?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:Dn(t,S)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,J.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":S(`models.workspace.mainAria`),children:[dr,pr,Ae&&(0,J.jsxs)(`div`,{className:`card`,"aria-label":S(`models.aliasesTable`),children:[(0,J.jsx)(`div`,{className:`row group-head`,children:(0,J.jsx)(`strong`,{children:S(`models.aliases`)})}),Object.entries(Oe.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,J.jsxs)(`div`,{className:`row models-model-row`,children:[(0,J.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,J.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,J.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?S(`models.aliasAuto`):S(`models.aliasUser`)}),n.stale&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:S(`models.aliasStale`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":S(`models.editModelAlias`),onClick:()=>void Ze(e,t),children:(0,J.jsx)(ge,{style:{width:13,height:13}})})]},`${e}/${t}`)))]}),(0,J.jsx)(`div`,{className:`models-provider-list`,children:ur.map(e=>lr(e))}),vn.length===0&&mr]})]}),hr]});return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:S(`nav.models`)}),(0,J.jsx)(`div`,{className:`page-head-actions`,children:(0,J.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,J.jsx)(fe,{})})})]}),(0,J.jsx)(Vc,{state:n,controller:{restarting:o,restart:s}}),(0,J.jsx)(Of,{tab:c,onSelect:p,meta:wn}),(0,J.jsx)(`p`,{className:`page-sub`,children:S(np[c])}),(0,J.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Ef(`catalog`),"aria-labelledby":Tf(`catalog`),hidden:c!==`catalog`,children:(0,J.jsx)(ul,{pageName:S(`models.tab.catalog`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:sr?(0,J.jsx)(cl,{label:S(`models.loading`),rows:5}):or===null?_r:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($,{tone:`err`,children:or}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>hn.refresh(),children:S(`common.retry`)})]})})}),(0,J.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:Ef(`combos`),"aria-labelledby":Tf(`combos`),hidden:c!==`combos`,children:u.has(`combos`)&&(0,J.jsx)(ul,{pageName:S(`models.tab.combos`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,J.jsx)(Su,{apiBase:e,active:c===`combos`,onCountChange:g})})}),(0,J.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Ef(`routing`),"aria-labelledby":Tf(`routing`),hidden:c!==`routing`,children:u.has(`routing`)&&(0,J.jsx)(ul,{pageName:S(`models.tab.routing`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,J.jsx)(sd,{apiBase:e,active:c===`routing`,onCountChange:y})})}),(0,J.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Ef(`compatibility`),"aria-labelledby":Tf(`compatibility`),hidden:c!==`compatibility`,children:u.has(`compatibility`)&&(0,J.jsx)(ul,{pageName:S(`models.tab.compatibility`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,J.jsx)(bf,{apiBase:e,active:c===`compatibility`,onCountChange:x})})})]})}var ap=`section`;function op(e,t){return[e,ap,t].join(`-`)}function sp(e){return[e,ap,``].join(`-`)}var cp=1200;function lp({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(op(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(op(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(op(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(sp(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(op(e,t));n&&(a.current=t,o.current!==null&&clearTimeout(o.current),o.current=setTimeout(c,cp),i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,J.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,J.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":op(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>l(t.id),children:[t.label,t.meta?(0,J.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function up({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=Q(),m=(c.hintText??``).trim().length>0;return(0,J.jsxs)(`div`,{className:`swi-delegation`,children:[d&&(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeLoadFail`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`common.retry`)})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`sub.delegation.model`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.delegation.modelHint`)})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,J.jsx)(Dt,{value:e,options:[{value:``,label:p(`dash.injectionNone`)},...r.map(e=>({value:e.namespaced,label:An(`${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,J.jsx)(Dt,{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,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`dash.syncCodexSubagentDefaults`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,J.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,J.jsx)(`span`,{className:`knob`})})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`dash.multiAgentGuidance`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.multiAgentGuidanceHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":p(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,J.jsx)(`span`,{className:`knob`})})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${m?`on`:``}`,onClick:()=>u({multiAgentModeHintText:m?null:fp}),disabled:o||l||!m&&!c.multiAgentV2Enabled,"aria-label":p(`sub.ultraMode`),"aria-pressed":m,children:(0,J.jsx)(`span`,{className:`knob`})}),!c.multiAgentV2Enabled&&(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeV2Required`)})]}),m&&(0,J.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,J.jsx)(dp,{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 dp({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,_.useState)(e);return(0,J.jsxs)(J.Fragment,{children:[(0,J.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,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>o(r),disabled:t,children:i.preset}),(0,J.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 fp=`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 pp({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=Q(),[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,J.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,J.jsx)(lp,{scope:`subagents`,items:p,ariaLabel:s(`sub.sections`)}),(0,J.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,J.jsxs)(`section`,{id:op(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,J.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,J.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,J.jsx)(ve,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:(0,J.jsx)(ut,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,J.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,J.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,J.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,J.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,J.jsx)(`span`,{className:`swi-featured-name`,children:il(e)}),(0,J.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,-1),disabled:n||a===0,"aria-label":s(`sub.moveUp`,{m:e}),children:(0,J.jsx)(be,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,1),disabled:n||a===t.length-1,"aria-label":s(`sub.moveDown`,{m:e}),children:(0,J.jsx)(xe,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>r(e),disabled:n,"aria-label":s(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,J.jsx)(ue,{})})]})]},e))}),(0,J.jsx)(`div`,{className:`swi-save-row`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,J.jsxs)(`section`,{id:op(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,J.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,J.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,J.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,J.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,J.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,J.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:s(`sub.noModels`)}):f.map(e=>{let i=u.has(e),a=i?t.indexOf(e)+1:null,o=!i&&(d||n);return(0,J.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,J.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,J.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,J.jsx)(ie,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:il(e)})]}),(0,J.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${i?` subagents-workspace-rail-toggle--on`:``}${o?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{o||r(e)},disabled:o,"aria-pressed":i,"aria-label":s(i?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:i?s(`sub.workspace.removeFromFeatured`,{m:e}):d?s(`sub.workspace.featuredFull`):s(`sub.workspace.addToFeatured`,{m:e}),children:i?(0,J.jsx)(le,{style:{width:14,height:14}}):(0,J.jsx)(de,{style:{width:14,height:14}})})]},e)})})]})]}),(0,J.jsxs)(`section`,{id:op(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,J.jsx)(`div`,{className:`swi-featured-head`,children:(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,J.jsx)(up,{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 mp(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=Tr(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 Wt(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 Wt(n))}catch{}finally{i(!1)}}},[e,v,r])}}function hp(e){return fr(e)}function gp({apiBase:e}){let t=Q(),n=`ocx.subagents.v1:${e}`,r=hp(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=mp(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 Pt(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 Pt(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 r=>{let i=await Pt(await fetch(`${e}/api/subagent-models`,{signal:r}),t(`sub.loadFail`));if(!i)throw Error(t(`sub.loadFail`));let o=i.available??[],s=new Set(o),c={available:o,chosen:(i.chosen??[]).filter(e=>s.has(e))};return a(c.chosen),gr(n,c),c},[e,n,t]),D=ol(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 Pt(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),gr(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,J.jsx)(cl,{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,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($,{tone:`err`,children:e}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),children:t(`common.retry`)})]})}return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,J.jsx)($,{tone:c?`ok`:`err`,children:o}),O.showError&&(0,J.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),(0,J.jsx)(pp,{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 _p(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 vp(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 yp(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var bp=(e,t)=>Math.abs(e-t)<1.01,xp=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Sp,Cp=()=>{if(Sp!==void 0)return Sp;if(typeof navigator>`u`)return Sp=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Sp=!0;let e=navigator.maxTouchPoints;return Sp=navigator.platform===`MacIntel`&&e!==void 0&&e>0},wp=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Tp=e=>e,Ep=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},Dp=(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(wp(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(wp(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Op={passive:!0},kp=typeof window>`u`||`onscrollend`in window,Ap=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&kp,o=0,s=a?null:xp(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,Op),a&&r.addEventListener(`scrollend`,u,Op),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},jp=(e,t)=>Ap(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Mp=(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`]},Np=(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})},Pp=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:Tp,rangeExtractor:Ep,onChange:()=>{},measureElement:Mp,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=vp(()=>(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,!(!Cp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Op),e.addEventListener(`touchend`,n,Op),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&&(Cp()&&(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=vp(()=>[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=vp(()=>[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=_p(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=vp(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Lp(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=vp(()=>{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=vp(()=>[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 yp(t[Fp(0,t.length-1,r?e=>n[e*2]:e=>yp(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:Cp()&&(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&&bp(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()}},Fp=(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 Ip(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 Lp(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=Ip(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=Fp(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 Rp=typeof document<`u`?_.useLayoutEffect:_.useEffect;function zp({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,mt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=_.useState(()=>{let e=new Pp(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),Rp(()=>l._didMount(),[]),Rp(()=>(o(l),l._willUpdate())),Rp(()=>{s(l)}),l}function Bp(e){return zp({observeElementRect:Dp,observeElementOffset:jp,scrollToFn:Np,...e})}var Vp=32;function Hp(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Up(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 Wp(e){let t=e.trim();if(t&&!Up(t)&&!(t.length>4096))return Hp(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,Vp)}function Gp(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r||n!==void 0&&e===n:!1}var Kp={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},fr:{label:`Requête incorrecte`,description:`Le proxy n’a pas pu comprendre la requête. Vérifiez le modèle, la structure des messages, les en-têtes et le corps JSON avant de réessayer.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{label:`错误请求`,description:`代理无法理解该请求。重试前请检查模型、消息结构、标头和 JSON 正文。`},"zh-TW":{label:`錯誤請求`,description:`代理無法理解該請求。重試前請檢查模型、訊息結構、標頭和 JSON 本文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`},ru:{label:`Некорректный запрос`,description:`Прокси не смог интерпретировать запрос. Перед повторной попыткой проверьте модель, формат сообщений, заголовки и тело JSON.`},ja:{label:`不正なリクエスト`,description:`プロキシがリクエストを解釈できませんでした。再試行前にモデル、メッセージ形式、ヘッダー、JSON 本文を確認してください。`},tr:{label:`Hatalı istek`,description:`Proxy isteği anlayamadı. Yeniden denemeden önce modeli, mesaj yapısını, başlıkları ve JSON gövdesini kontrol edin.`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},fr:{label:`Non autorisé`,description:`Les identifiants sont absents, expirés ou non valides. Reconnectez-vous ou actualisez les identifiants du compte ou du fournisseur utilisés par opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{label:`未授权`,description:`凭据缺失、已过期或无效。请重新登录,或刷新 opencodex 使用的账号/提供商凭据。`},"zh-TW":{label:`未授權`,description:`憑證缺失、已過期或無效。請重新登入,或重新整理 opencodex 使用的帳號/供應商憑證。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`},ru:{label:`Не авторизован`,description:`Учётные данные отсутствуют, истекли или недействительны. Войдите заново или обновите учётные данные аккаунта или провайдера, которые использует opencodex.`},ja:{label:`認証が必要`,description:`認証情報が不在・期限切れ・無効です。opencodex が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`},tr:{label:`Yetkisiz erişim`,description:`Kimlik bilgileri eksik, süresi dolmuş veya geçersiz. opencodex tarafından kullanılan hesap veya sağlayıcı kimlik bilgilerini yeniden doğrulayın.`}},402:{en:{label:`Payment required`,description:`The upstream provider rejected the request because billing, credits, or plan access is not available. Add credits, update billing, or switch provider.`},fr:{label:`Paiement requis`,description:`Le fournisseur en amont a rejeté la requête, car la facturation, les crédits ou l’accès à l’offre ne sont pas disponibles. Ajoutez des crédits, mettez à jour la facturation ou changez de fournisseur.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{label:`需要付款`,description:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},"zh-TW":{label:`需要付款`,description:`上游供應商因帳單、額度或方案許可權不可用而拒絕了請求。請儲值、更新帳單資訊或切換供應商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`},ru:{label:`Требуется оплата`,description:`Вышестоящий провайдер отклонил запрос из-за проблем с оплатой, кредитами или доступом по тарифному плану. Пополните баланс, обновите платёжные данные или переключитесь на другого провайдера.`},ja:{label:`支払いが必要`,description:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`},tr:{label:`Ödeme gerekli`,description:`Yukarı akış sağlayıcısı faturalandırma, kredi veya plan erişimi bulunmadığından isteği reddetti. Kredi ekleyin, ödeme bilgilerini güncelleyin veya sağlayıcı değiştirin.`}},403:{en:{label:`Forbidden`,description:`The account is authenticated but not allowed to use this model or operation. Often a plan/subscription gate (e.g. Ollama Cloud Pro), org policy, or model permission — not necessarily a bad API key.`},fr:{label:`Accès interdit`,description:`Le compte est authentifié, mais n’est pas autorisé à utiliser ce modèle ou cette opération. Il s’agit souvent d’une restriction liée à l’offre ou à l’abonnement (p. ex. Ollama Cloud Pro), à la politique de l’organisation ou aux autorisations du modèle — pas nécessairement d’une clé API incorrecte.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다.`},zh:{label:`禁止访问`,description:`账号已认证,但无权使用此模型或操作。常见原因是套餐/订阅限制(例如 Ollama Cloud Pro)、组织策略或模型权限——不一定是 API 密钥无效。`},"zh-TW":{label:`禁止存取`,description:`帳號已認證,但無權使用此模型或操作。常見原因是方案/訂閱限制(例如 Ollama Cloud Pro)、組織策略或模型許可權——不一定是 API 金鑰無效。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Oft Plan-/Abo-Sperre (z. B. Ollama Cloud Pro), Organisationsrichtlinie oder Modellrecht — nicht zwingend ein ungültiger API-Key.`},ru:{label:`Доступ запрещён`,description:`Аккаунт аутентифицирован, но не имеет права использовать эту модель или операцию. Часто причина — ограничение тарифа или подписки (например, Ollama Cloud Pro), политика организации или права доступа к модели, а не обязательно неверный API-ключ.`},ja:{label:`アクセス禁止`,description:`アカウントは認証済みですがこのモデルや操作の使用が許可されていません。多くはプラン/サブスクリプション制限(例: Ollama Cloud Pro)、組織ポリシー、モデル権限であり、API キーが不正とは限りません。`},tr:{label:`Erişim yasaklandı`,description:`Hesabın kimliği doğrulandı ancak bu modeli veya işlemi kullanma izni yok. Genellikle plan/abonelik sınırı (örn. Ollama Cloud Pro), organizasyon politikası veya model izni kaynaklıdır.`}},404:{en:{label:`Not found`,description:`The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration.`},fr:{label:`Introuvable`,description:`La route, le modèle, le compte ou la ressource en amont demandés sont introuvables. Vérifiez le nom du modèle et la configuration du fournisseur opencodex.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{label:`未找到`,description:`找不到请求的路由、模型、账号或上游资源。请确认模型名称和 opencodex 提供商配置。`},"zh-TW":{label:`未找到`,description:`找不到請求的路由、模型、帳號或上游資源。請確認模型名稱和 opencodex 供應商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`},ru:{label:`Не найдено`,description:`Запрошенный маршрут, модель, аккаунт или вышестоящий ресурс не найден. Проверьте имя модели и конфигурацию провайдера в opencodex.`},ja:{label:`見つかりません`,description:`要求されたルート、モデル、アカウント、上流リソースが見つかりませんでした。モデル名と opencodex プロバイダー設定を確認してください。`},tr:{label:`Bulunamadı`,description:`İstenen rota, model, hesap veya yukarı akış kaynağı bulunamadı. Model adını ve opencodex sağlayıcı yapılandırmasını doğrulayın.`}},408:{en:{label:`Request timeout`,description:`The request took too long before the proxy or upstream provider could complete it. Retry with a smaller request or a different provider.`},fr:{label:`Délai d’attente de la requête dépassé`,description:`La requête a pris trop de temps pour que le proxy ou le fournisseur en amont puisse la traiter. Réessayez avec une requête plus petite ou un autre fournisseur.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{label:`请求超时`,description:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},"zh-TW":{label:`請求逾時`,description:`代理或上游供應商未能在限定時間內完成請求。請縮小請求後重試,或切換供應商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`},ru:{label:`Тайм-аут запроса`,description:`Обработка запроса заняла слишком много времени, и прокси или вышестоящий провайдер не успел её завершить. Повторите попытку с меньшим запросом или через другого провайдера.`},ja:{label:`リクエストタイムアウト`,description:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`},tr:{label:`İstek zaman aşımı`,description:`Proxy veya yukarı akış sağlayıcısı isteği tamamlayamadan zaman aşımına uğradı. Daha küçük bir istek veya farklı bir sağlayıcı ile tekrar deneyin.`}},409:{en:{label:`Conflict`,description:`The request conflicts with the current account, session, or provider state. Refresh the session or retry after the active operation finishes.`},fr:{label:`Conflit`,description:`La requête entre en conflit avec l’état actuel du compte, de la session ou du fournisseur. Actualisez la session ou réessayez une fois l’opération en cours terminée.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{label:`状态冲突`,description:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},"zh-TW":{label:`狀態衝突`,description:`請求與當前帳號、會話或供應商狀態衝突。請重新整理會話,或等待當前操作完成後重試。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`},ru:{label:`Конфликт`,description:`Запрос конфликтует с текущим состоянием аккаунта, сессии или провайдера. Обновите сессию или повторите попытку после завершения текущей операции.`},ja:{label:`状態の衝突`,description:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`},tr:{label:`Durum çakışması`,description:`İstek mevcut hesap, oturum veya sağlayıcı durumuyla çakışıyor. Oturumu yenileyin veya aktif işlem bittikten sonra tekrar deneyin.`}},413:{en:{label:`Request too large`,description:`The prompt, attachments, or generated payload exceeds a proxy or upstream limit. Reduce tokens, file size, or conversation history.`},fr:{label:`Requête trop volumineuse`,description:`L’invite, les pièces jointes ou la charge utile générée dépassent une limite du proxy ou du fournisseur en amont. Réduisez le nombre de jetons, la taille des fichiers ou l’historique de la conversation.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{label:`请求过大`,description:`提示、附件或生成的负载超过了代理或上游限制。请减少 token、文件大小或对话历史。`},"zh-TW":{label:`請求過大`,description:`提示、附件或生成的負載超過了代理或上游限制。請減少 token、檔案大小或對話歷史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`},ru:{label:`Слишком большой запрос`,description:`Промпт, вложения или сформированная полезная нагрузка превышают лимит прокси или вышестоящего провайдера. Сократите количество токенов, размер файлов или историю диалога.`},ja:{label:`リクエストが大きすぎます`,description:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`},tr:{label:`İstek çok büyük`,description:`İstemi, ekler veya oluşturulan veri proxy ya da yukarı akış sınırını aşıyor. Jeton sayısını, dosya boyutunu veya sohbet geçmişini azaltın.`}},422:{en:{label:`Invalid content`,description:`The provider accepted the request format but rejected its contents. Check model options, tool definitions, message roles, and unsupported fields.`},fr:{label:`Contenu non valide`,description:`Le fournisseur a accepté le format de la requête, mais en a rejeté le contenu. Vérifiez les options du modèle, les définitions des outils, les rôles des messages et les champs non pris en charge.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{label:`内容无效`,description:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},"zh-TW":{label:`內容無效`,description:`供應商接受了請求格式,但拒絕了其中的內容。請檢查模型選項、工具定義、訊息角色和不支援的欄位。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`},ru:{label:`Недопустимое содержимое`,description:`Провайдер принял формат запроса, но отклонил его содержимое. Проверьте параметры модели, определения инструментов, роли сообщений и неподдерживаемые поля.`},ja:{label:`内容の検証失敗`,description:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`},tr:{label:`Geçersiz içerik`,description:`Sağlayıcı istek formatını kabul etti ancak içeriğini reddetti. Model seçeneklerini, araç tanımlarını, mesaj rollerini ve desteklenmeyen alanları kontrol edin.`}},424:{en:{label:`Provider dependency failed`,description:`A required upstream dependency failed while opencodex was routing the request. Retry later or switch to another configured provider.`},fr:{label:`Échec d’une dépendance du fournisseur`,description:`Une dépendance en amont requise a échoué pendant le routage de la requête par opencodex. Réessayez plus tard ou sélectionnez un autre fournisseur configuré.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{label:`提供商依赖失败`,description:`opencodex 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},"zh-TW":{label:`供應商依賴失敗`,description:`opencodex 路由請求時,必需的上游依賴失敗。請稍後重試,或切換到另一個已配置的供應商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`},ru:{label:`Сбой зависимости провайдера`,description:`Необходимая вышестоящая зависимость дала сбой, пока opencodex маршрутизировал запрос. Повторите попытку позже или переключитесь на другого настроенного провайдера.`},ja:{label:`プロバイダー依存の失敗`,description:`opencodex がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı bağımlılığı başarısız`,description:`opencodex isteği yönlendirirken gerekli bir yukarı akış bağımlılığı başarısız oldu. Daha sonra tekrar deneyin veya başka bir sağlayıcıya geçin.`}},429:{en:{label:`Rate limited`,description:`The upstream provider rate or quota limit has been reached. Wait for the quota window to reset or switch account/provider.`},fr:{label:`Limite de débit atteinte`,description:`La limite de débit ou de quota du fournisseur en amont a été atteinte. Attendez la réinitialisation de la fenêtre de quota ou changez de compte ou de fournisseur.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{label:`限流`,description:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},"zh-TW":{label:`限流`,description:`已達到上游供應商的速率或額度限制。請等待額度視窗重設,或切換帳號/供應商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`},ru:{label:`Превышен лимит запросов`,description:`Достигнут лимит скорости или квота вышестоящего провайдера. Дождитесь сброса окна квоты или переключитесь на другой аккаунт или провайдера.`},ja:{label:`レート制限`,description:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`},tr:{label:`Oran sınırı aşıldı`,description:`Yukarı akış sağlayıcısının hız veya kota sınırına ulaşıldı. Kota penceresinin sıfırlanmasını bekleyin ya da hesap/sağlayıcı değiştirin.`}},499:{en:{label:`Client closed request`,description:`The client disconnected or canceled the request before opencodex finished routing it. Retry if the cancellation was accidental.`},fr:{label:`Requête fermée par le client`,description:`Le client s’est déconnecté ou a annulé la requête avant la fin de son routage par opencodex. Réessayez si l’annulation était involontaire.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{label:`客户端已取消`,description:`opencodex 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},"zh-TW":{label:`客戶端已取消`,description:`opencodex 完成路由前,客戶端已斷開連線或取消請求。如果不是有意取消,請重試。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`},ru:{label:`Запрос закрыт клиентом`,description:`Клиент отключился или отменил запрос до того, как opencodex завершил его маршрутизацию. Если отмена была случайной, повторите попытку.`},ja:{label:`クライアントがリクエストをクローズ`,description:`opencodex がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`},tr:{label:`İstemci isteği kapattı`,description:`opencodex yönlendirmeyi bitirmeden önce istemci bağlantıyı kesti veya isteği iptal etti. İptal kazara yapıldıysa tekrar deneyin.`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},fr:{label:`Erreur du proxy`,description:`opencodex a rencontré une erreur interne lors du traitement de la requête. Réessayez une fois, puis consultez les journaux du proxy si l’erreur se reproduit.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{label:`代理错误`,description:`opencodex 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},"zh-TW":{label:`代理錯誤`,description:`opencodex 處理請求時發生內部錯誤。請先重試一次;如果重複出現,請檢查代理日誌。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`},ru:{label:`Ошибка прокси`,description:`В opencodex произошла внутренняя ошибка при обработке запроса. Повторите попытку один раз; если ошибка повторяется, проверьте логи прокси.`},ja:{label:`プロキシエラー`,description:`opencodex がリクエスト処理中に内部エラーに遭遇しました。1 回再試行し、繰り返す場合はプロキシログを確認してください。`},tr:{label:`Proxy hatası`,description:`opencodex isteği işlerken dahili bir hatayla karşılaştı. Bir kez tekrar deneyin, tekrarlarsa proxy günlüklerini kontrol edin.`}},502:{en:{label:`Bad upstream response`,description:`The upstream provider returned an invalid or failed response through the proxy. Retry or route the request to another provider.`},fr:{label:`Réponse incorrecte du fournisseur en amont`,description:`Le fournisseur en amont a renvoyé une réponse non valide ou en échec par l’intermédiaire du proxy. Réessayez ou acheminez la requête vers un autre fournisseur.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`上游响应错误`,description:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},"zh-TW":{label:`上游回應錯誤`,description:`上游供應商透過代理返回了無效或失敗的回應。請重試,或將請求路由到其他供應商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Некорректный ответ провайдера`,description:`Вышестоящий провайдер вернул через прокси недействительный или ошибочный ответ. Повторите попытку или направьте запрос другому провайдеру.`},ja:{label:`上流レスポンス不良`,description:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Kötü yukarı akış yanıtı`,description:`Yukarı akış sağlayıcısı proxy üzerinden geçersiz veya başarısız bir yanıt döndürdü. Tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},fr:{label:`Fournisseur indisponible`,description:`Le proxy ou le fournisseur en amont est temporairement indisponible ou surchargé. Patientez un instant, puis réessayez ou changez de fournisseur.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{label:`提供商不可用`,description:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},"zh-TW":{label:`供應商不可用`,description:`代理或上游供應商暫時不可用或過載。請稍後重試,或切換供應商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`},ru:{label:`Провайдер недоступен`,description:`Прокси или вышестоящий провайдер временно недоступен или перегружен. Немного подождите, затем повторите попытку или смените провайдера.`},ja:{label:`プロバイダー利用不可`,description:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`},tr:{label:`Sağlayıcı kullanılamıyor`,description:`Proxy veya yukarı akış sağlayıcısı geçici olarak kullanılamıyor veya aşırı yüklü. Kısa bir süre bekleyip tekrar deneyin ya da sağlayıcı değiştirin.`}},504:{en:{label:`Upstream timeout`,description:`The upstream provider did not respond before the proxy timeout. Retry with a smaller request or choose a faster provider.`},fr:{label:`Délai d’attente du fournisseur en amont dépassé`,description:`Le fournisseur en amont n’a pas répondu avant l’expiration du délai du proxy. Réessayez avec une requête plus petite ou choisissez un fournisseur plus rapide.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{label:`上游超时`,description:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},"zh-TW":{label:`上游逾時`,description:`上游供應商未在代理逾時前回應。請縮小請求後重試,或選擇回應更快的供應商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`},ru:{label:`Тайм-аут вышестоящего провайдера`,description:`Вышестоящий провайдер не ответил до истечения тайм-аута прокси. Повторите попытку с меньшим запросом или выберите более быстрого провайдера.`},ja:{label:`上流タイムアウト`,description:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`},tr:{label:`Yukarı akış zaman aşımı`,description:`Yukarı akış sağlayıcısı proxy zaman aşımı süresinden önce yanıt vermedi. Daha küçük bir istekle tekrar deneyin veya daha hızlı bir sağlayıcı seçin.`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},fr:{label:`Fournisseur surchargé`,description:`Le fournisseur en amont est surchargé ou sa capacité est limitée. Patientez et réessayez, ou changez de compte ou de fournisseur.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{label:`提供商过载`,description:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},"zh-TW":{label:`供應商過載`,description:`上游供應商過載或容量受限。請等待後重試,或切換到其他帳號/供應商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`},ru:{label:`Провайдер перегружен`,description:`Вышестоящий провайдер перегружен или ограничен по мощности. Подождите и повторите попытку либо переключитесь на другой аккаунт или провайдера.`},ja:{label:`プロバイダー過負荷`,description:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı aşırı yüklü`,description:`Yukarı akış sağlayıcısı aşırı yüklü veya kapasitesi sınırlı. Bekleyip tekrar deneyin veya başka bir hesap/sağlayıcıya geçin.`}}},qp={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},fr:{label:`Erreur de requête`,description:`Le proxy ou le fournisseur en amont a rejeté la requête. Vérifiez sa structure, les identifiants, le nom du modèle et la configuration du fournisseur.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{label:`请求错误`,description:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},"zh-TW":{label:`請求錯誤`,description:`代理或上游供應商拒絕了該請求。請檢查請求結構、憑證、模型名稱和供應商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`},ru:{label:`Ошибка запроса`,description:`Прокси или вышестоящий провайдер отклонил запрос. Проверьте структуру запроса, учётные данные, имя модели и конфигурацию провайдера.`},ja:{label:`リクエストエラー`,description:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`},tr:{label:`İstek hatası`,description:`Proxy veya yukarı akış sağlayıcısı isteği reddetti. İstek yapısını, kimlik bilgilerini, model adını ve sağlayıcı yapılandırmasını kontrol edin.`}},server:{en:{label:`Server or upstream error`,description:`opencodex or an upstream provider failed while processing the request. Retry later or route the request to another provider.`},fr:{label:`Erreur du serveur ou du fournisseur en amont`,description:`opencodex ou un fournisseur en amont a échoué lors du traitement de la requête. Réessayez plus tard ou acheminez la requête vers un autre fournisseur.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`服务器或上游错误`,description:`opencodex 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},"zh-TW":{label:`伺服器或上游錯誤`,description:`opencodex 或上游供應商處理請求時失敗。請稍後重試,或將請求路由到其他供應商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Ошибка сервера или провайдера`,description:`opencodex или вышестоящий провайдер завершил обработку запроса с ошибкой. Повторите попытку позже или направьте запрос другому провайдеру.`},ja:{label:`サーバーまたは上流エラー`,description:`opencodex または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Sunucu veya yukarı akış hatası`,description:`opencodex veya bir yukarı akış sağlayıcısı isteği işlerken başarısız oldu. Daha sonra tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}}};function Jp(e){return e.toLowerCase().startsWith(`fr`)?`fr`:e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function Yp(e,t){if(e<400)return null;let n=Jp(t);return(Kp[Math.trunc(e)]??(e<500?qp.client:qp.server))[n]}var Xp=[`provider`,`usage`,`injection`];function Zp(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function Qp(e){return new Date(e).toLocaleTimeString()}function $p(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function em(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function tm({entries:e}){let{t}=ct();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,J.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,J.jsx)(`div`,{style:{overflowX:`auto`},children:(0,J.jsxs)(`table`,{className:`table text-label`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,J.jsx)(`th`,{children:`thinking`}),(0,J.jsx)(`th`,{children:`effort`}),(0,J.jsx)(`th`,{children:`beta`}),(0,J.jsx)(`th`,{children:`metadata`}),(0,J.jsx)(`th`,{children:`system`})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted mono`,children:Qp(e.at)}),(0,J.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,J.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,J.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,J.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,J.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,J.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,J.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function nm({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=ct();return e?n?r.length===0?(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,J.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,J.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,J.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Zp(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function rm({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=ct();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=em(e,n);return(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,J.jsx)(Tt,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,J.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:i,children:o(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,J.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function im({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=ct();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,J.jsx)(`h2`,{children:o(`debug.title`)}),(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,J.jsx)(fe,{}),` `,o(`debug.refresh`)]}),(0,J.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function am(e){return`debug-settings:${e}`}function om({apiBase:e,embedded:t,active:n=!0}){let{t:r}=ct(),i=`ocx.debug.settings.v1:${e}`,a=fr(i),o=am(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=ol(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 gr(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),T=w.state,E=w.data??a??null,D=G(`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=Bp({count:d.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>d[e].seq}),k=(0,_.useCallback)(e=>$p(E,e),[E]);(0,_.useEffect)(()=>{if(!E||k(l))return;let e=Xp.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,_.useRef)(!1),P=(0,_.useEffectEvent)(()=>{if(N.current)return;N.current=!0;let e=Ln(1e4);M(!1,e.signal).finally(()=>{e.clear(),N.current=!1})});(0,_.useEffect)(()=>{if(!(!n||!p||!A))return Vn(()=>P(),1e3)},[n,p,A]),(0,_.useEffect)(()=>{p&&d.length>0&&O.scrollToIndex(d.length-1,{align:`end`})},[d,p,O]);let F=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;gr(i,a),K(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)}},I=async(e,t)=>{await F({[e]:t})},L=async()=>{await F({reset:!0})};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(im,{embedded:t,refreshing:h,streamEnabled:A,follow:p,onRefresh:()=>void M(!0),onFollowChange:m}),!E&&T.showError?(0,J.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,J.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:r(`common.retry`)})]}):T.showSkeleton&&!E?(0,J.jsx)(cl,{label:r(`debug.loading`),rows:3}):E?(0,J.jsx)(rm,{debug:E,debugBusy:s,stream:l,onSetFlag:(e,t)=>{I(e,t)},onReset:()=>{L()},onStreamChange:u}):null,E&&T.showError&&(0,J.jsx)($,{tone:`err`,children:r(`debug.loadFailed`)}),E?.claude&&(0,J.jsx)(tm,{entries:D}),(0,J.jsx)(nm,{debug:!!E,stream:l,streamEnabled:A,entries:d,scrollContainerRef:S,lineVirtualizer:O})]})}function sm(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function cm(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function lm(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),cm(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),cm(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function um(e,t){return[`${t(`logs.modelTooltip.model`)}=${e.model}`,e.resolvedModel?`${t(`logs.modelTooltip.resolvedModel`)}=${e.resolvedModel}`:void 0,e.requestedServiceTier?`${t(`logs.modelTooltip.requestedTier`)}=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`${t(`logs.modelTooltip.configuredTier`)}=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`${t(`logs.modelTooltip.responseTier`)}=${e.responseServiceTier}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function dm(e){return e.requestedSpeedLabel||void 0}function fm(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=new Intl.NumberFormat(n,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function pm(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):fm(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function mm(e){let t=0,n=!0,r=0,i=0,a=0;for(let o of e){if(o.usageStatus===`unsupported`){a+=1;continue}let e=o.displayMetrics?.cost;if(e?.kind===`value`){let i=e.estimate.cost.total;if(Number.isFinite(i)&&i>=0){t+=i,r+=1,n&&=e.estimate.priorityLowerBound===!0;continue}}i+=1}return{estimatedCostUsd:t,priorityLowerBound:r>0&&n,unpricedRequests:i,unmeteredRequests:a}}function hm(e){return e===`cursor`||e.startsWith(`cursor-`)}function gm(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 _m(e,t){if(!e.usage)return;let n=gm(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(hm(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function vm(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 ym(e){return e===void 0||typeof e==`string`}function bm(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!ym(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!ym(e.profile.id)||!ym(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!ym(e.selected.provider)||!ym(e.selected.model)||!ym(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`||!ym(t.provider)||!ym(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`||!ym(e.code))return!1}}return!0}function xm(e){if(e.routeDecision===void 0||bm(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function Sm(e){return`ocx.logs.list.v1:${e}`}function Cm(e){if(!Array.isArray(e))return null;for(let t of e)if(!t||typeof t!=`object`||typeof t.timestamp!=`number`||typeof t.model!=`string`||typeof t.provider!=`string`||typeof t.status!=`number`||typeof t.durationMs!=`number`||t.shadowCallRewrittenFrom!==void 0&&typeof t.shadowCallRewrittenFrom!=`string`||!bm(t.routeDecision))return null;return e}function wm(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 Tm(e){let t=wm(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function Em(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 Dm(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function Om(e,t){if(!e||e.kind===`unavailable`||!Number.isFinite(e.value)||e.value<=0)return`—`;let n=e.value>=100?0:1,r=new Intl.NumberFormat(t,{minimumFractionDigits:n,maximumFractionDigits:n}).format(e.value);return`${e.estimated?`~`:``}${r}`}var km=2e3,Am=4,jm=3,Mm={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`},Nm={usage_estimated:`logs.detail.estimate.usage_estimated`,cache_detail_missing:`logs.detail.estimate.cache_detail_missing`,expected_price_overlay:`logs.detail.estimate.expected_price_overlay`,provider_cost_overlay:`logs.detail.estimate.provider_cost_overlay`,priority_lower_bound:`logs.detail.estimate.priority_lower_bound`},Pm={"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 Fm(e){return Mm[e]}function Im(e){return Nm[e]}function Lm(e){return Pm[e]??`logs.detail.attempt.recovery.unknown`}function Rm(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function zm(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function Bm(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 Vm(e,t,n){let{date:r,time:i}=Bm(e,t,n);return`${r} ${i}`}function Hm(e){let t=0;for(let n of e){let e=wm(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...mm(e)}}function Um({apiBase:e}){let{t,locale:n}=ct(),r=Sm(e),i=Cm(fr(r)),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)({error:null,count:0}),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(`all`),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(),b=(0,_.useRef)(null),x=(0,_.useRef)({key:r,failures:0,nextAttemptAt:0,error:null}),S=et.find(e=>e.code===n)?.htmlLang,[C,w]=(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()&&w(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[T,E]=(0,_.useState)(sm),[D,O]=(0,_.useState)(()=>sm()===`debug`);(0,_.useEffect)(()=>{let e=()=>E(sm());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{T===`debug`&&O(!0)},[T]);let k=cm,A=(0,_.useCallback)(async t=>{let n=x.current;if(n.key!==r&&(n={key:r,failures:0,nextAttemptAt:0,error:null},x.current=n),n.failures>0&&Date.now()<n.nextAttemptAt)throw n.error;try{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(xm);return x.current={key:r,failures:0,nextAttemptAt:0,error:null},gr(r,a),a}catch(e){if(t.aborted)throw e;let i=e??Error(`log request failed`),a=n.failures+1,o=km*2**Math.min(a,Am);throw x.current={key:r,failures:a,nextAttemptAt:Date.now()+o,error:i},i}},[e,r]),j=ol(r,[e],A,{isEmpty:e=>e.length===0,enabled:T===`logs`,pollMs:a?km:void 0,initialData:i??void 0}),M=j.state,N=M.data??i??[],P=j.refresh,F=(0,_.useCallback)(()=>{x.current={key:r,failures:0,nextAttemptAt:0,error:null},P({forceLoading:!0})},[P,r]),I=!j.refreshing&&M.showError;!j.refreshing&&!M.showError&&M.data!==void 0&&s.count!==0?c({error:null,count:0}):I&&s.error!==M.error&&c(e=>({error:M.error,count:e.count+1}));let L=s.count>=jm||!a&&I,R=l?Yp(l.status,n):null,z=h.trim();(0,_.useEffect)(()=>{let e=!1;if(!z){y(void 0);return}return Wp(z).then(t=>{e||y(t)}),()=>{e=!0}},[z]);let B=N.filter(e=>vm(e,d)&&(!p||!!e.shadowCallRewrittenFrom)&&(!z||Gp(e.conversationId,z,v))),V=z?Hm(B):null,H=Bp({count:B.length,getScrollElement:()=>b.current,estimateSize:()=>44,overscan:15}),U=H.getVirtualItems(),W=U.length>0?U[0].start:0,ee=U.length>0?H.getTotalSize()-U[U.length-1].end:0;return(0,J.jsxs)(`div`,{className:`logs-page`,children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.logs`)}),T===`logs`&&(0,J.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,J.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":T===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:T===`logs`?0:-1,className:`page-tab${T===`logs`?` page-tab--active`:``}`,onClick:()=>k(`logs`),onKeyDown:lm,children:t(`logs.tabLogs`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":T===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:T===`debug`?0:-1,className:`page-tab${T===`debug`?` page-tab--active`:``}`,onClick:()=>k(`debug`),onKeyDown:lm,children:t(`logs.tabDebug`)})]}),D&&(0,J.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:T!==`debug`,children:(0,J.jsx)(om,{apiBase:e,embedded:!0,active:T===`debug`})}),(0,J.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:T!==`logs`,children:[(0,J.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,J.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,J.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":d===e,className:`btn btn-sm${d===e?` btn-primary`:` btn-ghost`}`,style:{background:d===e?void 0:`transparent`,color:d===e?void 0:`var(--muted)`},onClick:()=>f(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),t(`logs.filter.interceptedHelpersOnly`)]}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,J.jsx)(`input`,{type:`search`,className:`input mono`,value:h,onChange:e=>g(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),z&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g(``),children:t(`logs.filter.conversation.clear`)})]}),V&&(0,J.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,J.jsxs)($,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:V.requests,tokens:Pn(V.totalTokens,S??n),cost:fm(V.estimatedCostUsd,t,S,V.priorityLowerBound)}),` `,(0,J.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),V.unpricedRequests+V.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:V.unpricedRequests,unmetered:V.unmeteredRequests})}`:``]})]})}),M.kind===`failed-cold`&&(0,J.jsxs)($,{tone:`err`,children:[M.error instanceof Error?`${t(`logs.loadError`)} ${M.error.message}`:t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:M.refreshing,children:t(`common.retry`)})]}),L&&N.length>0&&(0,J.jsxs)($,{tone:`err`,children:[t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:j.refreshing,children:t(`common.retry`)})]}),M.kind===`failed-cold`?null:M.showSkeleton&&N.length===0?(0,J.jsx)(cl,{label:t(`common.loading`),rows:6}):B.length===0?(0,J.jsx)(Ot,{title:t(`logs.noRequests`)}):(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{ref:b,className:`tbl-wrap logs-table-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`logs.col.time`)}),(0,J.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,J.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,J.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,J.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,J.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,J.jsx)(`th`,{children:t(`logs.col.status`)}),(0,J.jsx)(`th`,{children:t(`logs.col.request`)}),(0,J.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,J.jsxs)(`tbody`,{children:[W>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:W}})}),U.map(e=>{let r=B[B.length-1-e.index],i=Dm(r),a=Bm(r.timestamp,S,C);return(0,J.jsxs)(`tr`,{"data-index":e.index,ref:H.measureElement,children:[(0,J.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:a.date}),(0,J.jsx)(`span`,{children:a.time})]})}),(0,J.jsx)(`td`,{className:`num mono log-col-tokens`,title:_m(r,t),children:(()=>{let e=Tm(r),{read:i,write:a}=gm(r);return e===void 0?(0,J.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,J.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,J.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Pn(e,n)]}),i!==void 0&&i>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,Pn(i,n)]}),a!==void 0&&a>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,Pn(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(hm(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,J.jsx)(`td`,{className:`num mono log-col-rate`,children:Om(r.displayMetrics?.tokPerSecond,S)}),(0,J.jsx)(`td`,{className:`num mono log-col-cost`,children:pm(r.displayMetrics?.cost,t,S)}),(0,J.jsx)(`td`,{className:`mono log-col-model`,title:um(r,t),children:(0,J.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,J.jsx)(`span`,{children:il(r.resolvedModel??r.model)}),r.shadowCallRewrittenFrom&&(0,J.jsx)(`span`,{className:`badge badge-muted`,style:{whiteSpace:`nowrap`},title:t(`logs.badge.interceptedHelperTitle`),children:t(`logs.badge.interceptedHelper`,{model:r.shadowCallRewrittenFrom})}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),dm(r)&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:dm(r)})]})}),(0,J.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:Em(r)}),i&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,J.jsx)(`td`,{className:`muted`,children:Dn(r.provider,t)}),(0,J.jsx)(`td`,{children:(0,J.jsxs)(`span`,{className:`log-status-cell`,children:[(0,J.jsx)(`span`,{className:`mono font-semibold`,style:{color:zm(r.status)},children:r.status}),(0,J.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>u(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,J.jsx)(`td`,{className:`muted mono`,children:(0,J.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,J.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),ee>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:ee}})})]})]})})}),l&&(0,J.jsx)(Gm,{detail:l,detailInfo:R,localeCode:n,localeTag:S,serverTimeZone:C,t,onClose:()=>u(null),onFilterConversation:e=>{g(e),u(null)}})]})]})}function Wm(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 Gm({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Wm(!0),[l,u]=(0,_.useState)(!1),d=gm(e),f=e.displayMetrics?.cost,p=Dm(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,J.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,J.jsx)(`span`,{className:`mono`,style:{color:zm(e.status)},children:e.status}),t&&(0,J.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,J.jsx)(ue,{})})]}),t&&(0,J.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,J.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,J.jsx)(`span`,{className:`mono`,children:Vm(e.timestamp,r,i)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,J.jsx)(`span`,{className:`mono`,children:il(e.resolvedModel??e.model)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,J.jsx)(`span`,{children:Dn(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[Em(e),p?` (${p})`:``]})]}),e.errorCode&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,J.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,J.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,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,J.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`span`,{className:`mono`,children:Om(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(Fm(e.displayMetrics.tokPerSecond.reason))})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,J.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,J.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,J.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(Rm(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,J.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,J.jsx)(`li`,{children:a(Im(e))},e))})]}):(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,J.jsx)(`span`,{children:f?.kind===`unavailable`?a(Fm(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,J.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,J.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{className:`num`,children:`#`}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,J.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=Dm(e),i=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(Lm(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(Fm(t.reason)):a(`logs.detail.attempt.completed`));return(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,J.jsxs)(`td`,{children:[(0,J.jsx)(`span`,{children:Dn(e.provider,a)}),(0,J.jsx)(`br`,{}),(0,J.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[Em(e),n?` (${n})`:``]})]}),i&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(Rm(i.status))]})]})]}),(0,J.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`td`,{className:`num mono`,children:Om(e.displayMetrics?.tokPerSecond,r)}),(0,J.jsx)(`td`,{className:`num mono`,children:pm(t,a,r)}),(0,J.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,J.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Pn(e.usage.inputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Pn(e.usage.outputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:Pn(d.read,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:Pn(d.write,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Pn(e.usage.reasoningOutputTokens,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,J.jsx)(`span`,{className:`mono`,children:Tm(e)===void 0?`—`:Pn(Tm(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:Pn(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,J.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,J.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,J.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function Km(e){return`${Math.round(e*100)}%`}function qm(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 Jm(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 Ym(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 Xm(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function Zm(e){let t=Ym(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?Xm(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 Qm({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,J.jsxs)(`div`,{className:`usage-filters`,children:[(0,J.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`logs.filter.surface.label`),children:[`all`,`codex`,`claude`,`grok`].map(t=>{let r=i(`logs.filter.surface.${t}`);return(0,J.jsxs)(`button`,{type:`button`,className:`usage-segmented-btn usage-source-btn${e===t?` active`:``}`,"aria-label":r,"aria-pressed":e===t,onClick:()=>n(t),children:[t===`codex`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,J.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,J.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(e===`all`?`usage.range.available`:`usage.range.${e}`);return(0,J.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${t===e?` active`:``}`,"aria-label":n,"aria-pressed":t===e,onClick:()=>r(e),children:n},e)})})]})}function $m({summary:e,activeDays:t,locale:n,t:r}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Pn(e.totalTokens,n)})]}),(0,J.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Pn(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,J.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,Pn(e.cacheCreationInputTokens??0,n)]})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Km(e.coverageRatio)})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,J.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,J.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,J.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:es(e.estimatedCostUsd,n)}),(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function eh({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,J.jsx)(`div`,{className:`daybars`,role:`img`,"aria-label":n(`usage.section.heatmap`),children:e.map(e=>{let n=Math.round(e.totalTokens/a*100),o=e.date.slice(5);return(0,J.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,J.jsx)(`div`,{className:`daybar-track`,children:(0,J.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:qm(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,J.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,J.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,J.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,J.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:qm(e.model,e.provider)}}),(0,J.jsx)(`span`,{className:`daybar-tip-name`,children:il(e.model)}),(0,J.jsx)(`span`,{className:`daybar-tip-val`,children:Pn(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,J.jsx)(`span`,{className:`daybar-count`,children:Pn(e.totalTokens,t)}),(0,J.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function th({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,_.useRef)(null),[o,s]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let e=a.current;if(!e)return;let t=()=>{e.scrollLeft=e.scrollWidth};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[t,e]),(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,J.jsx)(eh,{weekBars:n,locale:r,t:i}):(0,J.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,J.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,J.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,J.jsxs)(`div`,{className:`heatmap-body`,children:[(0,J.jsxs)(`div`,{className:`heatmap-days`,children:[(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,J.jsx)(`span`,{})]}),(0,J.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,J.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,J.jsx)(`div`,{className:`heatmap-cell heatmap-cell-${e.level}`,onMouseEnter:r=>{if(!e.date)return;let i=r.currentTarget.getBoundingClientRect();s({weekIndex:t,dayIndex:n,x:i.left+i.width/2,y:i.top})},onMouseLeave:()=>s(e=>e?.weekIndex===t&&e.dayIndex===n?null:e)},e.date||`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),o&&(()=>{let e=t.weeks[o.weekIndex]?.[o.dayIndex];return e?.date?(0,J.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,J.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,J.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:Pn(e.totalTokens,r)})}),(0,J.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,J.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,J.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,J.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,J.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function nh({title:e,titleId:t,children:n}){return(0,J.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,J.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function rh({models:e,modelQuery:t,onModelQuery:n,locale:r,t:i,workspace:a=!1}){let o=i(`usage.search.models`),s=i(`usage.section.models`),c=`usage-models-title`,l=(0,J.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`logs.col.model`)}),(0,J.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:il(e.model)}),(0,J.jsx)(`td`,{className:`muted`,children:Dn(e.provider,i)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Pn(e.totalTokens,r)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,J.jsxs)(nh,{title:s,titleId:c,children:[(0,J.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function ih({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:Dn(e.provider,n)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Pn(e.totalTokens,t)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,J.jsx)(nh,{title:i,titleId:a,children:o}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,J.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function ah({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,J.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,J.jsx)(nh,{title:r,titleId:i,children:a}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,J.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function oh({data:e,heatmap:t,weekBars:n,activeDays:r,filteredModels:i,modelQuery:a,onModelQuery:o,sortedProviders:s,range:c,locale:l,t:u}){let d=!!e&&e.summary.requests===0,f=[{id:`overview`,label:u(`usage.section.overview`),meta:e?`${e.summary.requests}`:`—`,body:e?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($m,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,J.jsx)(th,{range:c,heatmap:t,weekBars:n,locale:l,t:u})]}):null},{id:`models`,label:u(`usage.section.models`),meta:e?`${e.models.length}`:`—`,body:e?(0,J.jsx)(rh,{models:i,modelQuery:a,onModelQuery:o,locale:l,t:u,workspace:!0}):null},{id:`providers`,label:u(`usage.section.providers`),meta:e?`${e.providers.length}`:`—`,body:e?(0,J.jsx)(ih,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Km(e.summary.coverageRatio):`—`,body:e?(0,J.jsx)(ah,{summary:e.summary,t:u,workspace:!0}):null}];return(0,J.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,J.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,J.jsx)(lp,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,J.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,J.jsx)(Ot,{title:u(`usage.empty`)}):f.map(e=>(0,J.jsx)(`div`,{id:op(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var sh=new Map;function ch(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function lh(e,t,n){let r=ch(e,t,n);return sh.get(r)??fr(r)}function uh(e,t,n,r){let i=ch(e,t,n);sh.set(i,r),gr(i,r)}function dh({apiBase:e}){let{t,locale:n}=ct(),[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 uh(e,r,a,i),i},[e,r,a]),u=ch(e,r,a),d=lh(e,r,a),f=ol(u,[e,r,a],l,{isEmpty:()=>!1,initialData:d??void 0}),{state:p}=f,m=p.data??d??null,h=(0,_.useMemo)(()=>Zm(m?.days??[]),[m?.days]),g=(0,_.useMemo)(()=>Jm(m?.days??[]),[m?.days]),v=(0,_.useMemo)(()=>(m?.days??[]).filter(e=>e.requests>0).length,[m?.days]),y=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(m?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[m?.models,s]),b=(0,_.useMemo)(()=>(m?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[m?.providers]);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,J.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,J.jsx)(Qm,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),p.showSkeleton&&!m?(0,J.jsx)(cl,{label:t(`usage.loading`),rows:5}):p.kind===`failed-cold`?(0,J.jsxs)($,{tone:`err`,children:[p.error instanceof Error?`${t(`usage.loadError`)} ${p.error.message}`:t(`usage.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,J.jsxs)(J.Fragment,{children:[p.showError&&(0,J.jsx)($,{tone:`err`,children:t(`usage.loadError`)}),m?.historyTruncated&&(0,J.jsx)($,{tone:`warn`,children:(()=>{let e=fh(m.snapshotWindowStart),n=fh(m.snapshotWindowEnd);return e!==null&&n!==null?t(`usage.historyTruncatedWindow`,{start:e,end:n}):t(`usage.historyTruncated`)})()}),(0,J.jsx)(oh,{data:m,heatmap:h,weekBars:g,activeDays:v,filteredModels:y,modelQuery:s,onModelQuery:c,sortedProviders:b,range:r,locale:n,t})]})]})}function fh(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function ph(e,t){if(e<1024)return`${e} B`;let n=[`KiB`,`MiB`,`GiB`,`TiB`],r=e,i=-1;do r/=1024,i++;while(r>=1024&&i<n.length-1);return`${r.toLocaleString(t,{maximumFractionDigits:1})} ${n[i]}`}var mh={en:{compact:`Compact`,compactComplete:`Compaction complete (logical / on-disk reclaimed)`,pagesUnit:`pages`,compactPartial:`Compaction partial (logical / on-disk reclaimed)`,confirmCompact:`Confirm compaction`,cancel:`Cancel`,inspectionOnly:`Inspection only`,externalSqliteHome:`External SQLite storage`,inspectionUnavailable:`Diagnostic log inspection is unavailable.`,metricsSkippedLarge:`Row metrics skipped: the database is above {threshold}, and scanning it would stall the proxy.`,protection:`Protection`,compat:`Compatibility`,quiet:`Quiet`,disable:`Disable protection`,repair:`Repair protection`,applying:`Applying protection…`,"error.generic":`Could not change Codex log protection.`,"error.codex_running":`Quit Codex before changing log protection.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. Protection was not changed.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for protection.`,"error.trigger_collision":`A reserved Log Guard trigger name is already in use. Protection was not changed.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.config_write_failed":`The database changed, but OpenCodex could not save the protection setting. Fix config storage, then run Repair.`},de:{compact:`Komprimieren`,compactComplete:`Komprimierung abgeschlossen (logisch / auf Datentraeger freigegeben)`,pagesUnit:`Seiten`,compactPartial:`Komprimierung teilweise (logisch / auf Datentraeger freigegeben)`,confirmCompact:`Komprimierung bestätigen`,cancel:`Abbrechen`,inspectionOnly:`Nur Inspektion`,externalSqliteHome:`Externer SQLite-Speicher`,inspectionUnavailable:`Die Diagnoseprotokoll-Inspektion ist nicht verfügbar.`,metricsSkippedLarge:`Zeilenmetriken übersprungen: Die Datenbank ist größer als {threshold}; ein Scan würde den Proxy blockieren.`,protection:`Schutz`,compat:`Kompatibilität`,quiet:`Leise`,disable:`Schutz deaktivieren`,repair:`Schutz reparieren`,applying:`Schutz wird angewendet…`,"error.generic":`Der Schutz der Codex-Protokolle konnte nicht geändert werden.`,"error.codex_running":`Beende Codex, bevor du den Protokollschutz änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Schutz wurde nicht geändert.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für den Schutz nicht unterstützt.`,"error.trigger_collision":`Ein reservierter Log-Guard-Triggername wird bereits verwendet. Der Schutz wurde nicht geändert.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.config_write_failed":`Die Datenbank wurde geändert, aber OpenCodex konnte die Schutzeinstellung nicht speichern. Repariere den Konfigurationsspeicher und führe danach Reparieren aus.`},fr:{compact:`Compacter`,compactComplete:`Compactage termine (logique / recupere sur disque)`,pagesUnit:`pages`,compactPartial:`Compactage partiel (logique / recupere sur disque)`,confirmCompact:`Confirmer le compactage`,cancel:`Annuler`,inspectionOnly:`Inspection uniquement`,externalSqliteHome:`Stockage SQLite externe`,inspectionUnavailable:`L’inspection des journaux de diagnostic est indisponible.`,metricsSkippedLarge:`Métriques de lignes ignorées : la base dépasse {threshold} et son analyse bloquerait le proxy.`,protection:`Protection`,compat:`Compatibilité`,quiet:`Silencieux`,disable:`Désactiver la protection`,repair:`Réparer la protection`,applying:`Application de la protection…`,"error.generic":`Impossible de modifier la protection des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier la protection des journaux.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. La protection n’a pas été modifiée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour la protection.`,"error.trigger_collision":`Un nom de déclencheur Log Guard réservé est déjà utilisé. La protection n’a pas été modifiée.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.config_write_failed":`La base de données a été modifiée, mais OpenCodex n’a pas pu enregistrer le paramètre de protection. Corrigez le stockage de configuration, puis lancez Réparer.`},ko:{compact:`압축`,compactComplete:`압축 완료 (논리 / 디스크 회수량)`,pagesUnit:`페이지`,compactPartial:`압축 부분 완료 (논리 / 디스크 회수량)`,confirmCompact:`압축 확인`,cancel:`취소`,inspectionOnly:`검사 전용`,externalSqliteHome:`외부 SQLite 저장소`,inspectionUnavailable:`진단 로그 검사를 사용할 수 없습니다.`,metricsSkippedLarge:`행 지표를 건너뛰었습니다. 데이터베이스가 {threshold}보다 커서 스캔하면 프록시가 멈춥니다.`,protection:`보호`,compat:`호환 모드`,quiet:`조용한 모드`,disable:`보호 비활성화`,repair:`보호 복구`,applying:`보호 적용 중…`,"error.generic":`Codex 로그 보호를 변경하지 못했습니다.`,"error.codex_running":`로그 보호를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 보호를 변경하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 보호 기능을 지원하지 않습니다.`,"error.trigger_collision":`예약된 Log Guard 트리거 이름이 이미 사용 중입니다. 보호를 변경하지 않았습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.config_write_failed":`데이터베이스는 변경되었지만 OpenCodex가 보호 설정을 저장하지 못했습니다. 구성 저장소를 수정한 뒤 복구를 실행하세요.`},zh:{compact:`压缩`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`页`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`确认压缩`,cancel:`取消`,inspectionOnly:`仅检查`,externalSqliteHome:`外部 SQLite 存储`,inspectionUnavailable:`诊断日志检查当前不可用。`,metricsSkippedLarge:`已跳过行指标:数据库超过 {threshold},扫描会阻塞代理。`,protection:`保护`,compat:`兼容模式`,quiet:`静默模式`,disable:`禁用保护`,repair:`修复保护`,applying:`正在应用保护…`,"error.generic":`无法更改 Codex 日志保护。`,"error.codex_running":`更改 Codex 日志保护前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未更改保护设置。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持保护功能。`,"error.trigger_collision":`保留的 Log Guard 触发器名称已被占用,因此未更改保护设置。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.config_write_failed":`数据库已更改,但 OpenCodex 无法保存保护设置。请先修复配置存储,然后运行“修复保护”。`},"zh-TW":{compact:`壓縮`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`頁`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`確認壓縮`,cancel:`取消`,inspectionOnly:`僅檢查`,externalSqliteHome:`外部 SQLite 儲存空間`,inspectionUnavailable:`診斷記錄檢查目前無法使用。`,metricsSkippedLarge:`已略過列指標:資料庫超過 {threshold},掃描會阻塞代理。`,protection:`保護`,compat:`相容模式`,quiet:`靜默模式`,disable:`停用保護`,repair:`修復保護`,applying:`正在套用保護…`,"error.generic":`無法變更 Codex 日誌保護。`,"error.codex_running":`變更 Codex 日誌保護前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未變更保護設定。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援保護功能。`,"error.trigger_collision":`保留的 Log Guard 觸發器名稱已被使用,因此未變更保護設定。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.config_write_failed":`資料庫已變更,但 OpenCodex 無法儲存保護設定。請先修復設定儲存空間,再執行「修復保護」。`},ru:{compact:`Сжать`,compactComplete:`Сжатие завершено (логически / освобождено на диске)`,pagesUnit:`страниц`,compactPartial:`Сжатие частичное (логически / освобождено на диске)`,confirmCompact:`Подтвердить сжатие`,cancel:`Отмена`,inspectionOnly:`Только проверка`,externalSqliteHome:`Внешнее хранилище SQLite`,inspectionUnavailable:`Проверка диагностических журналов недоступна.`,metricsSkippedLarge:`Метрики строк пропущены: база больше {threshold}, и её сканирование заблокировало бы прокси.`,protection:`Защита`,compat:`Совместимость`,quiet:`Тихий режим`,disable:`Отключить защиту`,repair:`Восстановить защиту`,applying:`Применение защиты…`,"error.generic":`Не удалось изменить защиту журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением защиты журналов.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Защита не изменена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает защиту.`,"error.trigger_collision":`Зарезервированное имя триггера Log Guard уже используется. Защита не изменена.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.config_write_failed":`База была изменена, но OpenCodex не смог сохранить настройку защиты. Исправьте хранилище конфигурации и затем запустите восстановление.`},ja:{compact:`圧縮`,compactComplete:`圧縮完了(論理 / ディスク解放)`,pagesUnit:`ページ`,compactPartial:`圧縮は部分的に完了(論理 / ディスク解放)`,confirmCompact:`圧縮を確認`,cancel:`キャンセル`,inspectionOnly:`検査のみ`,externalSqliteHome:`外部 SQLite ストレージ`,inspectionUnavailable:`診断ログの検査を利用できません。`,metricsSkippedLarge:`行メトリクスをスキップしました。データベースが {threshold} を超えており、走査するとプロキシが停止します。`,protection:`保護`,compat:`互換モード`,quiet:`静音モード`,disable:`保護を無効化`,repair:`保護を修復`,applying:`保護を適用中…`,"error.generic":`Codex ログ保護を変更できませんでした。`,"error.codex_running":`ログ保護を変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、保護は変更されませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマでは保護機能を使用できません。`,"error.trigger_collision":`予約済みの Log Guard トリガー名が既に使用されています。保護は変更されませんでした。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.config_write_failed":`データベースは変更されましたが、OpenCodex は保護設定を保存できませんでした。設定ストレージを修正してから保護を修復してください。`},tr:{compact:`Sıkıştır`,compactComplete:`Sikistirma tamamlandi (mantiksal / diskte geri kazanilan)`,pagesUnit:`sayfa`,compactPartial:`Sikistirma kismi (mantiksal / diskte geri kazanilan)`,confirmCompact:`Sıkıştırmayı onayla`,cancel:`İptal`,inspectionOnly:`Yalnızca inceleme`,externalSqliteHome:`Harici SQLite depolaması`,inspectionUnavailable:`Tanılama günlüğü incelemesi kullanılamıyor.`,metricsSkippedLarge:`Satır ölçümleri atlandı: veritabanı {threshold} sınırının üzerinde ve taranması proxy’yi kilitler.`,protection:`Koruma`,compat:`Uyumluluk`,quiet:`Sessiz`,disable:`Korumayı devre dışı bırak`,repair:`Korumayı onar`,applying:`Koruma uygulanıyor…`,"error.generic":`Codex günlük koruması değiştirilemedi.`,"error.codex_running":`Günlük korumasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Koruma değiştirilmedi.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması koruma için desteklenmiyor.`,"error.trigger_collision":`Ayrılmış bir Log Guard tetikleyici adı zaten kullanılıyor. Koruma değiştirilmedi.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.config_write_failed":`Veritabanı değişti ancak OpenCodex koruma ayarını kaydedemedi. Yapılandırma depolamasını düzeltip ardından korumayı onarın.`}};function hh(e,t){return mh[e][t]}var gh={en:{applying:`Applying Log Guard change…`,"error.generic":`Could not update Codex log storage.`,"error.codex_running":`Quit Codex before changing Codex log storage.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. The Log Guard operation was not started.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for this operation.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.auto_vacuum_not_incremental":`This Codex logs database is not configured for incremental vacuum, so space cannot be reclaimed without a full rebuild.`,"error.integrity_check_failed":`The Codex logs database failed its integrity check. No space was reclaimed.`},de:{applying:`Log-Guard-Änderung wird angewendet…`,"error.generic":`Der Codex-Protokollspeicher konnte nicht aktualisiert werden.`,"error.codex_running":`Beende Codex, bevor du den Codex-Protokollspeicher änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Log-Guard-Vorgang wurde nicht gestartet.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für diesen Vorgang nicht unterstützt.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.auto_vacuum_not_incremental":`Diese Codex-Protokolldatenbank ist nicht fuer inkrementelles Vacuum konfiguriert; ohne vollstaendigen Neuaufbau kann kein Speicher freigegeben werden.`,"error.integrity_check_failed":`Die Integritaetspruefung der Codex-Protokolldatenbank ist fehlgeschlagen. Es wurde kein Speicher freigegeben.`},fr:{applying:`Application de la modification Log Guard…`,"error.generic":`Impossible de mettre à jour le stockage des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier le stockage des journaux Codex.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. L’opération Log Guard n’a pas été lancée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour cette opération.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.auto_vacuum_not_incremental":`Cette base de donnees de journaux Codex n'est pas configuree pour le vacuum incrementiel : l'espace ne peut pas etre recupere sans reconstruction complete.`,"error.integrity_check_failed":`La verification d'integrite de la base de donnees de journaux Codex a echoue. Aucun espace n'a ete recupere.`},ko:{applying:`Log Guard 변경 적용 중…`,"error.generic":`Codex 로그 저장소를 업데이트하지 못했습니다.`,"error.codex_running":`Codex 로그 저장소를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 Log Guard 작업을 시작하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 이 작업을 지원하지 않습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.auto_vacuum_not_incremental":`이 Codex 로그 데이터베이스는 증분 정리로 구성되어 있지 않아, 전체 재구축 없이는 공간을 회수할 수 없습니다.`,"error.integrity_check_failed":`Codex 로그 데이터베이스 무결성 검사에 실패했습니다. 공간이 회수되지 않았습니다.`},zh:{applying:`正在应用 Log Guard 更改…`,"error.generic":`无法更新 Codex 日志存储。`,"error.codex_running":`更改 Codex 日志存储前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未启动 Log Guard 操作。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持此操作。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},"zh-TW":{applying:`正在套用 Log Guard 變更…`,"error.generic":`無法更新 Codex 日誌儲存空間。`,"error.codex_running":`變更 Codex 日誌儲存空間前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未啟動 Log Guard 操作。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援此操作。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},ru:{applying:`Применение изменения Log Guard…`,"error.generic":`Не удалось обновить хранилище журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением хранилища журналов Codex.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Операция Log Guard не запущена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает эту операцию.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.auto_vacuum_not_incremental":`Эта база данных журналов Codex не настроена на инкрементальную очистку, поэтому освободить место без полной перестройки невозможно.`,"error.integrity_check_failed":`Проверка целостности базы данных журналов Codex не пройдена. Место не освобождено.`},ja:{applying:`Log Guard の変更を適用中…`,"error.generic":`Codex ログストレージを更新できませんでした。`,"error.codex_running":`Codex ログストレージを変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、Log Guard 操作を開始しませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマではこの操作を使用できません。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.auto_vacuum_not_incremental":`この Codex ログ データベースは増分バキューム用に構成されていないため、完全な再構築なしに領域を解放できません。`,"error.integrity_check_failed":`Codex ログ データベースの整合性チェックに失敗しました。領域は解放されていません。`},tr:{applying:`Log Guard değişikliği uygulanıyor…`,"error.generic":`Codex günlük depolaması güncellenemedi.`,"error.codex_running":`Codex günlük depolamasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Log Guard işlemi başlatılmadı.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması bu işlem için desteklenmiyor.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.auto_vacuum_not_incremental":`Bu Codex gunluk veritabani artimli vacuum icin yapilandirilmamis; tam yeniden olusturma olmadan alan geri kazanilamaz.`,"error.integrity_check_failed":`Codex gunluk veritabani butunluk denetiminden gecemedi. Alan geri kazanilmadi.`}};function _h(e,t){return gh[e][t]}var vh={en:{schema:{compatible:`Compatible`,missing:`Database not found`,unreadable:`Database unavailable`,unsupported:`Unsupported`},protection:{off:`Off`,active:`Active`,drifted:`Needs repair`,unsupported:`Unsupported`,unknown:`Unknown`},mode:{off:`Off`,compat:`Compatibility`,quiet:`Quiet`,collision:`Unknown`}},de:{schema:{compatible:`Kompatibel`,missing:`Datenbank nicht gefunden`,unreadable:`Datenbank nicht lesbar`,unsupported:`Nicht unterstützt`},protection:{off:`Aus`,active:`Aktiv`,drifted:`Reparatur erforderlich`,unsupported:`Nicht unterstützt`,unknown:`Unbekannt`},mode:{off:`Aus`,compat:`Kompatibilität`,quiet:`Leise`,collision:`Unbekannt`}},fr:{schema:{compatible:`Compatible`,missing:`Base de données introuvable`,unreadable:`Base de données indisponible`,unsupported:`Non pris en charge`},protection:{off:`Désactivée`,active:`Active`,drifted:`Réparation requise`,unsupported:`Non prise en charge`,unknown:`Inconnue`},mode:{off:`Désactivé`,compat:`Compatibilité`,quiet:`Silencieux`,collision:`Inconnu`}},ko:{schema:{compatible:`호환됨`,missing:`데이터베이스 없음`,unreadable:`데이터베이스를 읽을 수 없음`,unsupported:`지원되지 않음`},protection:{off:`꺼짐`,active:`활성`,drifted:`복구 필요`,unsupported:`지원되지 않음`,unknown:`알 수 없음`},mode:{off:`꺼짐`,compat:`호환 모드`,quiet:`조용한 모드`,collision:`알 수 없음`}},zh:{schema:{compatible:`兼容`,missing:`未找到数据库`,unreadable:`无法读取数据库`,unsupported:`不受支持`},protection:{off:`关闭`,active:`已启用`,drifted:`需要修复`,unsupported:`不受支持`,unknown:`未知`},mode:{off:`关闭`,compat:`兼容模式`,quiet:`静默模式`,collision:`未知`}},"zh-TW":{schema:{compatible:`相容`,missing:`找不到資料庫`,unreadable:`無法讀取資料庫`,unsupported:`不支援`},protection:{off:`關閉`,active:`已啟用`,drifted:`需要修復`,unsupported:`不支援`,unknown:`未知`},mode:{off:`關閉`,compat:`相容模式`,quiet:`靜默模式`,collision:`未知`}},ru:{schema:{compatible:`Совместимо`,missing:`База не найдена`,unreadable:`База недоступна`,unsupported:`Не поддерживается`},protection:{off:`Выключено`,active:`Активно`,drifted:`Требуется восстановление`,unsupported:`Не поддерживается`,unknown:`Неизвестно`},mode:{off:`Выключено`,compat:`Совместимость`,quiet:`Тихий режим`,collision:`Неизвестно`}},ja:{schema:{compatible:`互換`,missing:`データベースが見つかりません`,unreadable:`データベースを読み取れません`,unsupported:`未対応`},protection:{off:`オフ`,active:`有効`,drifted:`修復が必要`,unsupported:`未対応`,unknown:`不明`},mode:{off:`オフ`,compat:`互換モード`,quiet:`静音モード`,collision:`不明`}},tr:{schema:{compatible:`Uyumlu`,missing:`Veritabanı bulunamadı`,unreadable:`Veritabanı okunamıyor`,unsupported:`Desteklenmiyor`},protection:{off:`Kapalı`,active:`Etkin`,drifted:`Onarım gerekli`,unsupported:`Desteklenmiyor`,unknown:`Bilinmiyor`},mode:{off:`Kapalı`,compat:`Uyumluluk`,quiet:`Sessiz`,collision:`Bilinmiyor`}}};function yh(e,t){return vh[e].schema[t]}function bh(e,t){return vh[e].protection[t]}function xh(e,t){return vh[e].mode[t]}var Sh=``,Ch={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 wh(e,t){let n=Ch[e.key];return n?t(n):e.label}function Th(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function Eh(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function Dh(e,t){switch(t){case`codex_running`:return _h(e,`error.codex_running`);case`process_enumeration_failed`:return _h(e,`error.process_enumeration_failed`);case`busy`:return _h(e,`error.busy`);case`unsupported_schema`:return _h(e,`error.unsupported_schema`);case`trigger_collision`:return hh(e,`error.trigger_collision`);case`unsafe_path`:return _h(e,`error.unsafe_path`);case`database_error`:return _h(e,`error.database_error`);case`auto_vacuum_not_incremental`:return _h(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return _h(e,`error.integrity_check_failed`);case`config_write_failed`:return hh(e,`error.config_write_failed`);default:return _h(e,`error.generic`)}}function Oh({report:e,locale:t,t:n,busy:r,error:i,compaction:a,onAction:o}){let s=e.metrics,c=e.capabilities.protection.state===`unsupported`||e.capabilities.reclaim.state===`unsupported`,l=e.protection,u=r||e.capabilities.protection.state!==`supported`,d=l!==void 0&&e.capabilities.reclaim.state===`supported`&&(s?.reclaimableBytes??0)>0,[f,p]=(0,_.useState)(!1);return(0,J.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,J.jsxs)(`dl`,{className:`stw-kv`,children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`dash.status`)}),(0,J.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,J.jsx)(`code`,{children:yh(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,J.jsx)(`code`,{children:hh(t,`inspectionOnly`)})]}):null]})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(e.files.databaseBytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`WAL`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(e.files.walBytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`SHM`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(e.files.shmBytes,t)})]}),s&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`TRACE`})}),(0,J.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`freelist`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,J.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`muted`,children:hh(t,`metricsSkippedLarge`).replace(`{threshold}`,ph(e.metricsSkipped.thresholdBytes,t))})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`sqlite_home`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,J.jsx)(`code`,{children:e.externalSqliteHome?hh(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,J.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,J.jsx)(`h4`,{className:`stw-section-title`,children:hh(t,`protection`)}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`span`,{className:`muted`,children:(0,J.jsx)(`code`,{children:bh(t,l.state)})}),(0,J.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,J.jsx)(`code`,{children:xh(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,J.jsx)(`code`,{children:xh(t,l.observedMode)})]})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-compat`,disabled:u,"aria-pressed":l.desiredMode===`compat`,onClick:()=>o({action:`protect`,mode:`compat`}),children:hh(t,`compat`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-quiet`,disabled:u,"aria-pressed":l.desiredMode===`quiet`,onClick:()=>o({action:`protect`,mode:`quiet`}),children:hh(t,`quiet`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-unprotect`,disabled:u||l.desiredMode===`off`,onClick:()=>o({action:`unprotect`}),children:hh(t,`disable`)}),l.state===`drifted`&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:hh(t,`repair`)}),r&&(0,J.jsx)(`span`,{className:`muted`,role:`status`,children:_h(t,`applying`)})]}),i&&(0,J.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,J.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,J.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:hh(t,`confirmCompact`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:hh(t,`cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:hh(t,`compact`)})})}),a&&(0,J.jsx)(`div`,{className:`stw-section`,children:(0,J.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h4`,{className:`stw-section-title`,children:(0,J.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,J.jsx)(`code`,{children:e.target})}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,J.jsx)(`p`,{className:`stw-hint`,children:(0,J.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function kh({locale:e,t}){return(0,J.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,J.jsx)(`p`,{className:`stw-hint`,children:hh(e,`inspectionUnavailable`)})]})}function Ah({report:e,locale:t,logGuardBusy:n=!1,onLogGuardAction:r}){let i=Q(),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),h=(0,_.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),g=h.find(e=>e.key===a)??null,v=s?.generation===e.generatedAt?s.report:e.codexLogs??null,y=d?.generation===e.generatedAt?d.message:null,b=p?.generation===e.generatedAt?p.summary:null,x=n||l,S=(0,_.useMemo)(()=>{let t=[];for(let n of e.buckets)for(let e of n.largest??[])t.push({...e,bucketKey:n.key});return t.sort((e,t)=>t.bytes-e.bytes).slice(0,10)},[e.buckets]),C=(0,_.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,J.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":i(`storage.section.buckets`),children:[(0,J.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-title`,children:i(`storage.section.buckets`)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-count`,children:h.length})]}),(0,J.jsx)(`div`,{className:`storage-workspace-rail-list`,children:h.length===0?(0,J.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:i(`storage.empty`)}):h.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${a===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>o(t=>t===e.key?null:e.key),"aria-current":a===e.key?`true`:void 0,children:[(0,J.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-name`,children:wh(e,i)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-size`,children:ph(e.bytes,t)})]}),(0,J.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,i(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,J.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":g?wh(g,i):i(`storage.section.largest`),children:g?(0,J.jsxs)(`div`,{className:`stw-detail`,children:[(0,J.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>o(null),children:[(0,J.jsx)(Se,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),i(`modal.back`)]})}),(0,J.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,J.jsx)(`h2`,{className:`stw-detail-title`,children:wh(g,i)}),(0,J.jsxs)(`dl`,{className:`stw-kv`,children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.size`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(g.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.files`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:g.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.oldest`)}),(0,J.jsx)(`dd`,{children:Th(g.oldest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.newest`)}),(0,J.jsx)(`dd`,{children:Th(g.newest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:Eh(g,t,i)})]})]}),(g.largest?.length??0)>0&&(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:i(`storage.section.largest`)}),g.largest.map(e=>(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:ph(e.bytes,t)})]},e.path))]})]})]}):(0,J.jsxs)(`div`,{className:`stw-overview`,children:[(0,J.jsxs)(`div`,{className:`stw-summary`,children:[(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:i(`storage.card.total`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:ph(e.total.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:i(`storage.card.files`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:i(`storage.card.home`)}),(0,J.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),v?(0,J.jsx)(Oh,{report:v,locale:t,t:i,busy:x,error:y,compaction:b,onAction:n=>{if(r){r(n);return}if(l)return;let i=e.generatedAt;(async()=>{u(!0),f(null),n.action===`compact`&&m(null);try{let e=n.action===`protect`?`protect`:n.action,r={method:`POST`,...n.action===`protect`?{headers:{"content-type":`application/json`},body:JSON.stringify({mode:n.mode})}:{}},a=await fetch(`${Sh}/api/storage/codex-logs/${e}`,r);if(!a.ok){let e=await a.json().catch(()=>({}));f({generation:i,message:Dh(t,e.error)});return}if(n.action===`compact`){let e=(await a.json().catch(()=>null))?.report;if(e){let n=ph(e.logicalBytesReclaimed??0,t),r=ph(e.physicalDatabaseBytesReclaimed??0,t),a=e.complete?hh(t,`compactComplete`):hh(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;m({generation:i,summary:[`${a}${s}`,`${o.toLocaleString(t)} ${hh(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${Sh}/api/storage/codex-logs`);if(e.ok){let t=await e.json();c({generation:i,report:t})}}catch{}return}let o=await a.json();c({generation:i,report:o})}catch{f({generation:i,message:_h(t,`error.generic`)})}finally{u(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,J.jsx)(kh,{locale:t,t:i}):null,S.length>0?(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:i(`storage.section.largest`)}),S.map(e=>{let n=C.get(e.bucketKey);return(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,J.jsx)(`span`,{className:`stw-file-bucket`,children:wh(n,i)}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:ph(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,J.jsxs)(`p`,{className:`stw-hint`,children:[(0,J.jsx)(ce,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),i(`storage.workspace.selectBucket`)]})]})})]})}var jh=1024**3,Mh=[10,25,50],Nh=(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 Ph({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(Nh(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:ph(a.bytes,t)})),r()}catch(e){v(Nh(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,J.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,J.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,J.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,J.jsx)(`input`,{type:`range`,min:1,max:100,value:i,onChange:e=>a(Number(e.target.value)),disabled:f,style:{flex:1,minWidth:0},"aria-label":n(`storage.cleanup.slider`)})]}),(0,J.jsx)(`div`,{className:`storage-manual-panel__presets`,children:Mh.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:ph(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,J.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,J.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,J.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,J.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,J.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void E(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function Fh({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=ol(`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:ph(a.bytes,t)})),r()}catch(e){p(Nh(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},w=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},T=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:b.error instanceof Error?b.error.message:n(`storage.trash.listFailed`)}),b.refreshing&&!b.showSkeleton&&(0,J.jsx)(ll,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,J.jsx)(cl,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,J.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,J.jsx)(`th`,{})]})}),(0,J.jsx)(`tbody`,{children:x.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted`,children:w(e)}),(0,J.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,J.jsx)(`td`,{className:`num mono`,children:ph(e.bytes,t)}),(0,J.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,J.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:ph(c.bytes,t),id:c.id})}),f&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function Ih(e){let{job:t,...n}=e;return n}function Lh(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/jh*100)/100));return e.target.reduceToBytes===void 0?{policy:Ih(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:Ih(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/jh*100)/100))}}async function Rh(e){await new Promise(t=>window.setTimeout(t,e))}function zh({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=fr(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=Lh(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,gr(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*jh)}}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*jh)},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 Rh(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=Ih(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.ok&&f.metadataPersistenceError?(y(n(`storage.policy.metadataSaveWarning`)),f.removed!==void 0&&r()):f.skipped===`under_threshold`?g(n(`storage.policy.skippedUnder`)):f.skipped===`nothing_selected`?g(n(`storage.policy.skippedEmpty`)):f.deferred===`codex_busy`||f.error===`codex_busy`?y(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:ph(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:ph(f.freedBytes??0,t)})),r()):y(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;y(n(`storage.policy.runFailed`))}finally{O.current===i&&(O.current=null),a.aborted||m(!1)}},z=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,J.jsx)(`div`,{className:`storage-policy-enable`,children:(0,J.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,J.jsx)(`button`,{type:`button`,className:`toggle${s.enabled?` on`:``}`,disabled:d||p,"aria-pressed":s.enabled,"aria-label":n(`storage.policy.enabled`),title:n(`storage.policy.enabledHint`),onClick:()=>void L({enabled:!s.enabled}),children:(0,J.jsx)(`span`,{className:`toggle-knob`})}),(0,J.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,J.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,J.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,J.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,J.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:E,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>P(!0),onChange:e=>{N(),D(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(So,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D(xo(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D(xo(E,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,J.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:S,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>P(!0),onChange:e=>{N(),C(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(So,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C(xo(S,1,1,100))},onDecrement:()=>{N(),C(xo(S,-1,1,100))}})]})]}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:w,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>P(!0),onChange:e=>{N(),T(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(So,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T(xo(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T(xo(w,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,J.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;L({schedule:t})},children:[(0,J.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,J.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,J.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,J.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,J.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;L({mode:t})},children:[(0,J.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,J.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,J.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,J.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[z(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:ph(s.lastRun.freedBytes,t)})}`:``]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,J.jsx)(`span`,{className:`storage-policy-meta-value`,children:z(s.nextRun)})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void R(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,J.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,J.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function Bh({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,_.useState)(`policy`),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=[{id:`policy`,label:n(`storage.cleanupCard.tab.policy`),ref:u},{id:`quarantine`,label:n(`storage.cleanupCard.tab.quarantine`),ref:d}],p=e=>{l(e),window.requestAnimationFrame(()=>(e===`policy`?u:d).current?.focus())},m=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),p(c===`policy`?`quarantine`:`policy`)):e.key===`Home`?(e.preventDefault(),p(`policy`)):e.key===`End`&&(e.preventDefault(),p(`quarantine`))};return(0,J.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,J.jsx)(`div`,{className:`page-tabs storage-cleanup-card__tabs`,role:`tablist`,"aria-label":n(`storage.cleanupCard.tabs`),children:f.map(({id:e,label:t,ref:n})=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,ref:n,id:`storage-cleanup-tab-${e}`,"aria-selected":c===e,"aria-controls":`storage-cleanup-panel-${e}`,tabIndex:c===e?0:-1,className:`page-tab${c===e?` page-tab--active`:``}`,onKeyDown:m,onClick:()=>p(e),children:t},e))}),(0,J.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,J.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,J.jsxs)(`div`,{id:`storage-cleanup-panel-policy`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-policy`,className:`storage-cleanup-card__body storage-cleanup-policy-split`,"data-active":c===`policy`?`true`:`false`,"aria-hidden":c!==`policy`,...c===`policy`?{}:{inert:!0},children:[(0,J.jsx)(zh,{apiBase:e,locale:t,t:n,onDone:o}),(0,J.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,J.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,J.jsx)(Ph,{apiBase:e,locale:t,t:n,onDone:o}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,J.jsx)(`div`,{id:`storage-cleanup-panel-quarantine`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-quarantine`,className:`storage-cleanup-card__body`,"data-active":c===`quarantine`?`true`:`false`,"aria-hidden":c!==`quarantine`,...c===`quarantine`?{}:{inert:!0},children:i?(0,J.jsx)(Fh,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function Vh({apiBase:e}){let{t,locale:n}=ct(),r=`ocx.storage.report.v1:${e}`,i=fr(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 gr(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=ol(`storage-report:${e}`,[e],f,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),m=p.state,h=m.data??i,g=m.refreshing||m.showSkeleton&&!h,v=p.refresh,y=(0,_.useCallback)(()=>{o(null),l.current=!0,v(),c(e=>e+1)},[v]),b=(0,_.useCallback)(t=>{d({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=u.apiBase===e&&u.settled,S=u.apiBase===e&&u.hasEntries,C=h?.error!==void 0,w=!g&&!m.showError&&!C&&h.total.fileCount===0&&x&&!S,T=h?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!h&&!C,D=E&&(h.total.fileCount>0||!x||S);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,J.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,J.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,J.jsx)(fe,{}),` `,t(`storage.refresh`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,J.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,J.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,J.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,J.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,J.jsx)(cl,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,J.jsxs)(J.Fragment,{children:[m.showError&&(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,J.jsx)(Ot,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,J.jsx)(Ah,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,J.jsx)(ll,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,J.jsx)(Bh,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}var Hh=`/api/codex-auth/features/default-mode-request-user-input`;function Uh({apiBase:e}){let t=Q(),[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,n=Ln(15e3);try{let i=await fetch(`${e}${Hh}`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(f.current||t!==m.current)return;p.current=o.enabled===!0,r(p.current),a(!0),l(!1)}catch{!f.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=Vn(()=>{h()},3e4);return()=>{window.clearTimeout(e),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}${Hh}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),o=await Pt(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,J.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,J.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,J.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,J.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,J.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
79
+ `))&&(async()=>{u(null),g(typeof r?.pid==`number`?r.pid:null),c(`draining`);try{if(!(await fetch(`${e}/api/system/restart`,{method:`POST`})).ok)throw Error(`restart_failed`)}catch{c(`error`),g(null),u(n(`dash.mem.restartFailed`))}})()};if(a&&!r&&s===`idle`)return(0,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`font-semibold`,style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(se,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginTop:8},children:n(`dash.mem.unavailable`)})]});let y=r?.watchdog?Xn(r.watchdog.samples):null,b=r?r.observedBytes??r.watchdog?.observedBytes??Jn(r):null,x=r?Yn(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,J.jsxs)(`div`,{className:`panel`,style:{marginBottom:24},children:[(0,J.jsxs)(`div`,{className:`mem-head`,children:[(0,J.jsxs)(`div`,{className:`font-semibold mem-head-title`,children:[(0,J.jsx)(se,{width:16,height:16,"aria-hidden":`true`}),n(`dash.mem.title`)]}),p&&(0,J.jsxs)(`div`,{className:`mem-head-actions`,children:[(0,J.jsxs)(`span`,{className:`mem-inflight`,children:[(0,J.jsx)(`span`,{className:`mem-inflight-label`,children:n(`dash.mem.inFlight`)}),(0,J.jsx)(`span`,{className:`mem-inflight-value mono`,children:typeof w==`number`?Gn(t).format(w):`—`})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:T,onClick:v,children:n(`dash.mem.restart`)})]})]}),(0,J.jsx)(Qn,{observedBytes:b,thresholdBytes:r?.watchdog?.warnThresholdBytes??null,metric:x,locale:t,t:n}),(0,J.jsxs)(`div`,{className:`stat-row mem-stats`,children:[(0,J.jsx)(Zn,{label:n(`dash.mem.rss`),value:r?Kn(r.rss,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.jsHeap`),value:r?Kn(r.heapUsed,t):`—`,sub:r?n(`dash.mem.jsHeapArena`,{total:Kn(r.heapTotal,t)}):void 0}),(0,J.jsx)(Zn,{label:n(`dash.mem.jscHeap`),value:r?.jscHeap?Kn(r.jscHeap.heapSize,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.growth`),value:y===null?`—`:`${y>=0?`+`:`−`}${Kn(Math.abs(y),t)}${n(`dash.mem.perHour`)}`,tone:S})]}),(0,J.jsxs)(`details`,{style:{marginTop:10},children:[(0,J.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:n(`dash.mem.details`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{margin:`8px 0 0`},children:n(`dash.mem.hint`)}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.runtime`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(Zn,{label:n(`dash.mem.observed`),value:b===null?`—`:`${Kn(b,t)} (${x})`}),(0,J.jsx)(Zn,{label:n(`dash.mem.external`),value:r?.external===void 0?`—`:Kn(r.external,t)}),(0,J.jsx)(Zn,{label:n(`dash.mem.arrayBuffers`),value:r?.arrayBuffers===void 0?`—`:Kn(r.arrayBuffers,t)})]}),(0,J.jsx)(`div`,{className:`muted text-label`,style:{margin:`14px 0 6px`},children:n(`dash.mem.store`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:n(`dash.mem.storeHint`)}),(0,J.jsxs)(`div`,{className:`stat-row`,children:[(0,J.jsx)(Zn,{label:n(`dash.mem.storeEntries`),value:C?Gn(t).format(C.count):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.storeTotal`),value:C?Kn(C.totalBytes,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.storeLargest`),value:C?Kn(C.largestBytes,t):`—`}),(0,J.jsx)(Zn,{label:n(`dash.mem.storeOldest`),value:C?C.count===0?`—`:qn(C.oldestAgeMs,t):`—`})]}),r?.watchdog&&(0,J.jsxs)(`div`,{className:`stat-row`,style:{marginTop:16},children:[(0,J.jsx)(Zn,{label:n(`dash.mem.threshold`),value:Kn(r.watchdog.warnThresholdBytes,t)}),(0,J.jsx)(Zn,{label:n(`dash.mem.lastWarn`),value:r.watchdog.lastWarnAt?new Date(r.watchdog.lastWarnAt).toLocaleString(t):n(`dash.mem.never`)})]})]}),p&&(0,J.jsxs)(`div`,{className:`mem-status`,"aria-live":`polite`,children:[s===`draining`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.draining`,{count:typeof w==`number`?w:0})}),s===`reconnecting`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.reconnecting`)}),s===`error`&&l&&(0,J.jsx)(`span`,{className:`text-control`,style:{color:`var(--danger, #c44)`},children:l}),d&&s===`idle`&&(0,J.jsx)(`span`,{className:`muted text-control`,children:n(`dash.mem.restartNoSupervisor`)})]})]})}function rr({apiBase:e,d:t}){let{t:n,maMode:r,maModeResolved:i,effortCapHelpTriggerRef:a,effortCapHelpOpen:o,setEffortCapHelpOpen:s,effortCap:c,subagentEffortCap:l,effortCapSaving:u,setEffortCap:d,setSubagentEffortCap:f,setEffortCapSaving:p}=t;return!i||r===`v1`?null:(0,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`injection-head`,children:[(0,J.jsxs)(`span`,{className:`injection-label`,style:{display:`inline-flex`,alignItems:`center`,gap:6},children:[n(`dash.effortCapLabel`),(0,J.jsx)(`button`,{ref:a,type:`button`,className:`btn btn-ghost btn-sm`,style:{width:22,height:22,minWidth:22,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},onClick:()=>s(e=>!e),"aria-label":n(`dash.effortCapLabel`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`effort-cap-help-dialog`,children:(0,J.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})]}),(0,J.jsx)(Dt,{value:c,options:[{value:``,label:n(`dash.effortCapNone`)},...Gt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Wt(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,J.jsx)(Dt,{value:l,options:[{value:``,label:n(`dash.effortCapNone`)},...Gt.map(e=>({value:e,label:e}))],onChange:async t=>{if(!u){p(!0);try{let n=await Wt(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 ir({d:e}){let{t,injectionModel:n,injectionEffort:r,injectionEfforts:i,injectionAvailable:a,injectionSaving:o,saveInjection:s}=e;return(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.injectionLabel`)}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsx)(Dt,{value:n,options:[{value:``,label:t(`dash.injectionNone`)},...a.map(e=>({value:e.namespaced,label:An(`${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,J.jsx)(Dt,{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,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>pt(`#subagents`),children:t(`dash.injectionManage`)})]})]})}function ar({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,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`panel maintenance-panel`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-summary`,children:[(0,J.jsxs)(`div`,{className:`dash-sync-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.syncModels`)}),(0,J.jsx)(`div`,{className:`muted text-control dash-sync-hint`,children:t(`dash.syncModelsHint`)})]}),(0,J.jsxs)(`div`,{className:`maintenance-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:v,disabled:r,children:[(0,J.jsx)(fe,{className:r?`spin-icon`:void 0}),` `,t(r?`dash.syncing`:`dash.syncRun`)]}),(0,J.jsx)(`button`,{ref:i,type:`button`,className:`maintenance-update-anchor`,onClick:a,disabled:o,"aria-haspopup":`dialog`,"aria-controls":`dashboard-update-dialog`,"aria-expanded":s,"aria-label":t(`dash.checkUpdate`),tabIndex:-1})]})]}),u&&(0,J.jsxs)(`div`,{className:`notice ${u.status===`failed`?`notice-err`:`notice-ok`} maintenance-notice`,role:`status`,children:[u.status===`failed`?(0,J.jsx)(_e,{}):(0,J.jsx)(fe,{}),(0,J.jsxs)(`span`,{children:[Jt(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,J.jsxs)(`div`,{className:`action-toast notice ${p?`notice-warn`:`notice-ok`}`,role:`status`,"aria-live":`polite`,children:[p?(0,J.jsx)(_e,{}):(0,J.jsx)(le,{}),(0,J.jsxs)(`span`,{children:[t(`dash.syncOk`,{count:c.added}),c.warning?` ${c.warning}`:``,c.nativeSubagentDefaultsWarning?` ${c.nativeSubagentDefaultsWarning}`:``,c.staleAppServerHint?(0,J.jsxs)(J.Fragment,{children:[` `,(0,J.jsx)(ut,{k:`dash.syncStaleHint`,cmd:`ocx sync --restart-codex`})]}):null]}),(0,J.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,J.jsx)(ue,{width:13,height:13,"aria-hidden":`true`})})]}),!m&&l&&(0,J.jsxs)(`div`,{className:`action-toast notice notice-err`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(_e,{}),(0,J.jsx)(`span`,{children:t(`dash.syncFailed`,{error:l})}),(0,J.jsx)(`button`,{type:`button`,className:`action-toast-dismiss`,onClick:y,"aria-label":t(`api.dismiss`),children:(0,J.jsx)(ue,{width:13,height:13,"aria-hidden":`true`})})]})]})}function or({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(wt(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,J.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,J.jsx)(`div`,{className:`dash-vision-advanced-popover-title`,children:e(`dash.visionAdvancedPopover`)}),(0,J.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,J.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-max-label`,children:e(`dash.visionMaxDescriptions`)}),(0,J.jsx)(`span`,{className:`codex-auto-switch-input-wrap`,children:(0,J.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,J.jsx)(`span`,{id:`dash-vision-max-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionMaxDescriptionsInvalid`)})]}),(0,J.jsxs)(`label`,{className:`dash-vision-number`,children:[(0,J.jsx)(`span`,{className:`muted setting-hint`,id:`dash-vision-timeout-label`,children:e(`dash.visionTimeout`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:nn,max:tn,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,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`ms`})]}),s&&(0,J.jsx)(`span`,{id:`dash-vision-timeout-error`,className:`muted setting-hint`,role:`alert`,children:e(`dash.visionTimeoutInvalid`,{min:nn,max:tn})})]})]}):null}function sr({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=sn(l,y),S=ln(x,b),C=String(a?.vision.maxDescriptionsPerTurn??8),w=String(a?.vision.timeoutMs??en),[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=rn(e);if(t===void 0){E(e),A(!0);return}A(!1),E(null),t!==(a?.vision.maxDescriptionsPerTurn??8)&&u(Qt(t))},z=(e=L)=>{let t=an(e);if(t===void 0){O(e),M(!0);return}M(!1),O(null),t!==(a?.vision.timeoutMs??en)&&u($t(t))};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`panel`,children:(0,J.jsxs)(`div`,{className:`spread`,children:[(0,J.jsxs)(`div`,{style:{flex:1,minWidth:0},children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.codexAutoStart`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.codexAutoStartHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${n?.codexAutoStart??!0?`on`:``}`,onClick:i,disabled:!n||r,"aria-label":t(`dash.codexAutoStart`),"aria-pressed":n?.codexAutoStart??!0,children:(0,J.jsx)(`span`,{className:`knob`})})]})}),(0,J.jsxs)(`div`,{className:`dash-sidecar-grid`,children:[(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.webSearchSidecar`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.webSearchSidecarHint`)})]}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsx)(`div`,{className:`dash-sidecar-select-row`,children:(0,J.jsx)(Dt,{value:a?.webSearch.model??`gpt-5.6-luna`,options:s,onChange:e=>{u({webSearch:hn(l,s,e)})},disabled:!a||o,label:t(`dash.sidecarModel`),align:`right`})}),(0,J.jsxs)(`div`,{className:`dash-sidecar-trailing-row`,title:t(`dash.webSearchStreamHint`),children:[(0,J.jsx)(`span`,{className:`muted setting-hint dash-sidecar-toggle-label`,children:t(`dash.webSearchStream`)}),(0,J.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,J.jsx)(`span`,{className:`knob`})})]})]})]}),(0,J.jsxs)(`div`,{className:`panel dash-delegation-summary dash-sidecar-row-card dash-vision-sidecar-card`,"aria-busy":!a||void 0,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:t(`dash.visionSidecar`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:t(`dash.visionSidecarHint`)})]}),(0,J.jsxs)(`div`,{className:`dash-delegation-controls`,children:[(0,J.jsxs)(`div`,{className:`dash-sidecar-select-row`,children:[(0,J.jsx)(Dt,{value:y,options:[{value:``,label:t(`dash.visionOff`)},...c],onChange:e=>{if(e===``){u(Zt(!1));return}let t=ln(sn(l,e),S),n={vision:{model:e,backend:gn(l,c,e),reasoning:t}};v||(n.vision={...n.vision,enabled:!0}),u(n)},disabled:!a||o,label:t(`dash.sidecarModel`)}),(0,J.jsx)(Dt,{value:S,options:cn(x,S).map(e=>({value:e,label:e})),onChange:e=>{u(Xt(e))},disabled:!v||!a||o,align:`right`,label:`${t(`dash.visionSidecar`)} — ${t(`dash.injectionEffortLabel`)}`})]}),(0,J.jsx)(`div`,{className:`dash-sidecar-trailing-row`,children:(0,J.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,J.jsx)(`span`,{children:t(`dash.visionAdvanced`)}),(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`,style:{transform:N?`rotate(90deg)`:`none`,transition:`transform .12s`}})]})})]}),(0,mt.createPortal)((0,J.jsx)(or,{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:z}),document.body)]})]}),(0,J.jsx)(`div`,{className:`panel`,"aria-busy":!d||void 0,children:(0,J.jsxs)(`div`,{className:`spread`,style:{alignItems:`center`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`span`,{className:`font-semibold`,children:t(`dash.shadowCallIntercept`)}),(0,J.jsx)(`button`,{ref: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,J.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})}),(0,J.jsx)(`code`,{className:`muted text-caption`,children:`⚠ ${zt(d?.sourceModels)}`})]}),(0,J.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8,alignItems:`center`},children:[(0,J.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,J.jsx)(`span`,{className:`knob`})}),(0,J.jsx)(Dt,{value:d?.model??``,options:pn(l,d?.model,d?.sourceModels).map(e=>e.value===``?e:{...e,label:An(e.value,t)}),onChange:e=>{g({model:e})},disabled:!d||f||!d?.enabled,label:t(`dash.shadowCallModel`),align:`right`})]})]})})]})}function cr(e){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(rr,{apiBase:e.apiBase,d:e}),(0,J.jsxs)(`div`,{className:`dash-overview-tools`,children:[(0,J.jsx)(ir,{apiBase:e.apiBase,d:e}),(0,J.jsx)(ar,{d:e})]}),(0,J.jsx)(sr,{d:e}),(0,J.jsx)(nr,{apiBase:e.apiBase})]})}function lr(e){return(0,J.jsxs)(`div`,{className:`dash-overview-stack`,children:[(0,J.jsx)(In,{...e}),(0,J.jsx)(cr,{...e})]})}function ur({t:e,providers:t}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`h-section`,children:[e(`dash.activeProviders`),` `,(0,J.jsx)(`span`,{className:`count`,children:t.length})]}),t.length===0?(0,J.jsx)(Ot,{title:(0,J.jsx)(ut,{k:`dash.noProviders`,cmd:`ocx init`})}):(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:e(`dash.col.name`)}),(0,J.jsx)(`th`,{children:e(`dash.col.adapter`)}),(0,J.jsx)(`th`,{children:e(`dash.col.baseUrl`)}),(0,J.jsx)(`th`,{children:e(`dash.col.model`)})]})}),(0,J.jsx)(`tbody`,{children:t.map(t=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`font-semibold`,children:Dn(t.name,e)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`span`,{className:`chip`,children:t.adapter})}),(0,J.jsx)(`td`,{className:`muted mono text-label`,children:t.baseUrl}),(0,J.jsx)(`td`,{className:`muted`,children:t.defaultModel??`—`})]},t.name))})]})})]})}var dr=`__ocxCachedAt`;function fr(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return pr(n)?n.data:n}catch{return null}}function pr(e){return typeof e==`object`&&!!e&&typeof e[dr]==`number`&&`data`in e}function mr(e){try{let t=sessionStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return pr(n)?{data:n.data,cachedAt:n[dr]}:{data:n,cachedAt:null}}catch{return null}}function hr(e,t){try{sessionStorage.setItem(e,JSON.stringify({[dr]:Date.now(),data:t}))}catch{}}function gr(e,t){try{sessionStorage.setItem(e,JSON.stringify(t))}catch{}}function _r(e){return e.routingKind===`custom-local`?`startup.riskDetailCustomLocal`:e.shimCoverage===`cli-only`?`startup.riskDetailWindowsShim`:`startup.riskDetail`}function vr(e,t){return!t.mutationInFlight&&e.request===t.request&&e.mutation===t.mutation}function yr(e,t){return{request:++e.current,mutation:t.current}}var br=2e3;function xr(e){let t=e.status;return t!==`native`&&t!==`protected`&&t!==`at-risk`?null:t}function Sr(e){return e?e.stale&&e.status!==`error`:!1}function Cr(e,t){return!t||e!==null&&e!==`error`?e:t.status}var wr=3e4;function Tr(e){return{multiAgentGuidanceEnabled:e.multiAgentGuidanceEnabled!==!1,syncCodexSubagentDefaults:e.syncCodexSubagentDefaults===!0,injectionModel:e.model??``,injectionEffort:e.effort??``}}function Er(e,t){return t.aborted?!0:e instanceof Error&&e.name===`AbortError`}async function Dr(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=xr(r);if(!i)throw Error(`invalid startup health response`);return{status:i,stale:r.diagnosticStale===!0}}catch(e){if(Er(e,t))throw e;return{status:`error`,stale:!1}}}async function Or(e,t){try{return(await Ft(await fetch(`${e}/api/diagnostics/project-config`,{signal:t})))?.grouped??[]}catch{return[]}}async function kr(e,t){return Wt(await fetch(`${e}/api/models`,{signal:t}))}async function Ar(e,t){return Wt(await fetch(`${e}/api/usage?range=30d`,{signal:t}))}async function jr(e,t,n){let{request:r,mutation:i}=yr(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 Wt(a),c;try{if(o.ok){let e=await o.json();vr({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=e)}else vr({request:r,mutation:i},{request:n.shadowCallRequestEpochRef.current,mutation:n.shadowCallMutationEpochRef.current,mutationInFlight:n.shadowCallMutationInFlightRef.current})&&(c=null)}catch{vr({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 Mr(e,t,n){let{request:r,mutation:i}=yr(n.settingsRequestEpochRef,n.settingsMutationEpochRef),a=await Wt(await fetch(`${e}/api/settings`,{signal:t})),o,s;return vr({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 Nr(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(Er(e,t))throw e;return{maMode:`default`}}}async function Pr(e,t){try{let[n,r]=await Promise.all([fetch(`${e}/healthz`,{signal:t}),fetch(`${e}/api/providers`,{signal:t})]);return{health:await Wt(n),providers:await Wt(r),error:!1}}catch{return{health:null,providers:[],error:!0}}}async function Fr(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={...Tr(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 Ir(e,t=`all`){return t===`codex`?[`usage-summary-30d`,e,`codex`].join(`:`):[`usage-summary-30d`,e,`all`].join(`:`)}var Lr=`ocx.dash.controls.v1:`,Rr=`ocx.dash.overview.v1:`,zr=`ocx.dash.usage30d.v1:`,Br=`ocx.dash.startup.v1:`,Vr=`ocx.dash.maMode.v1:`;function Hr(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 Ur(e){return`${Lr}${e}`}function Wr(e){let{locale:t,t:n}=ct(),[r,i]=(0,_.useState)(Vt),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(new Set),l=(0,_.useMemo)(()=>fr(Ur(e)),[e]),u=(0,_.useMemo)(()=>fr(`${Rr}${e}`),[e]),d=(0,_.useMemo)(()=>fr(`${zr}${e}`),[e]),f=(0,_.useMemo)(()=>{let t=fr(`${Br}${e}`);return t===`error`?null:t},[e]),p=(0,_.useMemo)(()=>fr(`${Vr}${e}`),[e]),[m,h]=(0,_.useState)(()=>u?.health??null),[g,v]=(0,_.useState)(()=>f),[y,b]=(0,_.useState)(()=>u?.providers??[]),[x,S]=(0,_.useState)([]),[C,w]=(0,_.useState)(()=>l?.settings??null),[T,E]=(0,_.useState)(()=>l?.sidecar??null),[D,O]=(0,_.useState)(()=>l?.shadowCall??null),[k,A]=(0,_.useState)(()=>d),[j,M]=(0,_.useState)(!1),[N,P]=(0,_.useState)(!1),[F,I]=(0,_.useState)(!1),[L,R]=(0,_.useState)(!1),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(()=>p??`default`),[U,W]=(0,_.useState)(!1),[ee,K]=(0,_.useState)(null),[q,J]=(0,_.useState)(!1),[Y,te]=(0,_.useState)(!1),[ne,re]=(0,_.useState)(!1),[ie,ae]=(0,_.useState)(``),[oe,X]=(0,_.useState)(``),[se,ce]=(0,_.useState)([]),[le,ue]=(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,Z]=(0,_.useState)(!1),[Se,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)(null),[Ee,De]=(0,_.useState)([]),[Oe,ke]=(0,_.useState)(!1),[Ae,je]=(0,_.useState)(`latest`),[Me,Ne]=(0,_.useState)(!0),[Pe,Fe]=(0,_.useState)(!1),Ie=(0,_.useRef)(0),Le=(0,_.useRef)(null),Re=(0,_.useRef)(0),ze=(0,_.useRef)(0),Be=(0,_.useRef)(0),Ve=(0,_.useRef)(!1),He=(0,_.useRef)(0),Ue=(0,_.useRef)(0),We=(0,_.useRef)(!1),[Ge,Ke]=(0,_.useState)(null),[qe,Je]=(0,_.useState)(null),[Ye,Xe]=(0,_.useState)(null),[Ze,Qe]=(0,_.useState)(!1),[$e,et]=(0,_.useState)(!1),tt=(0,_.useRef)(null),nt=(0,_.useRef)(null),rt=(0,_.useRef)(null),it=(0,_.useRef)(null),at=yn(Y,tt),ot=yn(Oe,nt),st=yn(q,rt),Q=yn(ne,it);(0,_.useEffect)(()=>{let e=()=>i(Vt());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null)},[]);let lt=(0,_.useRef)(f),ut=(0,_.useRef)(0),dt=(0,_.useRef)({settingsRequestEpochRef:ze,settingsMutationEpochRef:Be,settingsMutationInFlightRef:Ve,shadowCallRequestEpochRef:He,shadowCallMutationEpochRef:Ue,shadowCallMutationInFlightRef:We}).current,pt=G(`dashboard-startup-health:${e}`,[e],t=>Dr(e,t),{pollMs:3e4}),mt=Sr(pt.data),ht=pt.refresh;(0,_.useEffect)(()=>{if(!mt)return;let e=window.setTimeout(()=>{ht()},br);return()=>window.clearTimeout(e)},[mt,ht]);let gt=G(`dashboard-overview:${e}`,[e],t=>Pr(e,t),{pollMs:5e3}),_t=m!==null||gt.data!==void 0,vt=G(`dashboard-ma-mode:${e}`,[e],t=>Nr(e,t),{pollMs:5e3}),yt=G(`dashboard-sidecars:${e}`,[e],async t=>{let n=ut.current;return{...await jr(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),bt=G(`dashboard-settings:${e}`,[e],async t=>{let n=ut.current;return{...await Mr(e,t,dt),startupHealthGeneration:n}},{pollMs:5e3}),xt=G(`dashboard-multi-agent:${e}`,[e],t=>Fr(e,t),{pollMs:5e3,enabled:_t}),St=G(Ir(e),[e],t=>Ar(e,t),{enabled:_t,deadlineMs:6e4}),Ct=G(`dashboard-diagnostics:${e}`,[e],t=>Or(e,t),{pollMs:wr,enabled:_t}),wt=G(`dashboard-models:${e}`,[e,$e],t=>kr(e,t),{enabled:_t&&!$e});(0,_.useEffect)(()=>{if(pt.data!==void 0){let t=pt.data;ut.current+=1,v(t.status),lt.current=t.status,t.status!==`error`&&!t.stale&&gr(`${Br}${e}`,t.status)}},[pt.data,e]),(0,_.useEffect)(()=>{let t=gt.data;t&&(t.health&&(h(t.health),b(t.providers),gr(`${Rr}${e}`,{health:t.health,providers:t.providers})),et(t.error))},[gt.data,e]),(0,_.useEffect)(()=>{vt.data!==void 0&&(H(vt.data.maMode),gr(`${Vr}${e}`,vt.data.maMode))},[vt.data,e]);let Tt=vt.data!==void 0||p!==null;(0,_.useEffect)(()=>{let e=xt.data;e&&(e.injection&&(me(e.injection.multiAgentGuidanceEnabled),ge(e.injection.syncCodexSubagentDefaults),ae(e.injection.injectionModel),X(e.injection.injectionEffort),ce(e.injection.injectionEfforts),ue(e.injection.injectionAvailable)),e.effortCaps&&(ve(e.effortCaps.effortCap),be(e.effortCaps.subagentEffortCap)))},[xt.data]),(0,_.useEffect)(()=>{let t=yt.data;if(!t)return;E(t.sidecar),t.shadowCall!==void 0&&O(t.shadowCall);let n=fr(Ur(e))??{};gr(Ur(e),{...n,sidecar:t.sidecar,...t.shadowCall===void 0?{}:{shadowCall:t.shadowCall}})},[yt.data,e]),(0,_.useEffect)(()=>{let t=bt.data;if(t){if(t.settings!==void 0&&w(t.settings),t.startupHealthSeed!==void 0&&t.startupHealthGeneration===ut.current){let n=Cr(lt.current,t.startupHealthSeed);v(n),lt.current=n,n&&gr(`${Br}${e}`,n)}if(t.settings!==void 0){let n=fr(Ur(e))??{};gr(Ur(e),{...n,settings:t.settings})}}},[bt.data,e]),(0,_.useEffect)(()=>{St.data!==void 0&&(A(St.data),gr(`${zr}${e}`,St.data))},[St.data,e]),(0,_.useEffect)(()=>{Ct.data&&De(Ct.data)},[Ct.data]),(0,_.useEffect)(()=>{wt.data&&S(wt.data),I(wt.loading)},[wt.data,wt.loading]),(0,_.useEffect)(()=>()=>{ze.current+=1,He.current+=1},[]);let $=G(Ye?.id&&Ye.restart?`update-job:${e}:${Ye.id}`:`update-job:idle:${e}`,[e,Ye?.id,Ye?.restart,Ye?.latestVersion],async t=>{if(!Ye?.id||!Ye.restart)return{reconnecting:!1};let n=Ye.latestVersion;try{let r=await Wt(await fetch(`${e}/api/update/status?jobId=${encodeURIComponent(Ye.id)}`,{signal:t}));if(r.job){if(r.job.status===`failed`)return{job:r.job,reconnecting:!1};if(n)try{if((await Wt(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:!!(Ye?.id&&Ye.restart),pauseWhenHidden:!1});(0,_.useEffect)(()=>{let e=$.data;e&&(`job`in e&&e.job&&Xe(e.job),Qe(e.reconnecting),`reload`in e&&e.reload&&window.location.reload())},[$.data]);let Et=(0,_.useMemo)(()=>Hr(x),[x]),Dt=(0,_.useMemo)(()=>{let e=a.trim().toLowerCase();if(!e)return Et;let t=[];for(let[n,r]of Et){let i=r.filter(t=>t.id.toLowerCase().includes(e)||n.toLowerCase().includes(e));i.length>0&&t.push([n,i])}return t},[Et,a]),Ot=(0,_.useMemo)(()=>{let e=T?.webSearch.backend;return dn(T?.webSearchModels,x,T?.webSearch.model,e===`routed`?void 0:e)},[x,T?.webSearchModels,T?.webSearch]),kt=(0,_.useMemo)(()=>fn(T?.visionModels,x,T?.vision?.model,T?.vision?.backend),[T?.visionModels,x,T?.vision]),At=async t=>{if(!T||j)return;let n=T,r={webSearch:Yt(T.webSearch,t.webSearch),vision:Yt(T.vision,t.vision),...T.visionModels?{visionModels:T.visionModels}:{},...T.webSearchModels?{webSearchModels:T.webSearchModels}:{}};M(!0),E(r);try{let n=await Wt(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}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}});let r=fr(Ur(e))??{};gr(Ur(e),{...r,sidecar:{webSearch:n.webSearch,vision:n.vision,...n.visionModels?{visionModels:n.visionModels}:{},...n.webSearchModels?{webSearchModels:n.webSearchModels}:{}}})}catch{E(n)}finally{M(!1)}};async function jt(t){if(!D||N)return;let n=D,r={...D,...t};P(!0),We.current=!0,O(r);try{if(!(await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})).ok)throw Error(`shadow-call save failed`);Ue.current+=1}catch{O(n)}finally{We.current=!1,P(!1)}}let Mt=async t=>{if(!(U||V===t)){W(!0),K(null);try{let r=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({multiAgentMode:t})});if(r.ok)H(t),gr(`${Vr}${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{}K(e)}}catch(e){K(e instanceof Error?e.message:n(`dash.maNetworkError`))}finally{W(!1)}}},Nt=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 Wt(await fetch(`${e}/api/injection-model`)),r=Tr(n);me(r.multiAgentGuidanceEnabled),ge(r.syncCodexSubagentDefaults),ae(r.injectionModel),X(r.injectionEffort),Array.isArray(n.efforts)&&ce(n.efforts),Array.isArray(n.available)&&ue(n.available)}catch{}finally{fe(!1)}}},Pt=async()=>{if(!C||L)return;let t=!C.codexAutoStart;R(!0),Ve.current=!0,w({...C,codexAutoStart:t});try{let n=await Wt(await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({codexAutoStart:t})}),`save failed`);Be.current+=1,w(e=>e&&{...e,codexAutoStart:n.codexAutoStart,startupHealth:n.startupHealth??e.startupHealth})}catch{w(e=>e&&{...e,codexAutoStart:!t}),et(!0)}finally{Ve.current=!1,R(!1)}},Ft=(0,_.useCallback)(()=>{Ce(null),Te(null)},[]),It=async()=>{if(!z){B(!0),Ce(null),Te(null);try{let t=await Wt(await fetch(`${e}/api/sync`,{method:`POST`}),`sync failed`);Ce(t),t.projectConfigGrouped&&De(t.projectConfigGrouped)}catch(e){Te(e instanceof Error?e.message:String(e))}finally{B(!1)}}},Lt=async(t,n=!1)=>{n&&(Ie.current=0),Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null);let r=++Re.current;Fe(!0),Je(null),Ke(null);try{let n=await Wt(await fetch(`${e}/api/update/check?tag=${t}`),`update check failed`);if(r!==Re.current)return;if(Ke(n),n.reason===`latest_unavailable`&&Ie.current<2){let e=++Ie.current;Le.current=window.setTimeout(()=>{r===Re.current&&(Le.current=null,Lt(t))},800*e);return}n.reason!==`latest_unavailable`&&(Ie.current=0),Fe(!1)}catch(e){if(r!==Re.current)return;Je(e instanceof Error?e.message:String(e)),Fe(!1)}},Rt=()=>{Re.current+=1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null),Fe(!1),ke(!1)},zt=()=>{let e=Kt(m?.version);je(e),Ne(!0),ke(!0),Lt(e,!0)},Bt=e=>{je(e),Lt(e,!0)},Ut=(0,_.useRef)(zt);return(0,_.useEffect)(()=>{Ut.current=zt}),(0,_.useEffect)(()=>{let e=()=>{Ht()&&(ft(`dashboard`),Ut.current())},t=Ht()?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:St.loading&&!k,healthLoading:gt.loading&&!m,sidecarSaving:j,shadowCallSaving:N,modelsLoading:F,settingsSaving:L,syncing:z,maMode:V,maModeResolved:Tt,maBusy:U,setMaHelpOpen:J,maHelpOpen:q,maError:ee,effortCapHelpOpen:Y,setEffortCapHelpOpen:te,shadowCallHelpOpen:ne,setShadowCallHelpOpen:re,injectionModel:ie,injectionEffort:oe,injectionEfforts:se,injectionAvailable:le,injectionSaving:de,multiAgentGuidanceEnabled:pe,syncCodexSubagentDefaults:he,saveInjection:Nt,effortCap:_e,subagentEffortCap:ye,effortCapSaving:xe,setEffortCap:ve,setSubagentEffortCap:be,setEffortCapSaving:Z,syncResult:Se,syncError:we,projectConfigWarnings:Ee,updateOpen:Oe,updateChannel:Ae,setUpdateRestart:Ne,updateRestart:Me,updateLoading:Pe,updateCheck:Ge,updateError:qe,updateJob:Ye,reconnecting:Ze,error:$e,effortCapHelpTriggerRef:tt,updateTriggerRef:nt,maHelpTriggerRef:rt,shadowCallHelpTriggerRef:it,effortCapHelpDialogRef:at,updateDialogRef:ot,maHelpDialogRef:st,shadowCallHelpDialogRef:Q,filteredGroups:Dt,sidecarModels:Ot,visionModels:kt,saveSidecar:At,saveShadowCall:jt,switchMaMode:Mt,toggleCodexAutoStart:Pt,runSync:It,clearSyncFeedback:Ft,fetchUpdateCheck:Lt,closeUpdateDialog:Rt,openUpdateDialog:zt,changeUpdateChannel:Bt,runUpdate:async()=>{if(Ge?.canUpdate){Je(null);try{let t=await Wt(await fetch(`${e}/api/update/run`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tag:Ae,restart:Me})}),`update failed to start`);if(!t.job)throw Error(`update failed to start`);Xe(t.job),Qe(!1),Rt()}catch(e){Je(e instanceof Error?e.message:String(e))}}}}}function Gr(e){pt(Ut(e))}function Kr({apiBase:e}){let t=Wr(e),{t:n,error:r,selectedSection:i,providers:a,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}=t;if(r)return(0,J.jsx)(Ot,{style:{marginTop:40},icon:(0,J.jsx)(_e,{}),title:(0,J.jsx)(`span`,{style:{color:`var(--red)`},children:n(`dash.cannotConnect`)}),children:(0,J.jsx)(ut,{k:`dash.runStart`,cmd:`ocx start`})});let p=(0,J.jsx)(lr,{...t}),m=(0,J.jsx)(ur,{t:n,providers:a}),h=(0,J.jsx)(jn,{t:n,models:o,modelsLoading:s,modelQuery:c,setModelQuery:l,filteredGroups:u,expandedProviders:d,setExpandedProviders:f}),g=(0,J.jsx)(bn,{...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=Gr,b=e=>{let t=_.findIndex(e=>e.id===i),n=-1;if(e.key===`ArrowRight`?n=(t+1)%_.length:e.key===`ArrowLeft`?n=(t-1+_.length)%_.length:e.key===`Home`?n=0:e.key===`End`&&(n=_.length-1),n<0)return;e.preventDefault();let r=_[n];y(r.id),document.getElementById(`dashboard-tab-${r.id}`)?.focus()};return(0,J.jsxs)(`div`,{className:`dashboard-workspace-shell`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:n(`nav.dashboard`)})}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`dash.subtitle`)}),(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":n(`dash.workspace.sections`),children:_.map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`dashboard-tab-${e.id}`,"aria-selected":i===e.id,"aria-controls":`dashboard-panel-${e.id}`,tabIndex:i===e.id?0:-1,className:`page-tab${i===e.id?` page-tab--active`:``}`,onClick:()=>y(e.id),onKeyDown:b,children:e.label},e.id))}),(0,J.jsx)(`section`,{className:`dashboard-workspace-main`,role:`tabpanel`,id:`dashboard-panel-${v.id}`,"aria-labelledby":`dashboard-tab-${v.id}`,tabIndex:0,children:v.body}),g]})}var qr=`https://chatgpt.com/backend-api/codex`,Jr=`openai`;function Yr(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 Xr=new URL(qr).protocol;function Zr(e,...t){return`${Xr}//${e}/${t.join(`/`)}`}var Qr={"cline-pass":{adapter:`openai-chat`,baseUrl:Zr(`api.cline.bot`,`api`,`v1`)},"mimo-free":{adapter:`mimo-free`,baseUrl:Zr(`api.xiaomimimo.com`,`api`,`free-ai`,`openai`,`chat`)}};function $r(e,t){let n=Qr[e];return!n||t.adapter!==n.adapter||Yr(t.baseUrl)!==Yr(n.baseUrl)}function ei(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 ti(e){return e.keyOptional===!0||e.authMode===`oauth`||e.authMode===`forward`||e.authMode===`local`||ei(e.baseUrl)||e.hasApiKey===!0}function ni(e){return e.adapter===`openai-responses`&&e.authMode===`forward`&&Yr(e.baseUrl)===qr}function ri(e,t){return e===Jr&&ni(t)}function ii(e){return e.freeTier===!0||e.keyOptional===!0||e.authMode===`local`||ei(e.baseUrl)}function ai(e,t){return ri(e,t)?`accounts`:ii(t)?`free`:`paid`}function oi(e,t){let n=[...e],r=(e,t)=>e.name.localeCompare(t.name,void 0,{sensitivity:`base`}),i=e=>e.tier??ai(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 si(e){let t=[],n=[],r=[];for(let[i,a]of Object.entries(e)){if(a.disabled){r.push({name:i,...a});continue}ti(a)?t.push({name:i,...a,tier:ai(i,a)}):n.push({name:i,...a})}return{ready:t,needsSetup:n,disabled:r}}function ci(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 li(e){return e.disabled?`disabled`:`activeNeedsReauth`in e&&e.activeNeedsReauth?`needs-setup`:ti(e)?`ready`:`needs-setup`}function ui(e){let t=e.openai,n=e.chatgpt;if(!t||!n||!ri(`openai`,t)||!ni(n))return e;let r={...e};return delete r.chatgpt,r}function di(e){return e.authMode===`local`||ei(e.baseUrl)}var fi=[`ollama`,`vllm`,`lm-studio`,`lmstudio`,`litellm`,`localai`];function pi(e){let t=(e.authMode??``).toLowerCase();if(t===`oauth`||t===`forward`)return`login`;if(di(e))return`local`;let n=`${e.name??``} ${e.adapter} ${e.baseUrl}`.toLowerCase();return fi.some(e=>n.includes(e))?`selfHosted`:`cloud`}function mi(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 hi(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 gi(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 _i(e){let t={};for(let[n,r]of Object.entries(mi(e)))t[n]=r.length;return t}function vi(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 yi={justNow:`Just now`,notChecked:`Not checked`,minutesAgo:e=>`${e}m ago`,hoursAgo:e=>`${e}h ago`,daysAgo:e=>`${e}d ago`};function bi(e,t,n){let r=typeof t==`object`&&t?t:yi,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 xi(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 Si(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 Ci(e){return e===`Active account needs re-authentication`?`reauth`:e===`Missing credentials`?`missing`:`custom`}function wi(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 Ti(e,t=`en`){return wi(e,t)}function Ei(e,t=`en`){return e==null||!Number.isFinite(e)||e<0?`—`:`~$${new Intl.NumberFormat(t,{minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function Di(e,t){let n=li(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 ki(e){let t=li(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 Ai({name:e,adapter:t,baseUrl:n,cls:r}){let i=Q(),a=En(e,{adapter:t,baseUrl:n});return(0,J.jsx)(`span`,{className:r,children:a?(0,J.jsx)(`img`,{src:a,alt:``,"aria-hidden":`true`}):(0,J.jsx)(ji,{name:e,label:Dn(e,i)})})}function ji({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,J.jsx)(`span`,{className:`provider-icon-fallback`,style:{background:`hsl(${n} 55% 90%)`,color:`hsl(${n} 65% 32%)`},"aria-hidden":`true`,children:r})}function Mi({item:e,selected:t,tabbable:n,modelCount:r,isDefault:i,showConfigId:a,onClick:o,onFocus:s}){let c=Q(),l=ii(e),u=di(e),d=Di(e,c),f=Dn(e.name,c),p=a?`${f} (${e.name})`:f,m=`${i?c(`pws.rail.suffixDefault`):``}${u?c(`pws.rail.suffixLocal`):l?c(`pws.rail.suffixFree`):``}`,h=r!==void 0&&r>0?r===1?c(`pws.modelCountOne`):c(`pws.modelCount`,{count:r}):``,g=[a?e.name:``,h].filter(Boolean).join(` · `);return(0,J.jsxs)(`button`,{type:`button`,className:`providers-workspace-rail-row${t?` providers-workspace-rail-row--selected`:``}`,onClick:o,role:`option`,"aria-selected":t,tabIndex:n?0:-1,"aria-label":c(`pws.rail.selectAria`,{name:p,status:d,suffix:m}),title:p,onFocus:s,children:[(0,J.jsx)(Ai,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`providers-workspace-rail-icon`}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-copy`,children:[(0,J.jsxs)(`span`,{className:`providers-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`providers-workspace-rail-name-label`,title:f,children:f}),u?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,title:c(`pws.localTitle`),children:c(`modal.badge.local`)}):l?(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,title:c(`pws.freeTitle`),children:c(`modal.badge.free`)}):null]}),(0,J.jsx)(`span`,{className:`providers-workspace-rail-secondary`,title:g||void 0,children:g||`\xA0`})]}),(0,J.jsxs)(`span`,{className:`providers-workspace-rail-trail`,children:[i&&(0,J.jsx)(`span`,{className:`pwi-default-star`,title:c(`prov.defaultBadge`),"aria-label":c(`prov.defaultBadge`),children:(0,J.jsx)(Ie,{width:17,height:17,"aria-hidden":`true`})}),(0,J.jsx)(`span`,{className:ki(e),title:d,"aria-hidden":`true`})]})]})}var Ni=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,Pi=e=>{let t=Ni(e);if(t===void 0)return;let n=t>1e10?t:t*1e3;return Number.isFinite(new Date(n).getTime())?t: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`||Ni(t.percent)===void 0?[]:[{label:t.label,percent:t.percent,...Ni(t.resetAt)===void 0?{}:{resetAt:t.resetAt}}]}):[],i=n.creditsUsd&&typeof n.creditsUsd==`object`&&!Array.isArray(n.creditsUsd)?n.creditsUsd:null,a=Ni(i?.used),o=Ni(i?.limit),s=Ni(i?.remaining),c=Ni(i?.percent),l=Pi(i?.expiresAt),u=a!==void 0&&o!==void 0&&s!==void 0&&c!==void 0?{used:a,limit:o,remaining:s,percent:c,...l===void 0?{}:{expiresAt:l},...typeof i?.unlimited==`boolean`?{unlimited:i.unlimited}:{}}:void 0,d={...Ni(n.fiveHourPercent)===void 0?{}:{fiveHourPercent:n.fiveHourPercent},...Ni(n.fiveHourResetAt)===void 0?{}:{fiveHourResetAt:n.fiveHourResetAt},...Ni(n.weeklyPercent)===void 0?{}:{weeklyPercent:n.weeklyPercent},...Ni(n.weeklyResetAt)===void 0?{}:{weeklyResetAt:n.weeklyResetAt},...Ni(n.monthlyPercent)===void 0?{}:{monthlyPercent:n.monthlyPercent},...Ni(n.monthlyResetAt)===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...r.length>0?{customWindows:r}:{},...u?{creditsUsd:u}:{},updatedAt:Ni(n.updatedAt)??t??Date.now()};return d.fiveHourPercent!==void 0||d.weeklyPercent!==void 0||d.monthlyPercent!==void 0||(d.customWindows?.length??0)>0||d.creditsUsd!==void 0?d:null}function Ii(e){return Fi(e?.quota,e?.updatedAt)}function Li(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n=Ni(t.usedPercent);if(n!==void 0)return{usedPercent:n,...typeof t.incomplete==`boolean`?{incomplete:t.incomplete}:{},...Ni(t.excludedAccounts)===void 0?{}:{excludedAccounts:t.excludedAccounts},...Ni(t.nextRecoveryAt)===void 0?{}:{nextRecoveryAt:t.nextRecoveryAt},...Ni(t.nextRecoveryPercent)===void 0?{}:{nextRecoveryPercent:t.nextRecoveryPercent}}}function Ri(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=Ni(n.excludedAccounts),i=Ni(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=Li(t);return typeof t.label==`string`&&n?[{label:t.label,...n}]:[]}):[],s=Li(n.fiveHour),c=Li(n.weekly),l=Li(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:Ni(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 zi(e){if(!e?.trim())return``;let[t,n]=e.split(`:`,2);return n?`${t} · ${n.replace(/-/g,` `)}`:e}function Bi(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 Hi(e,t){if(!e)return null;let n=e.shortPercent===void 0&&e.shortResetAt===void 0?e:{...e,fiveHourPercent:e.fiveHourPercent??e.shortPercent,fiveHourResetAt:e.fiveHourResetAt??e.shortResetAt};return Vi(t)?{...n.monthlyPercent===void 0?{}:{monthlyPercent:n.monthlyPercent},...n.monthlyResetAt===void 0?{}:{monthlyResetAt:n.monthlyResetAt},...n.creditsUsd===void 0?{}:{creditsUsd:n.creditsUsd},...n.resetCredits===void 0?{}:{resetCredits:n.resetCredits},updatedAt:n.updatedAt}:n}function Ui(e){return e===`5h`?0:e===`First-party models`?2:e===`API usage`?3:5}function Wi(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 Gi(e,t,n){let r=Hi(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=Wi(e.label,n);i.push({rank:Ui(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 Ki(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 qi(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function Ji(e){return e>=99.5}function Yi(e,t){return t>0&&e>=t}function Xi(e,t){return Yi(e,t)||Ji(e)?`bar-warn`:`bar-green`}function Zi(e){let t=Math.max(0,Math.min(100,e));return t<=0?0:Math.max(4,Math.round(t))}function Qi(e){return{"--bar-scale":String(Zi(e)/100)}}function $i({quota:e,plan:t,threshold:n,t:r,className:i,layout:a=`compact`,pending:o=!1,incompleteWindowKeys:s,incompleteCustomWindowLabels:c}){let{locale:l}=ct(),u=Gi(e,t,r);return u.length===0?o?a===`stacked`?(0,J.jsxs)(`div`,{className:`quota-stacked quota-stacked--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[Array.from({length:2},(e,t)=>(0,J.jsxs)(`div`,{className:`quota-stacked-row quota-stacked-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`,style:{width:72}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`,style:{width:64}})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`,style:{height:6,flex:1}}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`,style:{width:36}})]})]},t)),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):(0,J.jsxs)(`div`,{className:`codex-account-quota-slot quota-compact quota-compact--pending${i?` ${i}`:``}`,"aria-busy":`true`,role:`status`,children:[(0,J.jsxs)(`div`,{className:`quota-row quota-row--skeleton`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`quota-skel quota-skel--label`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--reset`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--day`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--time`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--bar`}),(0,J.jsx)(`span`,{className:`quota-skel quota-skel--val`})]}),(0,J.jsx)(`span`,{className:`sr-only`,children:r(`common.loading`)})]}):null:a===`stacked`?(0,J.jsx)(`div`,{className:`quota-stacked${i?` ${i}`:``}`,children:u.map(e=>(0,J.jsx)(ta,{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,J.jsx)(`div`,{className:`codex-account-quota-slot quota-compact${i?` ${i}`:``}`,children:u.map(e=>(0,J.jsx)(ea,{label:e.label,percent:e.percent,resetAt:e.resetAt,threshold:n,t:r,locale:l},e.label))})}function ea({label:e,percent:t,resetAt:n,threshold:r,t:i,locale:a}){let o=Ji(t),s=Yi(t,r),c=Xi(t,r),l=ra(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,J.jsxs)(`div`,{className:`quota-row${s?` quota-row--warn`:``}${o?` quota-row--exhausted`:``}`,children:[(0,J.jsx)(`span`,{className:`quota-label`,title:u,children:e}),(0,J.jsx)(`span`,{className:`quota-reset-label`,children:d?i(`codexAuth.resets`):``}),(0,J.jsx)(`span`,{className:`quota-reset-day`,children:l.day}),(0,J.jsx)(`span`,{className:`quota-reset-time`,children:l.time}),(0,J.jsx)(`div`,{className:`bar`,title:u,children:(0,J.jsx)(`div`,{className:`bar-fill ${c}`,style:Qi(t)})}),(0,J.jsxs)(`span`,{className:`quota-val${s?` quota-val--warn`:``}`,title:o?i(`quota.limitReached`):u,"aria-label":u,children:[s&&(0,J.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),Math.round(t),`%`,o?` · ${i(`quota.limitReached`)}`:``]})]})}function ta({row:e,threshold:t,t:n,locale:r,incomplete:i}){let a=Ji(e.percent),o=Yi(e.percent,t),s=Xi(e.percent,t),c=ia(e.resetAt,n,r);return(0,J.jsxs)(`div`,{className:`quota-stacked-row${o?` quota-stacked-row--warn`:``}${a?` quota-stacked-row--exhausted`:``}`,children:[(0,J.jsxs)(`div`,{className:`quota-stacked-head`,children:[(0,J.jsxs)(`span`,{className:`quota-stacked-limit-group`,children:[(0,J.jsx)(`span`,{className:`quota-stacked-limit`,children:e.limitLabel}),i&&(0,J.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,J.jsx)(`span`,{className:`quota-stacked-reset muted`,children:c})]}),(0,J.jsxs)(`div`,{className:`quota-stacked-bar-row`,children:[(0,J.jsx)(`div`,{className:`bar quota-stacked-bar`,children:(0,J.jsx)(`div`,{className:`bar-fill ${s}`,style:Qi(e.percent)})}),(0,J.jsx)(`span`,{className:`quota-stacked-used${o?` quota-stacked-used--warn`:``}`,children:n(`quota.usedPercent`,{pct:Math.round(e.percent)})})]}),a&&(0,J.jsxs)(`div`,{className:`quota-stacked-limit-reached`,role:`status`,children:[(0,J.jsx)(_e,{width:12,height:12,"aria-hidden":`true`}),n(`quota.limitReached`)]})]})}function na(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=e<1e10?e*1e3:e,n=new Date(t);return Number.isFinite(n.getTime())?{date:n,ms:t}:null}function ra(e,t,n){let r=na(e);if(!r)return{day:``,time:``};let{date:i}=r,a=new Date,o=qi(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 ia(e,t,n=`en`,r=Date.now()){let i=na(e);if(!i)return``;let{date:a,ms:o}=i,s=qi(n),c=new Intl.DateTimeFormat(s,{hour:`2-digit`,minute:`2-digit`,hour12:!1}).format(a),l=new Date(r),u=new Date(l.getFullYear(),l.getMonth(),l.getDate()).getTime(),d=new Date(a.getFullYear(),a.getMonth(),a.getDate()).getTime(),f=Math.round((d-u)/864e5);if(f===1)return t(`quota.resetsTomorrow`,{time:c});let p=a.getFullYear()!==l.getFullYear(),m=new Intl.DateTimeFormat(s,{day:`numeric`,month:`short`,...p?{year:`numeric`}:{}}).format(a);if(o<=r)return t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`});let h=Math.round((o-r)/6e4);if(h<60)return t(`quota.resetsRelativeMinutes`,{n:Math.max(1,h)});let g=Math.round(h/60);return g<12&&f===0?t(`quota.resetsRelativeHours`,{n:Math.max(1,g)}):f===0?t(`quota.resetsToday`,{time:c}):t(`quota.resetsAt`,{date:m,time:c,when:`${m}, ${c}`})}function aa(e){switch(e){case`en`:return`en-GB`;case`de`:return`de-DE`;case`fr`:return`fr-FR`;case`ko`:return`ko-KR`;case`zh`:return`zh-CN`;case`zh-TW`:return`zh-TW`;case`ru`:return`ru-RU`;case`ja`:return`ja-JP`;case`tr`:return`tr-TR`;default:return e}}function oa(e){let t=new Date(e>1e10?e:e*1e3);return Number.isFinite(t.getTime())?t:null}function sa({report:e,pending:t}){let n=Q(),{locale:r}=ct(),i=Ri(e),a=Ii(e),o=a?.creditsUsd,s=i?.presentation===`aggregate`,c=new Set,l=new Set;if(s&&i){i.fiveHour?.incomplete&&c.add(`fiveHour`),i.weekly?.incomplete&&c.add(`weekly`),i.monthly?.incomplete&&c.add(`monthly`);for(let e of i.customWindows??[])e.incomplete&&l.add(e.label)}let u=s&&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}))]:[],d=e=>new Intl.NumberFormat(r,{maximumFractionDigits:1}).format(e),f=e=>{let t=oa(e);return t===null?null:new Intl.DateTimeFormat(r,{dateStyle:`medium`,timeStyle:`short`}).format(t)},p=aa(r),m=e=>new Intl.NumberFormat(p,{style:`currency`,currency:`USD`}).format(e),h=o?.expiresAt===void 0?null:(e=>{let t=oa(e);return t===null?null:new Intl.DateTimeFormat(p,{dateStyle:`medium`}).format(t)})(o.expiresAt);return(0,J.jsxs)(J.Fragment,{children:[s&&(0,J.jsx)(`div`,{className:`pws-capacity-label`,children:n(`pws.capacity.estimate`)}),(a||t)&&(0,J.jsx)($i,{quota:a,threshold:80,t:n,layout:`stacked`,pending:t,incompleteWindowKeys:s?c:void 0,incompleteCustomWindowLabels:s?l:void 0}),(o||i)&&(0,J.jsxs)(`div`,{className:`pws-capacity-details`,children:[o&&(0,J.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,J.jsx)(`span`,{children:n(`quota.creditsBalance`)}),(0,J.jsx)(`strong`,{children:m(o.remaining)})]}),h!==null&&(0,J.jsx)(`div`,{className:`pws-capacity-recovery`,children:(0,J.jsx)(`span`,{children:n(`quota.creditsPeriodEnds`,{date:h})})}),u.flatMap(({key:e,label:t,window:r})=>{let i=r.nextRecoveryAt===void 0?null:f(r.nextRecoveryAt);return i!==null&&r.nextRecoveryPercent!==void 0?[(0,J.jsxs)(`div`,{className:`pws-capacity-recovery`,children:[(0,J.jsxs)(`span`,{children:[n(`pws.capacity.nextRecovery`),` · `,t,` · `,i]}),(0,J.jsx)(`strong`,{children:n(`pws.capacity.recoveryShare`,{percent:d(r.nextRecoveryPercent)})})]},e)]:[]}),s&&i&&i.currentAccount?.quota&&(0,J.jsxs)(`div`,{className:`pws-capacity-current`,children:[(0,J.jsxs)(`span`,{className:`pws-capacity-label`,children:[n(`pws.capacity.currentAccount`),i.currentAccount.plan?` · ${i.currentAccount.plan}`:``]}),(0,J.jsx)($i,{quota:i.currentAccount.quota,threshold:80,t:n,layout:`stacked`})]}),i&&i.incomplete&&i.excludedAccounts>0&&(0,J.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.incomplete`,{excluded:i.excludedAccounts,unknown:i.unknownPlanAccounts})}),i&&i.partialWindowAccounts>0&&(0,J.jsx)(`div`,{className:`pws-capacity-incomplete`,children:n(`pws.capacity.partial`,{count:i.partialWindowAccounts})})]})]})}function ca({sections:e,quotaReports:t,usageTotals:n,usageLoading:r=!1,quotasLoading:i=!1,onSelectProvider:a,onEditConfig:o}){let s=Q(),{locale:c}=ct(),l=xi(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)(()=>Si(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?Ii(r):null,a=r?Ri(r):null;r&&(i||a?.presentation===`coverage-only`)&&e.push({item:n,report:r,urgency:i?Ki(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 vi(e).slice(0,4)},[n,d]),b=e=>{let t=Ci(e);return t===`reauth`?s(`pws.attention.reauth`):t===`missing`?s(`pws.attention.missingCredentials`):e};return(0,J.jsxs)(`div`,{className:`pws-dashboard`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header`,children:[(0,J.jsxs)(`div`,{className:`pws-dashboard-header-text`,children:[(0,J.jsx)(`h2`,{className:`pws-dashboard-title`,children:s(`pws.dashboard.title`)}),(0,J.jsx)(`p`,{className:`muted pws-dashboard-subtitle`,children:s(`pws.dashboard.subtitle`)})]}),o&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:s(`prov.editJson`)})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-summary`,children:[(0,J.jsx)(la,{count:h,label:s(`pws.status.ready`),tone:`ok`}),(0,J.jsx)(la,{count:g,label:s(m>0?`pws.status.needsAttention`:`pws.status.needsSetup`),tone:`warn`}),(0,J.jsx)(la,{count:e.disabled.length,label:s(`prov.disabledBadge`),tone:`muted`})]}),p>0&&(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-attention`,"aria-label":s(`pws.attentionTitle`),children:[(0,J.jsxs)(`h3`,{className:`pws-dashboard-section-title`,children:[(0,J.jsx)(_e,{style:{width:14,height:14},"aria-hidden":`true`}),s(`pws.attentionTitle`)]}),(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:f.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row pws-dashboard-row--attention`,onClick:()=>a(e.name),children:[(0,J.jsx)(Ai,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Dn(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:b(e.reason)})]}),(0,J.jsx)(Se,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},`${e.name}:${e.reason}`))})]}),(0,J.jsxs)(`div`,{className:`pws-dashboard-columns`,children:[(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--rate-limits`,"aria-label":s(`pws.dashboard.rateLimits`),"aria-busy":i||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.rateLimits`)}),v.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:v.map(({item:e,report:t})=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Ai,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-dashboard-row-icon`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Dn(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-meta muted`,children:s(`pws.dashboard.checkedAgo`,{time:bi(t.updatedAt,l)})})]}),(0,J.jsx)(Se,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)(sa,{report:t,pending:i&&!t.quota})})]},e.name))}):i?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsxs)(`div`,{className:`pws-dashboard-row-info`,children:[(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--meta`})]}),(0,J.jsx)(`div`,{className:`pws-dashboard-row-bars`,children:(0,J.jsx)($i,{quota:null,threshold:80,t:s,layout:`stacked`,pending:!0})})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noRateLimits`)})]}),(0,J.jsxs)(`section`,{className:`pws-dashboard-section pws-dashboard-section--recent`,"aria-label":s(`pws.dashboard.recentlyUsed`),"aria-busy":r||void 0,children:[(0,J.jsx)(`h3`,{className:`pws-dashboard-section-title`,children:s(`pws.dashboard.recentlyUsed`)}),y.length>0?(0,J.jsx)(`div`,{className:`pws-dashboard-rows`,children:y.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`pws-dashboard-row`,onClick:()=>a(e.name),children:[(0,J.jsx)(Ai,{name:e.name,adapter:``,baseUrl:``,cls:`pws-dashboard-row-icon`}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-name`,children:Dn(e.name,s)}),(0,J.jsx)(`span`,{className:`pws-dashboard-row-count muted`,children:s(`pws.dashboard.requests`,{count:wi(e.requests,c)})}),(0,J.jsx)(Se,{className:`pws-dashboard-row-chevron`,"aria-hidden":`true`})]},e.name))}):r?(0,J.jsx)(`div`,{className:`pws-dashboard-rows pws-dashboard-rows--pending`,"aria-hidden":`true`,children:Array.from({length:3},(e,t)=>(0,J.jsxs)(`div`,{className:`pws-dashboard-row pws-dashboard-row--skeleton`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-row-icon pws-skel`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--name`}),(0,J.jsx)(`span`,{className:`pws-skel pws-skel--count`})]},t))}):(0,J.jsx)(`p`,{className:`muted pws-dashboard-empty`,children:s(`pws.dashboard.noUsage`)})]})]})]})}function la({count:e,label:t,tone:n}){return(0,J.jsxs)(`div`,{className:`pws-dashboard-card pws-dashboard-card--${n}`,children:[(0,J.jsx)(`span`,{className:`pws-dashboard-card-count`,children:e}),(0,J.jsx)(`span`,{className:`pws-dashboard-card-label`,children:t})]})}function ua({editor:e,providerName:t,saving:n,onSave:r,message:i}){let a=Q(),o=(0,_.useRef)(null);return(0,_.useEffect)(()=>{e.open&&o.current?.focus()},[e.open]),e.open?(0,J.jsxs)(`div`,{className:`pwi-json-panel`,children:[(0,J.jsxs)(`div`,{className:`pwi-json-panel-header`,children:[(0,J.jsx)(`span`,{className:`pwi-json-panel-title`,children:a(`pws.jsonEditorTitle`,{name:t})}),(0,J.jsxs)(`div`,{className:`pwi-json-panel-actions`,children:[e.onRestore&&e.isDirty&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onRestore,children:a(`pws.jsonRestore`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:e.onClose,children:a(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:r,disabled:n||!e.isDirty,children:a(n?`pws.saving`:`pws.jsonSave`)})]})]}),(0,J.jsx)(`p`,{className:`pwi-json-panel-desc muted`,children:a(`pws.jsonEditorDesc`)}),(0,J.jsx)(`textarea`,{ref:o,className:`input pwi-json-textarea`,value:e.draft,onChange:t=>e.onDraftChange(t.target.value),spellCheck:!1,rows:20,"aria-label":a(`pws.jsonEditorDesc`)}),i&&(0,J.jsx)(`div`,{className:i.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:i.text})]}):null}var da=[{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`}],fa=18e5;function pa(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>=fa||!(`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 ma(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=pa(i,t);r.trim()&&e&&(n[r]=e)}return n}function ha(e){return ma(fr(e))}function ga(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=pa(r,t);typeof e==`string`&&e.trim()&&i&&(n[e]=i)}return n}function _a({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=Q(),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)({ready:!0,needsSetup:!0,disabled:!0}),[x,S]=(0,_.useState)({free:!0,paid:!0}),[C,w]=(0,_.useState)({cloud:!0,local:!0,selfHosted:!0,login:!0}),[T,E]=(0,_.useState)(`az`),[D,O]=(0,_.useState)(!1),[k,A]=(0,_.useState)(null),[j,M]=(0,_.useState)({}),[N,P]=(0,_.useState)({}),[F,I]=(0,_.useState)({}),[L,R]=(0,_.useState)({}),[z,B]=(0,_.useState)(!1),[V,H]=(0,_.useState)(!1),U=`ocx.providers.quotas.v1:${t}`,W=`ocx.providers.usage.v1:${t}`,[ee,K]=(0,_.useState)(()=>fr(W)?.totals??{}),[q,Y]=(0,_.useState)(()=>fr(W)?.models??{}),[te,ne]=(0,_.useState)(()=>ha(U)??{}),[re,ie]=(0,_.useState)(()=>!fr(W)),[ae,oe]=(0,_.useState)(()=>{let e=ha(U);return!e||Object.keys(e).length===0}),[X,se]=(0,_.useState)(0),ce=(0,_.useRef)(null),le=G(Ir(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()},{deadlineMs:6e4}),ue=(0,_.useMemo)(()=>ci(si(ui(e)),d??{}),[e,d]),de=(0,_.useCallback)(()=>{se(e=>e+1)},[]);(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{B(!0),(async()=>{try{let n=await Pt(await fetch(`${t}/api/selected-models`));if(e)return;M(_i(n)),P(mi(n)),I(hi(n)),R(gi(n)),H(!1)}catch{if(e)return;H(!0)}finally{e||B(!1)}})()},0);return()=>{e=!0,window.clearTimeout(n)}},[t,u,X]),(0,_.useEffect)(()=>{let e=!1,t=window.setTimeout(()=>{let t=le.data;if(e)return;if(!t){le.loading&&ie(!fr(W));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}})}Y(r),gr(W,{totals:n,models:r}),ie(!1)},0);return()=>{e=!0,window.clearTimeout(t)}},[t,W,le.data,le.loading]),(0,_.useEffect)(()=>{let e=!1,n=window.setTimeout(()=>{let n=ha(U);(!n||Object.keys(n).length===0)&&oe(!0),fetch(`${t}/api/provider-quotas${p?`?refresh=1`:``}`).then(e=>Ft(e)).then(t=>{if(e||!t)return;let n=ga(t.reports);ne(n),gr(U,n)}).catch(()=>{e||ne(e=>{let t=ma(e)??{};return gr(U,t),t})}).finally(()=>{e||oe(!1)})},0);return()=>{e=!0,window.clearTimeout(n)}},[t,f,p,U]),(0,_.useEffect)(()=>{if(!D)return;let e=e=>{ce.current&&!ce.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 fe=(0,_.useMemo)(()=>[...ue.ready,...ue.needsSetup,...ue.disabled],[ue]),pe=(0,_.useMemo)(()=>fe.filter(ii).length,[fe]),me=fe.length-pe,ge=(0,_.useMemo)(()=>{let e={cloud:0,local:0,selfHosted:0,login:0};for(let t of fe)e[pi(t)]+=1;return e},[fe]),_e=(0,_.useMemo)(()=>{let e=g.trim().toLowerCase(),t=t=>oi(t.filter(t=>{if(e&&!t.name.toLowerCase().includes(e)&&!t.adapter.toLowerCase().includes(e))return!1;let n=ii(t);return!(n&&!x.free||!n&&!x.paid||!C[pi(t)])}),T);return{ready:y.ready?t(ue.ready):[],needsSetup:y.needsSetup?t(ue.needsSetup):[],disabled:y.disabled?t(ue.disabled):[]}},[ue,g,y,x,C,T]),ve=!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?fe.find(e=>e.name===r)??null:null,[r,fe]),Z=(0,_.useMemo)(()=>{let e=new Map;for(let t of fe){let n=Dn(t.name,h);e.set(n,(e.get(n)??0)+1)}let t=new Set;for(let[n,r]of e.entries())r>1&&t.add(n);return t},[fe,h]);if(fe.length===0)return(0,J.jsx)(va,{onAddProvider:o});let Se=[{key:`ready`,label:h(`pws.status.ready`),count:ue.ready.length},{key:`needsSetup`,label:h(`pws.status.needsSetup`),count:ue.needsSetup.length},{key:`disabled`,label:h(`prov.disabledBadge`),count:ue.disabled.length}],Ce=[{id:`ready`,label:h(`pws.status.ready`),count:_e.ready.length,ariaLabel:h(`pws.groupReady`,{count:_e.ready.length}),items:_e.ready},{id:`needs-setup`,label:h(`pws.status.needsSetup`),count:_e.needsSetup.length,ariaLabel:h(`pws.groupNeedsSetup`,{count:_e.needsSetup.length}),items:_e.needsSetup},{id:`disabled`,label:h(`prov.disabledBadge`),count:_e.disabled.length,ariaLabel:h(`pws.groupDisabled`,{count:_e.disabled.length}),items:_e.disabled}],we=Ce.flatMap(e=>e.items.map(e=>e.name)),Te=k&&we.includes(k)?k:r&&we.includes(r)?r:we[0]??null;return(0,J.jsx)(`div`,{className:`pws-shell-container`,children:(0,J.jsxs)(`div`,{className:`pws-root`,children:[(0,J.jsxs)(`aside`,{className:`pws-rail`,"aria-label":h(`pws.providerList`),children:[(0,J.jsxs)(`div`,{className:`pws-search-row`,children:[(0,J.jsxs)(`div`,{className:`pws-search-wrap`,children:[(0,J.jsx)(ye,{className:`pws-search-icon`,width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`input`,{type:`search`,className:`input pws-search-input`,placeholder:h(`pws.searchPlaceholder`),value:g,onChange:e=>v(e.target.value),"aria-label":h(`pws.searchPlaceholder`)})]}),(0,J.jsxs)(`div`,{className:`pws-filter-wrap`,ref:ce,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-filter-btn${ve||D?` pws-filter-btn--active`:``}`,onClick:()=>O(e=>!e),"aria-label":h(`pws.filterAria`),"aria-expanded":D,"aria-controls":`pws-provider-filters`,children:[(0,J.jsx)(Le,{width:18,height:18,"aria-hidden":`true`}),ve&&(0,J.jsx)(`span`,{className:`pws-filter-dot`,"aria-hidden":`true`})]}),D&&(0,J.jsxs)(`div`,{id:`pws-provider-filters`,className:`pws-filter-menu`,role:`group`,"aria-label":h(`pws.providerFiltersAria`),children:[(0,J.jsx)(`div`,{className:`pws-filter-title`,children:h(`pws.filters`)}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterStatus`)}),Se.map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:y[e],onChange:()=>b(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.pricing`)}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:x.free,onChange:()=>S(e=>({...e,free:!e.free}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`modal.badge.free`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:pe})]}),(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:x.paid,onChange:()=>S(e=>({...e,paid:!e.paid}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:h(`pws.paid`)}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:me})]}),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.filterType`)}),[{key:`cloud`,label:h(`pws.type.cloud`),count:ge.cloud},{key:`local`,label:h(`pws.type.local`),count:ge.local},{key:`selfHosted`,label:h(`pws.type.selfHosted`),count:ge.selfHosted},{key:`login`,label:h(`pws.type.login`),count:ge.login}].map(({key:e,label:t,count:n})=>(0,J.jsxs)(`label`,{className:`pws-filter-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:C[e],onChange:()=>w(t=>({...t,[e]:!t[e]}))}),(0,J.jsx)(`span`,{className:`pws-filter-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-filter-count`,children:n})]},e)),(0,J.jsx)(`div`,{className:`pws-filter-head`,children:h(`pws.sort`)}),(0,J.jsx)(`div`,{className:`pws-sort-grid`,role:`group`,"aria-label":h(`pws.sortProvidersAria`),children:da.map(e=>(0,J.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,J.jsx)(`div`,{className:`pws-filter-footer`,children:(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:be,disabled:!ve,children:h(`pws.resetAll`)})})]})]})]}),(0,J.jsxs)(`div`,{className:`pws-rail-list`,role:`listbox`,"aria-label":h(`pws.providersAria`),onKeyDown:e=>{let t=Array.from(e.currentTarget.querySelectorAll(`[role="option"]`));if(t.length===0)return;let n=document.activeElement,r=t.findIndex(e=>e===n||e.contains(n));if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let n=e.key===`ArrowDown`?1:-1;t[r<0?n>0?0:t.length-1:(r+n+t.length)%t.length]?.focus();return}if(e.key===`Home`){e.preventDefault(),t[0]?.focus();return}e.key===`End`&&(e.preventDefault(),t[t.length-1]?.focus())},children:[Object.values(_e).every(e=>e.length===0)&&(0,J.jsx)(`span`,{className:`muted pws-rail-empty`,role:`status`,children:h(g?`pws.noSearchResults`:ve?`pws.noMatchFilters`:`pws.noProvidersConfigured`)}),Ce.map(({id:e,label:t,count:o,ariaLabel:s,items:c})=>c.length===0?null:(0,J.jsxs)(`div`,{className:`pws-rail-group`,role:`group`,"aria-label":s,children:[(0,J.jsxs)(`div`,{className:`pws-rail-group-head`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`pws-rail-group-label`,children:t}),(0,J.jsx)(`span`,{className:`pws-rail-group-count`,children:o})]}),c.map(e=>(0,J.jsxs)(`div`,{className:`pws-rail-row-wrap`,children:[(0,J.jsx)(Mi,{item:e,selected:r===e.name,tabbable:Te===e.name,modelCount:j[e.name],isDefault:n===e.name,showConfigId:Z.has(Dn(e.name,h)),onClick:()=>i(e.name),onFocus:()=>A(e.name)}),a&&(0,J.jsx)(`button`,{type:`button`,className:`pws-rail-row-remove`,tabIndex:-1,"aria-hidden":`true`,onClick:t=>{t.stopPropagation(),a(e.name)},title:h(`pws.removeConfirmTitle`),children:(0,J.jsx)(he,{width:14,height:14})})]},e.name))]},e))]})]}),(0,J.jsx)(`main`,{className:`pws-main`,"aria-label":h(`pws.workspaceMainAria`),children:c?.open?(0,J.jsx)(ua,{editor:c,providerName:h(`nav.providers`),saving:l,onSave:()=>{c.onSave()}}):xe?m?.(xe,{usageTotals:ee[xe.name],modelUsage:q[xe.name],quotaReport:te[xe.name],availableModels:N[xe.name]??[],hasLiveModels:(F[xe.name]??0)>0,selectedModels:L[xe.name]??[],modelsLoading:z,modelsLoadFailed:V,onRetryModels:de})??(0,J.jsxs)(`div`,{className:`pws-detail-placeholder`,children:[(0,J.jsx)(`h3`,{children:Dn(xe.name,h)}),(0,J.jsx)(`p`,{className:`muted`,children:h(`pws.detailComingSoon`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>i(null),children:h(`modal.back`)})]}):(0,J.jsx)(ca,{sections:ue,quotaReports:te,usageTotals:ee,usageLoading:re,quotasLoading:ae,onSelectProvider:e=>i(e),onEditConfig:s})})]})})}function va({onAddProvider:e}){let t=Q();return(0,J.jsx)(`div`,{className:`pws-empty-root`,children:(0,J.jsxs)(`div`,{className:`pws-empty-hero`,children:[(0,J.jsx)(`div`,{"aria-hidden":`true`,children:(0,J.jsx)(re,{style:{width:64,height:64}})}),(0,J.jsx)(`h2`,{children:t(`pws.connectFirst`)}),(0,J.jsxs)(`div`,{className:`pws-empty-tiles`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`free`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Ne,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.browseFree`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.browseFreeDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({tier:`accounts`}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(De,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.connectAccount`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.connectAccountDesc`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`pws-empty-tile`,onClick:()=>e({custom:!0}),children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:(0,J.jsx)(Ee,{width:18,height:18})}),(0,J.jsx)(`span`,{className:`pws-empty-tile-label`,children:t(`pws.empty.addEndpoint`)}),(0,J.jsx)(`span`,{className:`pws-empty-tile-desc muted`,children:t(`pws.empty.addEndpointDesc`)})]})]})]})})}function ya(e){if(ri(e.name,e))return`codex-accounts`;let t=(e.authMode??``).toLowerCase();if(t===`forward`||t===`local`||di(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 ba(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 xa({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=Q(),{locale:m}=ct(),h=xi(p),g=li(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=Ii(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 Pt(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,J.jsxs)(`div`,{className:`pws-overview-layout`,children:[(0,J.jsxs)(`div`,{className:`pws-overview-main`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.connection`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.connection`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`dash.status`)}),(0,J.jsxs)(`dd`,{className:g===`ready`?`pws-status-ok`:`pws-status-warn`,children:[g===`ready`?(0,J.jsx)(le,{style:{width:13,height:13},"aria-hidden":`true`}):(0,J.jsx)(_e,{style:{width:13,height:13},"aria-hidden":`true`}),y]})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.baseUrl`)}),(0,J.jsx)(`dd`,{children:(0,J.jsx)(`code`,{children:e.baseUrl?.trim()?e.baseUrl:`—`})})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.auth`)}),(0,J.jsx)(`dd`,{children:r?`${Oi(e,p)} · ${r}`:Oi(e,p)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`modal.defaultModel`)}),(0,J.jsx)(`dd`,{children:e.defaultModel??(0,J.jsx)(`span`,{className:`muted`,children:`—`})})]}),e.note&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.cell.note`)}),(0,J.jsx)(`dd`,{className:`muted`,children:e.note})]})]}),a&&(0,J.jsxs)(`div`,{className:`row`,style:{marginTop:12,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:D,onClick:()=>void k(),children:p(D?`pws.testing`:`pws.testConnection`)}),O&&(0,J.jsx)(`span`,{role:`status`,className:A===`ok`?`pws-status-ok`:A===`failed`?`pws-status-warn`:`muted`,"data-connection-test-state":A,children:j})]}),s&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn pws-edit-settings-link`,onClick:s,children:p(`pws.editSettings`)})]}),n&&(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.rateLimits`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.rateLimits`)}),(0,J.jsx)(sa,{report:n,pending:!1})]}),(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.authSummary`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.authSummary`)}),v?(0,J.jsxs)(`div`,{className:`pws-auth-summary pws-auth-summary--warn`,role:`status`,children:[(0,J.jsx)(_e,{style:{width:14,height:14},"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pws-auth-summary-body`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:p(`pws.status.needsAttention`)}),` — `,e.authMode===`forward`?p(`pws.attention.reauthForward`):p(`pws.attention.reauth`)]}),u&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:f,onClick:()=>u(),children:p(f?`prov.waitingBrowser`:`pws.reauthenticate`)}),f&&d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>d(),children:p(`common.cancel`)})]})]}):(0,J.jsxs)(`div`,{className:`pws-auth-summary`,children:[(0,J.jsx)(`span`,{className:`pws-auth-dot`}),(0,J.jsx)(`span`,{children:e.authMode===`forward`?p(`pws.passthrough`):e.authMode===`oauth`?r?p(`pws.loggedInAs`,{email:r}):i?.loggedIn?p(`pws.loggedInTitle`):p(`pws.notLoggedIn`):e.hasApiKey?p(`pws.apiKeyConfigured`):Oi(e,p)})]})]})]}),(0,J.jsxs)(`aside`,{className:`pws-overview-sidebar`,children:[(0,J.jsxs)(`section`,{className:`pws-section`,"aria-label":p(`pws.statsAria`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:p(`pws.statsTitle`)}),(0,J.jsxs)(`dl`,{className:`pws-kv`,children:[typeof b==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalRequests`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:wi(b,m)})]}),typeof x==`number`&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.totalTokens`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,children:Ti(x,m)})]}),n&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:p(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{className:`pws-kv-mono`,title:n.source?zi(n.source):void 0,children:bi(n.updatedAt,h)})]}),typeof b!=`number`&&typeof x!=`number`&&!n&&(0,J.jsx)(`div`,{className:`muted`,children:p(`pws.usageUnavailable`)})]}),c&&(0,J.jsxs)(`button`,{type:`button`,className:`link-btn pws-view-usage-link`,onClick:c,children:[p(`pws.viewUsage`),` →`]}),S&&(0,J.jsx)(`div`,{className:`muted pws-stats-note`,children:p(`pws.stats.quotaTracked`)})]}),(0,J.jsx)(Sa,{item:e,onUpdateProvider:l})]})]})}function Sa({item:e,onUpdateProvider:t}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(``),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{r&&d.current?.focus()},[r]);let f=(0,_.useCallback)(async()=>{if(s||!t)return;let r=a.trim();if(r===(e.note??``)){i(!1),u(``);return}c(!0);try{let a=await t(e.name,{note:r||void 0});if(!a.ok){u(a.error||n(`prov.saveFailed`));return}u(``),i(!1)}finally{c(!1)}},[a,e.name,e.note,t,s,n]);return r?(0,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.jsx)(`textarea`,{ref:d,className:`pws-notes-textarea`,value:a,onChange:e=>o(e.target.value),onBlur:()=>void f(),onKeyDown:t=>{t.key===`Escape`&&(o(e.note??``),u(``),i(!1))},placeholder:n(`pws.notePlaceholder`),rows:3,disabled:s}),l?(0,J.jsx)(`p`,{className:`pws-inline-error`,role:`alert`,children:l}):null]}):(0,J.jsxs)(`section`,{className:`pws-section pws-notes-section`,"aria-label":n(`pws.notes`),children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:n(`pws.notes`)}),(0,J.jsx)(`button`,{type:`button`,className:`pws-notes-display`,onClick:()=>{t&&(o(e.note??``),u(``),i(!0))},disabled:!t,children:e.note||(0,J.jsx)(`span`,{className:`muted`,children:n(`pws.notePlaceholder`)})})]})}function Ca(e){return e.includes(`/`)?e.replaceAll(`/`,`-`):e}function wa(e,t){let n=Ca(e);for(let r of t)if(r!==e&&Ca(r)===n)return!0;return!1}function Ta({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=Q(),[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=[...n,...S,...P,...e.defaultModel?[e.defaultModel]:[]],L=!w||!F||n.includes(F)||S.includes(F)||P.includes(F)||e.defaultModel===F||wa(F,I),R=(0,_.useMemo)(()=>Bi(n,e.defaultModel,d,P,S,r),[n,e.defaultModel,d,P,S,r]);(0,_.useEffect)(()=>{let n=!0;return(async()=>{try{let r=await fetch(`${t}/api/custom-models`);if(!r.ok)throw Error();let i=await r.json();if(!Array.isArray(i))throw Error(`Invalid custom model list`);if(!n)return;C(i.flatMap(t=>{if(!t||typeof t!=`object`)return[];let n=t;return n.provider===e.name&&typeof n.modelId==`string`?[n.modelId]:[]})),D(!1),y(``),T(!0)}catch{if(!n)return;C([]),T(!1),D(!0),y(u(`models.networkError`))}})(),()=>{n=!1}},[t,e.name,u,O]);let z=()=>{T(!1),D(!1),y(``),k(e=>e+1)};(0,_.useEffect)(()=>()=>{M.current!=null&&window.clearTimeout(M.current)},[]);let B=async e=>{try{await navigator.clipboard.writeText(e),j(e),M.current!=null&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{j(t=>t===e?null:t),M.current=null},1200)}catch{}},V=async()=>{if(!(L||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=R.length>300,ee=W?R.slice(0,300):R;return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-section-head`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:u(`pws.tab.models`)}),R.length>0&&(0,J.jsx)(`span`,{className:`muted`,children:u(`pws.modelsAvailable`,{count:R.length})})]}),s&&(0,J.jsxs)(`div`,{className:`pws-inline-error`,role:`status`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsNeedsReauth`)}),l&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:l,children:u(`pws.tab.accounts`)})]}),U&&!s&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginBottom:10},children:u(`pws.modelsConfiguredFallback`)}),(0,J.jsx)(`label`,{className:`text-label pws-custom-model-label`,htmlFor:`pws-custom-model-${e.name}`,children:u(`models.customAdd`)}),(0,J.jsxs)(`div`,{className:`row pws-custom-model-row`,children:[(0,J.jsx)(`input`,{id:`pws-custom-model-${e.name}`,className:`input`,value:p,onChange:e=>m(e.target.value),onKeyDown:e=>{e.key===`Enter`&&V()},placeholder:u(`models.customFieldModelIdPlaceholder`),"aria-label":u(`models.customAdd`),disabled:h}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{V()},disabled:h||L,children:u(h?`models.customSaving`:`models.customAddBtn`)})]}),b&&(0,J.jsx)(`p`,{className:`muted text-label`,role:`status`,children:b}),v&&(0,J.jsxs)(`p`,{className:`pws-inline-error`,role:`alert`,children:[v,E&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:z,style:{marginLeft:8},children:u(`common.retry`)})]}),!H&&(0,J.jsx)(`input`,{type:`search`,className:`input pws-model-search`,placeholder:u(`pws.modelSearchPlaceholder`),value:d,onChange:e=>f(e.target.value),"aria-label":u(`pws.modelSearchPlaceholder`)}),a&&H?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.modelsLoading`)}):o&&H?(0,J.jsxs)(`div`,{role:`alert`,className:`pws-inline-error`,children:[(0,J.jsx)(`span`,{children:u(`pws.modelsLoadFailed`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:c,children:u(`pws.retry`)})]}):H?(0,J.jsx)(`p`,{className:`muted`,children:u(`pws.noModels`)}):R.length===0?(0,J.jsx)(`p`,{className:`muted`,role:`status`,children:u(`pws.noModelMatch`)}):(0,J.jsx)(`ul`,{className:`pws-model-list`,children:ee.map(t=>{let n=t===e.defaultModel,r=N.has(t);return(0,J.jsxs)(`li`,{className:`pws-model-chip`,children:[(0,J.jsx)(`button`,{type:`button`,className:`pws-model-chip-main`,onClick:()=>{B(t)},title:t,"aria-label":u(A===t?`pws.modelCopied`:`pws.copyModelId`),children:(0,J.jsx)(`span`,{className:`pws-model-id`,children:t})}),n?(0,J.jsx)(`span`,{className:`badge badge-muted pws-model-flag`,children:u(`prov.defaultBadge`)}):null,r?(0,J.jsx)(`span`,{className:`badge badge-accent pws-model-flag`,children:u(`pws.selected`)}):null]},t)})}),W&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:10},children:u(`pws.modelsTruncated`,{shown:`300`,total:String(R.length)})})]})}function Ea({item:e,usageTotals:t,quotaReport:n,modelUsage:r}){let i=Q(),{locale:a}=ct(),o=xi(i),s=t?.requests!==void 0,c=Ii(n),[l,u]=(0,_.useState)(null),d=(0,_.useMemo)(()=>r?.length?r.toSorted((e,t)=>t.totalTokens-e.totalTokens):[],[r]),f=(0,_.useMemo)(()=>{if(!d.length)return;let e=0,t=!1;for(let n of d)n.estimatedCostUsd!==void 0&&(e+=n.estimatedCostUsd,t=!0);return t?e:void 0},[d]);return(0,J.jsxs)(`div`,{className:`pws-section`,children:[(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.usageLast30d`)}),s?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`pws-usage-metrics pws-usage-metrics-3`,role:`group`,"aria-label":i(`pws.usageLast30d`),children:[(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value mono`,children:Ei(f,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.estimatedCost`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:wi(t?.requests,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricRequests`)})]}),(0,J.jsxs)(`div`,{className:`pws-usage-metric`,children:[(0,J.jsx)(`span`,{className:`pws-usage-metric-value`,children:Ti(t?.totalTokens,a)}),(0,J.jsx)(`span`,{className:`muted pws-usage-metric-label`,children:i(`pws.metricTokens`)})]})]}),(0,J.jsx)(`p`,{className:`muted pws-cost-disclaimer`,children:i(`pws.costDisclaimer`)})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.usageUnavailable`)})]}),d.length>0&&(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.modelBreakdown`)}),(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`pws-model-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`pws.col.model`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.cost`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.tokens`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`pws.col.requests`)}),(0,J.jsx)(`th`,{children:i(`pws.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:d.map(e=>{let t=e.model,n=l===t;return(0,J.jsxs)(_.Fragment,{children:[(0,J.jsxs)(`tr`,{className:`pws-model-row`,children:[(0,J.jsx)(`td`,{className:`mono`,children:(0,J.jsx)(`button`,{type:`button`,className:`pws-model-expand`,"aria-expanded":n,onClick:()=>u(n?null:t),children:e.model})}),(0,J.jsx)(`td`,{className:`num mono`,children:Ei(e.estimatedCostUsd,a)}),(0,J.jsx)(`td`,{className:`num mono`,children:Ti(e.totalTokens,a)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`pws-share-bar`,children:(0,J.jsx)(`div`,{className:`pws-share-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]}),n&&(0,J.jsx)(`tr`,{className:`pws-model-detail`,children:(0,J.jsx)(`td`,{colSpan:5,children:(0,J.jsxs)(`div`,{className:`pws-model-detail-grid`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenInput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Ti(e.inputTokens,a)]})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`muted`,children:i(`pws.tokenOutput`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[` `,Ti(e.outputTokens,a)]})]})]})})})]},t)})})]})})]}),(0,J.jsxs)(`div`,{className:`pws-usage-block`,children:[(0,J.jsx)(`h3`,{className:`pws-section-title`,children:i(`pws.rateLimits`)}),c?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($i,{quota:c,plan:null,threshold:80,t:i,layout:`stacked`}),(0,J.jsxs)(`dl`,{className:`pws-kv pws-usage-meta`,children:[n?.source?.trim()&&(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.source`)}),(0,J.jsx)(`dd`,{children:zi(n.source)})]}),(0,J.jsxs)(`div`,{className:`pws-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`pws.stats.quotaUpdated`)}),(0,J.jsx)(`dd`,{children:bi(n?.updatedAt,o)})]})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`pws.quotaUnavailable`)})]})]})}function Da(e){if(!e)return null;let t=e.trim();return t?t.length<=4?`account-…`:`account-…${t.slice(-4)}`:null}function Oa(e){return Da(e)??`account-…`}function ka(e){return e===`healthy`?`ok`:e===`cooldown`?`muted`:e===`reauth_required`||e===`warning`?`warn`:`muted`}function Aa(e){let t=ka(e);return t===`ok`?`badge badge-green`:t===`warn`?`badge badge-amber`:`badge badge-muted`}function ja(e){return e===`reauth_required`}function Ma(e){return!!e?.needsReauth||ja(e?.health?.status)}function Na(e){return e===`cooldown`}function Pa(e){return e===`warning`||e===`reauth_required`}function Fa(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 Ia(e,t){let n=Fa(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`):Oa(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 Ra(e){let t=navigator.clipboard?.writeText?.bind(navigator.clipboard);if(t)try{return await t(e),!0}catch{}return za(e)}function za(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 Ba(e,t){return e(t?t===`copied`?`pws.doctorCopied`:`pws.doctorCopyUnavailable`:`pws.copyDoctor`)}var Va=e=>({step:e?`oauth-waiting`:`pick`,id:``,error:``,authUrl:``,manualCode:``,manualCodeState:`idle`,statusNotice:``,statusTone:`ok`,flowId:null});function Ha(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 Ua({id:e,error:t,onIdChange:n,onStartOAuth:r,onClose:i}){let a=Q();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:a(`codexAuth.addTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:a(`codexAuth.addPickDesc`)}),(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`codex-account-id-input`,children:a(`codexAuth.addIdLabel`)}),(0,J.jsx)(`input`,{id:`codex-account-id-input`,className:`input`,placeholder:a(`codexAuth.addIdPlaceholder`),value:e,onChange:e=>n(e.target.value),style:{marginBottom:12}}),(0,J.jsx)(`button`,{type:`button`,className:`list-row`,onClick:r,style:{marginBottom:8},children:(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:10},children:[(0,J.jsx)(Ne,{width:20}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:a(`codexAuth.oauthLogin`)}),(0,J.jsx)(`div`,{className:`sub`,children:a(`codexAuth.oauthDesc`)})]})]})}),t&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:8},children:t}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:i,style:{width:`100%`},children:a(`codexAuth.cancel`)})]})}var Wa=2500;function Ga(){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;Ra(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)},Wa))})},[i])}}function Ka({url:e}){let t=Q(),{outcomeFor:n,copy:r}=Ga();if(!e)return null;let i=n(e),a=t(i===`copied`?`prov.linkCopied`:i===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyLink`);return(0,J.jsxs)(`div`,{className:`login-url-block`,children:[(0,J.jsx)(`code`,{className:`login-url-block-text`,children:e}),(0,J.jsxs)(`div`,{className:`login-url-block-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>r(e,e),children:[(0,J.jsx)(ke,{style:{width:13,height:13},"aria-hidden":`true`}),(0,J.jsx)(`span`,{"aria-live":`polite`,children:a})]}),(0,J.jsxs)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,className:`login-url-block-open`,children:[(0,J.jsx)(Te,{style:{width:13,height:13},"aria-hidden":`true`}),` `,t(`prov.didntOpen`)]})]})]})}function qa({hint:e,paste:t}){let n=Q(),r=Ga(),i=e.deviceCode??``,a=e.url??``;if(!i&&!a&&!e.instructions&&!t)return null;let o=r.outcomeFor(i),s=n(o===`copied`?`prov.codeCopied`:o===`unavailable`?`prov.linkCopyUnavailable`:`prov.copyCode`);return(0,J.jsxs)(`div`,{className:`login-hint`,children:[i&&(0,J.jsxs)(`div`,{className:`login-hint-device pwi-device-code-wrap`,children:[(0,J.jsx)(`span`,{className:`text-label`,children:n(`prov.deviceCode`)}),(0,J.jsx)(`code`,{className:`login-hint-device-code pwi-device-code`,children:i}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>r.copy(i,i),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:s})})]}),(0,J.jsx)(Ka,{url:a}),e.instructions&&(0,J.jsx)(`div`,{className:`muted text-label`,children:e.instructions}),t&&(0,J.jsxs)(`div`,{className:`login-hint-paste`,children:[(0,J.jsx)(`div`,{className:`muted text-label`,children:n(`prov.pasteRedirectHint`)}),(0,J.jsxs)(`div`,{className:`login-hint-paste-row`,children:[(0,J.jsx)(`input`,{type:`text`,autoComplete:`off`,spellCheck:!1,value:t.value,onChange:e=>t.onChange(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),t.onSubmit())},placeholder:n(`prov.pasteRedirect`),"aria-label":n(`prov.pasteRedirect`),disabled:t.busy,className:`input text-label login-hint-paste-input`}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:t.busy||t.disabled===!0||!t.value.trim(),onClick:t.onSubmit,children:t.busy?t.submittingLabel??n(`prov.pasteSubmitting`):n(`prov.pasteSubmit`)})]}),t.message&&(0,J.jsx)(`div`,{className:`text-label`,"aria-live":`polite`,style:{color:t.ok?`var(--accent-hover)`:`var(--amber)`},children:t.message})]})]})}function Ja({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=Q();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`h3`,{style:{marginBottom:4},children:f(e?`codexAuth.reauthenticate`:`codexAuth.oauthLogin`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:f(`codexAuth.oauthWaiting`)}),(0,J.jsx)(qa,{hint:{url:t},paste:{value:n,busy:r,disabled:r||i||!n.trim()||!s,submittingLabel:f(`codexAuth.oauthSubmittingCode`),message:``,ok:!0,onChange:l,onSubmit:u}}),a&&(0,J.jsx)(`div`,{className:o===`warn`?`notice-warn`:`notice notice-ok`,role:`status`,"aria-live":`polite`,style:{marginTop:12},children:a}),c&&(0,J.jsx)(`div`,{className:`notice notice-err`,style:{marginTop:12},children:c}),(0,J.jsx)(`div`,{style:{textAlign:`center`,padding:`24px 0`},children:(0,J.jsx)(`span`,{className:`spin`,style:{width:24,height:24}})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:d,style:{width:`100%`},children:f(`codexAuth.cancel`)})]})}var Ya=`ocx.oauth.openBrowser`;function Xa(){try{let e=window.localStorage.getItem(Ya);return e===`0`?!1:e===`1`||void 0}catch{return}}function Za(){let e=Xa();return e===void 0?{}:{openBrowser:e}}function Qa(e){try{window.localStorage.setItem(Ya,e?`1`:`0`)}catch{}}function $a(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 eo({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&&=(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({...Za(),...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 Pt(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=Vn(async()=>{if(s.current||v.signal.aborted)return;s.current=!0;let e=AbortSignal.any([v.signal,AbortSignal.timeout(1e4)]);try{let n=await Ft(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($a(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 to({apiBase:e,onClose:t,onAdded:n,reauthAccountId:r}){let i=Q(),[a,o]=(0,_.useReducer)(Ha,r,Va),s=(0,_.useRef)(null),c=(0,_.useRef)(null),{manualCodeBusy:l,manualCodeWaiting:u,bindCallbacks:d,closeModal:f,startOAuth:p,submitManualCode:m}=eo({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,J.jsx)(`dialog`,{ref:c,"aria-label":g,className:`modal-overlay`,onCancel:h,children:(0,J.jsxs)(`div`,{className:`modal-card`,style:{maxWidth:440},children:[a.step===`pick`&&(0,J.jsx)(Ua,{id:a.id,error:a.error,onIdChange:e=>o({type:`set-id`,id:e}),onStartOAuth:()=>{p(a.id)},onClose:f}),a.step===`oauth-waiting`&&(0,J.jsx)(Ja,{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 no=[2,1,0,-1,-2],ro=new Map([[2,`accountPool.priorityFirst`],[1,`accountPool.priorityEarlier`],[0,`accountPool.priorityNormal`],[-1,`accountPool.priorityLater`],[-2,`accountPool.priorityLast`]]);function io(e){return typeof e==`number`&&Number.isInteger(e)&&e>=-100&&e<=100?e:0}function ao(e){let t=io(e);return t>0?`+${t}`:String(t)}function oo(e){return ro.has(e)}function so(e){return ro.get(e)??null}function co(e,t){let n=io(t);return e(`accountPool.priorityOption`,{name:e(so(n)??`accountPool.priorityCustom`),value:ao(n)})}var lo=1e4;function uo(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=100?e:80}function fo(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}function po(e,t){return e>0?0:Number.isInteger(t)&&t>=1&&t<=100?t:80}function mo(e,t,n,r){return n===r?e||t?`defer`:`apply`:`ignore`}function ho(e){return e&&typeof e==`object`&&e&&`autoSwitchThreshold`in e?e.autoSwitchThreshold:e}function go(e,t,n){if(e<=0){let t=po(e,n);return{threshold:t,lastEnabled:t}}return{threshold:0,lastEnabled:fo(t)??po(0,n)}}async function _o(e,t,n=(e,t)=>fetch(e,t),r=lo){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 vo=3e4,yo=new Map;function bo(e,t=!0){let n=yo.get(e),[r,i]=(0,_.useState)(()=>n?.accounts??[]),a=G(Ir(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),I=(0,_.useRef)(null),L=(0,_.useRef)(null),R=(0,_.useCallback)(e=>(j.current.add(e),()=>{j.current.delete(e)}),[]),z=(0,_.useCallback)(()=>ho(M.current?.value),[]),B=(0,_.useCallback)(()=>M.current?.value,[]),V=(0,_.useCallback)(async(t=!1)=>{let n=++k.current,r=Ln(2e4);S(e=>e+1);try{let a=[...j.current],o=new Map;for(let e of a)o.set(e,e.beginActiveRead());!t&&!F.current&&l(`loading`);let c=null,u,d=(async()=>{try{let a=await fetch(`${e}/api/codex-auth/accounts${t?`?refresh=1`:``}`,{signal:r.signal});if(!a.ok)throw Error(`account load failed`);let o=await a.json();return k.current===n&&(c=(o.accounts??[]).map(e=>{let t=e.isMain?`main`:e.logLabel;return{...e,...t?{logLabel:t}:{},priority:io(e.priority)}}),i(c),P.current=c.length>0,F.current=!0,l(`ready`)),!0}catch{return!1}})(),f=(async()=>{try{let t=await fetch(`${e}/api/codex-auth/active`,{signal:r.signal});if(!t.ok)throw Error(`active account load failed`);let i=await t.json();if(k.current===n){let e=i.activeCodexAccountId??null,t=A.current;t&&e!==t.id||(A.current=null,u=e,s(e)),M.current={value:i},b(typeof i.pinnedAccountId==`string`?i.pinnedAccountId:null);for(let e of a)e.acceptActiveRead(i,o.get(e))}return!0}catch{if(k.current===n)for(let e of a)e.rejectActiveRead();return!1}})(),[p,m]=await Promise.all([d,f]);if(k.current!==n)return!1;if(p){l(`ready`),F.current=!0;let t=yo.get(e);return yo.set(e,{accounts:c??t?.accounts??[],activeId:u===void 0?t?.activeId??null:u}),m}return F.current||l(`error`),!1}finally{r.clear(),S(e=>Math.max(0,e-1)),w(!0)}},[e]);(0,_.useEffect)(()=>{t&&O.current!==e&&(O.current=e,Promise.resolve().then(()=>{V()}))},[e,t,V]);let H=r.some(e=>e.hasCredential&&!e.quota);(0,_.useEffect)(()=>{if(!t||!H||T>0)return;let e=[350,900,2e3].map(e=>window.setTimeout(()=>{V(!1)},e));return()=>{for(let t of e)window.clearTimeout(t)}},[t,H,T,V]),(0,_.useEffect)(()=>{if(!(!t||T>0))return Vn(()=>{V()},vo)},[t,V,T]);let U=(0,_.useCallback)(()=>{let e={};return D.current.add(e),E(D.current.size),e},[]),W=(0,_.useCallback)(e=>{D.current.delete(e)&&E(D.current.size)},[]),ee=(0,_.useCallback)(async t=>{if(N.current||L.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__`),V(),{ok:!0,activeId:r??null}}catch{return{ok:!1,reason:`request`}}finally{N.current=null,d(null)}},[e,V]),K=(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 V(),{ok:!0}):{ok:!1,reason:`request`}}catch{return{ok:!1,reason:`request`}}},[e,V]),q=(0,_.useCallback)(async(t,n)=>{if(I.current)return{ok:!1,reason:`busy`};I.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),V(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{I.current=null,p(null)}},[e,V]),J=(0,_.useCallback)(async(t,n)=>{if(L.current||N.current)return{ok:!1,reason:`busy`};L.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=io((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,V(),{ok:!0}}catch{return{ok:!1,reason:`request`}}finally{L.current=null,h(null)}},[e,V]),Y=(0,_.useCallback)(async()=>{if(I.current)return{ok:!1,reason:`busy`};I.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),V(),{ok:!0,pausedCount:r.pausedCount??a.size}}catch{return{ok:!1,reason:`request`}}finally{I.current=null,v(!1)}},[e,V]),te=(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=$a(await n.json().catch(()=>({})));return await V(),{ok:!0,...r}}catch{return{ok:!1,reason:`request`}}},[e,V]),ne=(0,_.useCallback)(async()=>await V()?{ok:!0}:{ok:!1,reason:`reload`},[V]),re=o&&o!==`__main__`?r.find(e=>e.id===o):null,ie=r.find(e=>e.isMain),ae=re??ie,oe=!ae?.paused&&Ma(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:V,switchAccount:ee,setAccountPaused:q,setAccountPriority:J,pauseExhaustedAccounts:Y,saveAlias:K,removeAccount:te,syncAfterAccountAdded:ne,pauseRefresh:U,resumeRefresh:W,subscribeLoadObserver:R,readLastThreshold:z,readLastActive:B}}function xo(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 So({disabled:e=!1,onIncrement:t,onDecrement:n,incrementLabel:r,decrementLabel:i}){return(0,J.jsxs)(`div`,{className:`ocx-stepper`,role:`group`,children:[(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":r,onMouseDown:e=>e.preventDefault(),onClick:t,children:(0,J.jsx)(be,{width:10,height:10,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`ocx-stepper__btn`,disabled:e,"aria-label":i,onMouseDown:e=>e.preventDefault(),onClick:n,children:(0,J.jsx)(xe,{width:10,height:10,"aria-hidden":`true`})})]})}var Co={quota:{on:`codexAuth.autoSwitchQuotaDesc`,off:`codexAuth.autoSwitchQuotaOffDesc`},"round-robin":{on:`codexAuth.autoSwitchRoundRobinDesc`,off:`codexAuth.autoSwitchRoundRobinDesc`},"fill-first":{on:`codexAuth.autoSwitchFillFirstDesc`,off:`codexAuth.autoSwitchFillFirstOffDesc`}};function wo({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=Q(),m=(0,_.useRef)(!1),h=e>0,g=Co[n][h?`on`:`off`],v=i||!r,y=i?p(`common.saving`):o?.message??``,b=i?`pending`:o?.tone,x=y?`codex-auto-switch-desc codex-auto-switch-feedback`:`codex-auto-switch-desc`;return(0,J.jsxs)(`div`,{className:`card card-row codex-auto-switch-card`,style:{marginTop:16},"aria-busy":i||!r&&!a||void 0,children:[(0,J.jsxs)(`div`,{className:`codex-auto-switch-copy`,children:[(0,J.jsx)(`strong`,{children:p(`codexAuth.autoSwitch`)}),(0,J.jsx)(`div`,{id:`codex-auto-switch-desc`,className:`card-sub`,role:a?`alert`:void 0,children:a?p(`codexAuth.autoSwitchLoadFailed`):p(g,{threshold:e})}),(0,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.failureRecoveryNote`)}),(0,J.jsx)(`div`,{className:`card-sub`,children:p(`codexAuth.cacheWarning`)})]}),(0,J.jsxs)(`div`,{className:`codex-auto-switch-controls`,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){if(c(!1),m.current){m.current=!1;return}h&&!v&&l()}},children:[a&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`pws.retryAccounts`)}),h&&(0,J.jsxs)(`label`,{className:`codex-auto-switch-threshold`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`codexAuth.autoSwitchThreshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,readOnly:v,"aria-disabled":v,"aria-label":p(`codexAuth.autoSwitchThresholdAria`),"aria-describedby":x,onChange:e=>s(e.target.value),onFocus:()=>{v||c(!0)},onKeyDown:e=>{e.nativeEvent.isComposing||v||(e.key===`Enter`?(e.preventDefault(),l()):e.key===`Escape`&&(e.preventDefault(),u()))}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(So,{disabled:v,incrementLabel:p(`codexAuth.autoSwitchThresholdInc`),decrementLabel:p(`codexAuth.autoSwitchThresholdDec`),onIncrement:()=>{c(!0),s(xo(t,1,1,100))},onDecrement:()=>{c(!0),s(xo(t,-1,1,100))}})]})]}),(0,J.jsx)(`span`,{className:`codex-auto-switch-toggle-slot`,children:(0,J.jsx)(`button`,{type:`button`,className:`toggle ${h?`on`:``}`,onPointerDownCapture:()=>{m.current=!0},onPointerUp:()=>{m.current=!1},onPointerCancel:()=>{m.current=!1},onClick:()=>{m.current=!1,d()},disabled:v,"aria-pressed":h,"aria-label":p(`codexAuth.autoSwitch`),"aria-describedby":x,title:p(`codexAuth.autoSwitch`),children:(0,J.jsx)(`span`,{className:`toggle-knob`})})})]}),y&&(0,J.jsx)(`div`,{id:`codex-auto-switch-feedback`,className:`codex-auto-switch-feedback${b===`err`?` is-error`:``}`,role:b===`err`?`alert`:`status`,"aria-atomic":`true`,children:y})]})}var To=[`quota`,`round-robin`,`fill-first`],Eo=[`five-hour`,`weekly`,`max-utilization`],Do=`quota`,Oo=`five-hour`,ko=new Set(To),Ao=new Set(Eo);function jo(e){return typeof e==`string`&&ko.has(e)?e:Do}function Mo(e){return typeof e==`string`&&Ao.has(e)?e:Oo}function No(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Po(e){let t=e.trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return n>=1&&n<=100?n:null}async function Fo(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:jo(i.accountPoolStrategy??t.strategy),stickyLimit:No(i.accountPoolStickyLimit??t.stickyLimit)}}catch{return{ok:!1}}}var Io={quota:`accountPool.strategyQuota`,"round-robin":`accountPool.strategyRoundRobin`,"fill-first":`accountPool.strategyFillFirst`},Lo={quota:`accountPool.strategyHintQuota`,"round-robin":`accountPool.strategyHintRoundRobin`,"fill-first":`accountPool.strategyHintFillFirst`};function Ro({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=Q(),l=To.map(e=>({value:e,label:c(Io[e])}));return(0,J.jsxs)(`div`,{className:`account-pool-strategy-controls`,children:[(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,id:`${r}-label`,children:c(`accountPool.strategy`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.strategyDesc`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(Lo[e])}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.unboundDefinition`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(Dt,{id:r,value:e,options:l,disabled:n,label:c(`accountPool.strategy`),onChange:e=>a(e)})})]}),e===`round-robin`&&(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`label`,{className:`setting-label`,htmlFor:i,children:[(0,J.jsx)(`span`,{className:`title`,children:c(`accountPool.stickyLimit`)}),(0,J.jsx)(`span`,{className:`desc`,children:c(`accountPool.stickyLimitHelp`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,children:[(0,J.jsx)(`input`,{id:i,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:t,disabled:n,"aria-label":c(`accountPool.stickyLimitAria`),onChange:e=>o(e.target.value),onBlur:()=>s(),onKeyDown:e=>{e.nativeEvent.isComposing||n||e.key===`Enter`&&(e.preventDefault(),s())}}),(0,J.jsx)(So,{disabled:n,incrementLabel:c(`accountPool.stickyLimitInc`),decrementLabel:c(`accountPool.stickyLimitDec`),onIncrement:()=>{let e=xo(t,1,1,100);o(e),s(e)},onDecrement:()=>{let e=xo(t,-1,1,100);o(e),s(e)}})]})})]})]})}function zo(e){if(!e||typeof e!=`object`)return null;let t=e;return!(`accountPoolStrategy`in t)&&!(`accountPoolStickyLimit`in t)?null:{strategy:jo(t.accountPoolStrategy),stickyLimit:No(t.accountPoolStickyLimit)}}function Bo({apiBase:e,subscribeLoadObserver:t,readLastActive:n,onStrategyResolved:r}){let i=Q(),[a,o]=(0,_.useState)(Do),[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=jo(e.accountPoolStrategy),n=No(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=zo(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 Fo(e,t);y.current+=1,d.ok?(o(d.strategy),r?.(d.strategy),c(d.stickyLimit),u(String(d.stickyLimit)),p.current=!0,f(!0)):(C(i(`accountPool.strategyUpdateFailed`)),o(n),r?.(n),c(l),u(String(l))),g.current=!1,h(!1),D()},[e,r,D,s,a,i]),k=m||b||!d;return(0,J.jsxs)(`div`,{className:`card account-pool-strategy-card`,"aria-busy":m||!d&&!b,children:[b&&(0,J.jsx)(`div`,{className:`card-sub`,role:`alert`,children:i(`accountPool.strategyLoadFailed`)}),b&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm account-pool-strategy-card__retry`,onClick:()=>{E()},children:i(`common.retry`)}),!b&&(0,J.jsx)(Ro,{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=Po(e??l);if(t===null){u(String(s)),C(i(`accountPool.stickyLimitInvalid`));return}if(t===s){u(String(t));return}O({stickyLimit:t})}}),S&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub account-pool-strategy-card__error`,children:S})]})}function Vo({t:e,open:t,onToggle:n,children:r}){return(0,J.jsxs)(`section`,{className:`codex-auth-advanced`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`codex-auth-advanced__toggle`,"aria-expanded":t,"aria-controls":`codex-auth-advanced-boxes`,onClick:n,children:[(0,J.jsx)(`span`,{children:e(`codexAuth.advancedSettings`)}),(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`,className:t?`codex-auth-advanced__chevron is-open`:`codex-auth-advanced__chevron`})]}),t&&(0,J.jsx)(`div`,{id:`codex-auth-advanced-boxes`,className:`codex-auth-advanced__boxes`,children:r})]})}function Ho(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=ho(e),r=mo(v.current,y.current,t,x.current);r===`defer`?S.current=uo(n):r===`apply`&&T(uo(n))},[T]),j=(0,_.useCallback)(e=>{h.current||v.current||y.current||(l(!1),w(uo(ho(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 _o(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=fo(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=go(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 Uo({value:e,disabled:t=!1,selectId:n,onChange:r}){let i=Q(),a=io(e),o=i(`accountPool.priorityHint`),s=`${n}-hint`,c=no.map(e=>({value:String(e),label:co(i,e)})),l=oo(a)?c:[{value:String(a),label:co(i,a)},...c];return(0,J.jsxs)(`div`,{className:`codex-account-priority`,children:[(0,J.jsx)(`label`,{className:`codex-account-priority-label`,htmlFor:n,children:i(`accountPool.priority`)}),(0,J.jsx)(Dt,{id:n,value:String(a),options:l,disabled:t,label:i(`accountPool.priorityAria`),describedBy:s,title:o,onChange:e=>r(io(Number.parseInt(e,10)))}),(0,J.jsx)(`span`,{id:s,className:`sr-only`,children:o})]})}function Wo({value:e}){let t=Q(),n=io(e);return n===0?null:(0,J.jsx)(`span`,{className:`badge badge-muted`,children:co(t,n)})}var Go=new Map;function Ko(e,t){return`${e??``}\0${JSON.stringify(t)}`}function qo(e,t){let n=Ko(e,t??{}),r=Go.get(n);return r||(r=new Intl.NumberFormat(e,t),Go.set(n,r)),r}var Jo={month:`short`,day:`numeric`,year:`numeric`},Yo={month:`short`,day:`numeric`,year:`numeric`,hour:`2-digit`,minute:`2-digit`},Xo=new Map;function Zo(e,t){let n=Ko(e,t),r=Xo.get(n);return r||(r=new Intl.DateTimeFormat(e,t),Xo.set(n,r)),r}function Qo(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Zo(t,Jo).format(n)}function $o(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?`—`:Zo(t,Yo).format(n)}function es(e,t){return!Number.isFinite(e)||e<0?`—`:`~${qo(t,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e)}`}function ts(e,t){return Qo(e,t)}function ns(e,t){return $o(e,t)}function rs(e){return Math.max(0,Math.ceil((new Date(e).getTime()-Date.now())/864e5))}function is({index:e,grantedAt:t,expiresAt:n,isNext:r,locale:i,t:a}){let o=rs(n),s=o<=7;return(0,J.jsxs)(`div`,{className:`credit-item${r?` credit-next`:``}`,children:[(0,J.jsxs)(`div`,{className:`credit-item-head`,children:[(0,J.jsx)(Oe,{width:13}),(0,J.jsx)(`span`,{className:`credit-item-label`,children:r?a(`codexAuth.creditNext`):a(`codexAuth.creditLabel`,{n:String(e+1)})}),r&&(0,J.jsx)(`span`,{className:`badge badge-amber text-micro`,style:{padding:`1px 6px`},children:a(`codexAuth.creditNextBadge`)})]}),(0,J.jsxs)(`div`,{className:`credit-item-dates`,children:[(0,J.jsx)(`span`,{children:a(`codexAuth.creditGranted`,{date:ts(t,i)})}),(0,J.jsx)(`span`,{className:s?`credit-urgent`:``,children:a(`codexAuth.creditExpires`,{date:ns(n,i),days:String(o)})})]})]})}function as({account:e,onClick:t,t:n}){let r=e.quota?.resetCredits;return e.quota==null?(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Oe,{width:12}),`0`]}):r===void 0?null:(0,J.jsxs)(`button`,{type:`button`,className:`badge ${typeof r==`number`&&r>0?`badge-amber`:`badge-muted`} badge-clickable`,onClick:e=>{e.stopPropagation(),t()},"aria-label":n(`codexAuth.resetCreditsAria`,{count:String(r)}),children:[(0,J.jsx)(Oe,{width:12}),r]})}function os({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,J.jsx)(`span`,{className:`codex-auth-pause-label`,style:{minWidth:`${s}ch`},children:o})}function ss({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=Q(),b=e=>!e.paused&&t===e.id;return(0,J.jsx)(J.Fragment,{children:e.map(e=>{let t=e.health?.status,x=!!e.needsReauth||ja(t),S=Na(t),C=Ia(y,e.health),w=La(y,`codex`,e.id,e.health);return(0,J.jsxs)(`div`,{className:`card ${b(e)?`card-active`:``}`,style:{marginBottom:8},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${x?`dot-amber`:b(e)?`dot-blue`:`dot-muted`}`}),(0,J.jsx)(`strong`,{children:e.alias??e.email}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,children:e.plan}),e.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:y(`codexAuth.pausedHint`),children:y(`codexAuth.paused`)}),(0,J.jsx)(Wo,{value:e.priority}),e.id===p&&!e.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:y(`codexAuth.pinned`)}),(0,J.jsx)(as,{t:y,account:e,onClick:()=>a(e)}),C&&(0,J.jsx)(`span`,{className:Aa(t),children:C}),x&&!C&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:y(`codexAuth.needsReauth`)}),b(e)&&!x&&!S&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:y(n===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`)})]}),!e.paused&&(!b(e)||p!==e.id)&&!x&&!S&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(e),children:r}),x&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>m(e.id),children:y(`codexAuth.reauthenticate`)}),_&&Pa(t)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>_(e.id),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Ba(y,v?.(e.id))})}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:()=>s(e),disabled:l,title:e.paused?y(`codexAuth.pausedHint`):void 0,"aria-label":e.paused?`${y(`codexAuth.resume`)}. ${y(`codexAuth.pausedHint`)}`:y(`codexAuth.pause`),children:[e.paused?(0,J.jsx)(me,{width:14}):(0,J.jsx)(pe,{width:14}),(0,J.jsx)(os,{t:y,paused:e.paused,saving:c===e.id})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void h(e),children:y(`prov.editAlias`)}),(0,J.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,J.jsx)(ue,{width:14})})]}),(0,J.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,J.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[e.email,e.plan?` · ${e.plan}`:``,` · `,y(`prov.accountId`),`: `,Oa(e.id)]}),(0,J.jsx)(Uo,{value:e.priority,selectId:`codex-account-priority-${e.id}`,disabled:d!==null||f!==null,onChange:t=>u(e,t)})]}),w&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:w}),S&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:y(`pws.healthCooldownHint`)}),x?(0,J.jsx)(`div`,{className:`card-sub faint`,children:y(`codexAuth.tokenExpired`)}):!S&&(0,J.jsx)($i,{quota:e.quota,plan:e.plan,threshold:i,t:y,pending:e.quota==null})]},e.id)})})}function cs({onReauth:e}){let t=Q();return(0,J.jsxs)(`div`,{className:`notice-warn`,style:{marginBottom:12,display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(_e,{width:14}),` `,t(`codexAuth.tokenExpired`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:e,children:t(`codexAuth.reauthenticate`)})]})}function ls({confirm:e,mainEmail:t,accountModeState:n,switchingId:r,orderBusy:i=!1,onCancel:a,onConfirm:o}){let s=Q(),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,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`codex-switch-title`,onCancel:l,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:a}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsx)(`h3`,{id:`codex-switch-title`,children:n===`direct`?s(`codexAuth.preparePoolTitle`):e.id===`__main__`?s(`codexAuth.switchBack`):s(`codexAuth.switchTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:n===`direct`?s(`codexAuth.preparePoolDesc`):e.id===`__main__`?s(`codexAuth.switchBackDesc`):s(`codexAuth.switchDesc`)}),(0,J.jsxs)(`div`,{className:`card`,style:{margin:`12px 0`},children:[(0,J.jsx)(`strong`,{children:e.id===`__main__`?t||s(`codexAuth.codexApp`):e.email}),e.plan&&(0,J.jsx)(`span`,{className:`badge badge-green`,style:{marginLeft:8},children:e.plan})]}),e.id!==`__main__`&&(0,J.jsxs)(`div`,{className:`notice-warn`,children:[(0,J.jsx)(_e,{width:14}),` `,s(`codexAuth.cacheWarning`)]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:a,children:s(`codexAuth.cancel`)}),(0,J.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 us({resetPopup:e,resetConfirm:t,creditDetails:n,creditDetailsLoading:r,redeeming:i,onClose:a,onShowConfirm:o,onCancelConfirm:s,onRedeem:c}){let{locale:l,t:u}=ct(),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,J.jsxs)(`dialog`,{ref:d,className:`modal-overlay`,"aria-labelledby":`codex-reset-title`,onCancel:f,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":u(`common.close`),tabIndex:-1,onClick:a}),(0,J.jsx)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),role:`document`,children:t?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{style:{textAlign:`center`,padding:`12px 0`},children:[(0,J.jsx)(`div`,{className:`confirm-icon`,children:(0,J.jsx)(_e,{width:22})}),(0,J.jsx)(`h3`,{id:`codex-reset-title`,children:u(`codexAuth.confirmResetTitle`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.confirmResetDesc`,{count:String(e.quota?.resetCredits??0)})}),n&&n[0]&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.confirmWhichCredit`,{date:ts(n[0].granted_at,l)})}),(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`codexAuth.irreversible`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:s,children:u(`codexAuth.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:c,disabled:i,children:u(i?`codexAuth.redeeming`:`codexAuth.useCredit`)})]})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`h3`,{id:`codex-reset-title`,children:[(0,J.jsx)(Oe,{width:16}),` `,u(`codexAuth.resetCreditsTitle`)]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[e.email,e.plan?` · ${e.plan}`:``]}),(0,J.jsx)(`div`,{style:{margin:`16px 0`},children:(e.quota?.resetCredits??0)>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{style:{marginBottom:12},children:u(`codexAuth.resetCreditsAvailable`,{count:String(e.quota?.resetCredits??0)})}),r&&(0,J.jsx)(`p`,{className:`faint text-label`,children:u(`common.loading`)}),n&&n.length>0&&(0,J.jsx)(`div`,{className:`credit-list`,children:n.map((e,t)=>(0,J.jsx)(is,{index:t,grantedAt:e.granted_at,expiresAt:e.expires_at,isNext:t===0,locale:l,t:u},`${e.granted_at}:${e.expires_at}`))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,style:{marginTop:12,width:`100%`},onClick:o,disabled:i,children:u(`codexAuth.useOneCredit`)}),(0,J.jsx)(`p`,{className:`card-sub text-caption`,style:{marginTop:8,textAlign:`center`},children:u(`codexAuth.fifoNote`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`faint`,children:u(`codexAuth.noResetCredits`)}),(0,J.jsx)(`p`,{className:`modal-desc`,children:u(`codexAuth.earnCreditsHint`)})]})})]})})]})}function ds({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||ja(t?.health?.status),x=Na(t?.health?.status),S=Ia(e,t?.health),C=t?La(e,`codex`,v,t.health):null;return(0,J.jsxs)(`div`,{className:`card ${n?`card-active`:``}`,style:{marginBottom:12},children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot ${b?`dot-amber`:`dot-green`}`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[t&&(0,J.jsx)(as,{t:e,account:{...t,id:`__main__`},onClick:()=>m({...t,id:`__main__`})}),t?.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,title:e(`codexAuth.pausedHint`),children:e(`codexAuth.paused`)}),(0,J.jsx)(Wo,{value:y.priority}),p===`__main__`&&!t?.paused&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:e(`codexAuth.pinned`)}),S&&(0,J.jsx)(`span`,{className:Aa(t?.health?.status),children:S}),b&&!S&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:e(`codexAuth.needsReauth`)}),!t?.paused&&(0,J.jsx)(`span`,{className:`badge ${n?`badge-primary`:`badge-muted`}`,children:e(n?r===`direct`?`codexAuth.poolPrepared`:`codexAuth.nextSession`:`codexAuth.current`)})]}),!t?.paused&&(!n||p!==`__main__`)&&!b&&!x&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-account-switch`,onClick:()=>o(y),children:a}),h&&Pa(t?.health?.status)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-auth-action-btn`,onClick:()=>h(v),children:(0,J.jsx)(`span`,{"aria-live":`polite`,children:Ba(e,g?.(v))})}),t&&(0,J.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,J.jsx)(me,{width:14}):(0,J.jsx)(pe,{width:14}),(0,J.jsx)(os,{t:e,paused:!!t.paused,saving:c===`__main__`})]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(De,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`codex-account-identity`,children:[(0,J.jsxs)(`div`,{className:`codex-account-identity-copy`,children:[t?.email||e(`codexAuth.appLogin`),t?.plan?` · ${t.plan}`:``]}),t&&(0,J.jsx)(Uo,{value:y.priority,selectId:`codex-account-priority-${y.id}`,disabled:d!==null||f!==null,onChange:e=>u(y,e)})]}),C&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:C}),x&&(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`pws.healthCooldownHint`)}),b?(0,J.jsx)(`div`,{className:`card-sub faint`,children:e(`codexAuth.mainTokenExpired`)}):!x&&(0,J.jsx)($i,{quota:t?.quota??null,plan:t?.plan,threshold:i,t:e,pending:t!=null&&t.quota==null})]})}function fs({t:e,embedded:t,refreshingQuota:n,pausingExhausted:r,pauseBusy:i,actionFeedback:a,actionFeedbackTone:o,onRefresh:s,onPauseExhausted:c,sparkVisible:l,sparkBusy:u,onToggleSpark:d}){return(0,J.jsxs)(`div`,{className:t?`row`:`page-head codex-auth-page-head`,style:t?{justifyContent:`flex-end`,marginBottom:8}:void 0,children:[!t&&(0,J.jsx)(`h2`,{className:`page-title`,children:e(`nav.codexAuth`)}),(0,J.jsxs)(`div`,{className:t?`row`:`codex-auth-page-head__actions`,children:[(0,J.jsx)(`span`,{className:`codex-auth-page-head__feedback${o===`ok`?` is-ok`:``}${o===`warn`?` is-warn`:``}${o===`err`?` is-err`:``}`,role:`status`,"aria-live":`polite`,children:a??``}),l!==void 0&&d&&(0,J.jsxs)(`span`,{className:`codex-auth-spark-toggle`,children:[(0,J.jsx)(`span`,{className:`codex-auth-spark-toggle__label`,children:e(`codexAuth.sparkQuota`)}),(0,J.jsx)(`button`,{type:`button`,className:`toggle ${l?`on`:``}`,onClick:d,disabled:!!u,"aria-pressed":l,"aria-label":e(`codexAuth.sparkQuota`),title:e(`codexAuth.sparkQuotaHint`),children:(0,J.jsx)(`span`,{className:`toggle-knob`})})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:c,disabled:n||r||!!i,children:[(0,J.jsx)(pe,{width:14}),` `,e(r?`codexAuth.pausingExhausted`:`codexAuth.pauseExhausted`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost codex-auth-action-btn`,onClick:s,disabled:n||r||!!i,children:[(0,J.jsx)(fe,{width:14}),` `,e(n?`codexAuth.refreshingQuota`:`codexAuth.refreshQuota`)]})]})]})}function ps({t:e,loadState:t,accountsCount:n,onRetry:r}){return t===`loading`&&n===0?(0,J.jsxs)(`div`,{className:`codex-auth-load-skeleton`,role:`status`,"aria-live":`polite`,"aria-busy":`true`,children:[(0,J.jsxs)(`div`,{className:`card codex-auth-load-skeleton__main`,style:{marginBottom:12},"aria-hidden":`true`,children:[(0,J.jsxs)(`div`,{className:`card-head`,children:[(0,J.jsx)(`span`,{className:`dot dot-muted`}),(0,J.jsx)(`strong`,{children:e(`codexAuth.mainAccount`)}),(0,J.jsxs)(`span`,{className:`card-badges`,children:[(0,J.jsxs)(`span`,{className:`badge badge-muted codex-ticket-badge-slot`,"aria-hidden":`true`,children:[(0,J.jsx)(Oe,{width:12}),`0`]}),(0,J.jsx)(`span`,{className:`badge badge-primary`,children:e(`codexAuth.nextSession`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(pe,{width:14}),` `,e(`codexAuth.pause`)]}),(0,J.jsxs)(`span`,{className:`card-right`,children:[(0,J.jsx)(De,{width:14}),` `,e(`codexAuth.appLogin`)]})]}),(0,J.jsxs)(`div`,{className:`card-sub`,children:[(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__strut`,children:e(`codexAuth.appLogin`)}),(0,J.jsx)(`span`,{className:`codex-auth-load-skeleton__line codex-auth-load-skeleton__line--sub`})]}),(0,J.jsx)($i,{quota:null,threshold:0,t:e,pending:!0})]}),(0,J.jsxs)(`div`,{className:`section-sep`,"aria-hidden":`true`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:e(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,tabIndex:-1,disabled:!0,children:[(0,J.jsx)(de,{width:14}),` `,e(`codexAuth.add`)]})]}),(0,J.jsx)(`div`,{className:`empty codex-auth-pool-empty codex-auth-load-skeleton__empty`,"aria-hidden":`true`,children:(0,J.jsx)(`div`,{className:`title`,children:e(`codexAuth.noPool`)})}),(0,J.jsx)(`span`,{className:`sr-only`,children:e(`pws.accountsLoading`)})]}):t===`error`?(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:e(`codexAuth.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:r,children:e(`pws.retryAccounts`)})]}):null}function ms(e,t){return t===void 0?e(`codexAuth.resetSuccessGeneric`):e(`codexAuth.resetSuccess`,{remaining:String(t)})}async function hs(e,t,n,r){try{let i=await Ft(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:ms(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 gs=`ocx doctor`;function _s({apiBase:e,accountModeState:t=null,banner:n=null,embedded:r=!1,onActiveNeedsReauthChange:i,controller:a,advancedExtras:o=null}){let s=Q(),c=Ho(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=bo(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),z=(0,_.useRef)(null),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(void 0),[W,ee]=(0,_.useState)(!1),[G,K]=(0,_.useState)(null),[q,Y]=(0,_.useState)(!1),[te,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(null),[ae,oe]=(0,_.useState)(!1),X=Ga(),se=(0,_.useCallback)((e,t=`ok`)=>{z.current&&clearTimeout(z.current),I(e),R(t),z.current=setTimeout(()=>{I(null),R(null),z.current=null},5e3)},[]);(0,_.useEffect)(()=>()=>{z.current&&clearTimeout(z.current)},[]);let ce=(0,_.useCallback)(e=>{X.copy(gs,e)},[X]),{subscribeLoadObserver:le,readLastThreshold:ue}=g;(0,_.useEffect)(()=>le({beginActiveRead:d,acceptActiveRead:f,rejectActiveRead:p}),[le,d,f,p]),(0,_.useEffect)(()=>{let e=ue();e!==void 0&&m(e)},[ue,m]),(0,_.useEffect)(()=>{if(!k)return;let e=g.pauseRefresh();return()=>g.resumeRefresh(e)},[g,k]);let fe=y&&y!==`__main__`?v.find(e=>e.id===y):null,pe=!fe?.paused&&Ma(fe);(0,_.useEffect)(()=>{i?.(pe)},[pe,i]);let me=(0,_.useCallback)(e=>{P(e),A(!0)},[]),he=(0,_.useCallback)(()=>{A(!1),P(null)},[]),ge=(0,_.useCallback)(e=>{g.syncAfterAccountAdded(),se(s(e.catalogRefreshPending?`codexAuth.catalogRefreshPending`:`codexAuth.accountAdded`),e.catalogRefreshPending?`warn`:`ok`),he()},[he,g,se,s]),_e=async e=>{let n=await g.switchAccount(e);if(!n.ok){if(n.reason===`busy`)return;se(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`);se(s(t===`direct`?`codexAuth.poolPreparedToast`:`codexAuth.switched`,{email:i}))},ve=async e=>{let t=window.prompt(s(`prov.aliasPrompt`),e.alias??``);if(t===null)return;let n=await g.saveAlias(e.id,t);se(s(n.ok?`prov.aliasSaved`:`prov.aliasSaveFailed`),n.ok?`ok`:`err`)},ye=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),se(s(n.ok?t?`codexAuth.pauseSucceeded`:`codexAuth.resumeSucceeded`:t?`codexAuth.pauseFailed`:`codexAuth.resumeFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`))},be=async(e,t)=>{if(t===e.priority)return;let n=await g.setAccountPriority(e.id,t);!n.ok&&n.reason===`busy`||se(s(n.ok?`accountPool.priorityUpdated`:`accountPool.priorityUpdateFailed`,{email:e.alias??e.email}),n.ok?`ok`:`err`)},xe=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&&se(s(`codexAuth.catalogRefreshPending`),`warn`):se(s(`codexAuth.removeFailed`),`err`)},Z=async()=>{V(!0);try{let e=await E(!0);se(s(e?`codexAuth.quotaRefreshed`:`codexAuth.quotaRefreshFailed`),e?`ok`:`err`)}finally{V(!1)}};(0,_.useEffect)(()=>{let t=new AbortController;return fetch(`${e}/api/settings`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(e=>{t.signal.aborted||typeof e?.showCodexSparkQuota!=`boolean`||U(e.showCodexSparkQuota)}).catch(()=>{}),()=>{t.abort()}},[e]);let Se=async()=>{if(W||H===void 0)return;let t=!H;ee(!0),U(t);try{let n=await fetch(`${e}/api/settings`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({showCodexSparkQuota:t})});if(!n.ok)throw Error(`save`);let r=await n.json(),i=typeof r.showCodexSparkQuota==`boolean`?r.showCodexSparkQuota:t;U(i),se(s(i?`codexAuth.sparkQuotaShown`:`codexAuth.sparkQuotaHidden`),`ok`),await E(!0)}catch{U(!t),se(s(`codexAuth.sparkQuotaFailed`),`err`)}finally{ee(!1)}},Ce=async()=>{let e=await g.pauseExhaustedAccounts();!e.ok&&e.reason===`busy`||se(e.ok?e.pausedCount>0?s(`codexAuth.pauseExhaustedSucceeded`,{count:String(e.pausedCount)}):s(`codexAuth.pauseExhaustedNone`):s(`codexAuth.pauseExhaustedFailed`),e.ok?`ok`:`err`)},we=async t=>{K(t),Y(!1),ie(null),oe(!0);try{let n=await Ft(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());ie(e)}}catch{}finally{oe(!1)}},Te=async t=>{ne(!0);try{let n=await hs(e,t,s,E);n.close&&(K(null),Y(!1)),n.toast&&se(n.toast,n.ok?`ok`:`err`)}finally{ne(!1)}},Ee=v.find(e=>e.isMain),De=v.filter(e=>!e.isMain),Oe=!Ee?.paused&&(!y||y===`__main__`),ke=s(t===`direct`?`codexAuth.prepareForPool`:`codexAuth.setAsNext`),Ae=S!==null||w,je=c.threshold??0,Me=!r;return(0,J.jsxs)(`div`,{children:[(0,J.jsx)(fs,{t:s,embedded:r,refreshingQuota:B,actionFeedback:F,actionFeedbackTone:L,pausingExhausted:w,pauseBusy:Ae,onRefresh:()=>{Z()},onPauseExhausted:()=>{Ce()},sparkVisible:H,sparkBusy:W,onToggleSpark:()=>{Se()}}),n,(0,J.jsx)(ps,{t:s,loadState:b,accountsCount:v.length,onRetry:()=>{E()}}),(b!==`loading`||v.length!==0)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(ds,{t:s,main:Ee,isMainActive:Oe,accountModeState:t,threshold:je,switchActionLabel:ke,onSwitch:O,onTogglePause:ye,pauseUpdatingId:S,pauseBusy:Ae,onPriorityChange:(e,t)=>{be(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onOpenReset:we,onCopyDoctor:Me?ce:void 0,doctorCopyOutcomeFor:Me?X.outcomeFor:void 0}),(0,J.jsxs)(`div`,{className:`section-sep`,children:[(0,J.jsx)(`span`,{className:`section-label`,children:s(`codexAuth.accountPool`)}),(0,J.jsx)(`div`,{className:`sep-line`}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-sm btn-ghost`,onClick:()=>A(!0),children:[(0,J.jsx)(de,{width:14}),` `,s(`codexAuth.add`)]})]}),pe&&fe&&(0,J.jsx)(cs,{onReauth:()=>me(fe.id)}),De.length===0&&(0,J.jsx)(Ot,{title:s(`codexAuth.noPool`)}),(0,J.jsx)(ss,{pool:De,activeId:y,accountModeState:t,switchActionLabel:ke,threshold:je,onOpenReset:we,onSwitch:O,onTogglePause:ye,pauseUpdatingId:S,pauseBusy:Ae,onPriorityChange:(e,t)=>{be(e,t)},priorityUpdatingId:C,switchingId:x,pinnedId:T,onReauth:me,onEditAlias:ve,onRemove:xe,onCopyDoctor:Me?ce:void 0,doctorCopyOutcomeFor:Me?X.outcomeFor:void 0})]}),(0,J.jsx)(Bo,{apiBase:e,subscribeLoadObserver:g.subscribeLoadObserver,readLastActive:g.readLastActive,onStrategyResolved:u}),(0,J.jsxs)(Vo,{t:s,open:j,onToggle:()=>M(e=>!e),children:[l!==null&&(0,J.jsx)(wo,{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,J.jsx)(ls,{confirm:D,mainEmail:Ee?.email,accountModeState:t,switchingId:x,orderBusy:C!==null,onCancel:()=>O(null),onConfirm:()=>{_e(D.id===`__main__`?`__main__`:D.id)}}),G&&(0,J.jsx)(us,{resetPopup:G,resetConfirm:q,creditDetails:re,creditDetailsLoading:ae,redeeming:te,onClose:()=>{K(null),Y(!1),ie(null)},onShowConfirm:()=>Y(!0),onCancelConfirm:()=>Y(!1),onRedeem:()=>{Te(G.id)}}),k&&(0,J.jsx)(to,{apiBase:e,reauthAccountId:N??void 0,onClose:he,onAdded:ge})]})}var vs={"five-hour":`accountPool.quotaWindowFiveHour`,weekly:`accountPool.quotaWindowWeekly`,"max-utilization":`accountPool.quotaWindowMaxUtilization`};function ys({apiBase:e,accountCount:t}){let n=Q(),[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=No(e.stickyLimit);i({enabled:e.enabled===!0,threshold:n,strategy:jo(e.strategy),stickyLimit:r,quotaWindow:Mo(e.quotaWindow)}),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,quotaWindow:t.quotaWindow}),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,quotaWindow:t.quotaWindow})});if(!n.ok)throw Error(`save`);let r=await n.json().catch(()=>null),a=jo(r?.strategy??t.strategy),s=No(r?.stickyLimit??t.stickyLimit),l=Mo(r?.quotaWindow??t.quotaWindow);i({enabled:t.enabled,threshold:t.threshold,strategy:a,stickyLimit:s,quotaWindow:l}),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?.quotaWindow??`five-hour`,S=y===`round-robin`,C=r===null&&!p,w=C||l||p||!g&&t<2;return(0,J.jsxs)(`div`,{className:`card anthropic-pool-card`,"aria-busy":C||l,children:[(0,J.jsxs)(`div`,{className:`card-row`,style:{alignItems:`flex-start`,gap:12},children:[(0,J.jsxs)(`div`,{style:{flex:1},children:[(0,J.jsx)(`strong`,{children:n(`anthropicPool.title`)}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:p?n(`anthropicPool.loadFailed`):C?n(`common.loading`):g?v===0?n(`anthropicPool.enabledNoProactiveDesc`,{window:n(vs[x])}):n(`anthropicPool.enabledDesc`,{threshold:v,window:n(vs[x])}):n(`anthropicPool.disabledDesc`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`toggle ${g?`on`:``}`,disabled:w,"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,quotaWindow:x})},children:(0,J.jsx)(`span`,{className:`toggle-knob`})})]}),(0,J.jsx)(`div`,{role:`alert`,className:`card-sub anthropic-pool-card__notice`,children:n(`anthropicPool.experimentalWarning`)}),t<2&&(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:8},children:n(`anthropicPool.needTwoAccounts`)}),g&&r&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`field anthropic-pool-card__field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`anthropicPool.threshold`)}),(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:0,max:100,step:1,value:a,disabled:l,"aria-label":n(`anthropicPool.thresholdAria`),onChange:e=>o(e.target.value),onBlur:()=>{let e=Number(a);if(!Number.isInteger(e)||e<0||e>100){o(String(v)),f(n(`anthropicPool.thresholdInvalid`));return}e!==v&&h({enabled:!0,threshold:e,strategy:y,stickyLimit:b,quotaWindow:x})}}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`anthropicPool.thresholdHelp`)})]}),(0,J.jsx)(Ro,{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,quotaWindow:x})},onStickyDraftChange:c,onStickyCommit:e=>{let t=Po(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,quotaWindow:x})}}),(0,J.jsxs)(`div`,{className:`field anthropic-pool-card__field anthropic-pool-card__field--quota-window`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`accountPool.quotaWindow`)}),(0,J.jsx)(Dt,{id:`anthropic-pool-quota-window`,value:x,options:Eo.map(e=>({value:e,label:n(vs[e])})),disabled:l||S,label:n(`accountPool.quotaWindow`),onChange:e=>{let t=Mo(e);t!==x&&h({enabled:!0,threshold:v,strategy:y,stickyLimit:b,quotaWindow:t})}}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(`accountPool.quotaWindowDesc`)}),(0,J.jsx)(`div`,{className:`card-sub`,style:{marginTop:4},children:n(S?`accountPool.quotaWindowInert`:`accountPool.quotaWindowHint`)})]})]}),d&&(0,J.jsx)(`div`,{role:`alert`,className:`card-sub`,style:{marginTop:8,color:`var(--danger, #c44)`},children:d})]})}function bs({serverDefault:e=!0}){let t=Q(),[n,r]=(0,_.useState)(Xa);return(0,J.jsxs)(`label`,{className:`open-browser-pref`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:!(n??e),onChange:e=>{let t=!e.target.checked;r(t),Qa(t)}}),(0,J.jsxs)(`span`,{className:`open-browser-pref-copy`,children:[(0,J.jsx)(`span`,{className:`text-label`,children:t(`prov.dontOpenBrowser`)}),(0,J.jsx)(`span`,{className:`muted text-label`,children:t(`prov.dontOpenBrowserHint`)})]})]})}var xs=4e3,Ss=262144,Cs=[],ws=[];function Ts({initialState:e,onUpdateProvider:t}){let n=Q(),[r,i]=(0,_.useState)(e),[a,o]=(0,_.useState)(e),[s,c]=(0,_.useState)(!1),[l,u]=(0,_.useState)(``);e!==a&&(o(e),i(e));let d=r===`mixed`,f=async()=>{if(!t||s)return;let e=r!==!0;c(!0),u(``);try{let r=await t(`xai`,{xaiResponsesOptIn:e});if(!r.ok){u(r.error??n(`prov.updateFail`));return}i(r.xaiResponsesOptInState??e)}catch{u(n(`prov.networkError`))}finally{c(!1)}};return(0,J.jsxs)(`div`,{className:`pwi-auth-optin-row`,children:[(0,J.jsxs)(`div`,{className:`pwi-auth-optin-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-optin-label`,children:n(`pws.xaiResponsesOptIn`)}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-secondary`,children:[n(`pws.xaiResponsesOptInDesc`),d&&(0,J.jsxs)(`span`,{className:`pwi-auth-optin-mixed`,children:[` `,n(`pws.xaiResponsesOptInMixed`)]})]}),l&&(0,J.jsx)(`span`,{className:`pwi-auth-optin-error`,role:`alert`,children:l})]}),(0,J.jsx)(Tt,{on:r===!0,mixed:d,onClick:()=>{f()},disabled:!t||s,label:n(`pws.xaiResponsesOptIn`)})]})}var Es=new Set([`totalCount`,`importedCount`,`updatedCount`,`failedCount`,`unsupportedCount`,`results`]),Ds=new Set([`imported`,`updated`,`failed`,`unsupported`]),Os={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 ks(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function As(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function js(e){if(!ks(e)||Object.keys(e).some(e=>!Es.has(e)))return null;let{totalCount:t,importedCount:n,updatedCount:r,failedCount:i,unsupportedCount:a,results:o}=e;if(!As(t)||!As(n)||!As(r)||!As(i)||!As(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(!ks(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||!Ds.has(n)||!Os[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 Ms({item:e,apiBase:t,oauth:n,accounts:r=Cs,keys:i=ws,accountLoadState:a=`ready`,switchingAccountId:o=null,busy:s=!1,loginHint:c,authHandlers:l,onCodexActiveNeedsReauthChange:u,codexController:d,onUpdateProvider:f}){let p=Q(),[m,h]=(0,_.useState)(!1),[g,v]=(0,_.useState)(``),[y,b]=(0,_.useState)(!1),[x,S]=(0,_.useState)(!1),[C,w]=(0,_.useState)(`idle`),[T,E]=(0,_.useState)(null),[D,O]=(0,_.useState)(!1),k=(0,_.useRef)(null),[A,j]=(0,_.useState)(``),[M,N]=(0,_.useState)(!1),[P,F]=(0,_.useState)(``),[I,L]=(0,_.useState)(!0);(0,_.useEffect)(()=>{if(r.length===0){O(!1);return}if(!r.some(e=>e.quota==null&&!e.quotaUnavailable)){O(!1);return}O(!0);let e=window.setTimeout(()=>O(!1),xs);return()=>window.clearTimeout(e)},[r]);let R=ya({...e,hasApiKey:e.hasApiKey||i.length>0}),z=R===`oauth-accounts`,B=R===`api-keys`;if(R===`codex-accounts`)return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":p(`pws.availableAccounts`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:p(`pws.availableAccounts`)}),(0,J.jsx)(`div`,{className:`pwi-auth-body`,children:(0,J.jsx)(_s,{apiBase:t,embedded:!0,controller:d,onActiveNeedsReauthChange:u})})]});if(!R||!l)return null;let V=c?.provider===e.name?c:null,H=async()=>{let n=A.trim();if(!(!n||M)){N(!0),F(``);try{let r=await fetch(`${t}/api/oauth/login/code`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.name,input:n})});if(!r.ok){let e=await r.json().catch(()=>({}));L(!1),F(p(`prov.pasteFail`,{error:e.error||r.statusText}));return}j(``),L(!0),F(p(`prov.pasteOk`))}catch{L(!1),F(p(`modal.networkError`))}finally{N(!1)}}},U=r.length>0||n?.loggedIn===!0,W=r.find(e=>e.active&&e.needsReauth),ee=!!W,G=async()=>{let t=g.trim();if(t){b(!0);try{await l.onAddApiKey(e.name,t)&&(v(``),h(!1))}finally{b(!1)}}},K=async n=>{if(!(!n||x)){S(!0),w(`idle`),E(null);try{if(!n.name.toLowerCase().endsWith(`.json`)||n.size>Ss){w(`invalid`);return}let r;try{r=JSON.parse(await n.text())}catch{w(`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){w(`failed`);return}let a=js(await i.json().catch(()=>null));if(!a){w(`failed`);return}E(a),w(`complete`);try{await l.onRetryAccounts?.(e.name)}catch{}}catch{w(`failed`)}finally{k.current&&(k.current.value=``),S(!1)}}};return(0,J.jsxs)(`section`,{className:`pwi-section pwi-auth-section`,"aria-label":p(z?`pws.availableAccounts`:`pws.apiKeys`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:p(z?`pws.availableAccounts`:`pws.apiKeys`)}),(0,J.jsxs)(`div`,{className:`pwi-auth-body`,children:[e.name===`xai`&&(0,J.jsx)(Ts,{initialState:e.xaiResponsesOptInState??!1,onUpdateProvider:f}),z&&(0,J.jsxs)(J.Fragment,{children:[e.name===`anthropic`&&(0,J.jsx)(ys,{apiBase:t,accountCount:r.length}),e.name===`google-antigravity`&&(0,J.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{id:`cockpit-import-description`,className:`pwi-auth-row-secondary`,children:p(`pws.cockpitImportDescription`)}),(0,J.jsx)(`label`,{className:`sr-only`,htmlFor:`cockpit-import-file`,children:p(`pws.cockpitImportFileLabel`)}),(0,J.jsx)(`input`,{ref:k,id:`cockpit-import-file`,type:`file`,accept:`application/json,.json`,className:`sr-only`,"aria-describedby":`cockpit-import-description cockpit-import-status`,disabled:x,onChange:e=>{K(e.currentTarget.files?.[0])}})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:x,onClick:()=>k.current?.click(),children:p(x?`pws.cockpitImporting`:`pws.cockpitImportChooseFile`)}),(0,J.jsxs)(`div`,{id:`cockpit-import-status`,role:`status`,"aria-live":`polite`,children:[C===`invalid`&&p(`pws.cockpitImportInvalid`),C===`failed`&&p(`pws.cockpitImportFailed`),C===`complete`&&T&&p(`pws.cockpitImportComplete`,{imported:T.importedCount,updated:T.updatedCount,failed:T.failedCount,unsupported:T.unsupportedCount})]})]}),(0,J.jsxs)(`div`,{className:`pwi-auth-status-row`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${ee?`pwi-auth-dot--warn`:U?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`pwi-auth-status-text`,children:U?r.length>0?p(`pws.loggedInTitle`):n?.email??p(`pws.loggedInTitle`):n?.error||p(`pws.notLoggedInTitle`)}),(0,J.jsxs)(`span`,{className:`pwi-auth-actions`,children:[W&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onReauth(e.name,W.id),children:p(`pws.reauthenticate`)}),U?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onLogout(e.name),children:p(`prov.logout`)}):(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:s,onClick:()=>void l.onLogin(e.name,!1),children:[s?(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}):(0,J.jsx)(De,{style:{width:13,height:13},"aria-hidden":`true`}),p(s?`prov.waitingBrowser`:`prov.login`)]})]})]}),!s&&(0,J.jsx)(bs,{}),s&&V&&(0,J.jsxs)(`div`,{className:`pwi-auth-wait`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),(0,J.jsxs)(`div`,{className:`pwi-auth-wait-copy`,children:[(0,J.jsx)(`div`,{className:`pwi-auth-wait-title`,children:p(`prov.waitingBrowser`)}),(0,J.jsx)(qa,{hint:{url:V.url,deviceCode:V.deviceCode,instructions:V.instructions},paste:{value:A,busy:M,message:P,ok:I,onChange:j,onSubmit:()=>{H()}}}),l.onCancelLogin&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onCancelLogin?.(e.name),children:p(`common.cancel`)})]})]}),a===`loading`&&r.length===0&&(0,J.jsxs)(`div`,{className:`pwi-auth-state`,role:`status`,children:[(0,J.jsx)(`span`,{className:`pwi-spin-inline`,"aria-hidden":`true`}),p(`pws.accountsLoading`)]}),a===`error`&&(0,J.jsxs)(`div`,{className:`pwi-auth-state pwi-auth-state--error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:p(`pws.accountsLoadFailed`)}),l.onRetryAccounts&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onRetryAccounts?.(e.name),children:p(`pws.retryAccounts`)})]}),r.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:r.map(t=>{let n=ba(r,t,p),i=o===t.id,a=t.health?.status,c=!!t.needsReauth||ja(a),u=Na(a),d=Oa(t.id),f=Ia(p,t.health),m=La(p,e.name,t.id,t.health);return(0,J.jsxs)(`li`,{className:`pwi-auth-acct${t.active?` pwi-auth-acct--active`:``}`,children:[(0,J.jsxs)(`div`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>{!t.active&&!c&&!u&&!o&&l.onSwitchAccount(e.name,t)},"aria-current":t.active?`true`:void 0,"aria-label":`${n}${t.active?` — ${p(`pws.accountCurrent`)}`:``}`,disabled:!!(c||u||o&&!i),children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${c?`pwi-auth-dot--warn`:t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:n}),(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary`,children:[t.email,`${p(`prov.accountId`)}: ${d}`].filter(Boolean).join(` · `)}),m&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:m}),u&&(0,J.jsx)(`span`,{className:`pwi-auth-row-secondary faint`,children:p(`pws.healthCooldownHint`)})]}),f&&(0,J.jsx)(`span`,{className:Aa(a),children:f}),c&&!f&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:p(`pws.reauth`)}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:p(`prov.accountActive`)}),i&&(0,J.jsx)(`span`,{className:`badge badge-muted`,children:p(`pws.accountSwitching`)})]}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:s||!!o,onClick:()=>void l.onReauth(e.name,t.id),children:p(`pws.reauthenticate`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`oauth`,t.id,t.alias),children:p(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${p(`common.remove`)} — ${n}`,title:`${p(`common.remove`)} — ${n}`,disabled:!!o,onClick:()=>void l.onRemoveAccount(e.name,t),children:(0,J.jsx)(he,{style:{width:13,height:13},"aria-hidden":`true`})})]}),(t.quota!=null||t.quotaUnavailable||D&&t.quota==null)&&(0,J.jsx)(`div`,{className:`pwi-auth-acct-quota`,children:t.quotaUnavailable?(0,J.jsx)(`p`,{className:`muted pwi-auth-acct-quota-stale`,children:p(`pws.accountQuotaUnavailable`)}):(0,J.jsx)($i,{quota:t.quota??null,plan:null,threshold:80,t:p,layout:`stacked`,pending:t.quota==null})})]},t.id)})}),a===`ready`&&U&&r.length===0&&(0,J.jsx)(`div`,{className:`pwi-auth-state pwi-auth-state--empty`,children:p(`pws.noAccounts`)}),U&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>void l.onLogin(e.name,!0),disabled:s||!!o,children:p(`pws.addAccount`)})]}),B&&(0,J.jsxs)(J.Fragment,{children:[i.length>0&&(0,J.jsx)(`ul`,{className:`pwi-auth-list`,children:i.map(t=>(0,J.jsxs)(`li`,{className:`pwi-auth-row${t.active?` pwi-auth-row--active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`pwi-auth-row-main`,onClick:()=>void l.onSwitchApiKey(e.name,t),disabled:t.active,children:[(0,J.jsx)(`span`,{className:`pwi-auth-dot ${t.active?`pwi-auth-dot--ok`:`pwi-auth-dot--off`}`,"aria-hidden":`true`}),(0,J.jsxs)(`span`,{className:`pwi-auth-row-copy`,children:[(0,J.jsx)(`span`,{className:`pwi-auth-row-label`,children:t.label??t.masked}),t.label&&(0,J.jsxs)(`code`,{className:`pwi-auth-row-secondary`,children:[t.masked,` · `,p(`prov.accountId`),`: `,t.id]})]}),t.active&&(0,J.jsx)(`span`,{className:`badge badge-primary`,children:p(`prov.accountActive`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void l.onEditAlias(e.name,`api-key`,t.id,t.label),children:p(`prov.editAlias`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-auth-row-remove`,"aria-label":`${p(`common.remove`)} — ${t.label??t.masked}`,title:`${p(`common.remove`)} — ${t.label??t.masked}`,onClick:()=>void l.onRemoveApiKey(e.name,t),children:(0,J.jsx)(he,{style:{width:13,height:13},"aria-hidden":`true`})})]},t.id))}),m?(0,J.jsxs)(`div`,{className:`pwi-auth-add-key`,children:[(0,J.jsx)(`input`,{className:`input`,type:`password`,value:g,onChange:e=>v(e.target.value),placeholder:p(`modal.apiKeyPlaceholder`),autoComplete:`off`,disabled:y}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void G(),disabled:y||!g.trim(),children:p(y?`pws.saving`:`pws.addKey`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h(!1),v(``)},children:p(`common.cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{marginTop:8},onClick:()=>h(!0),children:p(`pws.addKey`)})]})]})]})}function Ns(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 Ps(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 Fs(e,t,n){let r=e?.find(e=>e.id===t);return r?.baseUrl?r.baseUrl.trim():n.trim()}var Is=`https://chatgpt.com/backend-api/codex`;function Ls(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 Rs(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 zs(e){return e?e.adapter!==`openai-responses`||e.authMode!==`forward`||typeof e.baseUrl!=`string`||Ls(e.baseUrl)!==Is?`invalid`:e.disabled===!0?`disabled`:`ready`:`absent`}function Bs(e){return e.id===`openai`}function Vs(e){return e.id===`openai`?e.codexAccountMode===`direct`?`prov.openaiDirectDesc`:`prov.openaiPoolDesc`:null}function Hs(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 Us(e,t){return Bs(e)?Ws(e):{name:t.name.trim(),provider:Hs(t)}}function Ws(e){if(!e.provider)throw Error(`Missing canonical provider seed for ${e.id}`);return{name:e.id,provider:structuredClone(e.provider)}}var Gs=class extends Error{i18nKey;constructor(e){super(e),this.name=`OpenAiEnableError`,this.i18nKey=e}};async function Ks(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 Gs(`codexAuth.enableOpenaiFailed`)}let r=await n(`${e}/api/provider-presets`);if(!r.ok)throw new Gs(`codexAuth.openaiPresetLoadFailed`);let i=(await r.json()).providers?.find(e=>e.id===`openai`);if(!i?.provider)throw new Gs(`codexAuth.openaiPresetUnavailable`);if(!(await n(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(Ws(i))})).ok)throw new Gs(`codexAuth.enableOpenaiFailed`)}var qs=[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`],Js=[];function Ys(e){return e===`http1.1`||e===`h1`?`http1.1`:`http2`}function Xs(e){return e===void 0?``:String(e)}function Zs(e){if(!e.trim())return;let t=Number(e);return Number.isFinite(t)&&t>=1/60?t:void 0}function Qs(e){if(!e.trim())return;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0}function $s(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 ec({item:e,availableModels:t=Js,apiBase:n,onUpdateProvider:r,onDirtyChange:i,onRegisterSave:a}){let o=Q(),s=String(e.authMode??(e.keyOptional?`local`:`key`)),c=$r(e.name,e),l=c?e.liveModels!==!1:!1,u=Ys(e.upstreamHttpVersion),[d,f]=(0,_.useState)(e.adapter),[p,m]=(0,_.useState)(e.baseUrl),[h,g]=(0,_.useState)(e.defaultModel??``),[v,y]=(0,_.useState)(s),[b,x]=(0,_.useState)(e.apiKeyTransport??`x-api-key`),[S,C]=(0,_.useState)(e.note??``),[w,T]=(0,_.useState)(e.allowPrivateNetwork??!1),[E,D]=(0,_.useState)(l),[O,k]=(0,_.useState)(u),[A,j]=(0,_.useState)(!1),[M,N]=(0,_.useState)(null),[P,F]=(0,_.useState)(e.codexAccountMode??`pool`),[I,L]=(0,_.useState)(!1),[R,z]=(0,_.useState)(null),[B,V]=(0,_.useState)(),[H,U]=(0,_.useState)(n?`loading`:`idle`),[W,ee]=(0,_.useState)(()=>`custom`),[G,K]=(0,_.useState)(e.requestPacing?.enabled===!0),[q,Y]=(0,_.useState)(()=>Xs(e.requestPacing?.requestsPerMinute)),[te,ne]=(0,_.useState)(()=>Xs(e.requestPacing?.minIntervalMs)),[re,ie]=(0,_.useState)(()=>({...e.requestPacing?.models??{}})),[ae,oe]=(0,_.useState)(``),[X,se]=(0,_.useState)(``),[ce,le]=(0,_.useState)(``),[ue,de]=(0,_.useState)(null);(0,_.useEffect)(()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),y(String(e.authMode??(e.keyOptional?`local`:`key`))),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),D(l),k(u),K(e.requestPacing?.enabled===!0),Y(Xs(e.requestPacing?.requestsPerMinute)),ne(Xs(e.requestPacing?.minIntervalMs)),ie({...e.requestPacing?.models??{}}),N(null),z(null),queueMicrotask(()=>ee(Ps(B,e.baseUrl)))},[e.adapter,e.baseUrl,e.defaultModel,e.authMode,e.apiKeyTransport,e.keyOptional,e.note,e.allowPrivateNetwork,l,u,e.requestPacing,B]),(0,_.useEffect)(()=>{F(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=>Ft(e)).then(e=>{if(t)return;if(!e){V(void 0),U(`error`);return}let n=(e.providers??[]).find(e=>e.id===r)?.baseUrlChoices;V(n),U(`ready`),ee(Ps(n,i))}).catch(()=>{t||(V(void 0),U(`error`))}),()=>{t=!0}},[n,e.name]),(0,_.useEffect)(()=>{if(!n)return;let t=!0,r=!1,i=()=>{if(r)return;r=!0;let i=Ln(1e4);fetch(`${n}/api/provider-request-pacing?name=${encodeURIComponent(e.name)}`,{signal:i.signal}).then(e=>Ft(e)).then(e=>{t&&e&&de(e)}).catch(()=>void 0).finally(()=>{i.clear(),r=!1})};i();let a=Vn(i,2e3);return()=>{t=!1,a()}},[n,e.name]);let fe=(0,_.useMemo)(()=>({enabled:G,...Zs(q)===void 0?{}:{requestsPerMinute:Zs(q)},...Qs(te)===void 0?{}:{minIntervalMs:Qs(te)},...Object.keys(re).length>0?{models:re}:{}}),[te,G,re,q]),pe=d.trim()!==e.adapter||p.trim()!==e.baseUrl||h.trim()!==(e.defaultModel??``)||v!==String(e.authMode??(e.keyOptional?`local`:`key`))||d.trim()===`anthropic`&&v===`key`&&b!==(e.apiKeyTransport??`x-api-key`)||S.trim()!==(e.note??``)||w!==(e.allowPrivateNetwork??!1)||E!==l||d.trim()===`cursor`&&O!==u,me=$s(fe)!==$s(e.requestPacing),he=pe||me;(0,_.useEffect)(()=>(i?.(he),()=>i?.(!1)),[he,i]);let ge=(0,_.useMemo)(()=>{let n=new Set(t);return h.trim()&&n.add(h.trim()),e.defaultModel&&n.add(e.defaultModel),[...n].sort((e,t)=>e.localeCompare(t))},[t,h,e.defaultModel]),_e=(0,_.useMemo)(()=>{let e=[...qs];return d&&!e.includes(d)&&e.unshift(d),e},[d]),ve=On(e.name),ye=H===`ready`&&!!(B&&B.length>0),be=d.trim()===`anthropic`&&v===`key`,xe=e.name===`openai`?zs(e):`invalid`,Z=xe===`ready`||xe===`disabled`,Se=ve&&H!==`error`,Ce=async()=>{if(!r)return N({ok:!1,text:o(`pws.updatesUnavailable`)}),!1;if(I)return!1;let t=ye?Fs(B,W,p):p.trim();if(!d.trim()||!t)return N({ok:!1,text:o(`pws.adapterBaseRequired`)}),!1;j(!0),N(null);try{if(G&&!fe.requestsPerMinute&&!fe.minIntervalMs&&!fe.models)return N({ok:!1,text:o(`pws.pacingRuleRequired`)}),!1;let n=me&&!pe,i=n?{requestPacing:fe}:{adapter:d.trim(),baseUrl:t,defaultModel:h.trim(),authMode:v,note:S.trim(),allowPrivateNetwork:w,...me?{requestPacing:fe}:{}};n||(c&&E!==(e.liveModels!==!1)&&(i.liveModels=E),d.trim()===`cursor`&&O!==u&&(i.upstreamHttpVersion=O===`http1.1`?`http1.1`:null),be?i.apiKeyTransport=b:e.apiKeyTransport!==void 0&&(i.apiKeyTransport=``));let a=await r(e.name,i);return N(a.ok?{ok:!0,text:o(`pws.settingsSaved`)}:{ok:!1,text:a.error||o(`prov.saveFailed`)}),a.ok}finally{j(!1)}},we=(0,_.useRef)(Ce);(0,_.useEffect)(()=>{we.current=Ce}),(0,_.useEffect)(()=>{if(a)return a(()=>we.current()),()=>a(null)},[a]);let Te=async e=>{if(!(I||A||e===P)){if(!r){z({ok:!1,text:o(`pws.updatesUnavailable`)});return}L(!0),z(null);try{let t=await r(`openai`,{codexAccountMode:e});t.ok?(F(e),z({ok:!0,text:o(`pws.accountModeSaved`)})):z({ok:!1,text:t.error||o(`pws.accountModeFailed`)})}catch{z({ok:!1,text:o(`pws.accountModeFailed`)})}finally{L(!1)}}},Ee=()=>{f(e.adapter),m(e.baseUrl),g(e.defaultModel??``),y(s),x(e.apiKeyTransport??`x-api-key`),C(e.note??``),T(e.allowPrivateNetwork??!1),D(l),k(u),N(null),K(e.requestPacing?.enabled===!0),Y(Xs(e.requestPacing?.requestsPerMinute)),ne(Xs(e.requestPacing?.minIntervalMs)),ie({...e.requestPacing?.models??{}}),ee(Ps(B,e.baseUrl))},Oe=(e,t)=>{switch(e){case`token-plan`:return o(`modal.endpoint.tokenPlan`);case`payg`:return o(`modal.endpoint.payAsYouGo`);case`custom`:return o(`modal.endpoint.custom`);default:return t}};return(0,J.jsxs)(`div`,{className:`pwi-settings-form`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsxs)(`span`,{className:`pwi-settings-label`,children:[(0,J.jsx)(De,{style:{width:12,height:12}}),` `,o(`pws.providerId`)]}),(0,J.jsx)(`input`,{className:`input`,value:e.name,readOnly:!0,disabled:!0})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.adapter`)}),ve?(0,J.jsx)(`input`,{className:`input`,value:d,readOnly:!0,disabled:!0}):(0,J.jsx)(`select`,{className:`input`,value:d,onChange:e=>f(e.target.value),children:_e.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})]}),ye?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.endpoint`)}),(0,J.jsx)(`select`,{className:`input`,value:W,onChange:e=>{let t=e.target.value;ee(t),m(Ns(B,t,p))},children:B.map(e=>(0,J.jsx)(`option`,{value:e.id,children:Oe(e.id,e.label)},e.id))})]}),W===`custom`&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),placeholder:o(`modal.baseUrlPlaceholder`)})]})]}):(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.baseUrl`)}),(0,J.jsx)(`input`,{className:`input`,value:p,onChange:e=>m(e.target.value),readOnly:Se,disabled:Se})]}),d.trim()===`cursor`&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cursorTransport`)}),(0,J.jsxs)(`select`,{className:`input`,value:O,onChange:e=>k(e.target.value),children:[(0,J.jsx)(`option`,{value:`http2`,children:o(`pws.cursorTransportHttp2`)}),(0,J.jsx)(`option`,{value:`http1.1`,children:o(`pws.cursorTransportHttp1`)})]}),(0,J.jsx)(`span`,{className:`pwi-settings-hint`,children:o(`pws.cursorTransportDesc`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.cell.defaultModel`)}),ge.length>0?(0,J.jsxs)(`select`,{className:`input`,value:h,onChange:e=>g(e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:o(`pws.defaultModelNone`)}),ge.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}):(0,J.jsx)(`input`,{className:`input`,value:h,onChange:e=>g(e.target.value),placeholder:o(`pws.optionalPlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.authMode`)}),ve?(0,J.jsx)(`input`,{className:`input`,value:Oi(e,o),readOnly:!0,disabled:!0}):(0,J.jsxs)(`select`,{className:`input`,value:v,onChange:e=>y(e.target.value),children:[(0,J.jsx)(`option`,{value:`key`,children:o(`modal.badge.apiKey`)}),(0,J.jsx)(`option`,{value:`forward`,children:o(`pws.auth.chatgptPassthrough`)}),(0,J.jsx)(`option`,{value:`oauth`,children:o(`modal.badge.oauth`)}),(0,J.jsx)(`option`,{value:`local`,children:o(`modal.badge.local`)})]})]}),Z&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`codexAuth.accountModeTitle`)}),(0,J.jsxs)(`select`,{className:`input`,value:P,disabled:I||A,onChange:e=>{let t=e.target.value;if(t!==P){if(!window.confirm(o(`pws.accountModeConfirm`))){e.target.value=P;return}Te(t)}},children:[(0,J.jsx)(`option`,{value:`pool`,children:o(`codexAuth.accountModePool`)}),(0,J.jsx)(`option`,{value:`direct`,children:o(`codexAuth.accountModeDirect`)})]}),(0,J.jsx)(`span`,{className:`pwi-settings-hint`,children:o(P===`direct`?`codexAuth.accountModeDirectDesc`:`codexAuth.accountModePoolDesc`)}),I&&(0,J.jsx)(`span`,{className:`muted text-label`,children:o(`pws.accountSwitching`)}),R&&(0,J.jsx)(`span`,{role:R.ok?`status`:`alert`,className:R.ok?`pwi-settings-mode-msg pwi-settings-mode-msg--ok`:`pwi-settings-mode-msg pwi-settings-mode-msg--err`,children:R.text})]}),be&&(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`modal.apiKeyTransport`)}),(0,J.jsxs)(`select`,{className:`input`,value:b,onChange:e=>x(e.target.value),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:o(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:o(`modal.apiKeyTransportBearer`)})]})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.note`)}),(0,J.jsx)(`textarea`,{className:`input pwi-settings-textarea`,value:S,onChange:e=>C(e.target.value),rows:2})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:w,onChange:e=>T(e.target.checked)}),(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.allowPrivateNetwork`)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,style:{flexDirection:`row`,alignItems:`flex-start`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:E,disabled:!c,onChange:e=>D(e.target.checked)}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.liveModels`)}),(0,J.jsx)(`span`,{className:`muted text-label`,style:{display:`block`,marginTop:2},children:o(`pws.liveModelsDesc`)})]})]}),(0,J.jsxs)(`section`,{className:`pwi-pacing-card`,"aria-labelledby":`pwi-pacing-title`,children:[(0,J.jsxs)(`div`,{className:`pwi-pacing-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h3`,{id:`pwi-pacing-title`,children:o(`pws.pacingTitle`)}),(0,J.jsx)(`p`,{children:o(`pws.pacingDesc`)})]}),(0,J.jsxs)(`label`,{className:`pwi-pacing-toggle`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:G,onChange:e=>K(e.target.checked)}),` `,o(`pws.pacingEnabled`)]})]}),(0,J.jsxs)(`div`,{className:`pwi-pacing-grid`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:q,onChange:e=>Y(e.target.value),placeholder:`38`})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:te,onChange:e=>ne(e.target.value),placeholder:`1600`})]})]}),(0,J.jsx)(`p`,{className:`pwi-settings-hint`,children:o(`pws.pacingSlowerWins`)}),(0,J.jsxs)(`div`,{className:`pwi-pacing-status`,"aria-live":`polite`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:ue?.queued??0}),` `,o(`pws.pacingQueued`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsxs)(`strong`,{children:[ue?.nextSlotInMs??0,` ms`]}),` `,o(`pws.pacingNextSlot`)]}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:ue?.lastModelId??o(`pws.pacingNone`)}),` `,o(`pws.pacingLastModel`)]})]}),(0,J.jsx)(`h4`,{children:o(`pws.pacingModelOverrides`)}),(0,J.jsxs)(`div`,{className:`pwi-pacing-grid pwi-pacing-grid--model`,children:[(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingModel`)}),(0,J.jsx)(`input`,{className:`input`,list:`pacing-models-${e.name}`,value:ae,onChange:e=>oe(e.target.value)}),(0,J.jsx)(`datalist`,{id:`pacing-models-${e.name}`,children:t.map(e=>(0,J.jsx)(`option`,{value:e},e))})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingRpm`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`0.016667`,step:`any`,value:X,onChange:e=>se(e.target.value)})]}),(0,J.jsxs)(`label`,{className:`pwi-settings-field`,children:[(0,J.jsx)(`span`,{className:`pwi-settings-label`,children:o(`pws.pacingDelay`)}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:`1`,step:`1`,value:ce,onChange:e=>le(e.target.value)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{let e=ae.trim(),t=Zs(X),n=Qs(ce);!e||t===void 0&&n===void 0||(ie(r=>({...r,[e]:{...t===void 0?{}:{requestsPerMinute:t},...n===void 0?{}:{minIntervalMs:n}}})),oe(``),se(``),le(``))},children:o(`pws.pacingAdd`)})]}),Object.entries(re).length>0&&(0,J.jsx)(`div`,{className:`pwi-pacing-overrides`,children:Object.entries(re).map(([e,t])=>(0,J.jsxs)(`div`,{className:`pwi-pacing-row`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.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,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ie(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),"aria-label":o(`pws.pacingRemoveModel`,{model:e}),children:o(`pws.pacingRemove`)})]},e))})]}),he&&(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar`,children:[(0,J.jsx)(`span`,{className:`muted`,children:o(`pws.settingsUnsavedBar`)}),(0,J.jsxs)(`div`,{className:`pwi-settings-sticky-bar-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:Ee,disabled:A,children:o(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>void Ce(),disabled:A||I,children:o(A?`pws.saving`:`pws.saveSettings`)})]})]}),M&&(0,J.jsx)(`div`,{role:M.ok?`status`:`alert`,className:M.ok?`pwi-settings-msg pwi-settings-msg--ok`:`pwi-settings-msg pwi-settings-msg--err`,children:M.text})]})}function tc({providerName:e,defaultProviderName:t,onConfirm:n,onCancel:r}){let i=Q();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:r,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.removeConfirmTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.removeConfirmTitle`)}),(0,J.jsx)(`p`,{children:t?i(`pws.removeDefaultConfirmBody`,{name:e,defaultProvider:t}):i(`pws.removeConfirmBody`,{name:e})}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,onClick:n,children:i(`pws.removeConfirm`)})]})]})})}function nc({onSave:e,onDiscard:t,onCancel:n,saving:r=!1}){let i=Q();return(0,J.jsx)(`div`,{className:`dialog-backdrop`,onClick:n,children:(0,J.jsxs)(`div`,{className:`dialog`,role:`alertdialog`,"aria-label":i(`pws.unsavedLeaveTitle`),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{children:i(`pws.unsavedLeaveTitle`)}),(0,J.jsx)(`p`,{children:i(`pws.unsavedLeaveBody`)}),(0,J.jsxs)(`div`,{className:`dialog-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:i(`pws.discardSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:e,disabled:r,children:i(r?`pws.saving`:`pws.saveSettings`)})]})]})})}function rc({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=Q(),[M,N]=(0,_.useState)(`overview`),[P,F]=(0,_.useState)(!1),[I,L]=(0,_.useState)(null),[R,z]=(0,_.useState)(!1),B=(0,_.useRef)(null),[V,H]=(0,_.useState)(0),U=(0,_.useCallback)(e=>{B.current=e},[]),W=e.disabled===!0,ee=(0,_.useMemo)(()=>ii(e),[e]),G=(0,_.useMemo)(()=>di(e),[e]),K=(0,_.useMemo)(()=>ya(e),[e]),q=v===e.name?g:0,Y=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??``]),te=(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!==V&&!(q&&!K)&&(H(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)%te.length;else if(e.key===`ArrowLeft`)n=(t-1+te.length)%te.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=te.length-1;else return;e.preventDefault(),ne(te[n].id),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[ne,te]),ae=`pws-tab-${M}`,oe=`pws-panel-${M}`;return(0,J.jsxs)(`div`,{className:`pws-detail`,children:[(0,J.jsx)(`div`,{className:`pws-detail-head`,children:(0,J.jsxs)(`button`,{type:`button`,className:`pws-detail-back-link`,onClick:re,children:[(0,J.jsx)(Se,{className:`pws-detail-back-chevron`,"aria-hidden":`true`}),j(`pws.allProviders`)]})}),(0,J.jsxs)(`div`,{className:`pws-detail-head-main`,children:[(0,J.jsx)(Ai,{name:e.name,adapter:e.adapter,baseUrl:e.baseUrl,cls:`pws-detail-icon`}),(0,J.jsx)(`div`,{className:`pws-detail-title-wrap`,children:(0,J.jsxs)(`h2`,{className:`pws-detail-title`,children:[Dn(e.name,j),G&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--local`,children:j(`modal.badge.local`)}),!G&&ee&&(0,J.jsx)(`span`,{className:`pwi-rail-badge pwi-rail-badge--free`,children:j(`modal.badge.free`)})]})}),(0,J.jsxs)(`div`,{className:`pws-detail-actions`,children:[!D&&!W&&A&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A(e.name),children:j(`prov.setDefault`)}),O&&(0,J.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,J.jsx)(he,{style:{width:15,height:15},"aria-hidden":`true`})}),k&&(0,J.jsxs)(`div`,{className:`pws-detail-toggle`,children:[(0,J.jsx)(`span`,{className:`pws-detail-toggle-label`,children:j(`pws.enabledLabel`)}),(0,J.jsx)(Tt,{on:!W,onClick:()=>k(e.name,!W),disabled:D,label:j(`pws.enabledLabel`)})]})]})]}),(0,J.jsx)(`div`,{className:`pws-detail-tabs`,role:`tablist`,children:te.map((e,t)=>(0,J.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,J.jsxs)(`div`,{className:`pws-detail-panel`,role:`tabpanel`,id:oe,"aria-labelledby":ae,tabIndex:0,children:[M===`overview`&&(0,J.jsx)(xa,{item:e,apiBase:f,connectionIdentity:Y,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,J.jsx)(Ta,{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,J.jsx)(Ea,{item:e,usageTotals:t,quotaReport:r,modelUsage:n}),M===`accounts`&&(0,J.jsx)(Ms,{item:e,apiBase:f,oauth:p,accounts:m,keys:b,accountLoadState:h,switchingAccountId:y,busy:x===e.name,loginHint:S,authHandlers:C,onUpdateProvider:E,onCodexActiveNeedsReauthChange:w,codexController:T}),M===`settings`&&(0,J.jsx)(ec,{item:e,apiBase:f,availableModels:i,onUpdateProvider:E,onDirtyChange:F,onRegisterSave:U},e.name)]}),I&&(0,J.jsx)(nc,{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){z(!0);try{if(!(await B.current?.()??!1))return;let e=I;L(null),F(!1),e===`deselect`?d():e&&N(e)}finally{z(!1)}}})()}})]})}var ic=new Set([`anthropic`,`google-antigravity`]),ac=new Set([`github-copilot`,`cursor`]);function oc(e){let t=e.trim().toLowerCase();return ic.has(t)?`high`:ac.has(t)?`elevated`:null}function sc(e){switch(e){case`high`:return`oauthTos.highTitle`;case`elevated`:return`oauthTos.elevatedTitle`;default:return e}}function cc(e){switch(e){case`high`:return`oauthTos.highBody`;case`elevated`:return`oauthTos.elevatedBody`;default:return e}}function lc(e,t=!1){let n={};for(let[t,r]of Object.entries(e))Ma(r.accounts.find(e=>e.active)??r.accounts.find(e=>e.id===r.activeAccountId))&&(n[t]=!0);return t&&(n.openai=!0),n}function uc(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)}&quota=1`);if(!r.ok)return;let o=await r.json();if(!i.current||T.current[e]!==n)return;d(t=>({...t,[e]:{activeAccountId:o.activeAccountId??a.activeAccountId??null,accounts:o.accounts??a.accounts??[]}}))}catch{}})(),!0)}catch{return!i.current||T.current[e]!==n||(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=ba(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=ba(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)(()=>lc(u,l),[u,l])}}function dc(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 fc={xai:`xAI (Grok)`,anthropic:`Anthropic (Claude)`,kimi:`Kimi (Moonshot)`,"google-antigravity":`Google Antigravity`,"github-copilot":`GitHub Copilot`,cursor:`Cursor`},pc=e=>fc[e]??e;function mc({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:pc(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,...Za(),..._||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:pc(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 Ft(a)??null:null;if(!o)continue;if(o.error){c(e=>({...e,[d]:o})),l(/cancel/i.test(o.error)?t(`prov.loginCancelled`,{provider:pc(d)}):t(`prov.loginError`,{provider:pc(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:pc(d),error:t(`prov.reauthAccountMissing`)}),!1),s(null),y=!0;break}if(e?.needsReauth){l(t(`prov.loginError`,{provider:pc(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:pc(d)}),!1):l(t(`prov.loginOk`,{provider:pc(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:pc(d)}),!1),s(null))}catch{g.current.get(d)===b&&l(t(`prov.loginRequestFail`,{provider:pc(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:pc(n)}),!1);return}await Promise.all([f([n]),d(),u(),p(!0)]),m(),l(t(`prov.logoutOk`,{provider:pc(n)}),!0)}catch{l(t(`prov.logoutFail`,{provider:pc(n)}),!1)}}}}async function hc(e,t){try{let t=await e.json();if(typeof t.error==`string`&&t.error.trim())return t.error.trim()}catch{}return t}function gc(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 _c({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(gc(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 hc(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 hc(i,t(`prov.updateFail`))};let a=await i.json().catch(()=>({}));if(await s(),Object.hasOwn(r,`codexAccountMode`)){let e=[l(!0)];u&&e.push(Promise.resolve(u())),await Promise.all(e)}let o=a.xaiResponsesOptInState;return{ok:!0,...o===!0||o===!1||o===`mixed`?{xaiResponsesOptInState:o}:{}}}catch{return{ok:!1,error:t(`prov.networkError`)}}},[e,s,l,u,t]);return{removeProvider:d,confirmRemoveProvider:f,setProviderDisabled:p,setDefaultProvider:(0,_.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(gc(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 vc({apiBase:e,t,setConfig:n,setOauthProviders:r,setOauthStatus:i,notify:a,invalidateProviderQuotas:o,configCacheKey:s}){return{fetchConfig:(0,_.useCallback)(async()=>{try{let t=await Pt(await fetch(`${e}/api/config`));n(t??null),s&&t&&gr(s,t)}catch{a(t(`prov.loadConfigFail`),!1)}},[e,s,a,n,t]),fetchOauth:(0,_.useCallback)(async()=>{try{let t=(await Pt(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 Ft(n)??{loggedIn:!1}:{loggedIn:!1}]}));i(Object.fromEntries(n))}catch{}},[e,r,i]),fetchProviderQuotas:(0,_.useCallback)(async(e=!1)=>{o(e)},[o])}}function yc({providerId:e,providerLabel:t,onCancel:n,onContinue:r}){let i=Q(),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=oc(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`:cc(p),v=h===`anthropic`||h===`google-antigravity`;return(0,J.jsxs)(`dialog`,{ref:s,"aria-labelledby":a,"aria-describedby":o,className:`modal-overlay`,onCancel:m,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":i(`common.close`),tabIndex:-1,onClick:n}),(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),style:{maxWidth:460},children:[(0,J.jsx)(`h3`,{id:a,children:i(sc(p),{provider:t})}),(0,J.jsxs)(`div`,{id:o,className:`notice-warn`,style:{marginTop:12,display:`flex`,gap:8,alignItems:`flex-start`},children:[(0,J.jsx)(_e,{width:16,height:16,style:{flexShrink:0,marginTop:2},"aria-hidden":`true`}),(0,J.jsx)(`p`,{className:`modal-desc`,style:{margin:0},children:i(g,{provider:t})})]}),v&&(0,J.jsx)(`p`,{className:`muted text-label`,style:{marginTop:12},children:i(`oauthTos.saferPath`)}),(0,J.jsxs)(`label`,{className:`oauth-tos-ack`,style:{display:`flex`,gap:8,alignItems:`flex-start`,marginTop:14},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked),style:{marginTop:3},"aria-required":`true`}),(0,J.jsx)(`span`,{className:`text-label`,children:i(`oauthTos.acknowledge`)})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,children:i(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!l||d,onClick:()=>{!l||c.current||(c.current=!0,f(!0),r())},children:i(`oauthTos.continue`)})]})]})]})}function bc(e){return{adapter:e.adapter,baseUrl:e.baseUrl,authMode:e.auth,freeTier:!!e.freeTier,keyOptional:!!e.keyOptional}}function xc(e){return ai(e.id,bc(e))}function Sc(e){let t={accounts:[],free:[],paid:[]};for(let n of e)t[xc(n)].push(n);return t}function Cc(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.toLowerCase().includes(n)):e}function wc(e,t,n){return!n||e.kind!==`oauth`||t!==e.id?!1:n.provider===e.id}var Tc={},Ec=[],Dc={};function Oc({presets:e,usageRank:t=Tc,presetsLoading:n=!1,initialTier:r=`free`,onSelectPreset:i,onSelectCustom:a,accountRows:o=Ec,accountStatus:s=Dc,busyProvider:c=null,loginHint:l=null,paste:u,onLogin:d,onCancelLogin:f,onLogout:p,onManage:m}){let h=Q(),[g,v]=(0,_.useState)(r),[y,b]=(0,_.useState)(``),x=(0,_.useMemo)(()=>e.filter(e=>e.id!==`custom`),[e]),S=(0,_.useMemo)(()=>{let e=Object.keys(t).length>0;return x.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)})},[x,t]),C=(0,_.useMemo)(()=>Sc(S),[S])[g],w=(0,_.useMemo)(()=>Cc(C,y),[C,y]),T=e=>{let t=e.codexAccountMode===`direct`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:h(`modal.badge.direct`)}):e.codexAccountMode===`pool`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:h(`modal.badge.pool`)}):e.auth===`oauth`?(0,J.jsx)(`span`,{className:`badge badge-accent`,children:h(`modal.badge.oauth`)}):e.auth===`forward`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:h(`modal.badge.codexLogin`)}):e.auth===`local`?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:h(`modal.badge.local`)}):e.keyOptional?null:(0,J.jsx)(`span`,{className:`badge badge-muted`,children:h(`modal.badge.apiKey`)}),n=(e.freeTier||e.keyOptional)&&e.auth===`key`?(0,J.jsx)(`span`,{className:`badge badge-green`,children:h(`modal.badge.free`)}):null;return(0,J.jsxs)(J.Fragment,{children:[n,t]})};return(0,J.jsxs)(`div`,{className:`provider-catalog`,children:[(0,J.jsx)(`div`,{className:`provider-catalog-tabs`,role:`tablist`,children:[`accounts`,`free`,`paid`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":g===e,className:`provider-catalog-tab${g===e?` active`:``}`,onClick:()=>{v(e),b(``)},children:h(e===`accounts`?`modal.tab.accounts`:e===`free`?`modal.tab.free`:`modal.tab.paid`)},e))}),g===`accounts`&&(0,J.jsx)(`div`,{className:`provider-catalog-accounts-hint muted text-label`,children:h(`modal.accountsHint`)}),(0,J.jsx)(`input`,{className:`input provider-catalog-search`,value:y,onChange:e=>b(e.target.value),placeholder:h(`modal.search`)}),(0,J.jsxs)(`div`,{className:`provider-catalog-rows`,children:[n&&w.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:h(`modal.catalogLoading`)}),g!==`accounts`&&w.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`list-row`,onClick:()=>i(e),children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsxs)(`div`,{className:`sub`,children:[(0,J.jsx)(`code`,{className:`chip`,children:e.adapter}),e.note?` · ${e.note}`:``]})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:T(e)})]},e.id)),g!==`accounts`&&!n&&w.length===0&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:h(`modal.noMatch`)}),g===`accounts`&&o.map(e=>{let t=s[e.id],n=c===e.id,r=!!t?.loggedIn,i=r?t?.email??e.statusLabel??h(`modal.accountLoggedIn`):t?.error??e.statusLabel??h(`modal.accountLoggedOut`),a=wc(e,c,l);return(0,J.jsxs)(`div`,{className:`list-row provider-catalog-account-row${a?` provider-catalog-account-row--waiting`:``}`,children:[(0,J.jsxs)(`div`,{className:`provider-catalog-account-row-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`title`,children:e.label}),(0,J.jsx)(`div`,{className:`sub`,children:i})]}),(0,J.jsx)(`div`,{className:`provider-catalog-badges`,children:e.kind===`key`?null:e.kind===`codex`?(0,J.jsxs)(J.Fragment,{children:[r&&(0,J.jsx)(`a`,{className:`btn btn-ghost`,href:e.href??`#codex-set`,children:h(`modal.accountManage`)}),d&&(0,J.jsx)(`button`,{type:`button`,className:r?`btn btn-ghost`:`btn btn-primary`,disabled:n,onClick:()=>{n||d(e.id)},children:h(n?`codexAuth.enablingOpenai`:r?`modal.accountAdd`:`modal.accountLogin`)})]}):r?(0,J.jsxs)(J.Fragment,{children:[m&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>m(e.id),children:h(`modal.accountManage`)}),d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:n,onClick:()=>{n||d(e.id,!0)},children:h(n?`prov.waitingBrowser`:`modal.accountAdd`)}),n&&f&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>f(e.id),children:h(`common.cancel`)}),p&&!n&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>p(e.id),children:h(`modal.accountLogout`)})]}):n?f&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>f(e.id),children:h(`common.cancel`)}):d&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>d(e.id),children:h(`modal.accountLogin`)})})]}),a&&l&&(0,J.jsx)(qa,{hint:{url:l.url,deviceCode:l.deviceCode,instructions:l.instructions},...u?{paste:{value:u.value,busy:u.busy,message:u.message,ok:u.ok,onChange:u.onChange,onSubmit:()=>u.onSubmit(e.id)}}:{}})]},e.id)}),g===`accounts`&&o.length===0&&!n&&(0,J.jsx)(`div`,{className:`muted text-control provider-catalog-empty`,children:h(`modal.noMatch`)})]}),(0,J.jsxs)(`div`,{className:`provider-catalog-footer`,children:[(0,J.jsx)(`div`,{style:{flex:1}}),g!==`accounts`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:a,children:h(`modal.notListed`)})]})]})}function kc({preset:e,oauthSupported:t,oauthBusy:n,oauthMsg:r,oauthMsgTone:i,oauthUrl:a,oauthDeviceCode:o,oauthInstructions:s,manualCode:c,manualCodeBusy:l,manualCodeMsg:u,manualCodeOk:d,onRequestLogin:f,onUseApiKeyInstead:p,onManualCodeChange:m,onSubmitManualCode:h,onBack:g}){let _=Q();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:14},children:[(0,J.jsx)(`div`,{className:`muted text-control`,children:e.note??_(`modal.oauthDefaultNote`)}),t.includes(e.oauthProvider??``)?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>f(e.oauthProvider),disabled:n,style:{width:`100%`,padding:`12px 16px`},children:[(0,J.jsx)(De,{}),n?_(`modal.waitingBrowser`):_(`modal.logInWith`,{label:e.label})]}),!n&&(0,J.jsx)(bs,{})]}):(0,J.jsx)(`div`,{className:`text-control`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:_(`modal.oauthComingSoon`,{label:e.label})}),r&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:i===`warn`?`var(--amber)`:`var(--accent-hover)`},children:r}),n&&(0,J.jsx)(qa,{hint:{url:a,deviceCode:o,instructions:s},paste:{value:c,busy:l,disabled:!e.oauthProvider,message:u,ok:d,onChange:m,onSubmit:()=>{e.oauthProvider&&h(e.oauthProvider)}}}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:2},children:[(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:_(`modal.useApiKeyInstead`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:g,children:_(`modal.back`)})]})]})}function Ac({label:e,children:t}){return(0,J.jsxs)(`label`,{style:{display:`block`},children:[(0,J.jsx)(`span`,{className:`field-label`,children:e}),t]})}function jc({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=Q();return(0,J.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:10},children:[!c&&!o&&!s&&!e.keyOptional&&e.note&&(0,J.jsxs)(`details`,{className:`setup-guide`,children:[(0,J.jsx)(`summary`,{children:h(`modal.setupGuide`)}),(0,J.jsxs)(`ol`,{className:`text-label leading-relaxed`,style:{margin:`8px 0 0`,paddingLeft:18,color:`var(--muted)`},children:[(0,J.jsxs)(`li`,{children:[h(`modal.setupStep1Prefix`),` `,(0,J.jsx)(`a`,{href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,children:h(`modal.setupDashboardLink`,{label:e.label})}),` `,h(`modal.setupStep1Suffix`)]}),(0,J.jsx)(`li`,{children:h(`modal.setupStep2`)}),(0,J.jsx)(`li`,{children:h(`modal.setupStep3`)})]}),e.note&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--muted)`,marginTop:6,fontStyle:`italic`},children:e.note}),/\{[^}]*\}/.test(t.baseUrl)&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`,marginTop:6},children:h(`modal.baseUrlPlaceholderHint`)})]}),(0,J.jsx)(Ac,{label:h(`modal.providerName`),children:(0,J.jsx)(`input`,{className:`input`,value:t.name,readOnly:c,onChange:e=>u({...t,name:e.target.value}),placeholder:h(`modal.namePlaceholder`)})}),a&&(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--amber)`},children:h(`modal.duplicateWarn`,{name:t.name.trim()})}),!c&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Ac,{label:h(`modal.adapter`),children:(0,J.jsx)(`select`,{className:`input`,value:t.adapter,onChange:e=>u({...t,adapter:e.target.value}),children:[`openai-responses`,`openai-chat`,`anthropic`,`google`,`azure-openai`,`cursor`].map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))})}),e.baseUrlChoices&&e.baseUrlChoices.length>0?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Ac,{label:h(`modal.endpoint`),children:(0,J.jsx)(`select`,{className:`input`,value:n,onChange:n=>{let r=n.target.value;d(r),u({...t,baseUrl:Ns(e.baseUrlChoices,r,t.baseUrl)})},children:e.baseUrlChoices.map(e=>(0,J.jsx)(`option`,{value:e.id,children:e.id===`token-plan`?h(`modal.endpoint.tokenPlan`):e.id===`payg`?h(`modal.endpoint.payAsYouGo`):e.id===`custom`?h(`modal.endpoint.custom`):e.label},e.id))})}),n===`custom`&&(0,J.jsx)(Ac,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})})]}):(0,J.jsx)(Ac,{label:h(`modal.baseUrl`),children:(0,J.jsx)(`input`,{className:`input`,value:t.baseUrl,onChange:e=>u({...t,baseUrl:e.target.value}),placeholder:h(`modal.baseUrlPlaceholder`)})}),!c&&(0,J.jsxs)(`label`,{className:`modal-field`,style:{flexDirection:`row`,alignItems:`center`,gap:8},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:t?.allowPrivateNetwork??!1,onChange:e=>u({...t,allowPrivateNetwork:e.target.checked})}),(0,J.jsx)(`span`,{className:`muted text-control`,children:h(`modal.allowPrivateNetwork`)})]}),!c&&(t?.allowPrivateNetwork??!1)&&(0,J.jsx)(`p`,{className:`muted text-hint`,children:h(`modal.allowPrivateNetworkHint`)})]}),t.authMode===`forward`?(0,J.jsx)(`div`,{className:`text-label`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:l(e)}):t.authMode===`local`?(0,J.jsx)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--amber)`,background:`var(--amber-soft)`,border:`1px solid var(--amber)`,borderRadius:`var(--radius-sm)`,padding:`8px 10px`},children:h(`modal.localHint`)}):e.keyOptional?(0,J.jsxs)(`div`,{className:`text-label leading-relaxed`,style:{color:`var(--green)`,background:`var(--green-soft)`,border:`1px solid var(--green)`,borderRadius:`var(--radius-sm)`,padding:`10px 12px`},children:[(0,J.jsx)(`strong`,{children:h(`modal.freeTierTitle`)}),` — `,e.note??h(`modal.freeTierDefault`)]}):(0,J.jsxs)(J.Fragment,{children:[e.dashboardUrl&&(0,J.jsxs)(`a`,{className:`text-label`,href:e.dashboardUrl,target:`_blank`,rel:`noreferrer`,style:{display:`inline-flex`,alignItems:`center`,gap:5},children:[(0,J.jsx)(Ee,{style:{width:14,height:14}}),h(`modal.getApiKey`,{label:e.label}),(0,J.jsx)(Te,{style:{width:13,height:13}})]}),(0,J.jsx)(Ac,{label:h(`modal.apiKey`),children:(0,J.jsx)(`input`,{className:`input`,type:`password`,value:t.apiKey,onChange:e=>u({...t,apiKey:e.target.value}),placeholder:h(`modal.apiKeyPlaceholder`)})}),t.adapter===`anthropic`&&t.authMode===`key`&&(0,J.jsx)(Ac,{label:h(`modal.apiKeyTransport`),children:(0,J.jsxs)(`select`,{className:`input`,value:t.apiKeyTransport??`x-api-key`,onChange:e=>u({...t,apiKeyTransport:e.target.value===`bearer`?`bearer`:void 0}),children:[(0,J.jsx)(`option`,{value:`x-api-key`,children:h(`modal.apiKeyTransportNative`)}),(0,J.jsx)(`option`,{value:`bearer`,children:h(`modal.apiKeyTransportBearer`)})]})})]}),!c&&(0,J.jsx)(Ac,{label:h(`modal.defaultModel`),children:(0,J.jsx)(`input`,{className:`input`,value:t.defaultModel,onChange:e=>u({...t,defaultModel:e.target.value}),placeholder:h(`modal.defaultModelPlaceholder`)})}),r&&(0,J.jsx)(`div`,{className:`text-control`,role:`alert`,style:{color:`var(--red)`},children:r}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,marginTop:4,alignItems:`center`},children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:f,disabled:i,children:h(i?`modal.adding`:`modal.add`)}),e.auth===`oauth`&&(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:p,children:h(`modal.useOauthLogin`)}),(0,J.jsx)(`div`,{style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:m,children:h(`modal.back`)})]})]})}var Mc=2e3;function Nc({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,...Za()})});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();l(o.url??``,i,o.deviceCode,o.instructions),o.url||o.deviceCode?s(t(`modal.waitingLogin`)):s(o.instructions||t(`modal.loggingIn`));for(let a=0;a<100;a++){if(await new Promise(e=>setTimeout(e,Mc)),!n.current)return;let a=await fetch(`${e}/api/oauth/status?provider=${i}`).catch(()=>null),o=a?await Ft(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 Pc(e,t){return{preset:e?{id:`custom`,label:t,adapter:`openai-chat`,baseUrl:``,auth:`key`}:null,form:e?{name:``,adapter:`openai-chat`,baseUrl:``,authMode:`key`,apiKey:``,apiKeyTransport:void 0,defaultModel:``,allowPrivateNetwork:!1}:null,saving:!1,error:``,oauthBusy:!1,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,manualCode:``,manualCodeBusy:!1,manualCodeMsg:``,manualCodeOk:!0,endpointChoice:`custom`,oauthTosPending:null}}function Fc(e,t){switch(t.type){case`choose-preset`:return{...e,preset:t.preset,form:t.form,endpointChoice:t.endpointChoice,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`back`:return{...e,preset:null,form:null,endpointChoice:`custom`,error:``,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``,manualCodeOk:!0};case`set-form`:return{...e,form:t.form};case`set-endpoint-choice`:return{...e,endpointChoice:t.choice};case`set-saving`:return{...e,saving:t.saving};case`set-error`:return{...e,error:t.error};case`set-oauth-busy`:return{...e,oauthBusy:t.busy};case`set-oauth-msg`:return{...e,oauthMsg:t.msg,oauthMsgTone:t.tone??e.oauthMsgTone};case`set-oauth-tone`:return{...e,oauthMsgTone:t.tone};case`set-oauth-url`:return e.preset?.oauthProvider===t.providerId?{...e,oauthUrl:t.url,oauthDeviceCode:t.deviceCode??``,oauthInstructions:t.instructions??``,oauthUrlProvider:t.providerId}:e;case`set-manual-code`:return{...e,manualCode:t.code};case`set-manual-code-busy`:return{...e,manualCodeBusy:t.busy};case`set-manual-code-msg`:return{...e,manualCodeMsg:t.msg,manualCodeOk:t.ok??e.manualCodeOk};case`set-oauth-tos-pending`:return{...e,oauthTosPending:t.providerId};case`use-oauth-login`:return{...e,form:t.form,error:``,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null};case`use-api-key-instead`:return{...e,form:t.form,oauthMsg:``,oauthMsgTone:`ok`,oauthUrl:``,oauthDeviceCode:``,oauthInstructions:``,oauthUrlProvider:null,oauthBusy:!1,manualCode:``,manualCodeMsg:``};default:return e}}function Ic({apiBase:e,existingNames:t,onClose:n,onAdded:r,initialTier:i,initialCustom:a=!1,accountRows:o,accountStatus:s,accountBusy:c,accountLoginHint:l=null,onAccountLogin:u,onAccountCancelLogin:d,onAccountLogout:f,onAccountManage:p,onOpen:m}){let h=Q(),g=(0,_.useMemo)(()=>[{id:`custom`,label:h(`modal.customProvider`),adapter:`openai-chat`,baseUrl:``,auth:`key`}],[h]),[v,y]=(0,_.useReducer)(Fc,a,e=>Pc(e,h(`modal.customProvider`))),b=(0,_.useRef)(!0),x=(0,_.useRef)(null),S=(0,_.useRef)(null),C=G(`add-provider-oauth:${e}`,[e],async t=>{let n=await fetch(`${e}/api/oauth/providers`,{signal:t});return n.ok?(await n.json()).providers??[]:[]}),w=G(`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}),T=G(Ir(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()},{deadlineMs:6e4}),E=C.data??[],D=w.data??g,O=w.loading,k=Object.fromEntries((T.data?.providers??[]).map(e=>[e.provider,e.requests])),{preset:A,form:j,saving:M,error:N,oauthBusy:P,oauthMsg:F,oauthMsgTone:I,oauthUrl:L,oauthUrlProvider:R,oauthDeviceCode:z,oauthInstructions:B,manualCode:V,manualCodeBusy:H,manualCodeMsg:U,manualCodeOk:W,endpointChoice:ee,oauthTosPending:K}=v;(0,_.useEffect)(()=>{b.current=!0,x.current=document.activeElement,m?.();let e=S.current;if(e){let t=e.querySelector(`input:not([disabled]), button:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`);t&&t.focus()}return()=>{b.current=!1,x.current?.focus()}},[]),(0,_.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!K&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n,K]);let q=e=>{let t=Vs(e);return t?h(t):e.note},Y=e=>{let t=Ps(e.baseUrlChoices,e.baseUrl);y({type:`choose-preset`,preset:e,endpointChoice:t,form:{name:e.id===`custom`?``:e.id,adapter:e.adapter,baseUrl:e.baseUrlChoices?.length?Ns(e.baseUrlChoices,t,e.baseUrl):e.baseUrl,responsesPath:e.responsesPath,authMode:e.auth,apiKey:``,apiKeyTransport:void 0,defaultModel:e.defaultModel??``,allowPrivateNetwork:!1}})},te=async()=>{if(!j)return;let t=A?Bs(A):!1,n=A?.baseUrlChoices?.length?Fs(A.baseUrlChoices,ee,j.baseUrl):j.baseUrl.trim();if(!t&&!j.name.trim()){y({type:`set-error`,error:h(`modal.nameRequired`)});return}if(!t&&!n){y({type:`set-error`,error:h(`modal.baseUrlRequired`)});return}if(!t&&/\{[^}]*\}/.test(n)){y({type:`set-error`,error:h(`modal.baseUrlPlaceholderError`)});return}let i={...j,baseUrl:n},a;try{a=Us(A??{id:`custom`},i)}catch{y({type:`set-error`,error:h(`modal.invalidPreset`)});return}y({type:`set-saving`,saving:!0}),y({type:`set-error`,error:``});try{let t=await fetch(`${e}/api/providers`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a)});if(!t.ok){let e=await t.json().catch(()=>({}));y({type:`set-error`,error:e.error||h(`modal.failedStatus`,{status:t.status})});return}r(a.name)}catch{y({type:`set-error`,error:h(`modal.networkError`)})}finally{y({type:`set-saving`,saving:!1})}},{loginOAuth:ne,submitManualCode:re}=Nc({apiBase:e,t:h,aliveRef:b,onAdded:r}),ie={setOauthBusy:e=>y({type:`set-oauth-busy`,busy:e}),setOauthMsg:e=>y({type:`set-oauth-msg`,msg:e}),setOauthMsgTone:e=>y({type:`set-oauth-tone`,tone:e}),setOauthUrl:(e,t,n,r)=>y({type:`set-oauth-url`,url:e,providerId:t,deviceCode:n,instructions:r}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:U,ok:e})},ae=j?t.includes(j.name.trim())&&j.name.trim()!==``:!1,oe=e=>{if(!P){if(oc(e)){y({type:`set-oauth-tos-pending`,providerId:e});return}ne(e,ie)}},X=e=>{re(e,V,H,{setManualCodeBusy:e=>y({type:`set-manual-code-busy`,busy:e}),setManualCode:e=>y({type:`set-manual-code`,code:e}),setManualCodeOk:e=>y({type:`set-manual-code-msg`,msg:U,ok:e}),setManualCodeMsg:e=>y({type:`set-manual-code-msg`,msg:e})})},se=A?.id===`custom`,ce=j?.authMode===`local`,le=A?Bs(A):!1;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{role:`dialog`,"aria-modal":`true`,"aria-label":h(`modal.add`),className:`modal-overlay`,children:(0,J.jsxs)(`div`,{ref:S,className:`modal-card`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:A?h(`modal.addNamed`,{label:A.label}):h(`modal.add`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon`,"aria-label":h(`common.close`),onClick:n,children:(0,J.jsx)(ue,{})})]}),A?j&&(A.auth===`oauth`&&j.authMode===`oauth`?(0,J.jsx)(kc,{preset:A,oauthSupported:E,oauthBusy:P,oauthMsg:F,oauthMsgTone:I,oauthUrl:R===A.oauthProvider?L:``,oauthDeviceCode:R===A.oauthProvider?z:``,oauthInstructions:R===A.oauthProvider?B:``,manualCode:V,manualCodeBusy:H,manualCodeMsg:U,manualCodeOk:W,onRequestLogin:oe,onUseApiKeyInstead:()=>{y({type:`use-api-key-instead`,form:{...j,authMode:`key`}})},onManualCodeChange:e=>y({type:`set-manual-code`,code:e}),onSubmitManualCode:e=>{X(e)},onBack:()=>y({type:`back`})}):(0,J.jsx)(jc,{preset:A,form:j,endpointChoice:ee,error:N,saving:M,dup:ae,isCustom:se,isLocal:ce,isReservedForward:le,presetDescription:q,onFormChange:e=>y({type:`set-form`,form:e}),onEndpointChoiceChange:e=>y({type:`set-endpoint-choice`,choice:e}),onSubmit:()=>{te()},onUseOauthLogin:()=>y({type:`use-oauth-login`,form:{...j,authMode:`oauth`}}),onBack:()=>y({type:`back`})})):(0,J.jsx)(Oc,{presets:D,usageRank:k,presetsLoading:O,initialTier:i,onSelectPreset:e=>Y(e),onSelectCustom:()=>Y(g[0]),accountRows:o,accountStatus:s,busyProvider:c,onLogin:u,onCancelLogin:d,onLogout:f,onManage:p,loginHint:l,paste:{value:V,busy:H,message:U,ok:W,onChange:e=>y({type:`set-manual-code`,code:e}),onSubmit:e=>{X(e)}}})]})}),K&&(0,J.jsx)(yc,{providerId:K,providerLabel:A?.label??K,onCancel:()=>y({type:`set-oauth-tos-pending`,providerId:null}),onContinue:()=>{let e=K;e&&(y({type:`set-oauth-tos-pending`,providerId:null}),ne(e,ie))}},K)]})}function Lc({apiBase:e,config:t,adding:n,addIntent:r,busy:i,addModalAccountRows:a,accountLoginStatus:o,accountLoginHint:s,removeConfirmName:c,removeDefaultProvider:l,codexLoginOpen:u,jsonLeaveOpen:d,jsonSaving:f,oauthTosPending:p,onCloseAdd:m,onAdded:h,onAccountLogin:g,onAccountCancelLogin:_,onAccountLogout:v,onAccountManage:y,onOpenAdd:b,onCloseCodexLogin:x,onCodexAdded:S,onCancelRemove:C,onConfirmRemove:w,onCancelJsonLeave:T,onDiscardJson:E,onSaveJson:D,onCancelOauthTos:O,onContinueOauthTos:k}){return(0,J.jsxs)(J.Fragment,{children:[n&&(0,J.jsx)(Ic,{apiBase:e,existingNames:Object.keys(t.providers),initialTier:r?.tier,initialCustom:r?.custom,onClose:m,onAdded:h,accountRows:a,accountStatus:o,accountBusy:i,accountLoginHint:s??null,onAccountLogin:g,onAccountCancelLogin:_,onAccountLogout:v,onAccountManage:y,onOpen:b}),u&&(0,J.jsx)(to,{apiBase:e,onClose:x,onAdded:S}),c&&(0,J.jsx)(tc,{providerName:c,defaultProviderName:l,onCancel:C,onConfirm:w}),d&&T&&E&&D&&(0,J.jsx)(nc,{saving:f??!1,onCancel:T,onDiscard:E,onSave:D}),p&&(0,J.jsx)(yc,{providerId:p.provider,providerLabel:pc(p.provider),onCancel:O,onContinue:k},`${p.provider}:${p.addAccount?`add`:`login`}`)]})}function Rc(e,t,n){return[...Rs(e.providers).map(e=>({id:e,label:Dn(e,n),kind:`codex`,href:`#codex-set`})),...t.toSorted((e,t)=>e.localeCompare(t)).map(e=>({id:e,label:pc(e),kind:`oauth`}))]}function zc(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 Bc({apiBase:e}){let t=Q(),n=`ocx.providers.config.v1:${e}`,[r,i]=(0,_.useState)(()=>fr(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),[I,L]=(0,_.useState)({token:0,provider:null}),R=(0,_.useRef)(!0),z=(0,_.useRef)(null),B=(0,_.useRef)(!1),V=(0,_.useCallback)((e,t=!0)=>{c(e),u(t),f(t?`ok`:`err`),m(e=>e+1)},[]),H=(0,_.useCallback)(()=>{c(``),u(!1),f(`err`)},[]),U=(0,_.useCallback)(e=>{if(e.catalogRefreshPending){c(t(`codexAuth.catalogRefreshPending`)),u(!1),f(`warn`),m(e=>e+1);return}V(t(`codexAuth.accountAdded`),!0)},[V,t]);(0,_.useEffect)(()=>(R.current=!0,()=>{R.current=!1}),[]),(0,_.useEffect)(()=>{if(!s||!l)return;let e=window.setTimeout(H,4500);return()=>window.clearTimeout(e)},[s,l,p,H]);let W=(0,_.useCallback)(e=>{o(!1),D(null),T(e),L(t=>({token:t.token+1,provider:e}))},[]);G(`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}),G(Ir(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()},{deadlineMs:6e4});let[ee,K]=(0,_.useState)({epoch:0,force:!1}),{fetchConfig:q,fetchOauth:Y,fetchProviderQuotas:te}=vc({apiBase:e,t,setConfig:i,setOauthProviders:g,setOauthStatus:y,notify:V,invalidateProviderQuotas:(0,_.useCallback)((e=!1)=>{K(t=>({epoch:t.epoch+1,force:e}))},[]),configCacheKey:n}),ne=bo(e),re=ne.activeNeedsReauth,ie=(0,_.useMemo)(()=>{let e=ne.accounts;if(e.length===0&&ne.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}:{},...re?{needsReauth:!0}:{}}}},[v,ne.accounts,ne.loadState,re]),{accountSets:ae,setAccountSets:oe,accountLoadStates:X,switchingAccount:se,keyPools:ce,fetchAccountSets:le,switchAccount:ue,switchApiKey:fe,removeApiKey:pe,addApiKeyValue:me,editCredentialAlias:he,removeAccount:ge,activeAccountNeedsReauth:_e}=uc({apiBase:e,t,config:r,oauthStatus:ie,aliveRef:R,notify:V,fetchConfig:q,fetchOauth:Y,fetchProviderQuotas:te,codexActiveNeedsReauth:re}),{draft:ve,setDraft:ye,jsonEditorOpen:be,jsonSaving:xe,jsonLeaveOpen:Z,saveConfig:Se,openJsonEditor:Ce,discardJsonEditor:we,requestCloseJsonEditor:Te,restoreJsonEditor:Ee,jsonIsDirty:De,setJsonLeaveOpen:Oe}=dc({apiBase:e,config:r,notify:V,fetchConfig:q,fetchProviderQuotas:te,onSaved:()=>N(e=>e+1),t});(0,_.useEffect)(()=>{z.current!==e&&(z.current=e,Promise.resolve().then(()=>{q(),Y()}))},[e,q,Y]);let ke=()=>N(e=>e+1),{cancelLoginOAuth:Ae,loginOAuth:je,logoutOAuth:Me}=mc({apiBase:e,t,aliveRef:R,accountSets:ae,setAccountSets:oe,setBusy:x,setStatus:c,setLoginInfo:C,setOauthStatus:y,notify:V,fetchConfig:q,fetchOauth:Y,fetchAccountSets:le,fetchProviderQuotas:te,bumpModelsRefresh:ke,onLoginSettled:W}),{removeProvider:Ne,confirmRemoveProvider:Pe,setProviderDisabled:Fe,setDefaultProvider:Ie,updateProvider:Le}=_c({apiBase:e,t,removeBusyRef:B,workspaceSelected:w,setWorkspaceSelected:T,setRemoveConfirmName:k,notify:V,fetchConfig:q,fetchOauth:Y,fetchProviderQuotas:te,refreshCodexAccount:()=>ne.load(!0)}),Re=(e,t=!1)=>{if(b!==e){if(oc(e)){F({provider:e,addAccount:t});return}je(e,t)}};if(!r)return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.providers`)})}),s?(0,J.jsx)(Et,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}):(0,J.jsxs)(`div`,{className:`providers-workspace providers-workspace--boot`,"aria-busy":`true`,children:[(0,J.jsx)(`div`,{className:`providers-workspace-rail providers-workspace-rail--boot`,"aria-hidden":`true`}),(0,J.jsx)(`div`,{className:`providers-workspace-main`,children:(0,J.jsxs)(`p`,{className:`muted`,children:[(0,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),` `,t(`prov.loadingConfig`)]})})]})]});let ze=Rc(r,h,t),Be=zc(r,ie),Ve=e=>r.providers[e]?.authMode===`forward`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.providers`)}),(0,J.jsx)(`div`,{className:`row`,children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>o(!0),children:[(0,J.jsx)(de,{}),t(`prov.add`)]})})]}),s&&(0,J.jsx)(Et,{tone:d,onDismiss:H,dismissLabel:t(`common.close`),children:s}),(0,J.jsx)(_a,{onRemoveProvider:Ne,providers:r.providers,apiBase:e,defaultProvider:r.defaultProvider,selectedName:w,onSelect:T,onAddProvider:e=>{D(e??null),o(!0)},onEditConfig:Ce,jsonEditor:{open:be,draft:ve,isDirty:De,onDraftChange:ye,onSave:()=>Se(),onClose:Te,onRestore:Ee},jsonSaving:xe,modelsRefreshToken:M,activeAccountNeedsReauth:_e,quotaRefreshEpoch:ee.epoch,quotaForceRefresh:ee.force,detail:(t,n)=>{let i=Be[t.name]??v[t.name];return(0,J.jsx)(rc,{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:ae[t.name]?.accounts??[],keys:ce[t.name]??[],accountLoadState:X[t.name]??(t.authMode===`oauth`?`idle`:`ready`),accountsFocusToken:I.token,accountsFocusProvider:I.provider,switchingAccountId:se?.provider===t.name?se.accountId:null,busyProvider:b,loginHint:S,authHandlers:{onLogin:Re,onCancelLogin:Ae,onLogout:Me,onReauth:(e,t)=>je(e,!0,t),onSwitchAccount:ue,onRemoveAccount:ge,onRetryAccounts:async e=>{await le([e])},onAddApiKey:me,onSwitchApiKey:fe,onRemoveApiKey:pe,onEditAlias:he},isDefault:t.name===r.defaultProvider,onRemoveProvider:Ne,onSetDisabled:Fe,onSetDefault:e=>{Ie(e)},onUpdateProvider:Le,codexController:ne},t.name)}}),(0,J.jsx)(Lc,{apiBase:e,config:r,adding:a,addIntent:E,busy:b,addModalAccountRows:ze,accountLoginStatus:Be,accountLoginHint:S,removeConfirmName:O,removeDefaultProvider:O===r.defaultProvider?Object.entries(r.providers).find(([e,t])=>e!==O&&t.disabled!==!0)?.[0]??null:null,codexLoginOpen:A,jsonLeaveOpen:Z,jsonSaving:xe,oauthTosPending:P,onCloseAdd:()=>{b&&Ae(b),o(!1),D(null)},onAdded:e=>{o(!1),D(null),V(t(`prov.added`,{name:e,cmd:`ocx sync`}),!0),q(),Y(),te(!0),ke()},onAccountLogin:async(n,i=!1)=>{if(n===`openai`){if(b===`openai`)return;let n=r.providers.openai,i=zs(n);if(i===`invalid`){V(t(`codexAuth.openaiMissing`),!1);return}if(i===`absent`||i===`disabled`){x(`openai`);try{await Ks(e,i),await q()}catch(e){e instanceof Gs?V(t(e.i18nKey),!1):V(e instanceof Error?e.message:t(`prov.saveFailed`),!1);return}finally{R.current&&x(e=>e===`openai`?null:e)}}j(!0);return}if(Ve(n)){j(!0);return}(r.providers[n]?.authMode===`oauth`||h.includes(n))&&Re(n,i)},onAccountCancelLogin:e=>{Ae(e)},onAccountLogout:e=>{Me(e)},onAccountManage:e=>{W(e)},onOpenAdd:Y,onCloseCodexLogin:()=>j(!1),onCodexAdded:e=>{j(!1),U(e),q(),Y(),te(!0),ke()},onCancelRemove:()=>k(null),onConfirmRemove:()=>{Pe(O)},onCancelJsonLeave:()=>{xe||Oe(!1)},onDiscardJson:we,onSaveJson:()=>{Se()},onCancelOauthTos:()=>F(null),onContinueOauthTos:()=>{let e=P;e&&(F(null),je(e.provider,e.addAccount))}})]})}function Vc(e){let{t}=ct();return e.state===`stale`?(0,J.jsxs)(`div`,{className:`codex-stale-banner`,role:`status`,children:[(0,J.jsx)(`span`,{className:`codex-stale-banner-text`,children:t(`models.staleBanner`)}),(0,J.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 Hc=[`fresh`,`stale`,`not_running`,`unknown`],Uc=[`stopped`,`nothing_running`,`enumeration_unavailable`,`partially_stopped`];function Wc(e){return Array.isArray(e)&&e.every(e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0)}function Gc(e){if(typeof e!=`object`||!e)return!1;let t=e;if(!(typeof t.success==`boolean`&&typeof t.synced==`boolean`&&typeof t.stateBefore==`string`&&Hc.includes(t.stateBefore)&&typeof t.code==`string`&&Uc.includes(t.code)&&Wc(t.requested)&&Wc(t.stopped)&&Wc(t.surviving)&&Wc(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 Kc(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.state==`string`&&Hc.includes(t.state)&&typeof t.runningCount==`number`&&Number.isSafeInteger(t.runningCount)&&t.runningCount>=0}var qc={state:null,runningCount:0};async function Jc(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 qc;let i=await r.json().catch(()=>null);return Kc(i)?{state:i.state,runningCount:i.runningCount}:qc}catch{return qc}}var Yc=3e4;function Xc(e){return(e instanceof DOMException||e instanceof Error)&&(e.name===`AbortError`||e.name===`TimeoutError`)}async function Zc(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=Yc,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:Xc(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:Xc(e)?s():o()}}return Gc(l)?{ok:!0,result:l}:{ok:!1,message:o()}}function Qc(e){return e===`stopped`||e===`nothing_running`}function $c(e,t={}){let{t:n}=ct(),[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 Zc(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&&Qc(r.code)&&o.current?.(r.code),r.code},[e,n])}}var el={"gpt-5.6-sol":Ae,"gpt-5.6-terra":Ne,"gpt-5.6-luna":je,"gpt-daybreak-blue-latest":Ae,"daybreak-blue-latest":Ae,"daybreak-red-latest":De},tl={width:14,height:14,flexShrink:0,verticalAlign:`text-bottom`};function nl(e){return e.slice(e.lastIndexOf(`/`)+1)}function rl(e){return el[e]??el[nl(e)]??null}function il(e){let t=rl(e);return t?(0,_.createElement)(`span`,{className:`model-label`},(0,_.createElement)(t,{style:tl,"aria-hidden":!0}),e):e}function al(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 ol(e,t,n,r){let{isEmpty:i,sessionCacheKey:a,...o}=r,s=(0,_.useMemo)(()=>a?mr(a):null,[a]),c=G(e,t,(0,_.useCallback)(async e=>{let t=await n(e);return a&&hr(a,t),t},[n,a]),{...o,...a?{initialData:o.initialData??s?.data,initialDataCachedAt:o.initialDataCachedAt??s?.cachedAt??null}:{}});return{...c,state:al(c,i,r.enabled!==!1)}}function sl({className:e,style:t}){return(0,J.jsx)(`span`,{"aria-hidden":`true`,className:e?`data-surface-skeleton__block ${e}`:`data-surface-skeleton__block`,style:t})}function cl({label:e,rows:t=3,className:n}){let r=Math.max(1,Math.floor(t));return(0,J.jsxs)(`div`,{className:n?`data-surface-skeleton ${n}`:`data-surface-skeleton`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,"aria-busy":`true`,children:[(0,J.jsx)(`span`,{className:`sr-only`,children:e}),Array.from({length:r},(e,t)=>(0,J.jsx)(`div`,{className:`data-surface-skeleton__row`,"aria-hidden":`true`,children:(0,J.jsx)(sl,{})},t))]})}function ll({children:e,busy:t=!0,live:n=!0,className:r}){return(0,J.jsxs)(`div`,{className:r?`data-surface-status ${r}`:`data-surface-status`,role:n?`status`:void 0,"aria-live":n?`polite`:void 0,"aria-atomic":n?`true`:void 0,"aria-busy":t||void 0,children:[t&&(0,J.jsx)(`span`,{className:`spin`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:e})]})}var ul=class extends _.Component{state={error:null};static getDerivedStateFromError(e){return{error:e instanceof Error?e:Error(String(e))}}reload=()=>{this.setState({error:null})};render(){return this.state.error?(0,J.jsxs)(`section`,{className:`card`,role:`alert`,style:{maxWidth:720,padding:`var(--space-6)`},children:[(0,J.jsxs)(`h2`,{style:{margin:`0 0 var(--space-2)`,fontSize:`var(--text-title)`},children:[this.props.pageName,`: `,this.props.title]}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:`0 0 var(--space-4)`},children:this.props.message}),(0,J.jsxs)(`p`,{style:{margin:`0 0 var(--space-5)`,overflowWrap:`anywhere`},children:[(0,J.jsxs)(`strong`,{children:[this.props.detailsLabel,`:`]}),` `,this.state.error.message]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:this.reload,children:this.props.reloadLabel})]}):this.props.children}},dl=`gpt-daybreak-blue-latest`,fl=Object.freeze({[dl]:`gpt-5.6-sol`});Object.freeze(Object.keys(fl));var pl=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`,dl]),ml=[`low`,`medium`,`high`,`xhigh`,`max`,`ultra`],hl=[`failover`,`round-robin`,`random`,`least-used`,`reset-window`],gl={failover:`cws.strategy.failover`,"round-robin":`cws.strategy.roundRobin`,random:`cws.strategy.random`,"least-used":`cws.strategy.leastUsed`,"reset-window":`cws.strategy.resetWindow`},_l={failover:`cws.strategy.failoverHint`,"round-robin":`cws.strategy.roundRobinHint`,random:`cws.strategy.randomHint`,"least-used":`cws.strategy.leastUsedHint`,"reset-window":`cws.strategy.resetWindowHint`},vl={failover:`cws.targets.failoverHint`,"round-robin":`cws.targets.roundRobinHint`,random:`cws.targets.randomHint`,"least-used":`cws.targets.leastUsedHint`,"reset-window":`cws.targets.resetWindowHint`},yl=new Set(hl);function bl(e,t){let n=e.filter(e=>e.provider.trim()&&e.model.trim());if(n.length===0)return[...ml];let r=new Set(ml),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[...ml];let a=new Set(i);return ml.filter(e=>a.has(e))}var xl=0;function Sl(e={}){return{provider:e.provider??``,model:e.model??``,...e.weight===void 0?{}:{weight:e.weight},clientKey:e.clientKey??`ct-${++xl}`}}function Cl(e){return e===`disabled`?`disabled`:`auto`}var wl=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/,Tl=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}(\/[a-zA-Z0-9][a-zA-Z0-9._-]{0,63})?$/,El=/^(?:gpt-|o1-|o3-|o4-|codex-)/;function Dl(e){return wl.test(e.trim())}function Ol(e){return`combo/${e.trim()}`}function kl(e,t){return(typeof t==`string`?t.trim():``)||Ol(e)}function Al(e,t){let n=t.trim(),r=e.nativeAlias&&(!n||n.includes(`/`)||!El.test(n));return{...e,alias:n?t:null,model:kl(e.id,t),...r?{nativeAlias:!1,displayName:null}:{}}}function jl(e){return typeof e==`string`&&e.trim()?e.trim():null}function Ml(e){return typeof e==`string`&&yl.has(e)?e:`failover`}function Nl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=100?e:1}function Pl(e){return typeof e==`string`&&ml.includes(e)?e:null}function Fl(e){return typeof e==`number`&&Number.isInteger(e)&&e>=1&&e<=1e4?e:void 0}function Il(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=Fl(t.weight);a.push(Sl(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():kl(r,jl(t.alias)),alias:jl(t.alias),nativeAlias:t.nativeAlias===!0,displayName:jl(t.displayName),strategy:Ml(t.strategy),stickyLimit:Nl(t.stickyLimit),defaultEffort:Pl(t.defaultEffort),imageInput:Cl(t.imageInput),targets:a})}return n.sort((e,t)=>e.id.localeCompare(t.id,void 0,{sensitivity:`base`}))}function Ll(e){let t=[],n=[],r=[];for(let i of e)i.strategy===`failover`?t.push(i):i.strategy===`round-robin`?n.push(i):r.push(i);return{failover:t,roundRobin:n,other:r}}function Rl(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 zl(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Bl(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Vl(e,t){let n=Bl(e);return n!==null&&t-n<18e5}function Hl(e){let t=Bl(e);return t!==null&&Number.isInteger(t)&&t>=0?t:null}function Ul(e,t){let n=zl(e),r=Bl(n?.usedPercent);return!!n&&r!==null&&r>=0&&Hl(n.includedAccounts)!==null&&(Hl(n.includedAccounts)??0)>0&&Hl(n.excludedAccounts)===0&&n.incomplete===!1&&Vl(n.updatedAt,t)}function Wl(e,t){let n=zl(e);if(!n||n.kind!==`capacity-weighted-v1`||n.scope!==`routable-known`||n.presentation!==`aggregate`||n.incomplete!==!1)return!1;for(let e of[`includedAccounts`,`excludedAccounts`,`unknownPlanAccounts`,`missingQuotaAccounts`,`pausedAccounts`,`reauthAccounts`,`staleQuotaAccounts`,`partialWindowAccounts`])if(Hl(n[e])===null)return!1;if((Hl(n.includedAccounts)??0)===0)return!1;for(let e of[`excludedAccounts`,`unknownPlanAccounts`,`missingQuotaAccounts`,`pausedAccounts`,`reauthAccounts`,`staleQuotaAccounts`,`partialWindowAccounts`])if(n[e]!==0)return!1;let r=!1;for(let e of[`fiveHour`,`weekly`,`monthly`])if(Object.hasOwn(n,e)){if(!Ul(n[e],t))return!1;r=!0}if(Object.hasOwn(n,`customWindows`)){if(!Array.isArray(n.customWindows))return!1;for(let e of n.customWindows){let n=zl(e);if(!n||typeof n.label!=`string`||!n.label.trim()||!Ul(n,t))return!1;r=!0}}return r}function Gl(e,t){if(!Vl(e.updatedAt,t))return`unknown`;let n=zl(e.quota);if(!n||!Vl(n.updatedAt,t)||e.aggregation!==void 0&&!Wl(e.aggregation,t))return`unknown`;let r=!1,i=!1;for(let e of[`fiveHourPercent`,`weeklyPercent`,`monthlyPercent`]){if(!Object.hasOwn(n,e))continue;let t=Bl(n[e]);if(t===null||t<0)return`unknown`;r=!0,t>=100&&(i=!0)}for(let e of[`fiveHourResetAt`,`weeklyResetAt`,`monthlyResetAt`])if(Object.hasOwn(n,e)&&Bl(n[e])===null)return`unknown`;if(Object.hasOwn(n,`customWindows`)){if(!Array.isArray(n.customWindows))return`unknown`;for(let e of n.customWindows){let t=zl(e),n=Bl(t?.percent);if(!t||typeof t.label!=`string`||!t.label.trim()||n===null||n<0||Object.hasOwn(t,`resetAt`)&&Bl(t.resetAt)===null)return`unknown`;r=!0,n>=100&&(i=!0)}}if(Object.hasOwn(n,`creditsUsd`)){let e=zl(n.creditsUsd);if(!e)return`unknown`;let t=Bl(e.used),a=Bl(e.limit),o=Bl(e.remaining),s=Bl(e.percent);if(t===null||t<0||a===null||a<0||o===null||s===null||s<0||e.unlimited!==void 0&&typeof e.unlimited!=`boolean`||Object.hasOwn(e,`expiresAt`)&&Bl(e.expiresAt)===null)return`unknown`;r=!0,e.unlimited!==!0&&o<=0&&(i=!0)}return r?i?`exhausted`:`available`:`unknown`}function Kl(e,t=Date.now()){if(!Array.isArray(e))return{};let n={};for(let r of e){let e=zl(r),i=typeof e?.provider==`string`?e.provider.trim():``;if(!e||!i)continue;let a=Gl(e,t);n[i]=Object.hasOwn(n,i)&&n[i]!==a?`unknown`:a}return n}function ql(e,t,n){let r=e.flatMap(e=>{let t=e.provider.trim();return!t||!e.model.trim()||!Object.hasOwn(n,t)||n[t]?.disabled===!0?[]:[t]});if(r.length===0)return`unknown`;let i=!1;for(let e of r){let n=t[e]??`unknown`;if(n===`available`)return`available`;n===`unknown`&&(i=!0)}return i?`unknown`:`exhausted`}function Jl(e,t={}){let n=[],r=t.cataloguedComboIds;for(let i of e)i.targets.length===0?n.push({id:i.id,model:i.model,reason:`empty-targets`}):i.targets.length<2&&n.push({id:i.id,model:i.model,reason:`few-targets`}),r&&i.targets.length>0&&!r.has(i.id)&&n.push({id:i.id,model:i.model,reason:`catalog-omitted`}),t.providerQuotaStates&&t.providers&&ql(i.targets,t.providerQuotaStates,t.providers)===`exhausted`&&n.push({id:i.id,model:i.model,reason:`all-targets-exhausted`});return n}function Yl(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 Xl(e,t={}){let n=e.strategy===`round-robin`||e.strategy===`random`;return{id:e.id.trim(),...t.renameFrom?{renameFrom:t.renameFrom}:{},combo:{targets:e.targets.map(e=>n?{provider:e.provider.trim(),model:e.model.trim(),weight:e.weight??1}:{provider:e.provider.trim(),model:e.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 Zl(e,t){let n=e.id.trim();if(!n)return`missingId`;if(!Dl(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(!Tl.test(r))return`invalidAlias`;if(r===`combo`||r.startsWith(`combo/`))return`aliasReservedNamespace`;if(!r.includes(`/`)&&El.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&&!pl.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`&&(!Number.isInteger(e.stickyLimit)||e.stickyLimit<1||e.stickyLimit>100))return`invalidStickyLimit`;if(e.strategy===`round-robin`||e.strategy===`random`)for(let t of e.targets){let e=t.weight??1;if(!Number.isInteger(e)||e<1||e>1e4)return`invalidWeight`}return e.targets.some(e=>t.providers[e.provider.trim()]?.disabled!==!0)?null:`noEnabledTarget`}function Ql(e=``){return{id:e,model:e?Ol(e):`combo/`,alias:null,nativeAlias:!1,displayName:null,strategy:`failover`,stickyLimit:1,defaultEffort:null,imageInput:`auto`,targets:[Sl()]}}function $l(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 eu(e){return e.filter(e=>!e.disabled&&!e.hiddenFromPicker).sort((e,t)=>e.name.localeCompare(t.name))}function tu(e,t,n){if(e===``)return;let r=Number(e);if(Number.isFinite(r))return Math.min(n,Math.max(t,r))}function nu(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 ru(e,t,n){let r=new Set([t]),i=n.find(e=>e.name===t);(t.toLowerCase()===`chatgpt`||nu(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 iu({value:e,onChange:t,disabled:n}){let r=Q();return(0,J.jsxs)(`div`,{className:`cwi-strategy-seg`,role:`radiogroup`,"aria-label":r(`cws.strategy`),children:[[[`failover`,`cws.strategy.failover`],[`round-robin`,`cws.strategy.roundRobin`]].map(([i,a])=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===i,className:`btn btn-sm${e===i?` btn-primary`:` btn-ghost`}`,disabled:n,onClick:()=>t(i),children:r(a)},i)),e!==`failover`&&e!==`round-robin`?(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:r(gl[e])}):null]})}function au({id:e,value:t,onChange:n,disabled:r,allowedEfforts:i}){let a=Q(),o=i??ml,s=t!==null&&!o.includes(t);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`select`,{id:e,className:`input`,value:t??``,disabled:r,"aria-label":a(`cws.field.defaultEffort`),onChange:e=>n(e.target.value===``?null:e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:a(`cws.field.defaultEffortNone`)}),s&&t?(0,J.jsxs)(`option`,{value:t,children:[t,` (`,a(`cws.field.defaultEffortUnsupportedOption`),`)`]}):null,o.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),s?(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`4px 0 0`,color:`var(--danger, #b42318)`},children:a(`cws.field.defaultEffortUnsupported`)}):null]})}function ou({targets:e,models:t,imageInput:n,disabled:r,onChange:i}){let a=Q(),o=$l(e,t),s=o&&n!==`disabled`;return(0,J.jsxs)(`section`,{className:`cwi-capabilities`,"aria-label":a(`cws.capabilities`),children:[(0,J.jsx)(`span`,{className:`field-label`,children:a(`cws.capabilities`)}),(0,J.jsxs)(`div`,{className:`cwi-capability-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`span`,{className:`cwi-capability-label`,children:a(`cws.capability.imageInput`)}),(0,J.jsx)(`p`,{className:`muted cwi-capability-hint`,children:a(o?`cws.capability.imageInputHint`:`cws.capability.imageInputUnavailable`)})]}),(0,J.jsx)(Tt,{on:s,onClick:()=>{o&&i({imageInput:n===`auto`?`disabled`:`auto`})},disabled:r||!o,label:a(`cws.capability.imageInput`)})]})]})}function su({targets:e,strategy:t,providers:n,models:r,providerQuotaStates:i,onChange:a}){let o=Q(),s=eu(n),[c,l]=(0,_.useState)(null),[u,d]=(0,_.useState)(null),f=(t,n)=>{a(e.map((e,r)=>r===t?{...e,...n}:e))},p=(t,n)=>{if(t===n||t<0||n<0||t>=e.length||n>=e.length)return;let r=[...e],[i]=r.splice(t,1);r.splice(n,0,i),a(r)};return(0,J.jsxs)(`div`,{className:`cwi-target-list`,children:[e.map((m,h)=>{let g=n.find(e=>e.name===m.provider),_=g&&!s.some(e=>e.name===m.provider)?[...s,g]:s,v=ru(r,m.provider,n),y=m.model&&!v.includes(m.model)?[m.model,...v]:v,b=!m.provider,x=c===h,S=u===h&&c!==null&&c!==h,C=i[m.provider.trim()]??`unknown`;return(0,J.jsxs)(`div`,{className:[`cwi-target-row`,t===`failover`?`cwi-target-row--failover`:``,x?`cwi-target-row--dragging`:``,S?`cwi-target-row--drop`:``].filter(Boolean).join(` `),onDragOver:e=>{c!==null&&(e.preventDefault(),e.dataTransfer.dropEffect=`move`,u!==h&&d(h))},onDrop:e=>{e.preventDefault(),c!==null&&p(c,h),l(null),d(null)},onDragEnd:()=>{l(null),d(null)},children:[(0,J.jsx)(`button`,{type:`button`,className:`cwi-target-grip`,draggable:!0,"aria-label":o(`cws.target.drag`),title:o(`cws.target.drag`),onDragStart:e=>{l(h),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,String(h))},children:(0,J.jsx)(Fe,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsxs)(`div`,{className:`cwi-target-reorder`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:h===0,"aria-label":o(`cws.target.moveUp`),onClick:()=>p(h,h-1),children:(0,J.jsx)(be,{width:14,height:14,"aria-hidden":`true`})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:h===e.length-1,"aria-label":o(`cws.target.moveDown`),onClick:()=>p(h,h+1),children:(0,J.jsx)(xe,{width:14,height:14,"aria-hidden":`true`})})]}),(0,J.jsxs)(`select`,{className:`input`,value:m.provider,"aria-label":o(`cws.target.provider`),onChange:e=>{let t=e.target.value,i=ru(r,t,n)[0]??``;f(h,{provider:t,model:i})},children:[(0,J.jsx)(`option`,{value:``,children:o(`cws.target.pickProvider`)}),_.map(e=>(0,J.jsx)(`option`,{value:e.name,children:e.disabled?o(`cws.target.disabled`,{name:Dn(e.name,o)}):Dn(e.name,o)},e.name))]}),(0,J.jsxs)(`select`,{className:`input`,value:m.model,disabled:b,"aria-label":o(`cws.target.model`),onChange:e=>f(h,{model:e.target.value}),children:[(0,J.jsx)(`option`,{value:``,children:b?o(`cws.target.pickProviderFirst`):y.length===0?o(`cws.target.noModels`):o(`cws.target.pickModel`)}),y.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]}),(t===`round-robin`||t===`random`)&&(0,J.jsx)(`input`,{className:`input mono`,type:`number`,min:1,max:1e4,value:m.weight??1,"aria-label":o(`cws.target.weight`),onChange:e=>{let t=tu(e.target.value,1,1e4);t!==void 0&&f(h,{weight:t})}}),(0,J.jsx)(`span`,{className:`cwi-quota-badge cwi-quota-badge--${C}`,"aria-label":o(`cws.quota.${C}`),children:o(`cws.quota.${C}`)}),(0,J.jsx)(`div`,{className:`cwi-target-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:e.length<=1,onClick:()=>a(e.filter((e,t)=>t!==h)),"aria-label":o(`common.remove`),children:(0,J.jsx)(he,{width:14,height:14})})})]},m.clientKey??`${m.provider}:${m.model}`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{alignSelf:`flex-start`},onClick:()=>a([...e,Sl()]),children:[(0,J.jsx)(de,{width:14,height:14}),` `,o(`cws.target.add`)]})]})}function cu({existingIds:e,existingAliases:t,providerMap:n,providerQuotaStates:r,providers:i,models:a,onClose:o,onSubmit:s}){let c=Q(),l=(0,_.useRef)(null),[u,d]=(0,_.useState)(()=>Ql()),[f,p]=(0,_.useState)(!1),[m,h]=(0,_.useState)(``),g=(0,_.useMemo)(()=>{let e=new Map;for(let t of a)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[a]),v=(0,_.useMemo)(()=>bl(u.targets,g),[u.targets,g]),y=ql(u.targets,r,n)===`exhausted`;(0,_.useEffect)(()=>{let e=l.current;e&&!e.open&&e.showModal()},[]);let b=(0,_.useCallback)(()=>{f||o()},[f,o]),x=(0,_.useCallback)(e=>{e.preventDefault(),b()},[b]),S=async()=>{let r=Zl(u,{existingIds:e,existingAliases:t,isCreate:!0,providers:n});if(r){h(c(`cws.err.${r}`));return}p(!0),h(``);let i=u.id.trim(),a=u.alias?.trim()||null;try{let e=await s({...u,id:i,alias:a,model:kl(i,a)});if(!e.ok){h(e.error||c(`cws.saveFailed`));return}}finally{p(!1)}};return(0,J.jsxs)(`dialog`,{ref:l,className:`modal-overlay`,"aria-labelledby":`cwi-add-title`,onCancel:x,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":c(`common.close`),tabIndex:-1,onClick:b}),(0,J.jsxs)(`div`,{className:`modal-card`,style:{width:`min(560px, 94vw)`},onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`row`,style:{justifyContent:`space-between`,marginBottom:8},children:[(0,J.jsx)(`h3`,{id:`cwi-add-title`,style:{margin:0},children:c(`cws.addTitle`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:b,disabled:f,"aria-label":c(`common.close`),children:(0,J.jsx)(ue,{width:16,height:16})})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`,overflowWrap:`anywhere`},children:c(`cws.addSubtitle`)}),m&&(0,J.jsx)($,{tone:`err`,children:m}),y&&(0,J.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:c(`cws.quota.allExhausted`)}),(0,J.jsxs)(`div`,{className:`cwi-modal-form`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-id`,children:c(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-new-id`,className:`input mono`,value:u.id,disabled:f,onChange:e=>d(t=>({...t,id:e.target.value,model:kl(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.idInternalHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-alias`,children:c(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-new-alias`,className:`input mono`,value:u.alias??``,placeholder:c(`cws.field.aliasPlaceholder`),disabled:f,onChange:e=>d(t=>({...t,alias:e.target.value.trim()?e.target.value:null,model:kl(t.id,e.target.value)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.aliasHint`)}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.idHint`,{model:u.id.trim()?kl(u.id,u.alias):`…`})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:c(`cws.strategy`)}),(0,J.jsx)(iu,{value:u.strategy,disabled:f,onChange:e=>d(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(_l[u.strategy])})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-effort`,children:c(`cws.field.defaultEffort`)}),(0,J.jsx)(au,{id:`cwi-new-effort`,value:u.defaultEffort,disabled:f,allowedEfforts:v,onChange:e=>d(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.defaultEffortHint`)})]}),u.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-new-sticky`,children:c(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-new-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:u.stickyLimit,disabled:f,onChange:e=>{let t=tu(e.target.value,1,100);t!==void 0&&d(e=>({...e,stickyLimit:t}))}}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(`cws.field.stickyLimitHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:c(`cws.targets`)}),(0,J.jsx)(su,{targets:u.targets,strategy:u.strategy,providers:i,models:a,providerQuotaStates:r,onChange:e=>d(t=>({...t,targets:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:c(vl[u.strategy])})]}),(0,J.jsx)(ou,{targets:u.targets,models:a,imageInput:u.imageInput??`auto`,disabled:f,onChange:e=>d(t=>({...t,...e}))})]}),(0,J.jsxs)(`div`,{className:`cwi-modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:b,disabled:f,children:c(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>{S()},disabled:f||y,children:c(f?`common.saving`:`cws.create`)})]})]})]})}var lu=[`config`,`about`],uu=e=>`cws-detail-tab-${e}`,du=e=>`cws-detail-panel-${e}`;function fu({baseline:e,isCreate:t=!1,otherIds:n,otherAliases:r,providerMap:i,providerQuotaStates:a,providers:o,models:s,onBack:c,onSaved:l,onRequestRemove:u,onSave:d,onDirtyChange:f}){let p=Q(),[m,h]=(0,_.useState)(`config`),g=(0,_.useCallback)((e,t)=>{let n;if(e.key===`ArrowRight`)n=(t+1)%lu.length;else if(e.key===`ArrowLeft`)n=(t-1+lu.length)%lu.length;else if(e.key===`Home`)n=0;else if(e.key===`End`)n=lu.length-1;else return;e.preventDefault(),h(lu[n]),e.currentTarget.parentElement?.querySelectorAll(`[role="tab"]`)[n]?.focus()},[]),[v,y]=(0,_.useState)(e),[b,x]=(0,_.useState)(!1),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(!1),E=!Yl(v,e),D=ql(v.targets,a,i)===`exhausted`,O=`${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(`,`)}`,k=(0,_.useMemo)(()=>{let e=new Map;for(let t of s)e.set(`${t.provider}/${t.id}`,t.reasoningEfforts);return e},[s]),A=(0,_.useMemo)(()=>bl(v.targets,k),[v.targets,k]),j=(0,_.useCallback)(t=>{let n=t(v);y(n),f(!Yl(n,e))},[v,e,f]);(0,_.useEffect)(()=>{let t=window.setTimeout(()=>{y(e),C(null),h(`config`),f(!1)},0);return()=>window.clearTimeout(t)},[O]);let M=async()=>{try{await navigator.clipboard.writeText(e.model),T(!0),window.setTimeout(()=>T(!1),1200)}catch{}},N=async()=>{let a=Zl(v,{existingIds:n,existingAliases:r,isCreate:t,providers:i});if(a){C({ok:!1,text:p(`cws.err.${a}`)});return}x(!0);let o=v.id.trim(),s=v.alias?.trim()||null,c=v.displayName?.trim()||null,u={...v,id:o,alias:s,displayName:c,model:kl(o,s)},f=!t&&o!==e.id?e.id:void 0;try{let e=await d(u,t,f);if(!e.ok){C({ok:!1,text:e.error||p(`cws.saveFailed`)});return}C({ok:!0,text:t?p(`cws.created`,{model:u.model}):p(`cws.saved`)}),l(u)}finally{x(!1)}},P=t?v.id.trim()?kl(v.id,v.alias):p(`cws.addTitle`):e.model;return(0,J.jsxs)(`div`,{className:`combos-workspace-detail`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-detail-head`,children:[c&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm pwi-back-overview`,onClick:c,"aria-label":p(`cws.backToAll`),children:[(0,J.jsx)(Se,{style:{width:14,height:14,transform:`rotate(180deg)`},"aria-hidden":`true`}),p(`cws.allCombos`)]}),(0,J.jsx)(`h2`,{className:`combos-workspace-detail-title`,children:P}),!t&&(0,J.jsx)(`button`,{type:`button`,className:`chip cwi-copy-chip`,onClick:()=>{M()},title:p(`cws.copyModel`),children:p(w?`cws.copied`:`cws.copyModel`)}),(0,J.jsxs)(`div`,{className:`combos-workspace-detail-actions`,children:[!t&&u&&(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:u,children:[(0,J.jsx)(he,{width:14,height:14}),` `,p(`common.remove`)]}),(0,J.jsx)(`button`,{id:t?`cwi-edit-create`:`cwi-edit-save`,type:`button`,className:`btn btn-primary btn-sm`,disabled:!t&&!E||b||D,onClick:()=>{N()},children:p(b?`common.saving`:t?`cws.create`:`common.save`)})]})]}),S&&(0,J.jsx)($,{tone:S.ok?`ok`:`err`,children:S.text}),D&&(0,J.jsx)(`div`,{className:`cwi-quota-banner`,role:`status`,"aria-live":`polite`,children:p(`cws.quota.allExhausted`)}),(0,J.jsx)(`div`,{className:`segmented combos-workspace-segmented`,role:`tablist`,"aria-label":p(`cws.tabsLabel`),children:lu.map((e,t)=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:uu(e),"aria-selected":m===e,"aria-controls":du(e),tabIndex:m===e?0:-1,className:`btn btn-sm ${m===e?`btn-primary`:`btn-ghost`}`,onClick:()=>h(e),onKeyDown:e=>g(e,t),children:p(e===`config`?`cws.tab.config`:`cws.tab.about`)},e))}),(0,J.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:du(`config`),"aria-labelledby":uu(`config`),hidden:m!==`config`,children:(0,J.jsxs)(`div`,{className:`cwi-form-grid`,children:[(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-id`,children:p(`cws.field.id`)}),(0,J.jsx)(`input`,{id:`cwi-edit-id`,className:`input mono`,value:v.id,disabled:b,onChange:e=>j(t=>({...t,id:e.target.value,model:kl(e.target.value,t.alias)}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:t?p(`cws.field.idInternalHint`):p(`cws.field.idHintEdit`,{model:kl(v.id,v.alias)})})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-alias`,children:p(`cws.field.alias`)}),(0,J.jsx)(`input`,{id:`cwi-edit-alias`,className:`input mono`,value:v.alias??``,placeholder:Ol(v.id.trim()||`…`),disabled:b,onChange:e=>j(t=>Al(t,e.target.value))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.aliasHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsxs)(`label`,{htmlFor:`cwi-edit-native-alias`,children:[(0,J.jsx)(`input`,{id:`cwi-edit-native-alias`,type:`checkbox`,checked:v.nativeAlias,disabled:b,onChange:e=>j(t=>({...t,nativeAlias:e.target.checked}))}),` `,p(`cws.field.nativeAlias`)]}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.nativeAliasHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-edit-display-name`,children:p(`cws.field.displayName`)}),(0,J.jsx)(`input`,{id:`cwi-edit-display-name`,className:`input`,value:v.displayName??``,maxLength:128,disabled:b,onChange:e=>j(t=>({...t,displayName:e.target.value||null}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.displayNameHint`)})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`cws.strategy`)}),(0,J.jsx)(iu,{value:v.strategy,disabled:b,onChange:e=>j(t=>({...t,strategy:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(_l[v.strategy])})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-effort`,children:p(`cws.field.defaultEffort`)}),(0,J.jsx)(au,{id:`cwi-effort`,value:v.defaultEffort,disabled:b,allowedEfforts:A,onChange:e=>j(t=>({...t,defaultEffort:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(`cws.field.defaultEffortHint`)})]}),v.strategy===`round-robin`&&(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`label`,{htmlFor:`cwi-sticky`,children:p(`cws.field.stickyLimit`)}),(0,J.jsx)(`input`,{id:`cwi-sticky`,className:`input mono`,type:`number`,min:1,max:100,value:v.stickyLimit,disabled:b,onChange:e=>{let t=tu(e.target.value,1,100);t!==void 0&&j(e=>({...e,stickyLimit:t}))}})]}),(0,J.jsxs)(`div`,{className:`cwi-field`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:p(`cws.targets`)}),(0,J.jsx)(su,{targets:v.targets,strategy:v.strategy,providers:o,models:s,providerQuotaStates:a,onChange:e=>j(t=>({...t,targets:e}))}),(0,J.jsx)(`p`,{className:`muted`,style:{fontSize:12,margin:`8px 0 0`},children:p(vl[v.strategy])})]}),(0,J.jsx)(ou,{targets:v.targets,models:s,imageInput:v.imageInput??`auto`,disabled:b,onChange:e=>j(t=>({...t,...e}))})]})}),(0,J.jsx)(`div`,{className:`combos-workspace-tab-content`,role:`tabpanel`,id:du(`about`),"aria-labelledby":uu(`about`),hidden:m!==`about`,tabIndex:0,children:(0,J.jsxs)(`section`,{className:`pwi-section`,children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:p(`cws.aboutTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0,maxWidth:`70ch`,overflowWrap:`anywhere`},children:p(`cws.aboutBody`)})]})})]})}function pu({model:e,onCancel:t,onConfirm:n}){let r=Q(),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,J.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":`cwi-remove-title`,onCancel:a,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:t}),(0,J.jsxs)(`div`,{className:`modal-card pwi-remove-confirm-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-remove-title`,className:`pwi-remove-confirm-title`,children:r(`cws.removeConfirmTitle`,{model:e})}),(0,J.jsx)(`p`,{className:`muted pwi-remove-confirm-desc`,children:r(`cws.removeConfirmDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-remove-confirm-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:t,children:r(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn pwi-remove-confirm-danger`,onClick:n,children:r(`common.remove`)})]})]})]})}function mu({onKeep:e,onDiscard:t}){let n=Q(),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,J.jsxs)(`dialog`,{ref:r,className:`modal-overlay`,"aria-labelledby":`cwi-unsaved-title`,onCancel:i,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":n(`common.close`),tabIndex:-1,onClick:e}),(0,J.jsxs)(`div`,{className:`modal-card pwi-json-unsaved-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`cwi-unsaved-title`,className:`pwi-json-unsaved-title`,children:n(`cws.unsavedTitle`)}),(0,J.jsx)(`p`,{className:`muted pwi-json-unsaved-desc`,children:n(`cws.unsavedDesc`)}),(0,J.jsxs)(`div`,{className:`pwi-json-unsaved-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,"data-testid":`cwi-unsaved-keep`,onClick:e,children:n(`cws.keepEditing`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,"data-testid":`cwi-unsaved-discard`,onClick:t,children:n(`common.discard`)})]})]})]})}function hu(e,t){return t(e===`empty-targets`?`cws.attention.empty`:e===`catalog-omitted`?`cws.attention.catalogOmitted`:e===`all-targets-exhausted`?`cws.attention.allTargetsExhausted`:`cws.attention.few`)}function gu({combos:e,cataloguedComboIds:t,providerMap:n,providerQuotaStates:r,onSelect:i,onAdd:a}){let o=Q(),s=Ll(e),c=Jl(e,{cataloguedComboIds:t,providers:n,providerQuotaStates:r});return(0,J.jsxs)(`div`,{className:`combos-workspace-overview`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-overview-head`,children:[(0,J.jsx)(`h2`,{className:`combos-workspace-overview-title`,children:o(`cws.overviewTitle`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:[(0,J.jsx)(de,{width:14,height:14}),` `,o(`cws.add`)]})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:0,maxWidth:`62ch`},children:o(`cws.overviewBlurb`)}),(0,J.jsxs)(`div`,{className:`cwi-count-strip`,children:[(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:e.length}),(0,J.jsx)(`span`,{children:o(`cws.count.total`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:s.failover.length}),(0,J.jsx)(`span`,{children:o(`cws.count.failover`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:s.roundRobin.length}),(0,J.jsx)(`span`,{children:o(`cws.count.roundRobin`)})]}),(0,J.jsxs)(`div`,{className:`cwi-count-pill`,children:[(0,J.jsx)(`strong`,{children:s.other.length}),(0,J.jsx)(`span`,{children:o(`cws.count.other`)})]})]}),(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":o(`cws.howTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:o(`cws.howTitle`)}),(0,J.jsx)(`p`,{className:`muted`,style:{margin:0},children:o(`cws.howBody`)})]}),c.length>0&&(0,J.jsxs)(`section`,{className:`pwi-section`,"aria-label":o(`cws.attentionTitle`),children:[(0,J.jsx)(`h3`,{className:`pwi-section-title`,children:o(`cws.attentionTitle`)}),(0,J.jsx)(`div`,{className:`cwi-attention-list`,children:c.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`cwi-attention-row`,onClick:()=>i(e.id),children:[(0,J.jsx)(_e,{width:14,height:14,"aria-hidden":`true`}),(0,J.jsx)(`code`,{className:`chip`,children:e.model}),(0,J.jsx)(`span`,{className:`muted`,children:hu(e.reason,o)}),(0,J.jsx)(Se,{width:14,height:14,style:{marginLeft:`auto`},"aria-hidden":`true`})]},`${e.id}:${e.reason}`))})]})]})}function _u({combos:e,providerQuotaStates:t,providers:n,models:r,cataloguedComboIds:i,loading:a,onRefresh:o,onSave:s,onRemove:c,onAdd:l,adding:u,onCloseAdd:d,onCreated:f}){let p=Q(),m=(0,_.useMemo)(()=>Object.fromEntries(n.map(e=>[e.name,{disabled:e.disabled}])),[n]),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(void 0),[S,C]=(0,_.useState)(null),[w,T]=(0,_.useState)(null),E=(0,_.useMemo)(()=>Ql(),[]),D=(0,_.useMemo)(()=>Rl(e,h),[e,h]),O=(0,_.useMemo)(()=>Ll(D),[D]),k=(0,_.useMemo)(()=>e.flatMap(e=>e.alias?[e.alias]:[]),[e]),A=v&&e.some(e=>e.id===v)?v:null,j=e.find(e=>e.id===A)??null,M=j&&w?.id===j.id?w:j,[N,P]=(0,_.useState)(!1),F=[],I=[];if(M)for(let t of e)t.id!==M.id&&(F.push(t.id),t.alias&&I.push(t.alias));let L=(0,_.useCallback)(e=>{if(e!==A){if(!N){y(e),T(null);return}x(e)}},[A,N]),R=()=>{b!==void 0&&(y(b),T(null),P(!1),x(void 0))},z=()=>x(void 0),B=b!==void 0&&N,V=!a&&e.length===0;return(0,J.jsxs)(`div`,{className:`combos-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`combos-workspace-rail`,"aria-label":p(`cws.railAria`),children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-header`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`div`,{className:`combos-workspace-rail-title`,children:p(`nav.combos`)}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-count`,children:e.length})]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:()=>{if(V){document.getElementById(`cwi-edit-id`)?.focus();return}l()},"aria-label":p(`cws.add`),children:[(0,J.jsx)(de,{width:14,height:14}),` `,p(`cws.add`)]})]}),(0,J.jsx)(`div`,{className:`cwi-search-row`,children:(0,J.jsxs)(`div`,{className:`cwi-search-wrap`,children:[(0,J.jsx)(ye,{className:`cwi-search-icon`,"aria-hidden":`true`}),(0,J.jsx)(`input`,{className:`input cwi-search-input`,value:h,onChange:e=>g(e.target.value),placeholder:p(`cws.searchPlaceholder`),"aria-label":p(`cws.searchPlaceholder`)})]})}),(0,J.jsx)(`div`,{className:`combos-workspace-rail-list`,children:D.length===0&&e.length>0?(0,J.jsx)(`p`,{className:`muted`,style:{padding:`16px`},children:p(`cws.noSearchResults`)}):(0,J.jsx)(J.Fragment,{children:[[`failover`,O.failover,`cws.group.failover`],[`round-robin`,O.roundRobin,`cws.group.roundRobin`],[`other`,O.other,`cws.group.other`]].map(([e,t,n])=>t.length>0?(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group`,children:[(0,J.jsxs)(`div`,{className:`combos-workspace-rail-group-head`,children:[(0,J.jsx)(`span`,{className:`pwi-dot`,"aria-hidden":`true`}),p(n),(0,J.jsx)(`span`,{className:`combos-workspace-rail-count`,children:t.length})]}),t.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`combos-workspace-rail-row${A===e.id?` combos-workspace-rail-row--selected`:``}`,onClick:()=>L(e.id),"aria-current":A===e.id?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`combos-workspace-rail-icon`,"aria-hidden":`true`,children:(0,J.jsx)(Pe,{width:16,height:16})}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-name`,children:e.model}),(0,J.jsx)(`span`,{className:`combos-workspace-rail-meta`,children:e.targets.length===1?p(`cws.targetCountOne`):p(`cws.targetCount`,{count:e.targets.length})}),(0,J.jsx)(Se,{className:`combos-workspace-rail-chevron`,"aria-hidden":`true`})]},e.id))]},e):null)})})]}),(0,J.jsx)(`div`,{className:`combos-workspace-main`,children:M?(0,J.jsx)(fu,{baseline:M,otherIds:F,otherAliases:I,providerMap:m,providerQuotaStates:t,providers:n,models:r,onBack:()=>L(null),onSaved:e=>{P(!1),e.id===M.id?T(e):(y(e.id),T(null)),o()},onRequestRemove:()=>C(M.id),onSave:s,onDirtyChange:P},M.id):V?(0,J.jsx)(fu,{baseline:E,isCreate:!0,otherIds:[],otherAliases:[],providerMap:m,providerQuotaStates:t,providers:n,models:r,onSaved:e=>{P(!1),y(e.id),T(e),f(e.id)},onSave:s,onDirtyChange:P},`first-combo`):(0,J.jsx)(gu,{combos:e,cataloguedComboIds:i,providerMap:m,providerQuotaStates:t,onSelect:e=>L(e),onAdd:l})}),u&&!V&&(0,J.jsx)(cu,{existingIds:e.map(e=>e.id),existingAliases:k,providerMap:m,providerQuotaStates:t,providers:n,models:r,onClose:d,onSubmit:async e=>{let t=await s(e,!0);return t.ok&&(d(),f(e.id),y(e.id),T(null)),t}}),S&&(0,J.jsx)(pu,{model:e.find(e=>e.id===S)?.model??Ol(S),onCancel:()=>C(null),onConfirm:()=>{(async()=>{let e=await c(S);C(null),e.ok&&(A===S&&(y(null),T(null)),o())})()}}),B&&(0,J.jsx)(mu,{onKeep:z,onDiscard:R})]})}function vu(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e.error;return typeof t==`string`&&t.trim()?t:void 0}function yu(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function bu(e){return mr(e)?.data??null}function xu(e){return mr(e)?.cachedAt??null}function Su({apiBase:e,active:t=!0,onCountChange:n}){let r=Q(),i=`ocx.combos.workspace.v1:${e}`,a=(0,_.useMemo)(()=>bu(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=Il(o),f=c.providers??{},p=ui(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 hr(i,_),s(_),_},[e,i]),g=ol(i,[e],h,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:xu(i),staleAfterMs:6e4,enabled:t}),{state:v}=g,y=(0,_.useCallback)(async t=>{let n=await fetch(`${e}/api/provider-quotas`,{signal:t});if(!n.ok)throw Error(`combo quota load failed`);let r=await n.json();return r&&typeof r==`object`&&!Array.isArray(r)?r:{}},[e]),b=ol(`ocx.combos.provider-quotas.v1:${e}`,[e],y,{isEmpty:()=>!1,pollMs:6e4,pauseWhenHidden:!0,enabled:t}),x=(0,_.useMemo)(()=>b.lastAttemptOk?Kl(b.data?.reports):{},[b.data,b.lastAttemptOk]),S=v.data??o??void 0,C=S?.combos??[];(0,_.useEffect)(()=>{S&&n?.(C.length)},[C.length,S,n]);let w=S?.providers??[],T=S?.models??[],E=new Set(S?.cataloguedComboIds??[]),D=async(t,n,i)=>{try{let a=await fetch(`${e}/api/combos`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(Xl(t,i?{renameFrom:i}:{}))}),o=a.ok?await a.json():await a.json().catch(()=>null),s=vu(o);if(!a.ok||s||!yu(o)){let e=s||r(`cws.saveFailed`);return m(e,!1),{ok:!1,error:e}}return g.refresh(),m(i?r(`cws.renamed`,{from:Ol(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}}},O=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=vu(i);if(!n.ok||a||!yu(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&&!S)return(0,J.jsx)(cl,{label:r(`cws.loading`),rows:5});if(v.kind===`failed-cold`&&!S){let e=v.error instanceof Error?v.error.message:r(`cws.loadFailed`);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($,{tone:`err`,children:e}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g.refresh(),children:r(`common.retry`)})]})}return(0,J.jsxs)(`div`,{className:`combos-workspace-shell`,children:[c&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)($,{tone:u?`ok`:`err`,children:c})}),v.showError&&(0,J.jsx)(`div`,{className:`combos-workspace-shell-banner`,children:(0,J.jsx)($,{tone:`err`,children:r(`cws.loadFailed`)})}),(0,J.jsxs)(`div`,{className:`combos-workspace-shell-body`,"aria-busy":v.refreshing,children:[(0,J.jsx)(`span`,{className:`sr-only`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:v.refreshing?r(`common.loading`):``}),(0,J.jsx)(_u,{combos:C,providerQuotaStates:x,providers:w,models:T,cataloguedComboIds:E,loading:!1,onRefresh:()=>g.refresh(),onSave:D,onRemove:O,onAdd:()=>p(!0),adding:f,onCloseAdd:()=>p(!1),onCreated:()=>g.refresh()})]})]})}var Cu=0;function wu(){return Cu+=1,`candidate-${Cu}`}function Tu(e,t){return{provider:e,model:t,key:wu()}}function Eu(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 Du(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n={requiredSuites:Eu(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 Ou={latency:`0.55`,health:`0.25`,cost:`0.1`,quota:`0.1`},ku={capability:`exclude`,health:`penalize`,quota:`penalize`,cost:`penalize`};function Au(e){return e===!0?`true`:e===!1?`false`:``}function ju(e){return e===void 0?``:String(e)}function Mu(e=``,t=``){return{id:``,alias:``,candidates:[Tu(e,t)],require:{minContextWindow:``,minQuotaHeadroom:``,tools:``,imageInput:``,structuredOutput:``,reasoningEffort:``,serviceTier:``,localOnly:``,remoteAllowed:``,encryptedCodexTasks:``},optimize:{...Ou},limits:{maxEstimatedCostUsd:``,onUnknownCost:`allow`},unknownEvidence:{...ku},compatibility:{enabled:!1,requiredSuites:[],minStatus:``,maxEvidenceAgeMs:``,unknownEvidence:`exclude`,degradedEvidence:`penalize`}}}function Nu(e){let t=Du(e.compatibility);return{id:e.id,alias:e.alias??``,candidates:e.candidates.map(e=>({...e,key:wu()})),require:{minContextWindow:ju(e.require.minContextWindow),minQuotaHeadroom:ju(e.require.minQuotaHeadroom),tools:Au(e.require.tools),imageInput:Au(e.require.imageInput),structuredOutput:Au(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort??``,serviceTier:e.require.serviceTier??``,localOnly:Au(e.require.localOnly),remoteAllowed:Au(e.require.remoteAllowed),encryptedCodexTasks:Au(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:ju(e.limits.maxEstimatedCostUsd),onUnknownCost:e.limits.onUnknownCost===`exclude`?`exclude`:`allow`},unknownEvidence:{...e.unknownEvidence},compatibility:{enabled:!!t,requiredSuites:t?.requiredSuites??[],minStatus:t?.minStatus??``,maxEvidenceAgeMs:ju(t?.maxEvidenceAgeMs),unknownEvidence:t?.unknownEvidence??`exclude`,degradedEvidence:t?.degradedEvidence??`penalize`}}}function Pu(e){let t=e.trim();return t?Number(t):void 0}function Fu(e){if(e===`true`)return!0;if(e===`false`)return!1}function Iu(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}function Lu(e,t,n){let r=Iu({minContextWindow:Pu(e.require.minContextWindow),minQuotaHeadroom:Pu(e.require.minQuotaHeadroom),tools:Fu(e.require.tools),imageInput:Fu(e.require.imageInput),structuredOutput:Fu(e.require.structuredOutput),reasoningEffort:e.require.reasoningEffort.trim()||void 0,serviceTier:e.require.serviceTier.trim()||void 0,localOnly:Fu(e.require.localOnly),remoteAllowed:Fu(e.require.remoteAllowed),encryptedCodexTasks:Fu(e.require.encryptedCodexTasks)}),i=Pu(e.limits.maxEstimatedCostUsd),a=e.compatibility.enabled?Iu({requiredSuites:e.compatibility.requiredSuites,minStatus:e.compatibility.minStatus||void 0,maxEvidenceAgeMs:Pu(e.compatibility.maxEvidenceAgeMs),unknownEvidence:e.compatibility.unknownEvidence,degradedEvidence:e.compatibility.degradedEvidence}):void 0,o=Iu({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 Ru(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 zu(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&e.success===!0}function Bu(e,t){return e.filter(e=>e.provider===t)}var Vu={en:{maxEvidenceAgeMs:`Maximum evidence age (ms)`,unknownEvidence:`Unknown evidence`,degradedEvidence:`Degraded evidence`},de:{maxEvidenceAgeMs:`Maximales Evidenzalter (ms)`,unknownEvidence:`Unbekannte Evidenz`,degradedEvidence:`Eingeschränkte Evidenz`},fr:{maxEvidenceAgeMs:`Âge maximal des preuves (ms)`,unknownEvidence:`Preuves inconnues`,degradedEvidence:`Preuves dégradées`},ko:{maxEvidenceAgeMs:`최대 증거 유효 기간 (ms)`,unknownEvidence:`알 수 없는 증거`,degradedEvidence:`저하된 증거`},zh:{maxEvidenceAgeMs:`证据最大有效期(毫秒)`,unknownEvidence:`未知证据`,degradedEvidence:`降级证据`},"zh-TW":{maxEvidenceAgeMs:`證據最大有效期限(毫秒)`,unknownEvidence:`未知證據`,degradedEvidence:`降級證據`},ru:{maxEvidenceAgeMs:`Максимальный возраст доказательств (мс)`,unknownEvidence:`Неизвестные доказательства`,degradedEvidence:`Ухудшенные доказательства`},ja:{maxEvidenceAgeMs:`エビデンスの最大有効期間 (ms)`,unknownEvidence:`不明なエビデンス`,degradedEvidence:`低下したエビデンス`},tr:{maxEvidenceAgeMs:`Maksimum kanıt yaşı (ms)`,unknownEvidence:`Bilinmeyen kanıt`,degradedEvidence:`Bozulmuş kanıt`}},Hu=[`tools`,`imageInput`,`structuredOutput`,`localOnly`,`remoteAllowed`,`encryptedCodexTasks`],Uu=[`reasoningEffort`,`serviceTier`],Wu={minContextWindow:{min:1,max:void 0,step:1},minQuotaHeadroom:{min:0,max:1,step:`any`}},Gu=Object.keys(Wu),Ku=[`latency`,`health`,`cost`,`quota`],qu=[`capability`,`health`,`quota`,`cost`],Ju=[`allow`,`penalize`,`exclude`],Yu=[`allow`,`exclude`];function Xu(e){return`${e.evidenceLayer}:${e.suiteId}`}function Zu(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Qu(e){let t=new Set,n=[];for(let r of e){if(!Zu(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=Xu(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 $u(e,t){return e.some(e=>e.suiteId===t.suiteId&&e.evidenceLayer===t.evidenceLayer)}function ed(e,t){return e===void 0?t:`${Math.round(e)}ms`}function td(e,t){return e==null?t:`${Math.round(e*100)}%`}function nd(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 rd(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 id(e){if(!e||typeof e!=`object`||Array.isArray(e))return[];let t=e.profiles;return Array.isArray(t)?t.filter(e=>Zu(e)?typeof e.id==`string`&&typeof e.model==`string`&&typeof e.revision==`string`&&Array.isArray(e.candidates)&&Zu(e.require)&&Zu(e.optimize)&&Zu(e.limits)&&Zu(e.unknownEvidence):!1).map(e=>{let t=Du(`compatibility`in e?e.compatibility:void 0),n={...e};return delete n.compatibility,{...n,alias:e.alias??null,...t?{compatibility:t}:{}}}):[]}function ad(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 od(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 sd({apiBase:e,active:t=!0,onCountChange:n}){let{locale:r,t:i}=ct(),a=Vu[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,z]=(0,_.useState)(``),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)([]),[W,ee]=(0,_.useState)(!1),G=(0,_.useRef)(null),K=(0,_.useRef)(0),q=(0,_.useRef)(null),Y=(0,_.useRef)(!0),te=(0,_.useCallback)(()=>{Y.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),z(``),V(!1)},[]),ae=(0,_.useCallback)(e=>{G.current=e,x(e),C(e?Nu(e):null),T(null),ie()},[ie]),oe=(0,_.useCallback)(async t=>{if(!Y.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=id(d),b=G.current,S=od(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()]));G.current=S,c(y),x(S),C(S?Nu(S):null),u(p),f(T),m(E),g(ad(_)),v&&Array.isArray(v.scenarios)?(U(Qu(v.scenarios)),ee(!1)):(U([]),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){te();return}Y.current=!0;let e=window.setTimeout(()=>void oe(),0);return()=>{window.clearTimeout(e),te()}},[t,te,oe]),(0,_.useEffect)(()=>{n?.(s.length)},[n,s.length]);let X=d[0]??``,se=p[X]??Bu(h,X)[0]?.id??``,ce=()=>{G.current=null,x(null),C(Mu(X,se)),T(null),ie()},le=()=>{if(b){C(Nu(b)),T(null);return}ae(s[0]??null)},ue=async()=>{if(!(!S||E)){D(!0),T(null);try{let t=Lu(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 Ft(n);if(!n.ok){let e=await n.json().catch(()=>null);re(Ru(e)??i(`routing.loadFailed`),!1);return}if(!zu(r)){re(Ru(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 Ft(t);if(!t.ok){let e=await t.json().catch(()=>null);re(Ru(e)??i(`routing.loadFailed`),!1);return}if(!zu(n)){re(Ru(n)??i(`routing.loadFailed`),!1);return}G.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]??Bu(h,n)[0]?.id??``}:{...r,model:n}:r);return{...r,candidates:i}})},pe=()=>{C(e=>e&&{...e,candidates:[...e.candidates,Tu(X,se)]})},me=e=>{C(t=>t&&{...t,candidates:t.candidates.filter((t,n)=>n!==e)})},he=async()=>{if(!b)return;let t=++ne.current;V(!0),L(null),z(``);try{let n={},r=O.trim()?Number(O.trim()):NaN;Number.isFinite(r)&&r>0&&(n.contextWindow=r),A&&(n.toolsRequired=!0),M&&(n.imageInputRequired=!0),P&&(n.structuredOutputRequired=!0);let a=await fetch(`${e}/api/routing-profiles/dry-run`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({profile:b.id,evidence:n})});if(t!==ne.current)return;if(!a.ok){let e=await a.json().catch(()=>null);if(t!==ne.current)return;z(Ru(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;z(e instanceof Error?e.message:String(e))}finally{t===ne.current&&V(!1)}},ge=S?.candidates.map(e=>Bu(h,e.provider))??[];return(0,J.jsxs)(`div`,{className:`page`,"data-page":`routing`,children:[(0,J.jsxs)(`div`,{className:`row`,style:{display:`flex`,gap:8,justifyContent:`flex-end`,marginBottom:12},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:ce,children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.createProfile`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void oe(),children:i(`common.retry`)})]}),v?(0,J.jsxs)($,{tone:`err`,children:[i(`routing.loadFailed`),`: `,v]}):null,w?(0,J.jsx)($,{tone:w.ok?`ok`:`err`,children:w.message}):null,s.length>0?(0,J.jsx)(`div`,{className:`panel`,style:{display:`flex`,flexDirection:`column`,gap:12},children:s.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`model-card`,style:{textAlign:`left`,cursor:`pointer`},onClick:()=>ae(e),"aria-pressed":b?.id===e.id,children:(0,J.jsxs)(`div`,{className:`card-badges`,children:[(0,J.jsx)(`strong`,{children:e.id}),(0,J.jsx)(`span`,{className:`badge badge-muted`,children:e.model}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,e.revision]})]})},e.id))}):null,S?(0,J.jsxs)(`form`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:16},onSubmit:e=>{e.preventDefault(),ue()},children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsxs)(`h3`,{children:[i(`routing.detail`),`: `,b?.model??(0,J.jsx)(`code`,{children:`policy/…`})]}),b?(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.revision`),`: `,b.revision]}):null]}),(0,J.jsxs)(`div`,{className:`model-grid`,children:[(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`id`}),(0,J.jsx)(`input`,{className:`input`,required:!0,disabled:b!==null,value:S.id,onChange:e=>C(t=>t&&{...t,id:e.target.value})})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`alias`}),(0,J.jsx)(`input`,{className:`input`,value:S.alias,onChange:e=>C(t=>t&&{...t,alias:e.target.value})})]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.candidates`)}),(0,J.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,J.jsxs)(`div`,{className:`model-card`,children:[(0,J.jsxs)(`div`,{className:`model-grid`,children:[(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`provider`}),(0,J.jsxs)(`select`,{className:`input`,required:!0,value:e.provider,onChange:e=>fe(t,`provider`,e.target.value),children:[(0,J.jsx)(`option`,{value:``,disabled:!0,children:i(`routing.none`)}),n.map(e=>(0,J.jsx)(`option`,{value:e,children:e},e))]})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`model`}),(0,J.jsx)(`input`,{className:`input`,required:!0,list:r,value:e.model,onChange:e=>fe(t,`model`,e.target.value)}),(0,J.jsx)(`datalist`,{id:r,children:ge[t]?.map(e=>(0,J.jsx)(`option`,{value:e.id},e.id))})]})]}),(0,J.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,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:pe,children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` `,i(`routing.candidate`)]})]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.require`)}),(0,J.jsxs)(`div`,{className:`model-grid`,children:[Gu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsx)(`input`,{className:`input`,type:`number`,min:Wu[e].min,max:Wu[e].max,step:Wu[e].step,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Uu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsx)(`input`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}})})]},e)),Hu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsxs)(`select`,{className:`input`,value:S.require[e],onChange:t=>C(n=>n&&{...n,require:{...n.require,[e]:t.target.value}}),children:[(0,J.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,J.jsx)(`option`,{value:`true`,children:i(`routing.yes`)}),(0,J.jsx)(`option`,{value:`false`,children:i(`routing.no`)})]})]},e))]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.optimize`)}),(0,J.jsx)(`div`,{className:`model-grid`,children:Ku.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.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,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.limits`)}),(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`maxEstimatedCostUsd`}),(0,J.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,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:`onUnknownCost`}),(0,J.jsx)(`select`,{className:`input`,value:S.limits.onUnknownCost,onChange:e=>C(t=>t&&{...t,limits:{...t.limits,onUnknownCost:e.target.value}}),children:Yu.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.unknownEvidence`)}),(0,J.jsx)(`div`,{className:`model-grid`,children:qu.map(e=>(0,J.jsxs)(`label`,{className:`field-label`,children:[(0,J.jsx)(`code`,{children:e}),(0,J.jsx)(`select`,{className:`input`,value:S.unknownEvidence[e],onChange:t=>C(n=>n&&{...n,unknownEvidence:{...n.unknownEvidence,[e]:t.target.value}}),children:Ju.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]},e))})]}),(0,J.jsxs)(`fieldset`,{style:{border:0,padding:0,margin:0},children:[(0,J.jsx)(`legend`,{className:`field-label`,children:i(`routing.compatibility.title`)}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.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,J.jsxs)(`div`,{className:`model-grid`,style:{marginTop:10},children:[(0,J.jsxs)(`div`,{className:`field-label`,style:{gridColumn:`1 / -1`},children:[i(`routing.compatibility.requiredSuites`),W?(0,J.jsx)(`div`,{style:{marginTop:6},children:(0,J.jsx)($,{tone:`warn`,children:i(`routing.compatibility.catalogUnavailable`)})}):null,H.length>0?(0,J.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:4,marginTop:6},children:H.map(e=>(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:$u(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,J.jsxs)(`span`,{children:[e.suiteId,` `,(0,J.jsxs)(`span`,{className:`muted`,children:[`(`,i(`routing.compatibility.layer.${e.evidenceLayer}`),`)`]})]})]},e.key))}):null]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[i(`routing.compatibility.minStatus`),(0,J.jsxs)(`select`,{className:`input`,value:S.compatibility.minStatus,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,minStatus:e.target.value}}),children:[(0,J.jsx)(`option`,{value:``,children:i(`routing.none`)}),(0,J.jsx)(`option`,{value:`PROBED`,children:i(`lab.verdict.PROBED`)}),(0,J.jsx)(`option`,{value:`VERIFIED`,children:i(`lab.verdict.VERIFIED`)})]})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[a.maxEvidenceAgeMs,(0,J.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,J.jsxs)(`label`,{className:`field-label`,children:[a.unknownEvidence,(0,J.jsx)(`select`,{className:`input`,value:S.compatibility.unknownEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,unknownEvidence:e.target.value}}),children:Ju.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]}),(0,J.jsxs)(`label`,{className:`field-label`,children:[a.degradedEvidence,(0,J.jsx)(`select`,{className:`input`,value:S.compatibility.degradedEvidence,onChange:e=>C(t=>t&&{...t,compatibility:{...t.compatibility,degradedEvidence:e.target.value}}),children:Ju.map(e=>(0,J.jsx)(`option`,{value:e,children:i(`routing.unknownEvidence.${e}`)},e))})]})]}):null]}),(0,J.jsxs)(`div`,{style:{display:`flex`,gap:8,flexWrap:`wrap`},children:[(0,J.jsx)(`button`,{type:`submit`,className:`btn btn-primary`,disabled:E,children:i(E?`common.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:le,children:i(`common.cancel`)}),b?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:E,onClick:()=>void de(),children:i(`common.remove`)}):null]})]}):null,(0,J.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,J.jsx)(`h3`,{children:i(`routing.dryRun`)}),(0,J.jsxs)(`label`,{className:`field-label`,htmlFor:`routing-context`,children:[i(`routing.dryRunContext`),(0,J.jsx)(`input`,{id:`routing-context`,className:`input`,type:`number`,min:1,value:O,onChange:e=>{k(e.target.value),ie()}})]}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:A,onChange:e=>{j(e.target.checked),ie()}}),i(`routing.dryRunTools`)]}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>{N(e.target.checked),ie()}}),i(`routing.dryRunImage`)]}),(0,J.jsxs)(`label`,{className:`checkbox`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:P,onChange:e=>{F(e.target.checked),ie()}}),i(`routing.dryRunStructured`)]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!b||B,onClick:()=>void he(),children:i(`routing.dryRunRun`)}),R?(0,J.jsx)($,{tone:`err`,children:R}):null,I?(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`routing.candidate`)}),(0,J.jsx)(`th`,{children:i(`routing.eligible`)}),(0,J.jsx)(`th`,{children:i(`routing.exclusions`)}),(0,J.jsx)(`th`,{children:i(`routing.costCap`)}),(0,J.jsx)(`th`,{children:i(`routing.score`)})]})}),(0,J.jsx)(`tbody`,{children:I.candidates.map((e,t)=>(0,J.jsxs)(`tr`,{children:[(0,J.jsxs)(`td`,{children:[e.provider,`/`,e.model,t===I.selectedIndex?` ✓ (${i(`routing.selected`)})`:``]}),(0,J.jsx)(`td`,{children:e.eligible?i(`routing.yes`):i(`routing.no`)}),(0,J.jsx)(`td`,{children:e.exclusions.map(e=>rd(e.code,i)).join(`, `)||i(`routing.none`)}),(0,J.jsx)(`td`,{children:nd(e.cost?.capOutcome,i,o)}),(0,J.jsx)(`td`,{children:e.score?e.score.total.toFixed(3):o})]},`${e.provider}/${e.model}`))})]}):null]}),(0,J.jsxs)(`div`,{className:`panel`,style:{marginTop:14,display:`flex`,flexDirection:`column`,gap:10},children:[(0,J.jsx)(`h3`,{children:i(`routing.analytics`)}),l?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`card-badges`,children:[(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsTotal`),`: `,l.totalRequests]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsSuccessRate`),`: `,td(l.successRate,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsFallbackRate`),`: `,td(l.fallbackRate,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP50`),`: `,ed(l.durationMs.p50,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP95`),`: `,ed(l.durationMs.p95,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsP99`),`: `,ed(l.durationMs.p99,o)]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsCooldown`),`: `,l.cooldownTriggeringFailures]}),(0,J.jsxs)(`span`,{className:`badge badge-muted`,children:[i(`routing.analyticsConfidence`),`: `,l.confidence??o]}),l.historyTruncated?(0,J.jsx)(`span`,{className:`badge badge-muted`,children:i(`routing.analyticsTruncated`)}):null]}),(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`routing.candidate`)}),(0,J.jsx)(`th`,{children:i(`routing.analyticsRequests`)}),(0,J.jsx)(`th`,{children:i(`routing.analyticsSuccessRate`)}),(0,J.jsx)(`th`,{children:i(`routing.analyticsP50`)})]})}),(0,J.jsx)(`tbody`,{children:l.breakdown.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsxs)(`td`,{children:[e.provider,`/`,e.model]}),(0,J.jsx)(`td`,{children:e.requests}),(0,J.jsx)(`td`,{children:td(e.successRate,o)}),(0,J.jsx)(`td`,{children:ed(e.p50DurationMs,o)})]},`${e.provider}/${e.model}`))})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:i(`routing.analyticsEmpty`)})]})]})}var cd=[`protocol_conformance`,`live_route_compatibility`,`task_effectiveness`],ld=[`UNKNOWN`,`CLAIMED`,`PROBED`,`VERIFIED`,`DEGRADED`,`BLOCKED`,`UNSUPPORTED`],ud=[`present`,`corrupt`,`purged_unavailable`];function dd(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function fd(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function pd(e){return e===null||typeof e==`string`}function md(e){return e===void 0||typeof e==`number`&&Number.isFinite(e)}function hd(e){if(!dd(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(!md(e[t]))return null;return e.projectionSpecVersion!==void 0&&typeof e.projectionSpecVersion!=`string`?null:e}function gd(e){return!dd(e)||typeof e.projectionKey!=`string`||e.projectionKey.length===0||typeof e.subjectId!=`string`||e.subjectId.length===0||typeof e.evidenceLayer!=`string`||!cd.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`||!ld.includes(e.verdict)||typeof e.asOf!=`number`||!Number.isFinite(e.asOf)||!fd(e.scenarioManifestDigests)||!pd(e.claimSourceDigest)||!fd(e.contributingEventIds)||!fd(e.contradictingEventIds)||!fd(e.notes)?null:e}function _d(e){return!dd(e)||!Array.isArray(e.verdicts)?{verdicts:[],hasMore:!1}:{verdicts:e.verdicts.map(gd).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function vd(e){return!dd(e)||!Array.isArray(e.subjects)?{subjects:[],hasMore:!1}:{subjects:e.subjects.filter(e=>dd(e)&&typeof e.subjectId==`string`&&typeof e.subjectKind==`string`),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function yd(e){return!dd(e)||!dd(e.subject)||typeof e.subject.subjectKind!=`string`?null:e.subject}function bd(e){return!dd(e)||typeof e.eventId!=`string`||typeof e.subjectId!=`string`||typeof e.evidenceLayer!=`string`||!cd.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`||!pd(e.exclusionReason)?null:e}function xd(e){return!dd(e)||!Array.isArray(e.observations)?{observations:[],hasMore:!1}:{observations:e.observations.map(bd).filter(e=>e!==null),hasMore:e.hasMore===!0,nextCursor:typeof e.nextCursor==`string`?e.nextCursor:void 0}}function Sd(e){if(!dd(e)||!dd(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`||!pd(t.exclusionReason)?null:t}function Cd(e){if(!dd(e)||!dd(e.artifact))return null;let t=e.artifact;return typeof t.digest!=`string`||typeof t.status!=`string`||!ud.includes(t.status)||!pd(t.artifactClass)||!pd(t.mediaType)||t.byteCount!==null&&(typeof t.byteCount!=`number`||!Number.isFinite(t.byteCount))||!pd(t.lastError)?null:t}function wd(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 Td(){return{protocol_conformance:[],live_route_compatibility:[],task_effectiveness:[]}}function Ed(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:Td()},r.set(t.subjectId,e)),e.byLayer[t.evidenceLayer].push(t)}return[...r.values()].sort((e,t)=>e.subjectId.localeCompare(t.subjectId))}function Dd(e){return e.length<=16?e:`${e.slice(0,8)}.${e.slice(-6)}`}function Od(e,t){return!Number.isFinite(e)||e<=0?`-`:new Date(e).toLocaleString(t)}function kd(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 Ad=50,jd=200,Md=6,Nd=200;async function Pd(e,t,n){return Pt(await fetch(`${e}${t}`,{signal:n}))}function Fd(e,t){let n=new URLSearchParams({limit:String(Ad)});for(let[t,r]of Object.entries(e))r&&n.set(t,r);return t&&n.set(`cursor`,t),n.toString()}var Id=class extends Error{};function Ld(){return new Id}function Rd(e,t,n){if(e.hasMore!==void 0&&typeof e.hasMore!=`boolean`||e.nextCursor!==void 0&&typeof e.nextCursor!=`string`||t&&!n)throw Ld()}function zd(e){if(!dd(e)||!Array.isArray(e.verdicts))throw Ld();let t=_d(e);if(t.verdicts.length!==e.verdicts.length)throw Ld();return Rd(e,t.hasMore,t.nextCursor),t}function Bd(e){if(!dd(e)||!Array.isArray(e.subjects))throw Ld();let t=vd(e);if(t.subjects.length!==e.subjects.length)throw Ld();return Rd(e,t.hasMore,t.nextCursor),t}function Vd(e){if(!dd(e)||!Array.isArray(e.observations))throw Ld();let t=xd(e);if(t.observations.length!==e.observations.length)throw Ld();return Rd(e,t.hasMore,t.nextCursor),t}async function Hd(e,t){let n=hd(await Pd(e,`/api/lab/status`,t));if(!n)throw Ld();return n}async function Ud(e,t,n,r){return zd(await Pd(e,`/api/lab/verdicts?${Fd({layer:t.layer,verdict:t.verdict,subjectId:t.subjectId,suiteId:t.suiteId},n)}`,r))}async function Wd(e,t,n){return Bd(await Pd(e,`/api/lab/subjects?${Fd({},t)}`,n))}async function Gd(e){let t=[],n=new Set,r;for(let i=0;i<jd;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 Id;n.add(a),r=a}return{rows:t,truncated:!0}}async function Kd(e,t){return Gd(async n=>{let r=await Wd(e,n,t);return{rows:r.subjects,hasMore:r.hasMore,nextCursor:r.nextCursor}})}async function qd(e,t,n){let r=yd(await Pd(e,`/api/lab/subjects/${encodeURIComponent(t)}`,n));if(!r)throw Ld();return r}async function Jd(e,t,n,r){return Vd(await Pd(e,`/api/lab/observations?${Fd({subjectId:t.subjectId,layer:t.layer,suiteId:t.suiteId},n)}`,r))}async function Yd(e,t,n){return Gd(async r=>{let i=await Jd(e,t,r,n);return{rows:i.observations,hasMore:i.hasMore,nextCursor:i.nextCursor}})}async function Xd(e,t,n){let r=Sd(await Pd(e,`/api/lab/events/${encodeURIComponent(t)}`,n));if(!r)throw Ld();return r}async function Zd(e,t,n){let r=Cd(await Pd(e,`/api/lab/artifacts/${encodeURIComponent(t)}`,n));if(!r)throw Ld();return r}function Qd(e){if(!dd(e)||e.verificationStatus!==`not_verification`||!dd(e.summary))throw Ld();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 Ld();return{verificationStatus:`not_verification`,summary:t}}async function $d(e,t,n){return Qd(await Pd(e,`/api/lab/production-signals?${Fd({subjectId:t})}`,n))}function ef(e,t){let n=new Set(t);return Object.keys(e).every(e=>n.has(e))}function tf(e){return typeof e==`string`&&/^[0-9a-f]{64}$/.test(e)}function nf(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function rf(e){if(!dd(e)||!ef(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(!dd(n)||!ef(n,[`trustClass`,`status`,`bundleId`,`publisherKeyId`,`activeRecordCount`,`revokedRecordCount`])||n.trustClass!==`community_untrusted_v1`||n.status!==`cryptographically_valid`||!tf(n.bundleId)||!tf(n.publisherKeyId)||!nf(n.activeRecordCount)||!nf(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 af(e,t){let n=rf(await Pd(e,`/api/lab/public/community`,t));if(!n)throw Ld();return n}async function of(e,t,n){let[r,i]=await Promise.all([Hd(e,n),af(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([Ud(e,t,void 0,n),Kd(e,n)]);return{status:r,verdicts:a.verdicts,subjects:o.rows,subjectsTruncated:o.truncated,hasMore:a.hasMore,nextCursor:a.nextCursor,community:i}}async function sf(e,t,n,r){return Ud(e,t,n,r)}async function cf(e,t,n,r){let i=e.slice(0,Nd),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 lf(e,t,n){let r=[...new Set([...t.contributingEventIds,...t.contradictingEventIds])],i=kd(t),a={subjectId:t.subjectId,layer:t.evidenceLayer,suiteId:t.suiteId},[o,s,c,l,u]=await Promise.all([qd(e,t.subjectId,n),Yd(e,a,n),cf(r,Md,n,t=>Xd(e,t,n)),cf(i,Md,n,t=>Zd(e,t,n)),$d(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 uf={protocol_conformance:`lab.layer.protocol_conformance`,live_route_compatibility:`lab.layer.live_route_compatibility`,task_effectiveness:`lab.layer.task_effectiveness`},df={protocol_conformance:`lab.col.protocol`,live_route_compatibility:`lab.col.live`,task_effectiveness:`lab.col.task`},ff={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`},pf={present:`artifact.present`,corrupt:`artifact.corrupt`,purged_unavailable:`artifact.purged_unavailable`};function mf(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 hf({verdict:e,caption:t,label:n,selected:r,onSelect:i}){let a=`lab-verdict-badge${r?` lab-verdict-badge--selected`:``}`;return i?(0,J.jsxs)(`button`,{type:`button`,className:a,"data-verdict":e,title:t,onClick:i,children:[(0,J.jsx)(`span`,{children:n}),(0,J.jsx)(`span`,{className:`suite`,children:t})]}):(0,J.jsxs)(`span`,{className:a,"data-verdict":e,title:t,children:[(0,J.jsx)(`span`,{children:n}),(0,J.jsx)(`span`,{className:`suite`,children:t})]})}function gf({rows:e,t,selectedKey:n,onSelect:r}){return e.length===0?(0,J.jsx)(`span`,{className:`muted`,children:`-`}):(0,J.jsx)(`div`,{className:`lab-verdict-stack`,children:e.map(e=>(0,J.jsx)(hf,{verdict:e.verdict,caption:e.suiteId,label:t(ff[e.verdict]),selected:n===e.projectionKey,onSelect:()=>r(e)},e.projectionKey))})}function _f({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:Od(r.builtAtMs,n)}),(0,J.jsx)(`div`,{className:`lab-status-grid`,"aria-label":t(`lab.statusTitle`),children:i.map(e=>(0,J.jsxs)(`div`,{className:`lab-status-card`,children:[(0,J.jsx)(`span`,{className:`label`,children:e.label}),(0,J.jsx)(`span`,{className:`value`,children:e.value})]},e.label))})}function vf({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,J.jsxs)(`section`,{className:`lab-matrix-block`,"data-testid":`lab-community-evidence`,children:[(0,J.jsx)(`h3`,{className:`lab-matrix-title`,children:Ye(t,`community.title`)}),(0,J.jsx)(`p`,{className:`muted`,children:Ye(t,`community.notLocalVerdict`)}),(0,J.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:Ye(t,`community.bundles`)}),(0,J.jsx)(`dd`,{children:e.evidence.length})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:Ye(t,`community.activeRecords`)}),(0,J.jsx)(`dd`,{children:n})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:Ye(t,`community.revokedRecords`)}),(0,J.jsx)(`dd`,{children:r})]})]})]})}function yf({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,J.jsxs)(`aside`,{className:`lab-detail-pane`,"aria-label":i(`lab.detailTitle`),children:[(0,J.jsxs)(`div`,{className:`lab-detail-head`,children:[(0,J.jsx)(`h3`,{children:Dd(e.subjectId)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,children:i(`lab.detailClose`)})]}),(0,J.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.layer`)}),(0,J.jsx)(`dd`,{children:i(uf[e.evidenceLayer])})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.suite`)}),(0,J.jsx)(`dd`,{className:`mono`,children:e.suiteId})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.verdict`)}),(0,J.jsx)(`dd`,{children:i(ff[e.verdict])})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.col.asOf`)}),(0,J.jsx)(`dd`,{children:Od(e.asOf,a)})]})]}),n&&(0,J.jsx)(ll,{busy:!0,children:i(`common.loading`)}),r&&(0,J.jsx)($,{tone:`err`,children:r}),t&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsx)(`h4`,{children:i(`lab.detailSubject`)}),(0,J.jsx)(`p`,{className:`mono`,children:t.subject.subjectKind})]}),t.production&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,"data-testid":`lab-production-signals`,children:[(0,J.jsx)(`h4`,{children:i(`lab.production.title`)}),(0,J.jsx)(`p`,{className:`muted`,children:i(`lab.production.notVerification`)}),(0,J.jsxs)(`dl`,{className:`lab-detail-meta`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.attempts`)}),(0,J.jsx)(`dd`,{children:t.production.summary.recentProductionAttempts})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.successes`)}),(0,J.jsx)(`dd`,{children:t.production.summary.recentSuccessfulAttempts})]}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.routeErrors`)}),(0,J.jsx)(`dd`,{children:t.production.summary.recentRouteErrorSignals})]}),t.production.summary.lastObservedProductionAttempt!==void 0&&(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`dt`,{children:i(`lab.production.lastObserved`)}),(0,J.jsx)(`dd`,{children:Od(t.production.summary.lastObservedProductionAttempt,a)})]})]})]}),t.observations.length>0&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsx)(`h4`,{children:i(`lab.detailObservations`)}),(0,J.jsx)(`ul`,{className:`lab-detail-list`,children:t.observations.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`mono`,children:e.scenarioId}),(0,J.jsx)(`span`,{children:e.outcome}),(0,J.jsx)(`span`,{className:`muted`,children:Od(e.completedAt,a)})]},e.eventId))})]}),(t.events.length>0||s>0)&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsxs)(`h4`,{children:[i(`lab.detailEvents`),t.events.length<s?` (${t.events.length}/${s})`:``]}),(0,J.jsx)(`ul`,{className:`lab-detail-list`,children:t.events.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`mono`,children:e.eventId}),(0,J.jsx)(`span`,{children:e.eventKind})]},e.eventId))})]}),t.artifacts.length>0&&(0,J.jsxs)(`section`,{className:`lab-detail-section`,children:[(0,J.jsx)(`h4`,{children:i(`lab.detailArtifacts`)}),(0,J.jsx)(`ul`,{className:`lab-detail-list`,children:t.artifacts.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`mono`,title:e.digest,children:Dd(e.digest)}),(0,J.jsx)(`span`,{children:e.artifactClass??`-`}),(0,J.jsx)(`span`,{children:Ye(a,pf[e.status])})]},e.digest))})]})]})]})}function bf({apiBase:e,active:t=!0,onCountChange:n}){let{t:r,locale:i}=ct(),[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)(()=>wd(a),[a]),E=JSON.stringify(T),D=(0,_.useCallback)(t=>of(e,T,t),[e,T]),O=ol(`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?Ed(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 sf(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:mf(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 lf(e,n,i.signal);!i.signal.aborted&&w.current===n.projectionKey&&g(t)}catch(e){!i.signal.aborted&&w.current===n.projectionKey&&x(mf(e,r(`lab.detailLoadFailed`)))}finally{C.current===i&&(C.current=null,!i.signal.aborted&&w.current===n.projectionKey&&y(!1))}},[t,e,r]),z=O.refresh,B=(0,_.useCallback)(()=>{A(),k(),z({forceLoading:!0})},[A,z,k]),V=t?p:null,H=M?M.hasMore:O.data?.hasMore??!1,U=[{value:``,label:r(`lab.filter.all`)},...cd.map(e=>({value:e,label:r(uf[e])}))],W=[{value:``,label:r(`lab.filter.all`)},...ld.map(e=>({value:e,label:r(ff[e])}))],ee=[{value:``,label:r(`lab.filter.all`)},...(O.data?.subjects??[]).map(e=>({value:e.subjectId,label:`${Dd(e.subjectId)} · ${e.subjectKind}`}))];if(O.state.showSkeleton)return(0,J.jsx)(cl,{label:r(`lab.loading`),rows:5});let G=O.state.showError?mf(O.error,r(`lab.loadFailed`)):null,K=O.data?.status,q=K&&!K.projectionAvailable,Y=K?.projectionIncompatible===!0;return(0,J.jsxs)(`div`,{className:`lab-page`,children:[(0,J.jsx)(`div`,{className:`lab-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:B,disabled:O.refreshing,children:[(0,J.jsx)(fe,{}),r(`lab.refresh`)]})}),O.refreshing&&!O.state.showSkeleton&&(0,J.jsx)(ll,{busy:!0,live:!G,children:r(`common.loading`)}),G&&(0,J.jsx)($,{tone:`err`,children:G}),Y&&(0,J.jsx)($,{tone:`err`,children:r(`lab.projectionIncompatible`)}),q&&!Y&&(0,J.jsx)(Ot,{title:r(`lab.projectionUnavailable`)}),O.data&&(0,J.jsx)(vf,{community:O.data.community,locale:i}),O.data&&K?.projectionAvailable&&!Y&&(0,J.jsxs)(`div`,{className:`lab-layout`,children:[(0,J.jsxs)(`div`,{className:`lab-main`,children:[(0,J.jsx)(_f,{data:O.data,t:r,locale:i}),(0,J.jsxs)(`div`,{className:`lab-filters`,children:[(0,J.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,J.jsx)(`label`,{htmlFor:`lab-filter-layer`,children:r(`lab.filter.layer`)}),(0,J.jsx)(Dt,{id:`lab-filter-layer`,value:a.layer,options:U,onChange:e=>j(t=>({...t,layer:e})),label:r(`lab.filter.layer`),portal:!1})]}),(0,J.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,J.jsx)(`label`,{htmlFor:`lab-filter-verdict`,children:r(`lab.filter.verdict`)}),(0,J.jsx)(Dt,{id:`lab-filter-verdict`,value:a.verdict,options:W,onChange:e=>j(t=>({...t,verdict:e})),label:r(`lab.filter.verdict`),portal:!1})]}),(0,J.jsxs)(`div`,{className:`lab-filter-field`,children:[(0,J.jsx)(`label`,{htmlFor:`lab-filter-subject`,children:r(`lab.filter.subject`)}),(0,J.jsx)(Dt,{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,J.jsx)(Ot,{title:r(`lab.empty`)}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,J.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.matrixTitle`)}),(0,J.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,J.jsxs)(`table`,{className:`lab-matrix`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,J.jsx)(`th`,{children:r(`lab.subjectKind`)}),cd.map(e=>(0,J.jsx)(`th`,{children:r(df[e])},e))]})}),(0,J.jsx)(`tbody`,{children:I.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`subject`,title:e.subjectId,children:Dd(e.subjectId)}),(0,J.jsx)(`td`,{className:`kind`,children:e.subjectKind||Ye(i,`subjectKindUnknown`)}),cd.map(t=>(0,J.jsx)(`td`,{children:(0,J.jsx)(gf,{rows:e.byLayer[t],t:r,selectedKey:V?.projectionKey??null,onSelect:e=>{R(e)}})},t))]},e.subjectId))})]})})]}),(0,J.jsxs)(`div`,{className:`lab-matrix-block`,children:[(0,J.jsx)(`h3`,{className:`lab-matrix-title`,children:r(`lab.verdictsTitle`)}),(0,J.jsx)(`div`,{className:`lab-matrix-scroll`,children:(0,J.jsxs)(`table`,{className:`lab-detail-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:r(`lab.col.subject`)}),(0,J.jsx)(`th`,{children:r(`lab.col.layer`)}),(0,J.jsx)(`th`,{children:r(`lab.col.suite`)}),(0,J.jsx)(`th`,{children:r(`lab.col.verdict`)}),(0,J.jsx)(`th`,{children:r(`lab.col.asOf`)})]})}),(0,J.jsx)(`tbody`,{children:F.map(e=>{let t=V?.projectionKey===e.projectionKey;return(0,J.jsxs)(`tr`,{className:t?`selected`:``,children:[(0,J.jsx)(`td`,{className:`mono`,title:e.subjectId,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-verdict-detail":e.projectionKey,"aria-pressed":t,"aria-label":Ye(i,`selectVerdict`,{subject:Dd(e.subjectId)}),onClick:()=>{R(e)},children:Dd(e.subjectId)})}),(0,J.jsx)(`td`,{children:r(uf[e.evidenceLayer])}),(0,J.jsx)(`td`,{className:`mono`,children:e.suiteId}),(0,J.jsx)(`td`,{children:(0,J.jsx)(hf,{verdict:e.verdict,caption:e.suiteId,label:r(ff[e.verdict])})}),(0,J.jsx)(`td`,{children:Od(e.asOf,i)})]},e.projectionKey)})})]})})]}),N&&(0,J.jsx)($,{tone:`err`,children:N}),H&&(0,J.jsx)(`div`,{className:`lab-load-more`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:d,onClick:()=>{L()},children:r(d?`common.loading`:`lab.loadMore`)})})]})]}),V&&(0,J.jsx)(yf,{verdict:V,detail:h,loading:v,error:b,t:r,locale:i,onClose:A})]})]})}var xf=[`catalog`,`combos`,`routing`,`compatibility`];function Sf(e){return e===`catalog`?`models`:`models/${e}`}function Cf(e=window.location.hash){let t=dt(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 wf(e){pt(Sf(e))}function Tf(e){return`models-tab-${e}`}function Ef(e){return`models-panel-${e}`}var Df={catalog:`models.tab.catalog`,combos:`models.tab.combos`,routing:`models.tab.routing`,compatibility:`models.tab.compatibility`};function Of({tab:e,onSelect:t,meta:n}){let r=Q(),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=xf.indexOf(e),r=null;t.key===`ArrowLeft`?r=(n-1+xf.length)%xf.length:t.key===`ArrowRight`?r=(n+1)%xf.length:t.key===`Home`?r=0:t.key===`End`&&(r=xf.length-1),r!==null&&(t.preventDefault(),a(xf[r]))};return(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":r(`models.tabsLabel`),children:xf.map(t=>{let s=t===e,c=n?.[t];return(0,J.jsxs)(`button`,{ref:e=>{e?i.current.set(t,e):i.current.delete(t)},type:`button`,role:`tab`,id:Tf(t),"aria-selected":s,"aria-controls":Ef(t),tabIndex:s?0:-1,className:`page-tab${s?` page-tab--active`:``}`,onClick:()=>a(t),onKeyDown:o,children:[r(Df[t]),c?(0,J.jsx)(`span`,{className:`section-tab-meta`,children:c}):null]},t)})})}function kf(e,t){let n=new Map;for(let t of e){let e=n.get(t.provider);e?e.push(t):n.set(t.provider,[t])}let r=new Map(t.map(e=>[e.name,e]));for(let e of t){if(e.disabled===!0){n.delete(e.name);continue}e.authMode!==`forward`&&(n.has(e.name)||n.set(e.name,[]))}return[...n.entries()].map(([e,t])=>{let n=r.get(e);return{provider:e,rows:t,native:t.length>0&&t.every(e=>e.native===!0),nativeProviderGroup:t.some(e=>e.native===!0),liveModels:n?.liveModels!==!1,configuredModels:n?.models??[],contextWindow:n?.contextWindow,modelContextWindows:n?.modelContextWindows,discovery:n?.discovery}}).sort((e,t)=>e.nativeProviderGroup===t.nativeProviderGroup?e.provider.localeCompare(t.provider):e.nativeProviderGroup?-1:1)}function Af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jf(e){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw Error(`invalid model list`);return[...new Set(e)]}function Mf(e){if(!Af(e))throw Error(`invalid selected models response`);let t=e.selected;if(!Af(t))throw Error(`invalid selected models response`);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,jf(t)]))}async function Nf(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 Mf(await r.json())}function Pf(e,t,n,r=!1){if(r)return!0;let i=e[t];return!i||i.length===0||i.includes(n)}function Ff(e,t,n,r,i){return Pf(e,t,n,r)&&!i}async function If(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 Lf(e,t){return e===t}function Rf(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 zf=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Bf=Array.from({length:18},(e,t)=>1e5+t*5e4),Vf=new Set(Bf),Hf=272e3,Uf=922e3,Wf=[Hf,372e3,Uf],Gf=new Set(Wf),Kf=`custom`,qf=[4,8,16,32,64,128,256,500,1e3],Jf=new Set(qf),Yf=`ocx-models-collapsed:v2`;function Xf(e){return!Number.isFinite(e)||e<=0?String(e):e%1e3==0?e>=1e6?Number((e/1e6).toFixed(2))+`M`:`${e/1e3}k`:e.toLocaleString()}function Zf(e){let t=new Set;for(let n of e)n.disabled&&t.add(n.namespaced);return t}function Qf(e,t,n,r){let i=[];for(let a of e){let e=t.has(a.id)||t.has(a.namespaced);Ff(n,a.provider,a.id,a.native===!0,e)&&i.push({value:a.namespaced,label:r?An(a.namespaced,r):a.namespaced})}return i}function $f(e=localStorage){try{let t=e.getItem(Yf);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 ep(e,t=localStorage){try{t.setItem(Yf,JSON.stringify([...e]))}catch{}}function tp({liveModels:e,discovery:t,showFailureBadge:n=!0}){let r=Q(),i=e&&t?.status===`failed`?t:void 0;return(0,J.jsxs)(`div`,{className:`row muted text-label leading-body`,role:`status`,style:{alignItems:`flex-start`,gap:8,padding:`6px 0`},children:[(0,J.jsx)(ve,{width:15,height:15,"aria-hidden":`true`,style:{flexShrink:0,marginTop:2}}),(0,J.jsxs)(`span`,{children:[i&&n&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`badge badge-amber`,children:r(`models.discoveryFailedBadge`)}),` `]}),i?`${Rf(r,i)} `:`${r(e?`models.emptyDiscovery`:`models.emptyDiscoveryDisabled`)} `,(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>pt(`providers`),children:r(`models.openProviderSettings`)})]})]})}var np={catalog:`models.subtitle`,combos:`models.subtitle.combos`,routing:`models.subtitle.routing`,compatibility:`models.subtitle.compatibility`};function rp(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 ip({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=>{Jc(e,{signal:t}).then(e=>{t?.aborted||!i.current||r(e.state)})},[e]),{restarting:o,restart:s}=$c(e,{onSettled:()=>a()});(0,_.useEffect)(()=>{let e=new AbortController;return a(e.signal),()=>e.abort()},[a,t]);let[c,l]=(0,_.useState)(Cf),[u,d]=(0,_.useState)(()=>new Set([Cf()])),f=(0,_.useCallback)(e=>{l(e),d(t=>t.has(e)?t:new Set([...t,e]))},[]);(0,_.useEffect)(()=>{let e=()=>f(Cf());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[f]);let p=(0,_.useCallback)(e=>{wf(e),f(e)},[f]),m=c===`catalog`,[h,g]=(0,_.useState)(null),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)(null),S=Q(),C=`ocx.models.catalog.v1:${e}`,w=(0,_.useMemo)(()=>fr(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)({}),[L,R]=(0,_.useState)(()=>w?.contextCaps??{}),[z,B]=(0,_.useState)(()=>w?.contextCapValue??35e4),[V,H]=(0,_.useState)(``),[U,W]=(0,_.useState)(!1),[ee,G]=(0,_.useState)({}),[q,Y]=(0,_.useState)({}),te=$f(),[ne,ie]=(0,_.useState)(()=>te??new Set),ae=(0,_.useRef)(te===null),[oe,X]=(0,_.useState)(``),[se,ce]=(0,_.useState)(!1),[ue,de]=(0,_.useState)(0),pe=(e,t)=>{ce(e),X(t),de(e=>e+1)};(0,_.useEffect)(()=>{if(!oe)return;let e=setTimeout(()=>X(``),se?6e3:8e3);return()=>clearTimeout(e)},[oe,se,ue]);let[me,he]=(0,_.useState)(!1),ye=(0,_.useRef)(!1),be=(0,_.useRef)(0),xe=(0,_.useRef)(!1),[Z,Ce]=(0,_.useState)(null),[we,Te]=(0,_.useState)({}),[Ee,De]=(0,_.useState)(null),[Oe,ke]=(0,_.useState)({providers:{},models:{},defaults:{global:!1,providers:{}}}),[Ae,je]=(0,_.useState)(!1),[Me,Ne]=(0,_.useState)(null),[Pe,Fe]=(0,_.useState)(!0),[Ie,Le]=(0,_.useState)(!1),[Re,ze]=(0,_.useState)(``),Be=(0,_.useRef)(!1),[Ve,He]=(0,_.useState)(``),[Ue,We]=(0,_.useState)(!1),[Ge,Ke]=(0,_.useState)(!1),[qe,Je]=(0,_.useState)(!1),Ye=(0,_.useCallback)(async t=>{let n=await Ft(await fetch(`${e}/api/aliases`,{signal:t}));n&&!t?.aborted&&ke(n)},[e]);(0,_.useEffect)(()=>{let e=new AbortController;return Ye(e.signal),()=>e.abort()},[Ye]);let Xe=async t=>{let n=window.prompt(S(`models.aliasPrompt`),Oe.providers[t]??``);if(n!==null){if(!(await fetch(`${e}/api/providers/${encodeURIComponent(t)}/alias`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({alias:n.trim()||null})})).ok){pe(!1,S(`models.aliasConflict`));return}await Ye(),pe(!0,S(`models.aliasSaved`))}},Ze=async(t,n)=>{let r=Oe.models[t]?.[n]?.alias??``,i=window.prompt(S(`models.modelAliasPrompt`),r);if(i===null)return;let a=i.trim()?{set:{[n]:i.trim()}}:{remove:[n]};if(!(await fetch(`${e}/api/providers/${encodeURIComponent(t)}/model-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(a)})).ok){pe(!1,S(`models.aliasConflict`));return}await Ye(),pe(!0,S(`models.aliasSaved`))},Qe=async(t,n)=>{(await fetch(`${e}/api/default-aliases`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:t,...n?{provider:n}:{}})})).ok&&await Ye()},[$e,et]=(0,_.useState)(`add`),[tt,nt]=(0,_.useState)(``),[rt,it]=(0,_.useState)(``),[at,ot]=(0,_.useState)(``),[st,ct]=(0,_.useState)(``),[lt,ut]=(0,_.useState)(``),[dt,ft]=(0,_.useState)(!1),[pt,mt]=(0,_.useState)([`text`]),[ht,gt]=(0,_.useState)(!1),[_t,vt]=(0,_.useState)([]),yt=(0,_.useRef)(!1),[bt,xt]=(0,_.useState)(!1),[St,Ct]=(0,_.useState)(``),[wt,Et]=(0,_.useState)(null),[At,jt]=(0,_.useState)([]),[Mt,Nt]=(0,_.useState)(``),[It,Lt]=(0,_.useState)(``),[Bt,Vt]=(0,_.useState)({}),[Ht,Ut]=(0,_.useState)({contextWindow:null,modelContextWindows:{}}),[Wt,Gt]=(0,_.useState)(new Set),[Kt,qt]=(0,_.useState)(!1),[Jt,Yt]=(0,_.useState)(!1),[Xt,Zt]=(0,_.useState)(``),[Qt,$t]=(0,_.useState)(null),en=(0,_.useRef)(null),[tn,nn]=(0,_.useState)(null),[rn,an]=(0,_.useState)(!1),[on,sn]=(0,_.useState)(null);(0,_.useEffect)(()=>()=>{en.current&&clearTimeout(en.current)},[]);let cn=(0,_.useMemo)(()=>Qf(T,k,j??{},S),[T,k,j,S]),ln=(0,_.useMemo)(()=>{let e=new Set(cn.map(e=>e.value));return pn(T.filter(t=>e.has(t.namespaced)),tn?.model,tn?.sourceModels)},[T,tn?.model,tn?.sourceModels,cn]),un=(0,_.useCallback)(async()=>{let t=Ln(15e3);try{let n=await Ft(await fetch(`${e}/api/shadow-call-settings`,{signal:t.signal}));n&&nn(n)}catch{}finally{t.clear()}},[e]),dn=(0,_.useCallback)(async()=>{if(Be.current)return;let t=Ln(15e3);try{let n=await fetch(`${e}/api/v2`,{signal:t.signal});if(!(n.headers.get(`content-type`)??``).includes(`application/json`)){Ce(null);return}let r=await Ft(n);if(!r||typeof r.enabled!=`boolean`){Ce(null);return}Ce({enabled:r.enabled,agentsMaxThreadsConflict:r.agentsMaxThreadsConflict===!0,maxConcurrentThreadsPerSession:typeof r.maxConcurrentThreadsPerSession==`number`?r.maxConcurrentThreadsPerSession:null,multiAgentMode:r.multiAgentMode===`v1`||r.multiAgentMode===`v2`?r.multiAgentMode:`default`,keepNativeChatGptOnV1:r.keepNativeChatGptOnV1===!0})}catch{Ce(null)}finally{t.clear(),Fe(!1)}},[e]),fn=(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}),Nf(e,fetch,t)]),[o,s,c]=await Promise.all([Pt(n),Pt(r),Pt(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=Zf(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 gr(C,f),f},[e,C]),mn=(0,_.useCallback)(e=>{let t=kf(e.models,e.providers);sn(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),B(e.contextCapValue),R(e.contextCaps)},[]),hn=ol(C,[e],async e=>{let t=await fn(e);if(e.aborted)throw Error(`models request aborted`);return mn(t),t},{isEmpty:()=>!1,pollMs:1e4,initialData:w??void 0,enabled:m,deadlineMs:6e4}),gn=hn.state,_n=(0,_.useCallback)(async(e=!1)=>{if(xe.current&&!e)return!1;xe.current=!0;let t=++be.current;try{let e=await fn(new AbortController().signal);return Lf(t,be.current)?(mn(e),K(C,e),!0):!1}catch{return!1}finally{Lf(t,be.current)&&(xe.current=!1)}},[mn,C,fn]);(0,_.useEffect)(()=>{if(!m)return;let e=window.setTimeout(()=>{un(),dn(),Gn(),Kn()},0),t=Vn(()=>{Be.current||dn()},1e4);return()=>{window.clearTimeout(e),t()}},[m,un,dn]);let vn=(0,_.useMemo)(()=>kf(T,D),[T,D]),yn=T.length>0||gn.data!==void 0,bn=e=>{let t=[...new Set([...e.rows.map(e=>e.id),...e.configuredModels,...Object.keys(e.modelContextWindows??{})])].sort(),n=t[0]??``;Et(e.provider),jt(t),Nt(n);let r=e.contextWindow?String(e.contextWindow):``,i=Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,String(t)]));Lt(r),Vt(i),Ut({contextWindow:e.contextWindow??null,modelContextWindows:Object.fromEntries(Object.entries(e.modelContextWindows??{}).map(([e,t])=>[e,t]))}),Gt(new Set),qt(!1),Zt(``)},xn=e=>{Nt(e)},Sn=async()=>{if(!wt)return;let t=rp(It);if(!vn.find(e=>e.provider===wt)){Zt(S(`models.contextSaveFailed`));return}if(Kt&&t===void 0){Zt(S(`models.contextInvalid`));return}let n={};for(let e of Wt){let t=rp(Bt[e]??``);if(t===void 0){Zt(S(`models.contextInvalid`));return}t!==(Ht.modelContextWindows[e]??null)&&(n[e]=t)}let r=Kt&&t!==Ht.contextWindow;if(!r&&Object.keys(n).length===0){Et(null),pe(!0,S(`models.contextUnchanged`));return}Yt(!0),Zt(``);try{let i={};r&&(i.contextWindow=t),Object.keys(n).length>0&&(i.modelContextWindows=n),await Pt(await fetch(`${e}/api/providers?name=${encodeURIComponent(wt)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i)}),S(`models.contextSaveFailed`))}catch(e){Zt(e instanceof Error?e.message:S(`models.contextSaveFailed`));return}finally{Yt(!1)}Et(null),pe(!0,S(`models.contextSaved`)),await _n(!0)};(0,_.useEffect)(()=>{if(!ae.current||vn.length===0)return;ae.current=!1;let e=new Set(vn.map(e=>e.provider));ie(e),ep(e)},[vn]);let Cn=(0,_.useMemo)(()=>j?T.filter(e=>Ff(j,e.provider,e.id,e.native===!0,k.has(e.namespaced))).length:0,[k,T,j]),wn=(0,_.useMemo)(()=>({catalog:yn?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)}),[yn,h,b,Cn,T.length,v,S]),Tn=async(t,n,r,i)=>{++be.current,he(!0),ye.current=!0,X(``);let a=null;try{(await If(e,t,n,r,i)).ok||(a=`models.saveFailed`)}catch{a=`models.networkError`}finally{let e=await _n(!0);a?(ce(!1),X(S(a))):e&&(ce(!0),X(S(`models.applied`))),he(!1),ye.current=!1}},En=async(t,n=!1)=>{he(!0),ye.current=!0,X(``);let r=L[t]===void 0;try{let i=await fetch(`${e}/api/provider-context-caps`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(r&&n?{provider:t,enabled:r,value:Uf}:{provider:t,enabled:r})});try{let e=await Pt(i,S(`models.capSaveFailed`));R(e?.caps??{}),ce(!0),X(S(`models.capApplied`)),await _n(!0)}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{he(!1),ye.current=!1}},On=e=>{ie(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),ep(n),n})},jn=e=>{ie(()=>{let t=e?new Set(vn.map(e=>e.provider)):new Set;return ep(t),t})},Mn=async t=>{he(!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 Pt(n,S(`models.capSaveFailed`));typeof e?.value==`number`&&Number.isFinite(e.value)&&e.value>0&&B(e.value),R(e?.caps??{}),ce(!0),X(S(`models.capApplied`)),await _n(!0)}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.capSaveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{he(!1),ye.current=!1}},Nn=(0,_.useMemo)(()=>{let e=vn.filter(e=>!e.native);return e.length>0&&e.every(e=>L[e.provider]===z)&&Object.keys(L).every(e=>L[e]===z)},[vn,L,z]),Pn=e=>{!Number.isSafeInteger(e)||e<=0||Mn(Nn?{value:e,setAll:!0}:{value:e})},Fn=(e,t)=>{if(t===`custom`){G(t=>({...t,[e]:!0})),Y(t=>({...t,[e]:String(L[e]??z)}));return}G(t=>({...t,[e]:!1}));let n=Number(t);Number.isSafeInteger(n)&&n>0&&n!==L[e]&&Mn({provider:e,enabled:!0,value:n})},In=e=>{let t=Number((q[e]??``).replace(/[_,\s]/g,``));if(!Number.isSafeInteger(t)||t<=0){pe(!1,S(`models.capSaveFailed`));return}G(t=>({...t,[e]:!1})),Mn({provider:e,enabled:!0,value:t})},Rn=e=>{if(e===`custom`){W(!0),H(String(z));return}W(!1);let t=Number(e);Number.isSafeInteger(t)&&t>0&&t!==z&&Pn(t)},zn=()=>{let e=Number(V.replace(/[_,\s]/g,``));if(!Number.isSafeInteger(e)||e<=0){pe(!1,S(`models.capSaveFailed`));return}W(!1),Pn(e)},Bn=()=>{Mn({setAll:!Nn})},Hn=async t=>{if(!(!tn||rn)){an(!0),nn({...tn,...t});try{await fetch(`${e}/api/shadow-call-settings`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)})}finally{an(!1)}}},Un=async t=>{if(!(!Z||Be.current)){Le(!0),Be.current=!0,ze(``),X(``);try{let n=await fetch(`${e}/api/v2`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});try{let e=await Pt(n,S(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){ce(!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`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0}),ce(!0),X(S(`models.v2Applied`)),ze((e.warnings??[]).join(` `))}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{Le(!1),Be.current=!1}}},Wn=async e=>{!Z||Z.multiAgentMode===e||await Un({multiAgentMode:e})},Gn=async()=>{try{let t=Ln(15e3),n=await Ft(await fetch(`${e}/api/model-presets`,{signal:t.signal}));Te(n?.providers??{})}catch{Te({})}},Kn=async()=>{try{let t=await fetch(`${e}/api/model-discovery`);De(await Ft(t)??null)}catch{De(null)}},qn=async(t,n)=>{await Ft(await fetch(`${e}/api/model-discovery`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({policy:t,provider:n??null})})),await Promise.all([Kn(),_n()])},Jn=async(t,n)=>{if(!Me){Ne(t);try{let r=Ln(3e4),i=await Ft(await fetch(`${e}/api/model-presets`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({provider:t,mode:n}),signal:r.signal}))??{};i.fallback===`preset-empty`?pe(!1,S(`models.presetEmpty`,{provider:t})):pe(!0,n===`all`?S(`models.presetClearedToast`,{provider:t}):S(`models.presetAppliedToast`,{provider:t,count:String(i.selected?.length??0)})),await Promise.all([Gn(),_n()])}catch(e){pe(!1,e instanceof Error?e.message:String(e))}finally{Ne(null)}}},Yn=async e=>{!Z||Z.keepNativeChatGptOnV1===e||await Un({keepNativeChatGptOnV1:e})},Xn=async t=>{if(!(!Z||Be.current)){if(!Number.isInteger(t)||t<1){pe(!1,S(`models.v2ThreadsInvalid`));return}if(Z.maxConcurrentThreadsPerSession!==t){Le(!0),Be.current=!0,ze(``),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 Pt(n,S(`models.saveFailed`));if(!e||typeof e.enabled!=`boolean`){ce(!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`,keepNativeChatGptOnV1:e.keepNativeChatGptOnV1===!0}),ce(!0),X(S(`models.v2ThreadsApplied`)),We(!1)}catch(e){ce(!1),X(e instanceof Error?e.message:S(`models.saveFailed`))}}catch{ce(!1),X(S(`models.networkError`))}finally{Le(!1),Be.current=!1}}}},Zn=e=>{if(e===`custom`){We(!0),He(String(Z?.maxConcurrentThreadsPerSession??``));return}We(!1),Xn(Number(e))},Qn=(e,t)=>{en.current&&clearTimeout(en.current),en.current=setTimeout(()=>{$t({namespaced:e,rect:t.getBoundingClientRect()})},300)},$n=(e,t)=>{en.current&&clearTimeout(en.current),$t({namespaced:e,rect:t.getBoundingClientRect()})},er=()=>{en.current&&clearTimeout(en.current),en.current=setTimeout(()=>$t(null),120)},tr=()=>{en.current&&clearTimeout(en.current)},nr=async(t,n,r,i,a,o)=>{xt(!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 Pt(s,S(`models.customSaveFailed`)),Je(!1),pe(!0,S(`models.customAdded`)),await _n(!0)}catch(e){Ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{Ct(S(`models.networkError`))}finally{xt(!1)}},rr=async(t,n)=>{xt(!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 Pt(r,S(`models.customSaveFailed`)),Je(!1),pe(!0,S(`models.customUpdated`)),await _n(!0)}catch(e){Ct(e instanceof Error?e.message:S(`models.customSaveFailed`))}}catch{Ct(S(`models.networkError`))}finally{xt(!1)}},ir=async t=>{try{(await fetch(`${e}/api/custom-models/${encodeURIComponent(t)}`,{method:`DELETE`})).ok?(pe(!0,S(`models.customDeleted`)),await _n(!0)):pe(!1,S(`models.customSaveFailed`))}catch{pe(!1,S(`models.networkError`))}},ar=gn.data??w,or=gn.kind===`failed-cold`?gn.error instanceof Error?gn.error.message:S(`models.loadFail`):null,sr=gn.showSkeleton&&!ar,cr=j??{},lr=e=>{let{provider:t,rows:n,nativeProviderGroup:r,liveModels:i,discovery:a}=e,o=ne.has(t),s=e=>Ff(cr,t,e.id,e.native===!0,k.has(e.namespaced)),c=n.filter(s).length,l=Ee?.recentArrivals[t]??[],u=new Set(l.map(e=>e.id)),d=L[t]!==void 0,f=L[t]??z,p=n.reduce((e,t)=>{let n=typeof t.contextWindow==`number`&&t.contextWindow>0?t.contextWindow:void 0;return n===void 0?e:e===void 0||n>e?n:e},void 0),m=d?f:r?Hf:p??f,h=e.nativeProviderGroup?Wf:Bf,g=e.nativeProviderGroup?Gf:Vf,_=i&&a?.status===`failed`?a:void 0,v=(N[t]??``).trim().toLowerCase(),y=v?n.filter(e=>e.id.toLowerCase().includes(v)):n,b=y.toSorted((e,t)=>Number(!s(e))-Number(!s(t))),x=F[t]??60,C=b.slice(0,x),w=y.length-C.length,T=n.length>0,E=!T||n.every(s),D=!T||n.every(e=>!s(e)),O=e=>{T&&Tn(`provider`,t,n.map(e=>({id:e.id,native:e.native===!0})),e)};return(0,J.jsxs)(`div`,{className:`card models-provider-card`,children:[(0,J.jsxs)(`div`,{className:`row group-head models-provider-head${o?``:` open`}`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`row models-provider-toggle`,onClick:()=>On(t),"aria-expanded":!o,style:{flex:`1 1 auto`,border:0,background:`transparent`,padding:0,color:`inherit`,cursor:`pointer`,textAlign:`left`},children:[(0,J.jsx)(Se,{style:{width:14,height:14,color:`var(--muted)`,transform:o?`none`:`rotate(90deg)`,transition:`transform .12s`}}),(0,J.jsx)(`span`,{className:`text-body font-semibold`,style:{whiteSpace:`nowrap`},children:kn(t)}),Oe.providers[t]&&(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:Oe.providers[t]}),r&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.nativeGroupLabel`)}),_&&(0,J.jsx)(`span`,{className:`badge badge-amber`,role:`status`,title:Rf(S,_),children:S(`models.discoveryFailedBadge`)}),(0,J.jsx)(`span`,{className:`muted mono text-label`,children:S(`models.active`,{active:c,total:n.length})}),l.length>0&&(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:S(`models.newCount`,{count:l.length})})]}),(0,J.jsxs)(`div`,{className:`row models-provider-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":S(`models.editProviderAlias`),title:S(`models.editProviderAlias`),onClick:()=>void Xe(t),children:(0,J.jsx)(ge,{style:{width:14,height:14}})}),(0,J.jsx)(Tt,{on:Oe.defaults.providers[t]??Oe.defaults.global,onClick:()=>void Qe(!(Oe.defaults.providers[t]??Oe.defaults.global),t),label:S(`models.useDefaultAliases`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>bn(e),"aria-haspopup":`dialog`,children:S(`models.contextSettings`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:e=>{e.stopPropagation(),et(`add`),nt(t),it(``),ot(``),ct(``),ut(``),ft(!1),mt([`text`]),gt(!1),vt([]),yt.current=!1,Ct(``),Je(!0)},"aria-label":S(`models.customAdd`),"aria-haspopup":`dialog`,children:`+`}),(()=>{let e=we[t];if(!e)return null;let n=Me===t,r=e.mode===`custom`&&e.appliedVersion!==void 0&&e.appliedVersion<e.availableVersion;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.presetLabel`),children:[[`preset`,`all`].map(r=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.mode===r,className:`btn btn-sm${e.mode===r?` btn-primary`:` btn-ghost`}`,style:{background:e.mode===r?void 0:`transparent`,color:e.mode===r?void 0:`var(--muted)`},disabled:me||n,onClick:n=>{n.stopPropagation(),!(r===`preset`&&e.mode===`custom`&&!confirm(S(`models.presetConfirmReplace`,{count:String(e.presetCount)})))&&Jn(t,r)},children:S(`models.presetMode_${r}`)},r)),e.mode===`custom`&&(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":!0,className:`btn btn-sm btn-primary`,disabled:!0,children:S(`models.presetMode_custom`)})]}),e.mode===`preset`&&(0,J.jsx)(`span`,{className:`muted mono text-label`,children:S(`models.presetSummary`,{count:String(e.presetCount),total:String(e.totalCount),version:String(e.availableVersion)})}),r&&(0,J.jsx)(`span`,{className:`badge badge-amber`,role:`status`,children:S(`models.presetUpdateAvailable`,{version:String(e.availableVersion)})})]})})(),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:me||E,onClick:()=>O(!0),children:S(`models.allOn`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,disabled:me||D,onClick:()=>O(!1),children:S(`models.allOff`)}),(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Tt,{on:d,onClick:()=>En(t,r),disabled:me,label:S(`models.capValue`,{value:Xf(m)})}),(d||r)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Dt,{value:ee[t]?`custom`:String(m),options:[...!g.has(m)&&!ee[t]?[{value:String(m),label:Xf(m)}]:[],...h.map(e=>({value:String(e),label:Xf(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>Fn(t,e),disabled:me||!d,label:S(`models.capValue`,{value:Xf(m)})}),ee[t]&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:q[t]??``,onChange:e=>Y(n=>({...n,[t]:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&In(t)},disabled:me,"aria-label":S(`models.customPlaceholder`)}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>In(t),disabled:me,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]})]})]})]})]}),!o&&(0,J.jsxs)(`div`,{className:`models-provider-body`,children:[r&&(0,J.jsx)(`p`,{className:`muted text-label models-provider-hint`,children:S(`models.nativeHint`)}),!r&&Ee&&(0,J.jsxs)(`div`,{className:`row models-provider-hint`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:S(`models.newPolicyProvider`)}),(0,J.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.newPolicyProvider`),children:[`off`,`on`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Ee.providers[t]??`inherit`)===e,className:`btn btn-sm${(Ee.providers[t]??`inherit`)===e?` btn-primary`:` btn-ghost`}`,onClick:()=>void qn(e,t),children:S(`models.newPolicy_${e}`)},e))})]}),n.length===0&&(0,J.jsx)(tp,{liveModels:i,discovery:a,showFailureBadge:!1}),n.length>30&&(0,J.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`)}),C.map(e=>{let n=!s(e);return(0,J.jsxs)(`div`,{className:`model-row-wrap`,onMouseEnter:t=>Qn(e.namespaced,t.currentTarget),onMouseLeave:er,onFocus:t=>$n(e.namespaced,t.currentTarget),onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||$t(null)},children:[(0,J.jsxs)(`div`,{className:`row models-model-row`,children:[(0,J.jsx)(Tt,{on:!n,onClick:()=>void Tn(`models`,t,[{id:e.id,native:e.native===!0}],n),disabled:me,label:e.native?e.id:e.namespaced}),Oe.models[t]?.[e.id]&&(0,J.jsx)(`strong`,{className:`mono text-control`,children:Oe.models[t][e.id].alias}),(0,J.jsx)(`code`,{className:`mono text-control`,style:{color:n?`var(--faint)`:`var(--text)`,textDecoration:n?`line-through`:`none`},children:e.native?il(e.id):An(e.namespaced,S)}),Oe.models[t]?.[e.id]?.source===`builtin`&&(0,J.jsx)(`span`,{className:`models-chip muted text-caption`,children:S(`models.aliasAuto`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":S(`models.editModelAlias`),title:S(`models.editModelAlias`),onClick:()=>void Ze(t,e.id),children:(0,J.jsx)(ge,{style:{width:13,height:13}})}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.customBadge`)}),!e.custom&&u.has(e.id)&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:S(`models.newBadge`)}),e.contextCapped&&(0,J.jsx)(`span`,{className:`models-chip muted mono text-caption`,children:S(`models.contextCappedValue`,{value:Xf(e.contextCap??z)})})]}),Qt?.namespaced===e.namespaced&&(()=>{let t=Qt.rect,r=t.bottom+4,i=r+360>window.innerHeight;return(0,J.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:tr,onMouseLeave:er,children:[(0,J.jsx)(`div`,{className:`model-tip-id`,children:e.native?e.id:e.namespaced}),e.displayName&&(0,J.jsx)(`div`,{className:`model-tip-display`,children:e.displayName}),e.custom&&(0,J.jsx)(`span`,{className:`models-chip models-chip--tip muted mono text-caption`,children:S(`models.customBadge`)}),(0,J.jsxs)(`div`,{className:`model-tip-grid`,children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipProvider`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:Dn(e.provider,S)}),(e.contextWindow||e.contextCap)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipContext`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:Xf(e.contextWindow??e.contextCap??0)})]}),e.inputModalities&&e.inputModalities.length>0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipModalities`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:e.inputModalities.join(`, `)})]}),(0,J.jsx)(`span`,{className:`model-tip-key`,children:S(`models.tipStatus`)}),(0,J.jsx)(`span`,{className:`model-tip-val`,children:S(n?`models.tipDisabled`:`models.tipActive`)})]}),e.custom&&e.customId&&(0,J.jsxs)(`div`,{className:`model-tip-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>{et(`edit`),nt(e.provider),it(e.customId),ot(e.id),ct(e.displayName??``),ut(e.contextWindow?String(e.contextWindow):``),ft(!1),mt(e.inputModalities??[`text`]),gt(Array.isArray(e.reasoningEfforts)),vt(e.reasoningEfforts??[]),yt.current=Array.isArray(e.reasoningEfforts),Ct(``),Je(!0),$t(null)},children:S(`models.customEdit`)}),(0,J.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}))&&ir(e.customId),$t(null)},children:S(`models.customDelete`)})]})]})})()]},e.namespaced)}),w>0&&(0,J.jsx)(`button`,{type:`button`,onClick:()=>I(e=>({...e,[t]:x+60})),className:`btn btn-ghost btn-sm models-show-more`,children:S(`models.showMore`,{n:w})})]})]},t)},ur=on?vn.filter(e=>e.provider===on):vn,dr=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`models-control-top-row`,children:[Ee&&(0,J.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,children:[(0,J.jsx)(`span`,{className:`models-shadow-label`,children:S(`models.newPolicyGlobal`)}),(0,J.jsx)(Tt,{on:Ee.policy===`off`,onClick:()=>void qn(Ee.policy===`off`?`on`:`off`),label:S(`models.newPolicyGlobal`)})]}),(0,J.jsxs)(`div`,{className:`row`,children:[(0,J.jsx)(Tt,{on:Oe.defaults.global,onClick:()=>void Qe(!Oe.defaults.global),label:S(`models.useDefaultAliasesGlobal`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>je(e=>!e),children:S(`models.aliases`)})]}),(0,J.jsxs)(`div`,{className:`models-shadow-row row muted text-control`,"aria-busy":!tn||void 0,children:[(0,J.jsxs)(`span`,{className:`models-shadow-label`,children:[S(`models.shadowCallIntercept`),` `,(0,J.jsx)(kt,{content:S(`models.shadowCallInterceptHint`,{models:Rt(tn?.sourceModels)}),side:`top`,maxWidth:320,children:(0,J.jsx)(`span`,{style:{cursor:`help`},"aria-label":S(`models.shadowCallInterceptHint`,{models:Rt(tn?.sourceModels)}),children:`ⓘ`})})]}),(0,J.jsx)(`code`,{className:`text-caption models-shadow-warning`,style:{opacity:.6},children:S(`models.shadowCallOriginal`,{models:zt(tn?.sourceModels)})}),(0,J.jsx)(Tt,{on:tn?.enabled??!1,onClick:()=>void Hn({enabled:!tn?.enabled}),disabled:!tn||rn,label:S(`models.shadowCallIntercept`)}),(0,J.jsx)(`div`,{className:`models-shadow-model-slot`,children:(0,J.jsx)(Dt,{value:tn?.model??``,options:ln,onChange:e=>{nn(t=>t&&{...t,model:e}),Hn({model:e})},disabled:!tn||rn||!tn.enabled,label:S(`models.shadowCallIntercept`)})})]}),(Pe||Z)&&(0,J.jsxs)(`div`,{className:`models-v2-mode-row row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2Label`)}),(0,J.jsx)(`div`,{className:`segmented models-segmented`,role:`radiogroup`,"aria-label":S(`models.v2Label`),children:[`v1`,`default`,`v2`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":(Z?.multiAgentMode??`default`)===e,className:`btn btn-sm${(Z?.multiAgentMode??`default`)===e?` btn-primary`:` btn-ghost`}`,style:{background:(Z?.multiAgentMode??`default`)===e?void 0:`transparent`,color:(Z?.multiAgentMode??`default`)===e?void 0:`var(--muted)`},disabled:!Z||Ie,onClick:()=>void Wn(e),children:S(`models.v2Mode_${e}`)},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,style:{width:24,height:24,minWidth:24,flex:`0 0 24px`,padding:0,borderRadius:`var(--radius-pill)`,color:`var(--muted)`},disabled:!Z,onClick:()=>Ke(!0),"aria-label":S(`models.v2Label`),"aria-haspopup":`dialog`,children:(0,J.jsx)(ve,{width:14,height:14,"aria-hidden":`true`})})]}),Z&&Z.multiAgentMode===`v2`&&(0,J.jsx)(`div`,{className:`models-v2-keep-native-row`,children:(0,J.jsxs)(`div`,{className:`models-v2-keep-native`,children:[(0,J.jsx)(`span`,{className:`models-v2-keep-native-label text-caption`,children:S(`models.keepNativeOnV1`)}),(0,J.jsx)(Tt,{on:Z.keepNativeChatGptOnV1===!0,onClick:()=>void Yn(!Z.keepNativeChatGptOnV1),disabled:Ie,label:S(`models.keepNativeOnV1`)}),(0,J.jsx)(kt,{content:S(`models.keepNativeOnV1Hint`),side:`top`,maxWidth:360,children:(0,J.jsx)(`span`,{className:`models-v2-keep-native-info`,"aria-label":S(`models.keepNativeOnV1Hint`),children:(0,J.jsx)(ve,{width:13,height:13,"aria-hidden":`true`})})})]})})]}),Z&&(Z.enabled||Z.agentsMaxThreadsConflict||Re)&&(0,J.jsxs)(`div`,{className:`models-v2-detail-row row`,children:[Z.enabled&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:S(`models.v2ThreadsLabel`)}),(0,J.jsx)(Dt,{value:Ue?`custom`:Z.maxConcurrentThreadsPerSession!==null&&Z.maxConcurrentThreadsPerSession!==void 0?Jf.has(Z.maxConcurrentThreadsPerSession)?String(Z.maxConcurrentThreadsPerSession):`custom`:``,options:[...Z.maxConcurrentThreadsPerSession===null||Z.maxConcurrentThreadsPerSession===void 0?[{value:``,label:S(`models.v2ThreadsDefault`)}]:[],...Z.maxConcurrentThreadsPerSession!==null&&Z.maxConcurrentThreadsPerSession!==void 0&&!Jf.has(Z.maxConcurrentThreadsPerSession)&&!Ue?[{value:`custom`,label:String(Z.maxConcurrentThreadsPerSession)}]:[],...qf.map(e=>({value:String(e),label:String(e)})),{value:`custom`,label:S(`models.custom`)}],onChange:e=>Zn(e),disabled:Ie,label:S(`models.v2ThreadsLabel`)}),Ue&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:100},inputMode:`numeric`,value:Ve,onChange:e=>He(e.target.value),onKeyDown:e=>{e.key===`Enter`&&Xn(Number(Ve.replace(/[_,\s]/g,``)))},disabled:Ie,"aria-label":S(`models.v2ThreadsLabel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:Ie,onClick:()=>{Xn(Number(Ve.replace(/[_,\s]/g,``)))},children:S(`models.v2ThreadsApply`)})]})]}),Z.enabled&&Z.agentsMaxThreadsConflict&&(0,J.jsx)(`span`,{className:`mono text-label`,style:{color:`var(--err, #e5484d)`},children:S(`models.v2Conflict`)}),Re&&(0,J.jsx)(`span`,{className:`muted text-label`,children:Re})]}),(0,J.jsxs)(`div`,{className:`row models-cap-row`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:S(`models.contextCapLabel`)}),(0,J.jsx)(Dt,{value:U?Kf:String(z),options:[...!Vf.has(z)&&!U?[{value:String(z),label:Xf(z)}]:[],...Bf.map(e=>({value:String(e),label:Xf(e)})),{value:Kf,label:S(`models.custom`)}],onChange:e=>Rn(e),disabled:me,label:S(`models.contextCapLabel`)}),U&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`input`,{className:`input`,style:{width:160},inputMode:`numeric`,placeholder:S(`models.customPlaceholder`),value:V,onChange:e=>H(e.target.value),onKeyDown:e=>{e.key===`Enter`&&zn()},disabled:me,"aria-label":S(`models.customPlaceholder`)}),(0,J.jsx)(`button`,{type:`button`,onClick:zn,disabled:me,className:`btn btn-ghost btn-sm`,children:S(`models.customApply`)})]}),(0,J.jsx)(Tt,{on:Nn,onClick:Bn,disabled:me,label:S(`models.setAll`)}),(0,J.jsx)(`span`,{className:`muted text-label leading-body`,children:S(`models.setAllHint`,{value:Xf(z)})})]}),(()=>{let e=T.filter(e=>e.custom).length;return e===0?null:(0,J.jsx)(`div`,{className:`row muted text-label models-custom-summary`,children:(0,J.jsx)(`span`,{className:`models-chip mono text-caption`,children:S(`models.customSummary`,{count:e})})})})(),(0,J.jsxs)(`div`,{className:`row muted text-label leading-body models-order-hint`,children:[(0,J.jsx)(ve,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:S(`models.orderHint`)})]})]}),pr=(0,J.jsxs)(`div`,{className:`row models-collapse-controls`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>jn(!0),disabled:me,children:[(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`}),` `,S(`models.collapseAll`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>jn(!1),disabled:me,children:[(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,S(`models.expandAll`)]})]}),mr=(0,J.jsx)(J.Fragment,{children:vn.length===0&&(0,J.jsx)(Ot,{icon:(0,J.jsx)(re,{}),title:S(`models.noRouted`),children:S(`models.noRoutedHint`)})}),hr=(0,J.jsxs)(J.Fragment,{children:[Ge&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.v2Label`),onClick:()=>Ke(!1),onKeyDown:e=>{e.key===`Escape`&&Ke(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:S(`models.v2Label`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Ke(!1),"aria-label":S(`common.close`),children:`×`})]}),(0,J.jsx)(`div`,{className:`modal-desc leading-relaxed`,style:{whiteSpace:`pre-line`},children:S(`models.v2Help`)}),(0,J.jsx)(`div`,{className:`models-help-link`,children:(0,J.jsx)(`a`,{className:`text-control`,href:`https://opencodex.me/guides/sub-agent-surface/`,target:`_blank`,rel:`noreferrer`,style:{color:`var(--accent)`},children:S(`models.v2DocsLink`)})}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>Ke(!1),children:S(`common.ok`)})})]})}),wt&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.contextSettings`),onClick:()=>{Jt||Et(null)},onKeyDown:e=>{e.key===`Escape`&&!Jt&&Et(null)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:S(`models.contextSettingsTitle`,{provider:Dn(wt,S)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Et(null),disabled:Jt,"aria-label":S(`common.close`),children:`×`})]}),Xt&&(0,J.jsx)($,{tone:`err`,children:Xt}),(0,J.jsx)(`p`,{className:`modal-desc leading-relaxed`,children:S(`models.contextHint`)}),(0,J.jsxs)(`div`,{className:`models-context-fields`,children:[(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextDefault`),(0,J.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:It,onChange:e=>{Lt(e.target.value),qt(!0)},disabled:Jt,placeholder:S(`models.contextAutomatic`),autoFocus:!0})]}),At.length>0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.contextModel`),(0,J.jsx)(Dt,{value:Mt,options:At.map(e=>({value:e,label:e})),onChange:xn,disabled:Jt,label:S(`models.contextModel`)})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.contextModelOverride`),(0,J.jsx)(`input`,{className:`input`,inputMode:`numeric`,value:Bt[Mt]??``,onChange:e=>{Vt(t=>({...t,[Mt]:e.target.value})),Gt(e=>new Set(e).add(Mt))},disabled:Jt,placeholder:S(`models.contextAutomatic`)})]})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Et(null),disabled:Jt,children:S(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void Sn(),disabled:Jt,children:S(Jt?`models.customSaving`:`models.customApply`)})]})]})}),qe&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-label":S(`models.customAdd`),onClick:()=>{bt||Je(!1)},onKeyDown:e=>{e.key===`Escape`&&!bt&&Je(!1)},children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{children:S($e===`add`?`models.customAddTitle`:`models.customEditTitle`,{provider:Dn(tt,S)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>Je(!1),disabled:bt,"aria-label":S(`common.close`),children:`×`})]}),St&&(0,J.jsx)($,{tone:`err`,children:St}),(0,J.jsxs)(`div`,{className:`models-field-stack`,children:[(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldModelId`),(0,J.jsx)(`input`,{className:`input`,value:at,onChange:e=>ot(e.target.value),disabled:bt,placeholder:S(`models.customFieldModelIdPlaceholder`),autoFocus:!0})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldDisplayName`),(0,J.jsx)(`input`,{className:`input`,value:st,onChange:e=>ct(e.target.value),disabled:bt,placeholder:S(`models.customFieldDisplayNamePlaceholder`)})]}),(0,J.jsxs)(`label`,{className:`text-label models-field`,children:[S(`models.customFieldContext`),(0,J.jsxs)(`div`,{className:`row models-field-row`,children:[(0,J.jsx)(Dt,{value:dt?`custom`:lt,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`){ft(!0);return}ft(!1),ut(e)},disabled:bt,label:S(`models.customFieldContext`)}),dt&&(0,J.jsx)(`input`,{className:`input`,style:{width:120},inputMode:`numeric`,value:lt,onChange:e=>ut(e.target.value),disabled:bt,placeholder:S(`models.customPlaceholder`),"aria-label":S(`models.customFieldContext`)})]})]}),(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldModalities`),(0,J.jsx)(`div`,{className:`row models-field-row`,children:[`text`,`image`,`audio`].map(e=>(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:pt.includes(e),onChange:t=>{mt(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:bt}),(0,J.jsx)(`span`,{className:`text-control`,children:e})]},e))})]}),(0,J.jsxs)(`div`,{className:`text-label models-field`,children:[S(`models.customFieldReasoning`),(0,J.jsx)(`div`,{className:`row models-field-row`,children:(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:ht,onChange:e=>{if(gt(e.target.checked),e.target.checked&&!yt.current){yt.current=!0;let e=T.find(e=>e.provider===tt&&e.id===at),t=Array.isArray(e?.reasoningEfforts)?e.reasoningEfforts:void 0;vt(t??[...zf])}},disabled:bt}),(0,J.jsx)(`span`,{className:`text-control`,children:S(`models.customFieldReasoningOverride`)})]})}),ht&&(0,J.jsx)(`div`,{className:`row models-field-row`,style:{flexWrap:`wrap`},children:zf.map(e=>(0,J.jsxs)(`label`,{className:`row models-modality-option`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:_t.includes(e),onChange:t=>{vt(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))},disabled:bt}),(0,J.jsx)(`span`,{className:`text-control`,children:S(`models.reasoningEffort.${e}`)})]},e))})]})]}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>Je(!1),disabled:bt,children:S(`common.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:bt||!at.trim(),onClick:()=>{let e=at.trim(),t=st.trim(),n=lt?Number(lt.replace(/[_,\s]/g,``)):void 0,r=n&&n>0?Math.floor(n):void 0;if($e===`add`){let n=ht?_t:void 0;nr(tt,e,t||void 0,r,pt.length>0?pt:void 0,n)}else rr(rt,{modelId:e,displayName:t,contextWindow:r??null,inputModalities:pt,reasoningEfforts:ht?_t:null})},children:S(bt?`models.customSaving`:$e===`add`?`models.customAddBtn`:`models.customEditBtn`)})]})]})})]}),_r=(0,J.jsxs)(`div`,{className:`models-workspace-shell`,children:[oe&&(0,J.jsxs)(`div`,{className:`action-toast notice ${se?`notice-ok`:`notice-err`}`,role:`status`,"aria-live":`polite`,children:[se?(0,J.jsx)(le,{}):(0,J.jsx)(_e,{}),(0,J.jsx)(`span`,{children:oe})]}),gn.showError&&(0,J.jsx)($,{tone:`err`,children:S(`models.loadFail`)}),(0,J.jsxs)(`div`,{className:`models-workspace-root`,"aria-busy":gn.refreshing||void 0,children:[(0,J.jsxs)(`aside`,{className:`models-workspace-rail`,"aria-label":S(`nav.models`),children:[(0,J.jsxs)(`div`,{className:`models-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-title`,children:S(`models.workspace.providers`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-count`,children:vn.length})]}),(0,J.jsxs)(`div`,{className:`models-workspace-rail-list`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${on===null?` models-workspace-rail-row--selected`:``}`,onClick:()=>sn(null),"aria-current":on===null?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:S(`models.workspace.allProviders`)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:Cn,total:T.length})})]}),vn.map(e=>{let{provider:t,rows:n}=e,r=n.filter(e=>Ff(cr,t,e.id,e.native===!0,k.has(e.namespaced))).length;return(0,J.jsxs)(`button`,{type:`button`,className:`models-workspace-rail-row${on===t?` models-workspace-rail-row--selected`:``}`,onClick:()=>sn(t),"aria-current":on===t?`true`:void 0,children:[(0,J.jsx)(`span`,{className:`models-workspace-rail-name`,children:Dn(t,S)}),(0,J.jsx)(`span`,{className:`models-workspace-rail-meta`,children:S(`models.active`,{active:r,total:n.length})})]},t)})]})]}),(0,J.jsxs)(`section`,{className:`models-workspace-main`,"aria-label":S(`models.workspace.mainAria`),children:[dr,pr,Ae&&(0,J.jsxs)(`div`,{className:`card`,"aria-label":S(`models.aliasesTable`),children:[(0,J.jsx)(`div`,{className:`row group-head`,children:(0,J.jsx)(`strong`,{children:S(`models.aliases`)})}),Object.entries(Oe.models).flatMap(([e,t])=>Object.entries(t).map(([t,n])=>(0,J.jsxs)(`div`,{className:`row models-model-row`,children:[(0,J.jsxs)(`code`,{className:`mono text-caption`,style:{flex:1},children:[e,`/`,t]}),(0,J.jsx)(`strong`,{className:`mono text-control`,children:n.alias}),(0,J.jsx)(`span`,{className:`models-chip muted text-caption`,children:n.source===`builtin`?S(`models.aliasAuto`):S(`models.aliasUser`)}),n.stale&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:S(`models.aliasStale`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":S(`models.editModelAlias`),onClick:()=>void Ze(e,t),children:(0,J.jsx)(ge,{style:{width:13,height:13}})})]},`${e}/${t}`)))]}),(0,J.jsx)(`div`,{className:`models-provider-list`,children:ur.map(e=>lr(e))}),vn.length===0&&mr]})]}),hr]});return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:S(`nav.models`)}),(0,J.jsx)(`div`,{className:`page-head-actions`,children:(0,J.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,J.jsx)(fe,{})})})]}),(0,J.jsx)(Vc,{state:n,controller:{restarting:o,restart:s}}),(0,J.jsx)(Of,{tab:c,onSelect:p,meta:wn}),(0,J.jsx)(`p`,{className:`page-sub`,children:S(np[c])}),(0,J.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Ef(`catalog`),"aria-labelledby":Tf(`catalog`),hidden:c!==`catalog`,children:(0,J.jsx)(ul,{pageName:S(`models.tab.catalog`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:sr?(0,J.jsx)(cl,{label:S(`models.loading`),rows:5}):or===null?_r:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($,{tone:`err`,children:or}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>hn.refresh(),children:S(`common.retry`)})]})})}),(0,J.jsx)(`div`,{className:`models-tab-panel models-tab-panel--fill`,role:`tabpanel`,id:Ef(`combos`),"aria-labelledby":Tf(`combos`),hidden:c!==`combos`,children:u.has(`combos`)&&(0,J.jsx)(ul,{pageName:S(`models.tab.combos`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,J.jsx)(Su,{apiBase:e,active:c===`combos`,onCountChange:g})})}),(0,J.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Ef(`routing`),"aria-labelledby":Tf(`routing`),hidden:c!==`routing`,children:u.has(`routing`)&&(0,J.jsx)(ul,{pageName:S(`models.tab.routing`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,J.jsx)(sd,{apiBase:e,active:c===`routing`,onCountChange:y})})}),(0,J.jsx)(`div`,{className:`models-tab-panel`,role:`tabpanel`,id:Ef(`compatibility`),"aria-labelledby":Tf(`compatibility`),hidden:c!==`compatibility`,children:u.has(`compatibility`)&&(0,J.jsx)(ul,{pageName:S(`models.tab.compatibility`),title:S(`errorBoundary.title`),message:S(`errorBoundary.message`),detailsLabel:S(`errorBoundary.details`),reloadLabel:S(`errorBoundary.reload`),children:(0,J.jsx)(bf,{apiBase:e,active:c===`compatibility`,onCountChange:x})})})]})}var ap=`section`;function op(e,t){return[e,ap,t].join(`-`)}function sp(e){return[e,ap,``].join(`-`)}var cp=1200;function lp({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(op(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(op(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(op(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(sp(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(op(e,t));n&&(a.current=t,o.current!==null&&clearTimeout(o.current),o.current=setTimeout(c,cp),i(t),n.scrollIntoView({behavior:`smooth`,block:`start`}))};return(0,J.jsx)(`div`,{className:`page-tabs section-tabs`,role:`tablist`,"aria-label":n,children:t.map(t=>(0,J.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r===t.id,"aria-controls":op(e,t.id),tabIndex:r===t.id?0:-1,className:`page-tab${r===t.id?` page-tab--active`:``}`,onClick:()=>l(t.id),children:[t.label,t.meta?(0,J.jsx)(`span`,{className:`section-tab-meta`,children:t.meta}):null]},t.id))})}function up({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=Q(),m=(c.hintText??``).trim().length>0;return(0,J.jsxs)(`div`,{className:`swi-delegation`,children:[d&&(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeLoadFail`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:f,children:p(`common.retry`)})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`sub.delegation.model`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.delegation.modelHint`)})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-controls`,children:[(0,J.jsx)(Dt,{value:e,options:[{value:``,label:p(`dash.injectionNone`)},...r.map(e=>({value:e.namespaced,label:An(`${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,J.jsx)(Dt,{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,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`dash.syncCodexSubagentDefaults`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.syncCodexSubagentDefaultsHint`)})]}),(0,J.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,J.jsx)(`span`,{className:`knob`})})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`dash.multiAgentGuidance`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`dash.multiAgentGuidanceHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${i?`on`:``}`,onClick:()=>s({multiAgentGuidanceEnabled:!i}),disabled:o,"aria-label":p(`dash.multiAgentGuidance`),"aria-pressed":i,children:(0,J.jsx)(`span`,{className:`knob`})})]}),(0,J.jsxs)(`div`,{className:`swi-delegation-row`,children:[(0,J.jsxs)(`div`,{className:`setting-copy`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,children:p(`sub.ultraMode`)}),(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeHint`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`switch ${m?`on`:``}`,onClick:()=>u({multiAgentModeHintText:m?null:fp}),disabled:o||l||!m&&!c.multiAgentV2Enabled,"aria-label":p(`sub.ultraMode`),"aria-pressed":m,children:(0,J.jsx)(`span`,{className:`knob`})}),!c.multiAgentV2Enabled&&(0,J.jsx)(`div`,{className:`muted setting-hint`,children:p(`sub.ultraModeV2Required`)})]}),m&&(0,J.jsx)(`div`,{className:`swi-delegation-row swi-ultra-mode-editor`,children:(0,J.jsx)(dp,{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 dp({initialHint:e,disabled:t,onSave:n,preset:r,labels:i}){let[a,o]=(0,_.useState)(e);return(0,J.jsxs)(J.Fragment,{children:[(0,J.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,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>o(r),disabled:t,children:i.preset}),(0,J.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 fp=`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 pp({available:e,chosen:t,busy:n=!1,onToggle:r,onMove:i,onSave:a,delegation:o}){let s=Q(),[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,J.jsxs)(`div`,{className:`subagents-workspace-shell`,children:[(0,J.jsx)(lp,{scope:`subagents`,items:p,ariaLabel:s(`sub.sections`)}),(0,J.jsxs)(`div`,{className:`subagents-workspace-root`,children:[(0,J.jsxs)(`section`,{id:op(`subagents`,`featured`),className:`subagents-workspace-section`,"aria-label":s(`sub.featured`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.featured`)}),(0,J.jsxs)(`span`,{className:`swi-featured-count`,children:[t.length,`/`,5]})]}),(0,J.jsxs)(`p`,{className:`swi-featured-hint`,children:[(0,J.jsx)(ve,{width:15,height:15,"aria-hidden":`true`}),(0,J.jsx)(`span`,{children:(0,J.jsx)(ut,{k:`sub.orderHint`,cmd:`spawn_agent`})})]}),t.length===0?(0,J.jsx)(`div`,{className:`swi-featured-empty`,children:s(`sub.noneSelected`)}):(0,J.jsx)(`div`,{className:`swi-featured-list`,children:t.map((e,a)=>(0,J.jsxs)(`div`,{className:`swi-featured-row`,children:[(0,J.jsx)(`span`,{className:`swi-featured-pos`,children:a+1}),(0,J.jsx)(`span`,{className:`swi-featured-name`,children:il(e)}),(0,J.jsxs)(`span`,{className:`swi-featured-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,-1),disabled:n||a===0,"aria-label":s(`sub.moveUp`,{m:e}),children:(0,J.jsx)(be,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>i(a,1),disabled:n||a===t.length-1,"aria-label":s(`sub.moveDown`,{m:e}),children:(0,J.jsx)(xe,{})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>r(e),disabled:n,"aria-label":s(`sub.removeAria`,{m:e}),style:{color:`var(--red)`},children:(0,J.jsx)(ue,{})})]})]},e))}),(0,J.jsx)(`div`,{className:`swi-save-row`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:a,disabled:n,children:s(`common.save`)})})]}),(0,J.jsxs)(`section`,{id:op(`subagents`,`models`),className:`subagents-workspace-section`,"aria-label":s(`sub.models`),children:[(0,J.jsxs)(`div`,{className:`swi-featured-head`,children:[(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.models`)}),(0,J.jsx)(`span`,{className:`swi-featured-count`,children:f.length})]}),(0,J.jsxs)(`div`,{className:`swi-picker-box`,children:[(0,J.jsx)(`div`,{className:`subagents-workspace-rail-search`,children:(0,J.jsx)(`input`,{className:`input`,value:c,onChange:e=>l(e.target.value),placeholder:s(`sub.search`),"aria-label":s(`sub.search`)})}),(0,J.jsx)(`div`,{className:`subagents-workspace-rail-list`,children:f.length===0?(0,J.jsx)(`span`,{className:`subagents-workspace-rail-empty`,children:s(`sub.noModels`)}):f.map(e=>{let i=u.has(e),a=i?t.indexOf(e)+1:null,o=!i&&(d||n);return(0,J.jsxs)(`div`,{className:`subagents-workspace-rail-row${i?` subagents-workspace-rail-row--selected`:``}`,children:[(0,J.jsxs)(`span`,{className:`subagents-workspace-rail-row-main`,children:[(0,J.jsx)(`span`,{className:`swi-rail-priority`,children:a??``}),(0,J.jsx)(ie,{className:`swi-rail-icon`,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:`subagents-workspace-rail-name`,children:il(e)})]}),(0,J.jsx)(`button`,{type:`button`,className:`subagents-workspace-rail-toggle${i?` subagents-workspace-rail-toggle--on`:``}${o?` subagents-workspace-rail-toggle--disabled`:``}`,onClick:()=>{o||r(e)},disabled:o,"aria-pressed":i,"aria-label":s(i?`sub.workspace.removeFromFeatured`:`sub.workspace.addToFeatured`,{m:e}),title:i?s(`sub.workspace.removeFromFeatured`,{m:e}):d?s(`sub.workspace.featuredFull`):s(`sub.workspace.addToFeatured`,{m:e}),children:i?(0,J.jsx)(le,{style:{width:14,height:14}}):(0,J.jsx)(de,{style:{width:14,height:14}})})]},e)})})]})]}),(0,J.jsxs)(`section`,{id:op(`subagents`,`settings`),className:`subagents-workspace-section`,"aria-label":s(`sub.settings`),children:[(0,J.jsx)(`div`,{className:`swi-featured-head`,children:(0,J.jsx)(`h2`,{className:`swi-featured-title`,children:s(`sub.settings`)})}),(0,J.jsx)(up,{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 mp(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=Tr(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 Wt(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 Wt(n))}catch{}finally{i(!1)}}},[e,v,r])}}function hp(e){return fr(e)}function gp({apiBase:e}){let t=Q(),n=`ocx.subagents.v1:${e}`,r=hp(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=mp(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 Pt(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 Pt(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 r=>{let i=await Pt(await fetch(`${e}/api/subagent-models`,{signal:r}),t(`sub.loadFail`));if(!i)throw Error(t(`sub.loadFail`));let o=i.available??[],s=new Set(o),c={available:o,chosen:(i.chosen??[]).filter(e=>s.has(e))};return a(c.chosen),gr(n,c),c},[e,n,t]),D=ol(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 Pt(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),gr(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,J.jsx)(cl,{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,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($,{tone:`err`,children:e}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>k(),children:t(`common.retry`)})]})}return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.subagents`)})}),o&&(0,J.jsx)($,{tone:c?`ok`:`err`,children:o}),O.showError&&(0,J.jsx)($,{tone:`err`,children:t(`sub.loadFail`)}),(0,J.jsx)(pp,{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 _p(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 vp(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 yp(e,t){if(e===void 0)throw Error(`Unexpected undefined${t?`: ${t}`:``}`);return e}var bp=(e,t)=>Math.abs(e-t)<1.01,xp=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},Sp,Cp=()=>{if(Sp!==void 0)return Sp;if(typeof navigator>`u`)return Sp=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return Sp=!0;let e=navigator.maxTouchPoints;return Sp=navigator.platform===`MacIntel`&&e!==void 0&&e>0},wp=e=>{let{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},Tp=e=>e,Ep=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},Dp=(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(wp(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(wp(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(r):r()});return a.observe(n,{box:`border-box`}),()=>{a.unobserve(n)}},Op={passive:!0},kp=typeof window>`u`||`onscrollend`in window,Ap=(e,t,n)=>{let r=e.scrollElement;if(!r)return;let i=e.targetWindow;if(!i)return;let a=e.options.useScrollendEvent&&kp,o=0,s=a?null:xp(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,Op),a&&r.addEventListener(`scrollend`,u,Op),()=>{r.removeEventListener(`scroll`,l),a&&r.removeEventListener(`scrollend`,u)}},jp=(e,t)=>Ap(e,t,t=>{let{horizontal:n,isRtl:r}=e.options;return n?t.scrollLeft*(r&&-1||1):t.scrollTop}),Mp=(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`]},Np=(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})},Pp=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:Tp,rangeExtractor:Ep,onChange:()=>{},measureElement:Mp,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=vp(()=>(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,!(!Cp()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};e.addEventListener(`touchstart`,t,Op),e.addEventListener(`touchend`,n,Op),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&&(Cp()&&(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=vp(()=>[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=vp(()=>[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=_p(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=vp(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(e,t,n,r)=>e.length===0||t===0?(this.range=null,null):(this.range=Lp(e,t,n,r,r===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=vp(()=>{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=vp(()=>[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 yp(t[Fp(0,t.length-1,r?e=>n[e*2]:e=>yp(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:Cp()&&(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&&bp(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()}},Fp=(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 Ip(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 Lp(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=Ip(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=Fp(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 Rp=typeof document<`u`?_.useLayoutEffect:_.useEffect;function zp({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,mt.flushSync)(i):i()),(o=r.onChange)==null||o.call(r,t,n)}},[l]=_.useState(()=>{let e=new Pp(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),Rp(()=>l._didMount(),[]),Rp(()=>(o(l),l._willUpdate())),Rp(()=>{s(l)}),l}function Bp(e){return zp({observeElementRect:Dp,observeElementOffset:jp,scrollToFn:Np,...e})}var Vp=32;function Hp(e){return[...new Uint8Array(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function Up(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 Wp(e){let t=e.trim();if(t&&!Up(t)&&!(t.length>4096))return Hp(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(t))).slice(0,Vp)}function Gp(e,t,n){if(!e)return!1;let r=t.trim();return r?e===r||n!==void 0&&e===n:!1}var Kp={400:{en:{label:`Bad request`,description:`The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying.`},fr:{label:`Requête incorrecte`,description:`Le proxy n’a pas pu comprendre la requête. Vérifiez le modèle, la structure des messages, les en-têtes et le corps JSON avant de réessayer.`},ko:{label:`잘못된 요청`,description:`프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다.`},zh:{label:`错误请求`,description:`代理无法理解该请求。重试前请检查模型、消息结构、标头和 JSON 正文。`},"zh-TW":{label:`錯誤請求`,description:`代理無法理解該請求。重試前請檢查模型、訊息結構、標頭和 JSON 本文。`},de:{label:`Ungültige Anfrage`,description:`Der Proxy konnte die Anfrage nicht verstehen. Prüfe Modell, Nachrichtenformat, Header und JSON-Body vor einem erneuten Versuch.`},ru:{label:`Некорректный запрос`,description:`Прокси не смог интерпретировать запрос. Перед повторной попыткой проверьте модель, формат сообщений, заголовки и тело JSON.`},ja:{label:`不正なリクエスト`,description:`プロキシがリクエストを解釈できませんでした。再試行前にモデル、メッセージ形式、ヘッダー、JSON 本文を確認してください。`},tr:{label:`Hatalı istek`,description:`Proxy isteği anlayamadı. Yeniden denemeden önce modeli, mesaj yapısını, başlıkları ve JSON gövdesini kontrol edin.`}},401:{en:{label:`Unauthorized`,description:`Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex.`},fr:{label:`Non autorisé`,description:`Les identifiants sont absents, expirés ou non valides. Reconnectez-vous ou actualisez les identifiants du compte ou du fournisseur utilisés par opencodex.`},ko:{label:`인증 필요`,description:`자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다.`},zh:{label:`未授权`,description:`凭据缺失、已过期或无效。请重新登录,或刷新 opencodex 使用的账号/提供商凭据。`},"zh-TW":{label:`未授權`,description:`憑證缺失、已過期或無效。請重新登入,或重新整理 opencodex 使用的帳號/供應商憑證。`},de:{label:`Nicht autorisiert`,description:`Anmeldedaten fehlen, sind abgelaufen oder ungültig. Melde dich erneut an oder aktualisiere die von opencodex genutzten Konto-/Anbieter-Zugangsdaten.`},ru:{label:`Не авторизован`,description:`Учётные данные отсутствуют, истекли или недействительны. Войдите заново или обновите учётные данные аккаунта или провайдера, которые использует opencodex.`},ja:{label:`認証が必要`,description:`認証情報が不在・期限切れ・無効です。opencodex が使用するアカウントまたはプロバイダー認証情報を再ログインまたは更新してください。`},tr:{label:`Yetkisiz erişim`,description:`Kimlik bilgileri eksik, süresi dolmuş veya geçersiz. opencodex tarafından kullanılan hesap veya sağlayıcı kimlik bilgilerini yeniden doğrulayın.`}},402:{en:{label:`Payment required`,description:`The upstream provider rejected the request because billing, credits, or plan access is not available. Add credits, update billing, or switch provider.`},fr:{label:`Paiement requis`,description:`Le fournisseur en amont a rejeté la requête, car la facturation, les crédits ou l’accès à l’offre ne sont pas disponibles. Ajoutez des crédits, mettez à jour la facturation ou changez de fournisseur.`},ko:{label:`결제 필요`,description:`청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다.`},zh:{label:`需要付款`,description:`上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。`},"zh-TW":{label:`需要付款`,description:`上游供應商因帳單、額度或方案許可權不可用而拒絕了請求。請儲值、更新帳單資訊或切換供應商。`},de:{label:`Zahlung erforderlich`,description:`Der Upstream-Anbieter hat die Anfrage abgelehnt, weil Abrechnung, Guthaben oder Planzugriff nicht verfügbar ist. Guthaben aufladen, Abrechnung aktualisieren oder Anbieter wechseln.`},ru:{label:`Требуется оплата`,description:`Вышестоящий провайдер отклонил запрос из-за проблем с оплатой, кредитами или доступом по тарифному плану. Пополните баланс, обновите платёжные данные или переключитесь на другого провайдера.`},ja:{label:`支払いが必要`,description:`課金、クレジット、プランアクセスが利用できないため上流プロバイダーがリクエストを拒否しました。クレジット追加、支払い情報更新、プロバイダー切替が必要です。`},tr:{label:`Ödeme gerekli`,description:`Yukarı akış sağlayıcısı faturalandırma, kredi veya plan erişimi bulunmadığından isteği reddetti. Kredi ekleyin, ödeme bilgilerini güncelleyin veya sağlayıcı değiştirin.`}},403:{en:{label:`Forbidden`,description:`The account is authenticated but not allowed to use this model or operation. Often a plan/subscription gate (e.g. Ollama Cloud Pro), org policy, or model permission — not necessarily a bad API key.`},fr:{label:`Accès interdit`,description:`Le compte est authentifié, mais n’est pas autorisé à utiliser ce modèle ou cette opération. Il s’agit souvent d’une restriction liée à l’offre ou à l’abonnement (p. ex. Ollama Cloud Pro), à la politique de l’organisation ou aux autorisations du modèle — pas nécessairement d’une clé API incorrecte.`},ko:{label:`권한 없음`,description:`계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다.`},zh:{label:`禁止访问`,description:`账号已认证,但无权使用此模型或操作。常见原因是套餐/订阅限制(例如 Ollama Cloud Pro)、组织策略或模型权限——不一定是 API 密钥无效。`},"zh-TW":{label:`禁止存取`,description:`帳號已認證,但無權使用此模型或操作。常見原因是方案/訂閱限制(例如 Ollama Cloud Pro)、組織策略或模型許可權——不一定是 API 金鑰無效。`},de:{label:`Verboten`,description:`Das Konto ist authentifiziert, darf dieses Modell oder diese Operation aber nicht nutzen. Oft Plan-/Abo-Sperre (z. B. Ollama Cloud Pro), Organisationsrichtlinie oder Modellrecht — nicht zwingend ein ungültiger API-Key.`},ru:{label:`Доступ запрещён`,description:`Аккаунт аутентифицирован, но не имеет права использовать эту модель или операцию. Часто причина — ограничение тарифа или подписки (например, Ollama Cloud Pro), политика организации или права доступа к модели, а не обязательно неверный API-ключ.`},ja:{label:`アクセス禁止`,description:`アカウントは認証済みですがこのモデルや操作の使用が許可されていません。多くはプラン/サブスクリプション制限(例: Ollama Cloud Pro)、組織ポリシー、モデル権限であり、API キーが不正とは限りません。`},tr:{label:`Erişim yasaklandı`,description:`Hesabın kimliği doğrulandı ancak bu modeli veya işlemi kullanma izni yok. Genellikle plan/abonelik sınırı (örn. Ollama Cloud Pro), organizasyon politikası veya model izni kaynaklıdır.`}},404:{en:{label:`Not found`,description:`The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration.`},fr:{label:`Introuvable`,description:`La route, le modèle, le compte ou la ressource en amont demandés sont introuvables. Vérifiez le nom du modèle et la configuration du fournisseur opencodex.`},ko:{label:`찾을 수 없음`,description:`요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다.`},zh:{label:`未找到`,description:`找不到请求的路由、模型、账号或上游资源。请确认模型名称和 opencodex 提供商配置。`},"zh-TW":{label:`未找到`,description:`找不到請求的路由、模型、帳號或上游資源。請確認模型名稱和 opencodex 供應商配置。`},de:{label:`Nicht gefunden`,description:`Die angeforderte Route, das Modell, das Konto oder die Upstream-Ressource wurde nicht gefunden. Prüfe Modellname und opencodex-Anbieterkonfiguration.`},ru:{label:`Не найдено`,description:`Запрошенный маршрут, модель, аккаунт или вышестоящий ресурс не найден. Проверьте имя модели и конфигурацию провайдера в opencodex.`},ja:{label:`見つかりません`,description:`要求されたルート、モデル、アカウント、上流リソースが見つかりませんでした。モデル名と opencodex プロバイダー設定を確認してください。`},tr:{label:`Bulunamadı`,description:`İstenen rota, model, hesap veya yukarı akış kaynağı bulunamadı. Model adını ve opencodex sağlayıcı yapılandırmasını doğrulayın.`}},408:{en:{label:`Request timeout`,description:`The request took too long before the proxy or upstream provider could complete it. Retry with a smaller request or a different provider.`},fr:{label:`Délai d’attente de la requête dépassé`,description:`La requête a pris trop de temps pour que le proxy ou le fournisseur en amont puisse la traiter. Réessayez avec une requête plus petite ou un autre fournisseur.`},ko:{label:`요청 시간 초과`,description:`프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다.`},zh:{label:`请求超时`,description:`代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。`},"zh-TW":{label:`請求逾時`,description:`代理或上游供應商未能在限定時間內完成請求。請縮小請求後重試,或切換供應商。`},de:{label:`Anfrage-Timeout`,description:`Die Anfrage dauerte zu lange, bevor Proxy oder Upstream-Anbieter sie abschließen konnten. Mit kleinerer Anfrage oder anderem Anbieter erneut versuchen.`},ru:{label:`Тайм-аут запроса`,description:`Обработка запроса заняла слишком много времени, и прокси или вышестоящий провайдер не успел её завершить. Повторите попытку с меньшим запросом или через другого провайдера.`},ja:{label:`リクエストタイムアウト`,description:`プロキシまたは上流プロバイダーがリクエストを完了する前に時間切れになりました。より小さいリクエストで再試行するか、別のプロバイダーに切り替えてください。`},tr:{label:`İstek zaman aşımı`,description:`Proxy veya yukarı akış sağlayıcısı isteği tamamlayamadan zaman aşımına uğradı. Daha küçük bir istek veya farklı bir sağlayıcı ile tekrar deneyin.`}},409:{en:{label:`Conflict`,description:`The request conflicts with the current account, session, or provider state. Refresh the session or retry after the active operation finishes.`},fr:{label:`Conflit`,description:`La requête entre en conflit avec l’état actuel du compte, de la session ou du fournisseur. Actualisez la session ou réessayez une fois l’opération en cours terminée.`},ko:{label:`상태 충돌`,description:`요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다.`},zh:{label:`状态冲突`,description:`请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。`},"zh-TW":{label:`狀態衝突`,description:`請求與當前帳號、會話或供應商狀態衝突。請重新整理會話,或等待當前操作完成後重試。`},de:{label:`Konflikt`,description:`Die Anfrage kollidiert mit dem aktuellen Konto-, Sitzungs- oder Anbieterstatus. Sitzung aktualisieren oder nach Abschluss der laufenden Operation erneut versuchen.`},ru:{label:`Конфликт`,description:`Запрос конфликтует с текущим состоянием аккаунта, сессии или провайдера. Обновите сессию или повторите попытку после завершения текущей операции.`},ja:{label:`状態の衝突`,description:`リクエストが現在のアカウント、セッション、プロバイダー状態と衝突しています。セッションを更新するか、進行中の操作が終わった後に再試行してください。`},tr:{label:`Durum çakışması`,description:`İstek mevcut hesap, oturum veya sağlayıcı durumuyla çakışıyor. Oturumu yenileyin veya aktif işlem bittikten sonra tekrar deneyin.`}},413:{en:{label:`Request too large`,description:`The prompt, attachments, or generated payload exceeds a proxy or upstream limit. Reduce tokens, file size, or conversation history.`},fr:{label:`Requête trop volumineuse`,description:`L’invite, les pièces jointes ou la charge utile générée dépassent une limite du proxy ou du fournisseur en amont. Réduisez le nombre de jetons, la taille des fichiers ou l’historique de la conversation.`},ko:{label:`요청 과대`,description:`프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다.`},zh:{label:`请求过大`,description:`提示、附件或生成的负载超过了代理或上游限制。请减少 token、文件大小或对话历史。`},"zh-TW":{label:`請求過大`,description:`提示、附件或生成的負載超過了代理或上游限制。請減少 token、檔案大小或對話歷史。`},de:{label:`Anfrage zu groß`,description:`Prompt, Anhänge oder generierte Nutzlast überschreiten ein Proxy- oder Upstream-Limit. Tokens, Dateigröße oder Verlauf reduzieren.`},ru:{label:`Слишком большой запрос`,description:`Промпт, вложения или сформированная полезная нагрузка превышают лимит прокси или вышестоящего провайдера. Сократите количество токенов, размер файлов или историю диалога.`},ja:{label:`リクエストが大きすぎます`,description:`プロンプト、添付ファイル、生成ペイロードがプロキシまたは上流の制限を超えました。トークン、ファイルサイズ、会話履歴を減らしてください。`},tr:{label:`İstek çok büyük`,description:`İstemi, ekler veya oluşturulan veri proxy ya da yukarı akış sınırını aşıyor. Jeton sayısını, dosya boyutunu veya sohbet geçmişini azaltın.`}},422:{en:{label:`Invalid content`,description:`The provider accepted the request format but rejected its contents. Check model options, tool definitions, message roles, and unsupported fields.`},fr:{label:`Contenu non valide`,description:`Le fournisseur a accepté le format de la requête, mais en a rejeté le contenu. Vérifiez les options du modèle, les définitions des outils, les rôles des messages et les champs non pris en charge.`},ko:{label:`내용 검증 실패`,description:`제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다.`},zh:{label:`内容无效`,description:`提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。`},"zh-TW":{label:`內容無效`,description:`供應商接受了請求格式,但拒絕了其中的內容。請檢查模型選項、工具定義、訊息角色和不支援的欄位。`},de:{label:`Ungültiger Inhalt`,description:`Der Anbieter akzeptierte das Anfrageformat, lehnte den Inhalt aber ab. Prüfe Modelloptionen, Tool-Definitionen, Nachrichtenrollen und nicht unterstützte Felder.`},ru:{label:`Недопустимое содержимое`,description:`Провайдер принял формат запроса, но отклонил его содержимое. Проверьте параметры модели, определения инструментов, роли сообщений и неподдерживаемые поля.`},ja:{label:`内容の検証失敗`,description:`プロバイダーはリクエスト形式を受け付けましたが内容を拒否しました。モデルオプション、ツール定義、メッセージロール、未サポートのフィールドを確認してください。`},tr:{label:`Geçersiz içerik`,description:`Sağlayıcı istek formatını kabul etti ancak içeriğini reddetti. Model seçeneklerini, araç tanımlarını, mesaj rollerini ve desteklenmeyen alanları kontrol edin.`}},424:{en:{label:`Provider dependency failed`,description:`A required upstream dependency failed while opencodex was routing the request. Retry later or switch to another configured provider.`},fr:{label:`Échec d’une dépendance du fournisseur`,description:`Une dépendance en amont requise a échoué pendant le routage de la requête par opencodex. Réessayez plus tard ou sélectionnez un autre fournisseur configuré.`},ko:{label:`제공자 의존성 실패`,description:`opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다.`},zh:{label:`提供商依赖失败`,description:`opencodex 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。`},"zh-TW":{label:`供應商依賴失敗`,description:`opencodex 路由請求時,必需的上游依賴失敗。請稍後重試,或切換到另一個已配置的供應商。`},de:{label:`Anbieter-Abhängigkeit fehlgeschlagen`,description:`Eine erforderliche Upstream-Abhängigkeit ist fehlgeschlagen, während opencodex die Anfrage geroutet hat. Später erneut versuchen oder zu einem anderen Anbieter wechseln.`},ru:{label:`Сбой зависимости провайдера`,description:`Необходимая вышестоящая зависимость дала сбой, пока opencodex маршрутизировал запрос. Повторите попытку позже или переключитесь на другого настроенного провайдера.`},ja:{label:`プロバイダー依存の失敗`,description:`opencodex がリクエストをルーティング中に必要な上流依存が失敗しました。後で再試行するか、別の設定済みプロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı bağımlılığı başarısız`,description:`opencodex isteği yönlendirirken gerekli bir yukarı akış bağımlılığı başarısız oldu. Daha sonra tekrar deneyin veya başka bir sağlayıcıya geçin.`}},429:{en:{label:`Rate limited`,description:`The upstream provider rate or quota limit has been reached. Wait for the quota window to reset or switch account/provider.`},fr:{label:`Limite de débit atteinte`,description:`La limite de débit ou de quota du fournisseur en amont a été atteinte. Attendez la réinitialisation de la fenêtre de quota ou changez de compte ou de fournisseur.`},ko:{label:`한도 초과`,description:`업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다.`},zh:{label:`限流`,description:`已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。`},"zh-TW":{label:`限流`,description:`已達到上游供應商的速率或額度限制。請等待額度視窗重設,或切換帳號/供應商。`},de:{label:`Ratenlimit erreicht`,description:`Das Raten- oder Kontingentlimit des Upstream-Anbieters ist erreicht. Auf Reset des Kontingentfensters warten oder Konto/Anbieter wechseln.`},ru:{label:`Превышен лимит запросов`,description:`Достигнут лимит скорости или квота вышестоящего провайдера. Дождитесь сброса окна квоты или переключитесь на другой аккаунт или провайдера.`},ja:{label:`レート制限`,description:`上流プロバイダーのレートまたはクォータ制限に達しました。クォータウィンドウがリセットされるまで待つか、アカウント/プロバイダーを切り替えてください。`},tr:{label:`Oran sınırı aşıldı`,description:`Yukarı akış sağlayıcısının hız veya kota sınırına ulaşıldı. Kota penceresinin sıfırlanmasını bekleyin ya da hesap/sağlayıcı değiştirin.`}},499:{en:{label:`Client closed request`,description:`The client disconnected or canceled the request before opencodex finished routing it. Retry if the cancellation was accidental.`},fr:{label:`Requête fermée par le client`,description:`Le client s’est déconnecté ou a annulé la requête avant la fin de son routage par opencodex. Réessayez si l’annulation était involontaire.`},ko:{label:`클라이언트 취소`,description:`opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다.`},zh:{label:`客户端已取消`,description:`opencodex 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。`},"zh-TW":{label:`客戶端已取消`,description:`opencodex 完成路由前,客戶端已斷開連線或取消請求。如果不是有意取消,請重試。`},de:{label:`Client hat Anfrage geschlossen`,description:`Der Client hat die Verbindung getrennt oder die Anfrage abgebrochen, bevor opencodex das Routing abgeschlossen hat. Bei versehentlichem Abbruch erneut versuchen.`},ru:{label:`Запрос закрыт клиентом`,description:`Клиент отключился или отменил запрос до того, как opencodex завершил его маршрутизацию. Если отмена была случайной, повторите попытку.`},ja:{label:`クライアントがリクエストをクローズ`,description:`opencodex がルーティングを終える前にクライアントが切断またはキャンセルしました。意図しないキャンセルなら再試行してください。`},tr:{label:`İstemci isteği kapattı`,description:`opencodex yönlendirmeyi bitirmeden önce istemci bağlantıyı kesti veya isteği iptal etti. İptal kazara yapıldıysa tekrar deneyin.`}},500:{en:{label:`Proxy error`,description:`opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats.`},fr:{label:`Erreur du proxy`,description:`opencodex a rencontré une erreur interne lors du traitement de la requête. Réessayez une fois, puis consultez les journaux du proxy si l’erreur se reproduit.`},ko:{label:`프록시 오류`,description:`opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다.`},zh:{label:`代理错误`,description:`opencodex 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。`},"zh-TW":{label:`代理錯誤`,description:`opencodex 處理請求時發生內部錯誤。請先重試一次;如果重複出現,請檢查代理日誌。`},de:{label:`Proxy-Fehler`,description:`opencodex ist bei der Anfragebearbeitung auf einen internen Fehler gestoßen. Einmal erneut versuchen, bei Wiederholung Proxy-Logs prüfen.`},ru:{label:`Ошибка прокси`,description:`В opencodex произошла внутренняя ошибка при обработке запроса. Повторите попытку один раз; если ошибка повторяется, проверьте логи прокси.`},ja:{label:`プロキシエラー`,description:`opencodex がリクエスト処理中に内部エラーに遭遇しました。1 回再試行し、繰り返す場合はプロキシログを確認してください。`},tr:{label:`Proxy hatası`,description:`opencodex isteği işlerken dahili bir hatayla karşılaştı. Bir kez tekrar deneyin, tekrarlarsa proxy günlüklerini kontrol edin.`}},502:{en:{label:`Bad upstream response`,description:`The upstream provider returned an invalid or failed response through the proxy. Retry or route the request to another provider.`},fr:{label:`Réponse incorrecte du fournisseur en amont`,description:`Le fournisseur en amont a renvoyé une réponse non valide ou en échec par l’intermédiaire du proxy. Réessayez ou acheminez la requête vers un autre fournisseur.`},ko:{label:`업스트림 응답 오류`,description:`업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`上游响应错误`,description:`上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。`},"zh-TW":{label:`上游回應錯誤`,description:`上游供應商透過代理返回了無效或失敗的回應。請重試,或將請求路由到其他供應商。`},de:{label:`Ungültige Upstream-Antwort`,description:`Der Upstream-Anbieter lieferte über den Proxy eine ungültige oder fehlgeschlagene Antwort. Erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Некорректный ответ провайдера`,description:`Вышестоящий провайдер вернул через прокси недействительный или ошибочный ответ. Повторите попытку или направьте запрос другому провайдеру.`},ja:{label:`上流レスポンス不良`,description:`上流プロバイダーがプロキシ経由で無効または失敗したレスポンスを返しました。再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Kötü yukarı akış yanıtı`,description:`Yukarı akış sağlayıcısı proxy üzerinden geçersiz veya başarısız bir yanıt döndürdü. Tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}},503:{en:{label:`Provider unavailable`,description:`The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider.`},fr:{label:`Fournisseur indisponible`,description:`Le proxy ou le fournisseur en amont est temporairement indisponible ou surchargé. Patientez un instant, puis réessayez ou changez de fournisseur.`},ko:{label:`제공자 사용 불가`,description:`프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다.`},zh:{label:`提供商不可用`,description:`代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。`},"zh-TW":{label:`供應商不可用`,description:`代理或上游供應商暫時不可用或過載。請稍後重試,或切換供應商。`},de:{label:`Anbieter nicht verfügbar`,description:`Proxy oder Upstream-Anbieter ist vorübergehend nicht verfügbar oder überlastet. Kurz warten, dann erneut versuchen oder Anbieter wechseln.`},ru:{label:`Провайдер недоступен`,description:`Прокси или вышестоящий провайдер временно недоступен или перегружен. Немного подождите, затем повторите попытку или смените провайдера.`},ja:{label:`プロバイダー利用不可`,description:`プロキシまたは上流プロバイダーが一時的に利用不可または過負荷です。少し待ってから再試行するか、プロバイダーを切り替えてください。`},tr:{label:`Sağlayıcı kullanılamıyor`,description:`Proxy veya yukarı akış sağlayıcısı geçici olarak kullanılamıyor veya aşırı yüklü. Kısa bir süre bekleyip tekrar deneyin ya da sağlayıcı değiştirin.`}},504:{en:{label:`Upstream timeout`,description:`The upstream provider did not respond before the proxy timeout. Retry with a smaller request or choose a faster provider.`},fr:{label:`Délai d’attente du fournisseur en amont dépassé`,description:`Le fournisseur en amont n’a pas répondu avant l’expiration du délai du proxy. Réessayez avec une requête plus petite ou choisissez un fournisseur plus rapide.`},ko:{label:`업스트림 시간 초과`,description:`프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다.`},zh:{label:`上游超时`,description:`上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。`},"zh-TW":{label:`上游逾時`,description:`上游供應商未在代理逾時前回應。請縮小請求後重試,或選擇回應更快的供應商。`},de:{label:`Upstream-Timeout`,description:`Der Upstream-Anbieter antwortete nicht vor dem Proxy-Timeout. Mit kleinerer Anfrage erneut versuchen oder schnelleren Anbieter wählen.`},ru:{label:`Тайм-аут вышестоящего провайдера`,description:`Вышестоящий провайдер не ответил до истечения тайм-аута прокси. Повторите попытку с меньшим запросом или выберите более быстрого провайдера.`},ja:{label:`上流タイムアウト`,description:`上流プロバイダーがプロキシタイムアウト前に応答しませんでした。より小さいリクエストで再試行するか、より速いプロバイダーを選んでください。`},tr:{label:`Yukarı akış zaman aşımı`,description:`Yukarı akış sağlayıcısı proxy zaman aşımı süresinden önce yanıt vermedi. Daha küçük bir istekle tekrar deneyin veya daha hızlı bir sağlayıcı seçin.`}},529:{en:{label:`Provider overloaded`,description:`The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider.`},fr:{label:`Fournisseur surchargé`,description:`Le fournisseur en amont est surchargé ou sa capacité est limitée. Patientez et réessayez, ou changez de compte ou de fournisseur.`},ko:{label:`제공자 과부하`,description:`업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다.`},zh:{label:`提供商过载`,description:`上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。`},"zh-TW":{label:`供應商過載`,description:`上游供應商過載或容量受限。請等待後重試,或切換到其他帳號/供應商。`},de:{label:`Anbieter überlastet`,description:`Der Upstream-Anbieter ist überlastet oder kapazitätsbegrenzt. Warten und erneut versuchen oder anderes Konto/Anbieter nutzen.`},ru:{label:`Провайдер перегружен`,description:`Вышестоящий провайдер перегружен или ограничен по мощности. Подождите и повторите попытку либо переключитесь на другой аккаунт или провайдера.`},ja:{label:`プロバイダー過負荷`,description:`上流プロバイダーが過負荷または容量制限されています。待ってから再試行するか、別のアカウント/プロバイダーに切り替えてください。`},tr:{label:`Sağlayıcı aşırı yüklü`,description:`Yukarı akış sağlayıcısı aşırı yüklü veya kapasitesi sınırlı. Bekleyip tekrar deneyin veya başka bir hesap/sağlayıcıya geçin.`}}},qp={client:{en:{label:`Request error`,description:`The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration.`},fr:{label:`Erreur de requête`,description:`Le proxy ou le fournisseur en amont a rejeté la requête. Vérifiez sa structure, les identifiants, le nom du modèle et la configuration du fournisseur.`},ko:{label:`요청 오류`,description:`프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다.`},zh:{label:`请求错误`,description:`代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。`},"zh-TW":{label:`請求錯誤`,description:`代理或上游供應商拒絕了該請求。請檢查請求結構、憑證、模型名稱和供應商配置。`},de:{label:`Anfragefehler`,description:`Der Proxy oder Upstream-Anbieter hat die Anfrage abgelehnt. Prüfe Anfrageformat, Anmeldedaten, Modellname und Anbieterkonfiguration.`},ru:{label:`Ошибка запроса`,description:`Прокси или вышестоящий провайдер отклонил запрос. Проверьте структуру запроса, учётные данные, имя модели и конфигурацию провайдера.`},ja:{label:`リクエストエラー`,description:`プロキシまたは上流プロバイダーがリクエストを拒否しました。リクエスト形式、認証情報、モデル名、プロバイダー設定を確認してください。`},tr:{label:`İstek hatası`,description:`Proxy veya yukarı akış sağlayıcısı isteği reddetti. İstek yapısını, kimlik bilgilerini, model adını ve sağlayıcı yapılandırmasını kontrol edin.`}},server:{en:{label:`Server or upstream error`,description:`opencodex or an upstream provider failed while processing the request. Retry later or route the request to another provider.`},fr:{label:`Erreur du serveur ou du fournisseur en amont`,description:`opencodex ou un fournisseur en amont a échoué lors du traitement de la requête. Réessayez plus tard ou acheminez la requête vers un autre fournisseur.`},ko:{label:`서버 또는 업스트림 오류`,description:`opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다.`},zh:{label:`服务器或上游错误`,description:`opencodex 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。`},"zh-TW":{label:`伺服器或上游錯誤`,description:`opencodex 或上游供應商處理請求時失敗。請稍後重試,或將請求路由到其他供應商。`},de:{label:`Server- oder Upstream-Fehler`,description:`opencodex oder ein Upstream-Anbieter ist bei der Anfragebearbeitung fehlgeschlagen. Später erneut versuchen oder zu einem anderen Anbieter routen.`},ru:{label:`Ошибка сервера или провайдера`,description:`opencodex или вышестоящий провайдер завершил обработку запроса с ошибкой. Повторите попытку позже или направьте запрос другому провайдеру.`},ja:{label:`サーバーまたは上流エラー`,description:`opencodex または上流プロバイダーがリクエスト処理中に失敗しました。後で再試行するか、リクエストを別のプロバイダーにルーティングしてください。`},tr:{label:`Sunucu veya yukarı akış hatası`,description:`opencodex veya bir yukarı akış sağlayıcısı isteği işlerken başarısız oldu. Daha sonra tekrar deneyin veya isteği başka bir sağlayıcıya yönlendirin.`}}};function Jp(e){return e.toLowerCase().startsWith(`fr`)?`fr`:e===`de`||e===`ko`||e===`zh`||e===`zh-TW`||e===`ru`||e===`ja`||e===`tr`?e:`en`}function Yp(e,t){if(e<400)return null;let n=Jp(t);return(Kp[Math.trunc(e)]??(e<500?qp.client:qp.server))[n]}var Xp=[`provider`,`usage`,`injection`];function Zp(e){return e>0?`[${new Date(e).toLocaleTimeString()}] `:``}function Qp(e){return new Date(e).toLocaleTimeString()}function $p(e,t){return t===`provider`?!!e?.enabled:t===`usage`?!!e?.usage:!!e?.injection}function em(e,t){return t===`debug`?e.enabled:t===`usage`?e.usage:t===`injection`?e.injection:e.claude}function tm({entries:e}){let{t}=ct();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:4},children:t(`debug.claudeInbound.title`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{marginBottom:10},children:t(`debug.claudeInbound.sub`)}),e.length===0?(0,J.jsx)(`div`,{className:`muted text-control`,children:t(`debug.claudeInbound.empty`)}):(0,J.jsx)(`div`,{style:{overflowX:`auto`},children:(0,J.jsxs)(`table`,{className:`table text-label`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.time`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.endpoint`)}),(0,J.jsx)(`th`,{children:t(`debug.claudeInbound.model`)}),(0,J.jsx)(`th`,{children:`thinking`}),(0,J.jsx)(`th`,{children:`effort`}),(0,J.jsx)(`th`,{children:`beta`}),(0,J.jsx)(`th`,{children:`metadata`}),(0,J.jsx)(`th`,{children:`system`})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted mono`,children:Qp(e.at)}),(0,J.jsx)(`td`,{className:`mono`,children:e.endpoint}),(0,J.jsxs)(`td`,{className:`mono`,title:e.resolvedModel,children:[e.model,e.resolvedModel&&e.resolvedModel!==e.model&&(0,J.jsxs)(`span`,{className:`muted`,children:[` → `,e.resolvedModel]})]}),(0,J.jsxs)(`td`,{className:`mono`,children:[e.thinkingType??`-`,e.thinkingBudgetTokens!==void 0&&(0,J.jsxs)(`span`,{className:`muted`,children:[` (`,e.thinkingBudgetTokens,`)`]})]}),(0,J.jsx)(`td`,{className:`mono`,children:e.outputConfigEffort??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.anthropicBeta,style:{maxWidth:160,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:e.anthropicBeta??`-`}),(0,J.jsx)(`td`,{className:`mono`,title:e.metadataKeys?.join(`, `),children:e.hasMetadataUserId?`user_id ${e.userIdTag??``}`:t(`debug.claudeInbound.none`)}),(0,J.jsx)(`td`,{className:`mono`,children:e.hasSystem?e.systemTag??`yes`:t(`debug.claudeInbound.none`)})]},e.id))})]})})]})}function nm({debug:e,stream:t,streamEnabled:n,entries:r,scrollContainerRef:i,lineVirtualizer:a}){let{t:o}=ct();return e?n?r.length===0?(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.noLinesTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.noLines.${t}`)})]}):(0,J.jsx)(`div`,{ref:i,className:`log-detail-json`,style:{maxHeight:`calc(100vh - 280px)`,overflow:`auto`},children:(0,J.jsx)(`div`,{style:{position:`relative`,height:a.getTotalSize(),width:`100%`},children:a.getVirtualItems().map(e=>(0,J.jsx)(`div`,{ref:a.measureElement,"data-index":e.index,style:{position:`absolute`,top:0,left:0,width:`100%`,transform:`translateY(${e.start}px)`},children:`${Zp(r[e.index].at)}${r[e.index].line}`},e.key))})}):(0,J.jsxs)(`div`,{className:`empty`,children:[(0,J.jsx)(`div`,{className:`font-semibold`,style:{marginBottom:6},children:o(`debug.emptyTitle`)}),(0,J.jsx)(`div`,{className:`muted text-control`,style:{maxWidth:560,marginInline:`auto`},children:o(`debug.empty`)})]}):null}function rm({debug:e,debugBusy:t,stream:n,onSetFlag:r,onReset:i,onStreamChange:a}){let{t:o}=ct();return(0,J.jsxs)(`div`,{className:`card`,style:{marginBottom:16,padding:`12px 14px`},children:[(0,J.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:12,flexWrap:`wrap`},children:[(0,J.jsx)(`div`,{style:{display:`flex`,flexWrap:`wrap`,gap:16},children:[`debug`,`usage`,`injection`,`claude`].map(n=>{let i=em(e,n);return(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:10,minWidth:220},children:[(0,J.jsx)(Tt,{on:i,disabled:t,label:o(`debug.${n}`),onClick:()=>r(n,!i)}),(0,J.jsx)(`span`,{className:`text-control`,children:o(`debug.${n}`)})]},n)})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t,onClick:i,children:o(`debug.reset`)})]}),(e.enabled||e.usage||e.injection)&&(0,J.jsxs)(`div`,{style:{display:`inline-flex`,gap:6,marginTop:12},children:[e.enabled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`provider`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`provider`),children:o(`debug.streamProvider`)}),e.usage&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`usage`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`usage`),children:o(`debug.streamUsage`)}),e.injection&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm${n===`injection`?` btn-primary`:` btn-ghost`}`,onClick:()=>a(`injection`),children:o(`debug.streamInjection`)})]})]})}function im({embedded:e,refreshing:t,streamEnabled:n,follow:r,onRefresh:i,onFollowChange:a}){let{t:o}=ct();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:e?`row`:`page-head`,style:e?{justifyContent:`flex-end`,marginBottom:4}:void 0,children:[!e&&(0,J.jsx)(`h2`,{children:o(`debug.title`)}),(0,J.jsxs)(`div`,{style:{display:`inline-flex`,alignItems:`center`,gap:12},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:t||!n,onClick:i,children:[(0,J.jsx)(fe,{}),` `,o(`debug.refresh`)]}),(0,J.jsxs)(`label`,{className:`muted text-control`,style:{cursor:`pointer`,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:r,onChange:e=>a(e.target.checked)}),o(`debug.follow`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:o(`debug.subtitle`)})]})}function am(e){return`debug-settings:${e}`}function om({apiBase:e,embedded:t,active:n=!0}){let{t:r}=ct(),i=`ocx.debug.settings.v1:${e}`,a=fr(i),o=am(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=ol(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 gr(i,r),r},{pollMs:2e3,enabled:n,isEmpty:()=>!1,initialData:a??void 0}),T=w.state,E=w.data??a??null,D=G(`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=Bp({count:d.length,getScrollElement:()=>S.current,estimateSize:()=>20,overscan:30,getItemKey:e=>d[e].seq}),k=(0,_.useCallback)(e=>$p(E,e),[E]);(0,_.useEffect)(()=>{if(!E||k(l))return;let e=Xp.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,_.useRef)(!1),P=(0,_.useEffectEvent)(()=>{if(N.current)return;N.current=!0;let e=Ln(1e4);M(!1,e.signal).finally(()=>{e.clear(),N.current=!1})});(0,_.useEffect)(()=>{if(!(!n||!p||!A))return Vn(()=>P(),1e3)},[n,p,A]),(0,_.useEffect)(()=>{p&&d.length>0&&O.scrollToIndex(d.length-1,{align:`end`})},[d,p,O]);let F=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;gr(i,a),K(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)}},I=async(e,t)=>{await F({[e]:t})},L=async()=>{await F({reset:!0})};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(im,{embedded:t,refreshing:h,streamEnabled:A,follow:p,onRefresh:()=>void M(!0),onFollowChange:m}),!E&&T.showError?(0,J.jsxs)(`div`,{className:`notice notice-err`,role:`alert`,children:[(0,J.jsx)(`span`,{children:r(`debug.loadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>w.refresh(),children:r(`common.retry`)})]}):T.showSkeleton&&!E?(0,J.jsx)(cl,{label:r(`debug.loading`),rows:3}):E?(0,J.jsx)(rm,{debug:E,debugBusy:s,stream:l,onSetFlag:(e,t)=>{I(e,t)},onReset:()=>{L()},onStreamChange:u}):null,E&&T.showError&&(0,J.jsx)($,{tone:`err`,children:r(`debug.loadFailed`)}),E?.claude&&(0,J.jsx)(tm,{entries:D}),(0,J.jsx)(nm,{debug:!!E,stream:l,streamEnabled:A,entries:d,scrollContainerRef:S,lineVirtualizer:O})]})}function sm(){return window.location.hash.replace(/^#\/?/,``)===`logs/debug`?`debug`:`logs`}function cm(e){window.location.hash=e===`debug`?`logs/debug`:`logs`}function lm(e){e.key===`ArrowLeft`||e.key===`Home`?(e.preventDefault(),cm(`logs`),document.getElementById(`logs-tab-logs`)?.focus()):(e.key===`ArrowRight`||e.key===`End`)&&(e.preventDefault(),cm(`debug`),document.getElementById(`logs-tab-debug`)?.focus())}function um(e,t){return[`${t(`logs.modelTooltip.model`)}=${e.model}`,e.resolvedModel?`${t(`logs.modelTooltip.resolvedModel`)}=${e.resolvedModel}`:void 0,e.requestedServiceTier?`${t(`logs.modelTooltip.requestedTier`)}=${e.requestedServiceTier}`:void 0,e.configuredServiceTier?`${t(`logs.modelTooltip.configuredTier`)}=${e.configuredServiceTier}`:void 0,e.responseServiceTier?`${t(`logs.modelTooltip.responseTier`)}=${e.responseServiceTier}`:void 0,e.modelSupportsServiceTier===void 0?void 0:`${t(`logs.modelTooltip.supportsTier`)}=${e.modelSupportsServiceTier}`].filter(Boolean).join(` · `)}function dm(e){return e.requestedSpeedLabel||void 0}function fm(e,t,n,r=!1){if(!Number.isFinite(e)||e<0)return t(`logs.cost.unavailable`);let i=new Intl.NumberFormat(n,{style:`currency`,currency:`USD`,minimumFractionDigits:4,maximumFractionDigits:4}).format(e);return t(r?`logs.cost.lowerBound`:`logs.cost.approximate`,{amount:i})}function pm(e,t,n){return!e||e.kind===`unavailable`?t(`logs.cost.unavailable`):fm(e.estimate.cost.total,t,n,e.estimate.priorityLowerBound)}function mm(e){let t=0,n=!0,r=0,i=0,a=0;for(let o of e){if(o.usageStatus===`unsupported`){a+=1;continue}let e=o.displayMetrics?.cost;if(e?.kind===`value`){let i=e.estimate.cost.total;if(Number.isFinite(i)&&i>=0){t+=i,r+=1,n&&=e.estimate.priorityLowerBound===!0;continue}}i+=1}return{estimatedCostUsd:t,priorityLowerBound:r>0&&n,unpricedRequests:i,unmeteredRequests:a}}function hm(e){return e===`cursor`||e.startsWith(`cursor-`)}function gm(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 _m(e,t){if(!e.usage)return;let n=gm(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(hm(e.provider)?`logs.tokens.noCacheCursorNote`:`logs.tokens.noCacheNote`)),r.join(` · `)}function vm(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 ym(e){return e===void 0||typeof e==`string`}function bm(e){if(e===void 0)return!0;if(!e||typeof e!=`object`||!ym(e.routeKind)||e.profile!==void 0&&(!e.profile||typeof e.profile!=`object`||!ym(e.profile.id)||!ym(e.profile.revision))||e.selected!==void 0&&(!e.selected||typeof e.selected!=`object`||!ym(e.selected.provider)||!ym(e.selected.model)||!ym(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`||!ym(t.provider)||!ym(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`||!ym(e.code))return!1}}return!0}function xm(e){if(e.routeDecision===void 0||bm(e.routeDecision))return e;let t={...e};return delete t.routeDecision,t}function Sm(e){return`ocx.logs.list.v1:${e}`}function Cm(e){if(!Array.isArray(e))return null;for(let t of e)if(!t||typeof t!=`object`||typeof t.timestamp!=`number`||typeof t.model!=`string`||typeof t.provider!=`string`||typeof t.status!=`number`||typeof t.durationMs!=`number`||t.shadowCallRewrittenFrom!==void 0&&typeof t.shadowCallRewrittenFrom!=`string`||!bm(t.routeDecision))return null;return e}function wm(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 Tm(e){let t=wm(e),n=e.usage?.contextTotalTokens;return typeof n==`number`?Math.max(t??0,n)||void 0:t}function Em(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 Dm(e){if(!(!e.reasoningWireField||e.reasoningWireValue===void 0))return`${e.reasoningWireField}=${e.reasoningWireValue}`}function Om(e,t){if(!e||e.kind===`unavailable`||!Number.isFinite(e.value)||e.value<=0)return`—`;let n=e.value>=100?0:1,r=new Intl.NumberFormat(t,{minimumFractionDigits:n,maximumFractionDigits:n}).format(e.value);return`${e.estimated?`~`:``}${r}`}var km=2e3,Am=4,jm=3,Mm={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`},Nm={usage_estimated:`logs.detail.estimate.usage_estimated`,cache_detail_missing:`logs.detail.estimate.cache_detail_missing`,expected_price_overlay:`logs.detail.estimate.expected_price_overlay`,provider_cost_overlay:`logs.detail.estimate.provider_cost_overlay`,priority_lower_bound:`logs.detail.estimate.priority_lower_bound`},Pm={"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 Fm(e){return Mm[e]}function Im(e){return Nm[e]}function Lm(e){return Pm[e]??`logs.detail.attempt.recovery.unknown`}function Rm(e){return e===`verified`?`logs.detail.verification.verified`:`logs.detail.verification.derived`}function zm(e){return e>=200&&e<300?`var(--green)`:e>=400?`var(--red)`:`var(--amber)`}function Bm(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 Vm(e,t,n){let{date:r,time:i}=Bm(e,t,n);return`${r} ${i}`}function Hm(e){let t=0;for(let n of e){let e=wm(n);e!==void 0&&(t+=e)}return{requests:e.length,totalTokens:t,...mm(e)}}function Um({apiBase:e}){let{t,locale:n}=ct(),r=Sm(e),i=Cm(fr(r)),[a,o]=(0,_.useState)(!0),[s,c]=(0,_.useState)({error:null,count:0}),[l,u]=(0,_.useState)(null),[d,f]=(0,_.useState)(`all`),[p,m]=(0,_.useState)(!1),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(),b=(0,_.useRef)(null),x=(0,_.useRef)({key:r,failures:0,nextAttemptAt:0,error:null}),S=et.find(e=>e.code===n)?.htmlLang,[C,w]=(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()&&w(e.timeZone.trim())}).catch(()=>{}),()=>{n=!0,t.abort()}},[e]);let[T,E]=(0,_.useState)(sm),[D,O]=(0,_.useState)(()=>sm()===`debug`);(0,_.useEffect)(()=>{let e=()=>E(sm());return window.addEventListener(`hashchange`,e),()=>window.removeEventListener(`hashchange`,e)},[]),(0,_.useEffect)(()=>{T===`debug`&&O(!0)},[T]);let k=cm,A=(0,_.useCallback)(async t=>{let n=x.current;if(n.key!==r&&(n={key:r,failures:0,nextAttemptAt:0,error:null},x.current=n),n.failures>0&&Date.now()<n.nextAttemptAt)throw n.error;try{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(xm);return x.current={key:r,failures:0,nextAttemptAt:0,error:null},gr(r,a),a}catch(e){if(t.aborted)throw e;let i=e??Error(`log request failed`),a=n.failures+1,o=km*2**Math.min(a,Am);throw x.current={key:r,failures:a,nextAttemptAt:Date.now()+o,error:i},i}},[e,r]),j=ol(r,[e],A,{isEmpty:e=>e.length===0,enabled:T===`logs`,pollMs:a?km:void 0,initialData:i??void 0}),M=j.state,N=M.data??i??[],P=j.refresh,F=(0,_.useCallback)(()=>{x.current={key:r,failures:0,nextAttemptAt:0,error:null},P({forceLoading:!0})},[P,r]),I=!j.refreshing&&M.showError;!j.refreshing&&!M.showError&&M.data!==void 0&&s.count!==0?c({error:null,count:0}):I&&s.error!==M.error&&c(e=>({error:M.error,count:e.count+1}));let L=s.count>=jm||!a&&I,R=l?Yp(l.status,n):null,z=h.trim();(0,_.useEffect)(()=>{let e=!1;if(!z){y(void 0);return}return Wp(z).then(t=>{e||y(t)}),()=>{e=!0}},[z]);let B=N.filter(e=>vm(e,d)&&(!p||!!e.shadowCallRewrittenFrom)&&(!z||Gp(e.conversationId,z,v))),V=z?Hm(B):null,H=Bp({count:B.length,getScrollElement:()=>b.current,estimateSize:()=>44,overscan:15}),U=H.getVirtualItems(),W=U.length>0?U[0].start:0,ee=U.length>0?H.getTotalSize()-U[U.length-1].end:0;return(0,J.jsxs)(`div`,{className:`logs-page`,children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{children:t(`nav.logs`)}),T===`logs`&&(0,J.jsxs)(`label`,{className:`muted text-control logs-auto-refresh`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:a,onChange:e=>o(e.target.checked)}),t(`logs.autoRefresh`)]})]}),(0,J.jsxs)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`nav.logs`),children:[(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-logs`,"aria-selected":T===`logs`,"aria-controls":`logs-panel-logs`,tabIndex:T===`logs`?0:-1,className:`page-tab${T===`logs`?` page-tab--active`:``}`,onClick:()=>k(`logs`),onKeyDown:lm,children:t(`logs.tabLogs`)}),(0,J.jsx)(`button`,{type:`button`,role:`tab`,id:`logs-tab-debug`,"aria-selected":T===`debug`,"aria-controls":`logs-panel-debug`,tabIndex:T===`debug`?0:-1,className:`page-tab${T===`debug`?` page-tab--active`:``}`,onClick:()=>k(`debug`),onKeyDown:lm,children:t(`logs.tabDebug`)})]}),D&&(0,J.jsx)(`div`,{role:`tabpanel`,id:`logs-panel-debug`,"aria-labelledby":`logs-tab-debug`,hidden:T!==`debug`,children:(0,J.jsx)(om,{apiBase:e,embedded:!0,active:T===`debug`})}),(0,J.jsxs)(`div`,{role:`tabpanel`,id:`logs-panel-logs`,"aria-labelledby":`logs-tab-logs`,hidden:T!==`logs`,children:[(0,J.jsx)(`p`,{className:`page-sub`,children:t(`logs.subtitle`)}),(0,J.jsxs)(`div`,{className:`logs-toolbar`,children:[(0,J.jsx)(`span`,{className:`muted text-control`,children:t(`logs.filter.surface.label`)}),(0,J.jsx)(`div`,{className:`segmented logs-segmented`,role:`radiogroup`,"aria-label":t(`logs.filter.surface.label`),children:[`all`,`claude`,`codex`,`grok`].map(e=>(0,J.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":d===e,className:`btn btn-sm${d===e?` btn-primary`:` btn-ghost`}`,style:{background:d===e?void 0:`transparent`,color:d===e?void 0:`var(--muted)`},onClick:()=>f(e),children:t(`logs.filter.surface.${e}`)},e))}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:p,onChange:e=>m(e.target.checked)}),t(`logs.filter.interceptedHelpersOnly`)]}),(0,J.jsxs)(`label`,{className:`muted text-control logs-filter-field`,children:[t(`logs.filter.conversation.label`),(0,J.jsx)(`input`,{type:`search`,className:`input mono`,value:h,onChange:e=>g(e.target.value),placeholder:t(`logs.filter.conversation.placeholder`),"aria-label":t(`logs.filter.conversation.label`)})]}),z&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>g(``),children:t(`logs.filter.conversation.clear`)})]}),V&&(0,J.jsx)(`div`,{className:`logs-conversation-totals`,children:(0,J.jsxs)($,{tone:`ok`,children:[t(`logs.conversation.totals`,{requests:V.requests,tokens:Pn(V.totalTokens,S??n),cost:fm(V.estimatedCostUsd,t,S,V.priorityLowerBound)}),` `,(0,J.jsxs)(`span`,{className:`muted`,children:[t(`logs.conversation.scope`),V.unpricedRequests+V.unmeteredRequests>0?` ${t(`logs.conversation.excluded`,{unpriced:V.unpricedRequests,unmetered:V.unmeteredRequests})}`:``]})]})}),M.kind===`failed-cold`&&(0,J.jsxs)($,{tone:`err`,children:[M.error instanceof Error?`${t(`logs.loadError`)} ${M.error.message}`:t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:M.refreshing,children:t(`common.retry`)})]}),L&&N.length>0&&(0,J.jsxs)($,{tone:`err`,children:[t(`logs.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:F,disabled:j.refreshing,children:t(`common.retry`)})]}),M.kind===`failed-cold`?null:M.showSkeleton&&N.length===0?(0,J.jsx)(cl,{label:t(`common.loading`),rows:6}):B.length===0?(0,J.jsx)(Ot,{title:t(`logs.noRequests`)}):(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{ref:b,className:`tbl-wrap logs-table-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl logs-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:t(`logs.col.time`)}),(0,J.jsx)(`th`,{className:`num log-col-tokens`,children:t(`logs.col.tokens`)}),(0,J.jsx)(`th`,{className:`num log-col-rate`,title:t(`logs.metric.tokPerSecTitle`),children:t(`logs.col.tokPerSec`)}),(0,J.jsx)(`th`,{className:`num log-col-cost`,title:t(`logs.metric.estimatedCostTitle`),children:t(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{className:`log-col-model`,children:t(`logs.col.model`)}),(0,J.jsx)(`th`,{children:t(`logs.col.effort`)}),(0,J.jsx)(`th`,{children:t(`logs.col.provider`)}),(0,J.jsx)(`th`,{children:t(`logs.col.status`)}),(0,J.jsx)(`th`,{children:t(`logs.col.request`)}),(0,J.jsx)(`th`,{className:`num log-col-duration`,children:t(`logs.col.duration`)})]})}),(0,J.jsxs)(`tbody`,{children:[W>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:W}})}),U.map(e=>{let r=B[B.length-1-e.index],i=Dm(r),a=Bm(r.timestamp,S,C);return(0,J.jsxs)(`tr`,{"data-index":e.index,ref:H.measureElement,children:[(0,J.jsx)(`td`,{className:`muted mono log-col-time`,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:a.date}),(0,J.jsx)(`span`,{children:a.time})]})}),(0,J.jsx)(`td`,{className:`num mono log-col-tokens`,title:_m(r,t),children:(()=>{let e=Tm(r),{read:i,write:a}=gm(r);return e===void 0?(0,J.jsx)(`span`,{className:`muted`,children:t(`logs.tokens.${r.usageStatus??`unreported`}`)}):(0,J.jsxs)(`span`,{className:`logs-stack-end`,children:[(0,J.jsxs)(`span`,{children:[r.usageStatus===`estimated`?`~`:``,Pn(e,n)]}),i!==void 0&&i>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`c `,Pn(i,n)]}),a!==void 0&&a>0&&(0,J.jsxs)(`span`,{className:`muted text-caption leading-tight`,children:[`w `,Pn(a,n)]}),r.usageStatus===`estimated`&&i===void 0&&a===void 0&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:t(hm(r.provider)?`logs.tokens.noCacheCursor`:`logs.tokens.noCache`)})]})})()}),(0,J.jsx)(`td`,{className:`num mono log-col-rate`,children:Om(r.displayMetrics?.tokPerSecond,S)}),(0,J.jsx)(`td`,{className:`num mono log-col-cost`,children:pm(r.displayMetrics?.cost,t,S)}),(0,J.jsx)(`td`,{className:`mono log-col-model`,title:um(r,t),children:(0,J.jsxs)(`span`,{className:`logs-model-cell`,children:[(0,J.jsx)(`span`,{children:il(r.resolvedModel??r.model)}),r.shadowCallRewrittenFrom&&(0,J.jsx)(`span`,{className:`badge badge-muted`,style:{whiteSpace:`nowrap`},title:t(`logs.badge.interceptedHelperTitle`),children:t(`logs.badge.interceptedHelper`,{model:r.shadowCallRewrittenFrom})}),(r.surface===`claude`||r.surface===`claude-desktop`)&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.claude`)}),r.surface===`grok`&&(0,J.jsx)(`span`,{className:`badge badge-accent`,children:t(`logs.badge.grok`)}),dm(r)&&(0,J.jsx)(`span`,{className:`badge badge-amber`,children:dm(r)})]})}),(0,J.jsx)(`td`,{className:`mono log-reasoning-cell`,title:i,children:(0,J.jsxs)(`span`,{className:`logs-stack-start`,children:[(0,J.jsx)(`span`,{children:Em(r)}),i&&(0,J.jsx)(`span`,{className:`muted text-caption leading-tight`,children:i})]})}),(0,J.jsx)(`td`,{className:`muted`,children:Dn(r.provider,t)}),(0,J.jsx)(`td`,{children:(0,J.jsxs)(`span`,{className:`log-status-cell`,children:[(0,J.jsx)(`span`,{className:`mono font-semibold`,style:{color:zm(r.status)},children:r.status}),(0,J.jsx)(`button`,{type:`button`,className:`log-detail-btn`,onClick:()=>u(r),"aria-label":`${t(`logs.details`)}: ${r.requestId??r.status}`,children:t(`logs.details`)})]})}),(0,J.jsx)(`td`,{className:`muted mono`,children:(0,J.jsx)(`span`,{className:`log-reqid`,title:r.requestId,children:r.requestId??`-`})}),(0,J.jsxs)(`td`,{className:`num log-col-duration`,children:[r.durationMs,`ms`]})]},r.requestId??`${r.timestamp}-${e.index}`)}),ee>0&&(0,J.jsx)(`tr`,{children:(0,J.jsx)(`td`,{colSpan:10,className:`logs-virtual-spacer`,style:{height:ee}})})]})]})})}),l&&(0,J.jsx)(Gm,{detail:l,detailInfo:R,localeCode:n,localeTag:S,serverTimeZone:C,t,onClose:()=>u(null),onFilterConversation:e=>{g(e),u(null)}})]})]})}function Wm(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 Gm({detail:e,detailInfo:t,localeCode:n,localeTag:r,serverTimeZone:i,t:a,onClose:o,onFilterConversation:s}){let c=Wm(!0),[l,u]=(0,_.useState)(!1),d=gm(e),f=e.displayMetrics?.cost,p=Dm(e),m=async()=>{if(e.requestId)try{await navigator.clipboard.writeText(e.requestId),u(!0),window.setTimeout(()=>u(!1),1200)}catch{}};return(0,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":`log-detail-title`,onCancel:e=>{e.preventDefault(),o()},children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":a(`common.close`),tabIndex:-1,onClick:o}),(0,J.jsxs)(`div`,{className:`modal-card log-detail-card`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsxs)(`h3`,{id:`log-detail-title`,children:[(0,J.jsx)(`span`,{className:`mono`,style:{color:zm(e.status)},children:e.status}),t&&(0,J.jsx)(`span`,{className:`logs-detail-info`,children:t.label})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:o,"aria-label":a(`common.cancel`),children:(0,J.jsx)(ue,{})})]}),t&&(0,J.jsx)(`p`,{className:`modal-desc`,children:t.description}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-basic`,children:[(0,J.jsx)(`h4`,{id:`log-detail-basic`,className:`log-detail-section-title`,children:a(`logs.detail.section.basic`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.time`)}),(0,J.jsx)(`span`,{className:`mono`,children:Vm(e.timestamp,r,i)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.request`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.requestId??`—`}),e.requestId&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void m(),children:a(l?`logs.detail.copied`:`logs.detail.copyRequestId`)})]}),e.conversationId&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.conversation`)}),(0,J.jsxs)(`span`,{className:`log-detail-request-row`,children:[(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.conversationId}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e.conversationId),children:a(`logs.filter.conversation.apply`)})]})]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.model`)}),(0,J.jsx)(`span`,{className:`mono`,children:il(e.resolvedModel??e.model)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.provider`)}),(0,J.jsx)(`span`,{children:Dn(e.provider,a)}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.effort`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[Em(e),p?` (${p})`:``]})]}),e.errorCode&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.error`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.errorCode})]}),e.upstreamError&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.upstreamReason`)}),(0,J.jsx)(`span`,{className:`mono log-detail-break`,children:e.upstreamError})]})]})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-route`,children:[(0,J.jsx)(`h4`,{id:`log-detail-route`,className:`log-detail-section-title`,children:a(`logs.detail.route.section`)}),e.routeDecision?(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.kind`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.routeDecision.routeKind??`–`}),e.routeDecision.profile?.id&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.profile`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.profile.id,` (`,e.routeDecision.profile.revision,`)`]})]}),e.routeDecision.selected?.provider&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.selected`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.routeDecision.selected.provider,`/`,e.routeDecision.selected.model,e.routeDecision.selected.reason?` — ${e.routeDecision.selected.reason}`:``]})]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.route.candidates`)}),(0,J.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,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.route.unknown`)})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-performance`,children:[(0,J.jsx)(`h4`,{id:`log-detail-performance`,className:`log-detail-section-title`,children:a(`logs.detail.section.performance`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.duration`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`span`,{className:`mono`,children:Om(e.displayMetrics?.tokPerSecond,r)}),e.firstOutputMs!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.ttft`)}),(0,J.jsxs)(`span`,{className:`mono`,children:[e.firstOutputMs,`ms`]})]})]}),e.displayMetrics?.tokPerSecond.kind===`unavailable`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(Fm(e.displayMetrics.tokPerSecond.reason))})]}),(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-cost`,children:[(0,J.jsx)(`h4`,{id:`log-detail-cost`,className:`log-detail-section-title`,children:a(`logs.detail.section.cost`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`usage.cost.disclaimer`)}),f?.kind===`value`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.total,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.input,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.cacheRead,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.cacheWrite,a,r,f.estimate.priorityLowerBound)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:fm(f.estimate.cost.output,a,r,f.estimate.priorityLowerBound)}),f.estimate.price&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.matchedKey`)}),(0,J.jsxs)(`span`,{className:`mono log-detail-break`,children:[f.estimate.price.jawcodeProvider??f.estimate.price.provider,`/`,f.estimate.price.modelId]}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.priceSource`)}),(0,J.jsxs)(`span`,{children:[a(`logs.detail.source.${f.estimate.price.source}`),` · `,a(Rm(f.estimate.price.status))]})]})]}),f.estimateReasons.length>0&&(0,J.jsx)(`ul`,{className:`log-detail-notes`,children:f.estimateReasons.map(e=>(0,J.jsx)(`li`,{children:a(Im(e))},e))})]}):(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.costTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:a(`logs.cost.unavailable`)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.unavailableReason`)}),(0,J.jsx)(`span`,{children:f?.kind===`unavailable`?a(Fm(f.reason)):a(`logs.detail.reason.usage_missing`)})]})]}),e.attempts?.length?(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-attempts`,children:[(0,J.jsx)(`h4`,{id:`log-detail-attempts`,className:`log-detail-section-title`,children:a(`logs.detail.section.attempts`)}),(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.detail.attempt.e2eNote`)}),(0,J.jsx)(`div`,{className:`log-detail-attempts-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl log-detail-attempts`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{className:`num`,children:`#`}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.target`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.duration`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.tokPerSec`)}),(0,J.jsx)(`th`,{className:`num`,children:a(`logs.col.estimatedCost`)}),(0,J.jsx)(`th`,{children:a(`logs.detail.attempt.reason`)})]})}),(0,J.jsx)(`tbody`,{children:e.attempts.toSorted((e,t)=>e.ordinal-t.ordinal).map(e=>{let t=e.displayMetrics?.cost,n=Dm(e),i=t?.kind===`value`?t.estimate.price:void 0,o=e.errorCode??(e.recoveryKinds.length?e.recoveryKinds.map(e=>a(Lm(e))).join(`, `):void 0)??(t?.kind===`unavailable`?a(Fm(t.reason)):a(`logs.detail.attempt.completed`));return(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`num mono`,children:e.ordinal}),(0,J.jsxs)(`td`,{children:[(0,J.jsx)(`span`,{children:Dn(e.provider,a)}),(0,J.jsx)(`br`,{}),(0,J.jsx)(`span`,{className:`mono muted log-detail-break`,children:e.model}),(e.requestedEffort||e.effectiveEffort)&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`mono muted text-caption log-detail-break`,children:[Em(e),n?` (${n})`:``]})]}),i&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`br`,{}),(0,J.jsxs)(`span`,{className:`muted text-caption log-detail-break`,children:[i.jawcodeProvider??i.provider,`/`,i.modelId,` · `,a(`logs.detail.source.${i.source}`),` · `,a(Rm(i.status))]})]})]}),(0,J.jsxs)(`td`,{className:`num mono`,children:[e.durationMs,`ms`]}),(0,J.jsx)(`td`,{className:`num mono`,children:Om(e.displayMetrics?.tokPerSecond,r)}),(0,J.jsx)(`td`,{className:`num mono`,children:pm(t,a,r)}),(0,J.jsx)(`td`,{className:`log-detail-break`,children:o})]},`${e.ordinal}-${e.provider}-${e.model}`)})})]})})]}):null,(0,J.jsxs)(`section`,{className:`log-detail-section`,"aria-labelledby":`log-detail-usage`,children:[(0,J.jsx)(`h4`,{id:`log-detail-usage`,className:`log-detail-section-title`,children:a(`logs.detail.section.usage`)}),(0,J.jsxs)(`div`,{className:`log-detail-grid`,children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.input`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Pn(e.usage.inputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.output`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?Pn(e.usage.outputTokens,n):`—`}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheRead`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.read===void 0?`—`:Pn(d.read,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.cacheWrite`)}),(0,J.jsx)(`span`,{className:`mono`,children:d.write===void 0?`—`:Pn(d.write,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.reasoning`)}),(0,J.jsx)(`span`,{className:`mono`,children:e.usage?.reasoningOutputTokens===void 0?`—`:Pn(e.usage.reasoningOutputTokens,n)}),(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.detail.totalTokens`)}),(0,J.jsx)(`span`,{className:`mono`,children:Tm(e)===void 0?`—`:Pn(Tm(e),n)}),e.usage?.contextTotalTokens!==void 0&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{className:`muted`,children:a(`logs.tokens.contextTotal`)}),(0,J.jsx)(`span`,{className:`mono`,children:Pn(e.usage.contextTotalTokens,n)})]})]}),e.usageStatus===`estimated`&&(0,J.jsx)(`p`,{className:`log-detail-notes-line muted`,children:a(`logs.tokens.estimatedNote`)})]}),(0,J.jsxs)(`details`,{className:`log-detail-raw`,children:[(0,J.jsx)(`summary`,{children:a(`logs.detailRaw`)}),(0,J.jsx)(`pre`,{className:`log-detail-json`,children:JSON.stringify(e,null,2)})]})]})]})}function Km(e){return`${Math.round(e*100)}%`}function qm(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 Jm(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 Ym(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 Xm(e,t){return e<=0?0:e<=t[0]?1:e<=t[1]?2:e<=t[2]?3:4}function Zm(e){let t=Ym(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?Xm(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 Qm({surface:e,range:t,onSurface:n,onRange:r,t:i}){return(0,J.jsxs)(`div`,{className:`usage-filters`,children:[(0,J.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`logs.filter.surface.label`),children:[`all`,`codex`,`claude`,`grok`].map(t=>{let r=i(`logs.filter.surface.${t}`);return(0,J.jsxs)(`button`,{type:`button`,className:`usage-segmented-btn usage-source-btn${e===t?` active`:``}`,"aria-label":r,"aria-pressed":e===t,onClick:()=>n(t),children:[t===`codex`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/openai.svg`,alt:``,"aria-hidden":`true`}),t===`claude`&&(0,J.jsx)(`img`,{className:`usage-source-mark`,src:`/provider-icons/claude-color.svg`,alt:``,"aria-hidden":`true`}),t===`grok`&&(0,J.jsx)(`img`,{className:`usage-source-mark usage-source-mark--mono`,src:`/provider-icons/grok.svg`,alt:``,"aria-hidden":`true`}),(0,J.jsx)(`span`,{className:t===`all`?`usage-source-label`:`usage-source-label usage-source-label-collapsible`,children:r})]},t)})}),(0,J.jsx)(`div`,{className:`usage-segmented`,role:`group`,"aria-label":i(`usage.title`),children:[`all`,`30d`,`7d`].map(e=>{let n=i(e===`all`?`usage.range.available`:`usage.range.${e}`);return(0,J.jsx)(`button`,{type:`button`,className:`usage-segmented-btn${t===e?` active`:``}`,"aria-label":n,"aria-pressed":t===e,onClick:()=>r(e),children:n},e)})})]})}function $m({summary:e,activeDays:t,locale:n,t:r}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,role:`group`,"aria-label":r(`usage.title`),children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.requests`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.requests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.totalTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Pn(e.totalTokens,n)})]}),(0,J.jsxs)(`div`,{className:`stat`,title:r(`usage.card.cachedTokensHint`),children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.cachedTokens`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Pn(e.cacheReadInputTokens??e.cachedInputTokens,n)}),(e.cacheCreationInputTokens??0)>0&&(0,J.jsxs)(`div`,{className:`muted text-caption`,children:[r(`usage.card.cacheWriteTokens`),`: `,Pn(e.cacheCreationInputTokens??0,n)]})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.coverage`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:Km(e.coverageRatio)})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:r(`usage.card.activeDays`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:t})]})]}),e.estimatedCostUsd!==void 0&&(0,J.jsxs)(`div`,{className:`usage-cost-row`,role:`note`,children:[(0,J.jsx)(`span`,{className:`muted`,children:r(`usage.cost.total`)}),(0,J.jsx)(`span`,{className:`stat-value mono usage-cost-value`,children:es(e.estimatedCostUsd,n)}),(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.disclaimer`)}),(e.unpricedRequests??0)+(e.unmeteredRequests??0)>0&&(0,J.jsx)(`span`,{className:`muted text-caption`,children:r(`usage.cost.unpricedNote`).replace(`{count}`,String((e.unpricedRequests??0)+(e.unmeteredRequests??0)))})]})]})}function eh({weekBars:e,locale:t,t:n}){let[r,i]=(0,_.useState)(null),a=Math.max(1,...e.map(e=>e.totalTokens));return(0,J.jsx)(`div`,{className:`daybars`,role:`img`,"aria-label":n(`usage.section.heatmap`),children:e.map(e=>{let n=Math.round(e.totalTokens/a*100),o=e.date.slice(5);return(0,J.jsxs)(`div`,{className:`daybar`,onMouseEnter:()=>i(e.date),onMouseLeave:()=>i(t=>t===e.date?null:t),children:[(0,J.jsx)(`div`,{className:`daybar-track`,children:(0,J.jsxs)(`div`,{className:`daybar-stack`,style:{"--daybar-scale":String(Math.max(0,Math.min(1,n/100)))},children:[e.models.map(e=>(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:e.totalTokens,background:qm(e.model,e.provider)}},`${e.provider}/${e.model}`)),e.models.length===0&&e.totalTokens>0&&(0,J.jsx)(`div`,{className:`daybar-seg`,style:{flexGrow:1,background:`var(--green)`}})]})}),r===e.date&&e.totalTokens>0&&(0,J.jsxs)(`div`,{className:`daybar-tip`,role:`tooltip`,children:[(0,J.jsx)(`div`,{className:`daybar-tip-date`,children:e.date}),e.models.slice(0,8).map(e=>(0,J.jsxs)(`div`,{className:`daybar-tip-row`,children:[(0,J.jsx)(`span`,{className:`daybar-tip-swatch`,style:{background:qm(e.model,e.provider)}}),(0,J.jsx)(`span`,{className:`daybar-tip-name`,children:il(e.model)}),(0,J.jsx)(`span`,{className:`daybar-tip-val`,children:Pn(e.totalTokens,t)})]},`${e.provider}/${e.model}`))]}),(0,J.jsx)(`span`,{className:`daybar-count`,children:Pn(e.totalTokens,t)}),(0,J.jsx)(`span`,{className:`daybar-label muted`,children:o})]},e.date)})})}function th({range:e,heatmap:t,weekBars:n,locale:r,t:i}){let a=(0,_.useRef)(null),[o,s]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let e=a.current;if(!e)return;let t=()=>{e.scrollLeft=e.scrollWidth};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[t,e]),(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsx)(`h3`,{id:`usage-heatmap-title`,className:`panel-title`,children:i(`usage.section.heatmap`)}),e===`7d`?(0,J.jsx)(eh,{weekBars:n,locale:r,t:i}):(0,J.jsxs)(`div`,{className:`heatmap`,ref:a,role:`img`,"aria-labelledby":`usage-heatmap-title`,children:[(0,J.jsxs)(`div`,{className:`heatmap-months`,style:{gridTemplateColumns:`28px repeat(${t.weeks.length}, calc(var(--hm-cell) + var(--hm-gap)))`},children:[(0,J.jsx)(`span`,{className:`heatmap-day-spacer`}),t.months.map(e=>(0,J.jsx)(`span`,{className:`heatmap-month`,style:{gridColumn:e.col+2},children:e.label},`${e.label}-${e.col}`))]}),(0,J.jsxs)(`div`,{className:`heatmap-body`,children:[(0,J.jsxs)(`div`,{className:`heatmap-days`,children:[(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayMon`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayWed`)}),(0,J.jsx)(`span`,{}),(0,J.jsx)(`span`,{children:i(`usage.dayFri`)}),(0,J.jsx)(`span`,{})]}),(0,J.jsx)(`div`,{className:`heatmap-grid`,style:{gridTemplateColumns:`repeat(${t.weeks.length}, var(--hm-cell))`},children:t.weeks.map((e,t)=>(0,J.jsx)(`div`,{className:`heatmap-week`,children:e.map((e,n)=>(0,J.jsx)(`div`,{className:`heatmap-cell heatmap-cell-${e.level}`,onMouseEnter:r=>{if(!e.date)return;let i=r.currentTarget.getBoundingClientRect();s({weekIndex:t,dayIndex:n,x:i.left+i.width/2,y:i.top})},onMouseLeave:()=>s(e=>e?.weekIndex===t&&e.dayIndex===n?null:e)},e.date||`pad-${t}-${n}`))},e[0]?.date||`week-${t}`))})]}),o&&(()=>{let e=t.weeks[o.weekIndex]?.[o.dayIndex];return e?.date?(0,J.jsxs)(`div`,{className:`heatmap-tip`,role:`tooltip`,style:{left:o.x,top:o.y},children:[(0,J.jsx)(`div`,{className:`heatmap-tip-date`,children:e.date}),(0,J.jsx)(`div`,{className:`heatmap-tip-val`,children:i(`usage.heatmap.tooltipTokens`,{tokens:Pn(e.totalTokens,r)})}),(0,J.jsx)(`div`,{className:`heatmap-tip-req muted`,children:i(`usage.heatmap.tooltipRequests`,{requests:e.requests})})]}):null})(),(0,J.jsxs)(`div`,{className:`heatmap-legend muted`,children:[(0,J.jsx)(`span`,{children:i(`usage.heatmap.less`)}),[0,1,2,3,4].map(e=>(0,J.jsx)(`span`,{className:`heatmap-cell heatmap-cell-${e}`},e)),(0,J.jsx)(`span`,{children:i(`usage.heatmap.more`)})]})]})]})}function nh({title:e,titleId:t,children:n}){return(0,J.jsxs)(`section`,{className:`usw-section`,"aria-labelledby":t,children:[(0,J.jsx)(`h3`,{id:t,className:`h-section`,children:e}),n]})}function rh({models:e,modelQuery:t,onModelQuery:n,locale:r,t:i,workspace:a=!1}){let o=i(`usage.search.models`),s=i(`usage.section.models`),c=`usage-models-title`,l=(0,J.jsx)(`input`,{className:`input`,"aria-label":o,placeholder:o,value:t,onChange:e=>n(e.target.value)}),u=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:i(`logs.col.model`)}),(0,J.jsx)(`th`,{children:i(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:i(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:i(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:il(e.model)}),(0,J.jsx)(`td`,{className:`muted`,children:Dn(e.provider,i)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Pn(e.totalTokens,r)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},`${e.provider}/${e.model}`))})]})});return a?(0,J.jsxs)(nh,{title:s,titleId:c,children:[(0,J.jsx)(`div`,{className:`usw-section-toolbar`,children:l}),u]}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":c,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{id:c,className:`panel-title`,children:s}),l]}),u]})}function ih({providers:e,locale:t,t:n,workspace:r=!1}){let i=n(`usage.section.providers`),a=`usage-providers-title`,o=(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`logs.col.provider`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.requests`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.measured`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`usage.col.tokens`)}),(0,J.jsx)(`th`,{children:n(`usage.col.share`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`mono`,children:Dn(e.provider,n)}),(0,J.jsx)(`td`,{className:`num`,children:e.requests}),(0,J.jsx)(`td`,{className:`num`,children:e.measuredRequests}),(0,J.jsx)(`td`,{className:`num mono`,children:Pn(e.totalTokens,t)}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`div`,{className:`usage-bar`,children:(0,J.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${Math.round(e.shareRatio*100)}%`}})})})]},e.provider))})]})});return r?(0,J.jsx)(nh,{title:i,titleId:a,children:o}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":a,children:[(0,J.jsx)(`h3`,{id:a,className:`panel-title`,children:i}),o]})}function ah({summary:e,t,workspace:n=!1}){let r=t(`usage.section.coverage`),i=`usage-coverage-title`,a=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`usage-cards usage-cards-3x2`,children:[(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.measured`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.measuredRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.reported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.reportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`usage.coverage.estimated`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.estimatedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unreported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unreportedRequests})]}),(0,J.jsxs)(`div`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`muted`,children:t(`logs.tokens.unsupported`)}),(0,J.jsx)(`div`,{className:`stat-value`,children:e.unsupportedRequests})]})]}),(0,J.jsx)(`p`,{className:`muted text-control`,style:{marginTop:12},children:t(`usage.coverage.note`)})]});return n?(0,J.jsx)(nh,{title:r,titleId:i,children:a}):(0,J.jsxs)(`section`,{className:`panel`,style:{marginTop:16},"aria-labelledby":i,children:[(0,J.jsx)(`h3`,{id:i,className:`panel-title`,children:r}),a]})}function oh({data:e,heatmap:t,weekBars:n,activeDays:r,filteredModels:i,modelQuery:a,onModelQuery:o,sortedProviders:s,range:c,locale:l,t:u}){let d=!!e&&e.summary.requests===0,f=[{id:`overview`,label:u(`usage.section.overview`),meta:e?`${e.summary.requests}`:`—`,body:e?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($m,{summary:e.summary,activeDays:r,locale:l,t:u}),(0,J.jsx)(th,{range:c,heatmap:t,weekBars:n,locale:l,t:u})]}):null},{id:`models`,label:u(`usage.section.models`),meta:e?`${e.models.length}`:`—`,body:e?(0,J.jsx)(rh,{models:i,modelQuery:a,onModelQuery:o,locale:l,t:u,workspace:!0}):null},{id:`providers`,label:u(`usage.section.providers`),meta:e?`${e.providers.length}`:`—`,body:e?(0,J.jsx)(ih,{providers:s,locale:l,t:u,workspace:!0}):null},{id:`coverage`,label:u(`usage.section.coverage`),meta:e?Km(e.summary.coverageRatio):`—`,body:e?(0,J.jsx)(ah,{summary:e.summary,t:u,workspace:!0}):null}];return(0,J.jsx)(`div`,{className:`usage-workspace-shell`,children:(0,J.jsxs)(`div`,{className:`usage-workspace-root`,children:[(0,J.jsx)(lp,{scope:`usage`,ariaLabel:u(`usage.workspace.sections`),items:f.map(e=>({id:e.id,label:e.label,meta:e.meta}))}),(0,J.jsx)(`section`,{className:`usage-workspace-main`,"aria-label":u(`usage.workspace.report`),children:d?(0,J.jsx)(Ot,{title:u(`usage.empty`)}):f.map(e=>(0,J.jsx)(`div`,{id:op(`usage`,e.id),className:`usw-body usw-section-block`,children:e.body},e.id))})]})})}var sh=new Map;function ch(e,t,n){return`ocx.usage.v1:${e}:${t}:${n}`}function lh(e,t,n){let r=ch(e,t,n);return sh.get(r)??fr(r)}function uh(e,t,n,r){let i=ch(e,t,n);sh.set(i,r),gr(i,r)}function dh({apiBase:e}){let{t,locale:n}=ct(),[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 uh(e,r,a,i),i},[e,r,a]),u=ch(e,r,a),d=lh(e,r,a),f=ol(u,[e,r,a],l,{isEmpty:()=>!1,initialData:d??void 0}),{state:p}=f,m=p.data??d??null,h=(0,_.useMemo)(()=>Zm(m?.days??[]),[m?.days]),g=(0,_.useMemo)(()=>Jm(m?.days??[]),[m?.days]),v=(0,_.useMemo)(()=>(m?.days??[]).filter(e=>e.requests>0).length,[m?.days]),y=(0,_.useMemo)(()=>{let e=s.trim().toLowerCase(),t=(m?.models??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens);return e?t.filter(t=>t.model.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)||(t.resolvedModel??``).toLowerCase().includes(e)).slice(0,100):t.slice(0,100)},[m?.models,s]),b=(0,_.useMemo)(()=>(m?.providers??[]).toSorted((e,t)=>t.totalTokens-e.totalTokens),[m?.providers]);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head usage-head`,children:[(0,J.jsx)(`h2`,{id:`usage-page-title`,children:t(`usage.title`)}),(0,J.jsx)(Qm,{surface:a,range:r,onSurface:o,onRange:i,t})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`usage.subtitle`)}),p.showSkeleton&&!m?(0,J.jsx)(cl,{label:t(`usage.loading`),rows:5}):p.kind===`failed-cold`?(0,J.jsxs)($,{tone:`err`,children:[p.error instanceof Error?`${t(`usage.loadError`)} ${p.error.message}`:t(`usage.loadError`),` `,(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>f.refresh(),children:t(`common.retry`)})]}):(0,J.jsxs)(J.Fragment,{children:[p.showError&&(0,J.jsx)($,{tone:`err`,children:t(`usage.loadError`)}),m?.historyTruncated&&(0,J.jsx)($,{tone:`warn`,children:(()=>{let e=fh(m.snapshotWindowStart),n=fh(m.snapshotWindowEnd);return e!==null&&n!==null?t(`usage.historyTruncatedWindow`,{start:e,end:n}):t(`usage.historyTruncated`)})()}),(0,J.jsx)(oh,{data:m,heatmap:h,weekBars:g,activeDays:v,filteredModels:y,modelQuery:s,onModelQuery:c,sortedProviders:b,range:r,locale:n,t})]})]})}function fh(e){if(typeof e!=`number`||!Number.isFinite(e))return null;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleString():null}function ph(e,t){if(e<1024)return`${e} B`;let n=[`KiB`,`MiB`,`GiB`,`TiB`],r=e,i=-1;do r/=1024,i++;while(r>=1024&&i<n.length-1);return`${r.toLocaleString(t,{maximumFractionDigits:1})} ${n[i]}`}var mh={en:{compact:`Compact`,compactComplete:`Compaction complete (logical / on-disk reclaimed)`,pagesUnit:`pages`,compactPartial:`Compaction partial (logical / on-disk reclaimed)`,confirmCompact:`Confirm compaction`,cancel:`Cancel`,inspectionOnly:`Inspection only`,externalSqliteHome:`External SQLite storage`,inspectionUnavailable:`Diagnostic log inspection is unavailable.`,metricsSkippedLarge:`Row metrics skipped: the database is above {threshold}, and scanning it would stall the proxy.`,protection:`Protection`,compat:`Compatibility`,quiet:`Quiet`,disable:`Disable protection`,repair:`Repair protection`,applying:`Applying protection…`,"error.generic":`Could not change Codex log protection.`,"error.codex_running":`Quit Codex before changing log protection.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. Protection was not changed.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for protection.`,"error.trigger_collision":`A reserved Log Guard trigger name is already in use. Protection was not changed.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.config_write_failed":`The database changed, but OpenCodex could not save the protection setting. Fix config storage, then run Repair.`},de:{compact:`Komprimieren`,compactComplete:`Komprimierung abgeschlossen (logisch / auf Datentraeger freigegeben)`,pagesUnit:`Seiten`,compactPartial:`Komprimierung teilweise (logisch / auf Datentraeger freigegeben)`,confirmCompact:`Komprimierung bestätigen`,cancel:`Abbrechen`,inspectionOnly:`Nur Inspektion`,externalSqliteHome:`Externer SQLite-Speicher`,inspectionUnavailable:`Die Diagnoseprotokoll-Inspektion ist nicht verfügbar.`,metricsSkippedLarge:`Zeilenmetriken übersprungen: Die Datenbank ist größer als {threshold}; ein Scan würde den Proxy blockieren.`,protection:`Schutz`,compat:`Kompatibilität`,quiet:`Leise`,disable:`Schutz deaktivieren`,repair:`Schutz reparieren`,applying:`Schutz wird angewendet…`,"error.generic":`Der Schutz der Codex-Protokolle konnte nicht geändert werden.`,"error.codex_running":`Beende Codex, bevor du den Protokollschutz änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Schutz wurde nicht geändert.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für den Schutz nicht unterstützt.`,"error.trigger_collision":`Ein reservierter Log-Guard-Triggername wird bereits verwendet. Der Schutz wurde nicht geändert.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.config_write_failed":`Die Datenbank wurde geändert, aber OpenCodex konnte die Schutzeinstellung nicht speichern. Repariere den Konfigurationsspeicher und führe danach Reparieren aus.`},fr:{compact:`Compacter`,compactComplete:`Compactage termine (logique / recupere sur disque)`,pagesUnit:`pages`,compactPartial:`Compactage partiel (logique / recupere sur disque)`,confirmCompact:`Confirmer le compactage`,cancel:`Annuler`,inspectionOnly:`Inspection uniquement`,externalSqliteHome:`Stockage SQLite externe`,inspectionUnavailable:`L’inspection des journaux de diagnostic est indisponible.`,metricsSkippedLarge:`Métriques de lignes ignorées : la base dépasse {threshold} et son analyse bloquerait le proxy.`,protection:`Protection`,compat:`Compatibilité`,quiet:`Silencieux`,disable:`Désactiver la protection`,repair:`Réparer la protection`,applying:`Application de la protection…`,"error.generic":`Impossible de modifier la protection des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier la protection des journaux.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. La protection n’a pas été modifiée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour la protection.`,"error.trigger_collision":`Un nom de déclencheur Log Guard réservé est déjà utilisé. La protection n’a pas été modifiée.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.config_write_failed":`La base de données a été modifiée, mais OpenCodex n’a pas pu enregistrer le paramètre de protection. Corrigez le stockage de configuration, puis lancez Réparer.`},ko:{compact:`압축`,compactComplete:`압축 완료 (논리 / 디스크 회수량)`,pagesUnit:`페이지`,compactPartial:`압축 부분 완료 (논리 / 디스크 회수량)`,confirmCompact:`압축 확인`,cancel:`취소`,inspectionOnly:`검사 전용`,externalSqliteHome:`외부 SQLite 저장소`,inspectionUnavailable:`진단 로그 검사를 사용할 수 없습니다.`,metricsSkippedLarge:`행 지표를 건너뛰었습니다. 데이터베이스가 {threshold}보다 커서 스캔하면 프록시가 멈춥니다.`,protection:`보호`,compat:`호환 모드`,quiet:`조용한 모드`,disable:`보호 비활성화`,repair:`보호 복구`,applying:`보호 적용 중…`,"error.generic":`Codex 로그 보호를 변경하지 못했습니다.`,"error.codex_running":`로그 보호를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 보호를 변경하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 보호 기능을 지원하지 않습니다.`,"error.trigger_collision":`예약된 Log Guard 트리거 이름이 이미 사용 중입니다. 보호를 변경하지 않았습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.config_write_failed":`데이터베이스는 변경되었지만 OpenCodex가 보호 설정을 저장하지 못했습니다. 구성 저장소를 수정한 뒤 복구를 실행하세요.`},zh:{compact:`压缩`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`页`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`确认压缩`,cancel:`取消`,inspectionOnly:`仅检查`,externalSqliteHome:`外部 SQLite 存储`,inspectionUnavailable:`诊断日志检查当前不可用。`,metricsSkippedLarge:`已跳过行指标:数据库超过 {threshold},扫描会阻塞代理。`,protection:`保护`,compat:`兼容模式`,quiet:`静默模式`,disable:`禁用保护`,repair:`修复保护`,applying:`正在应用保护…`,"error.generic":`无法更改 Codex 日志保护。`,"error.codex_running":`更改 Codex 日志保护前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未更改保护设置。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持保护功能。`,"error.trigger_collision":`保留的 Log Guard 触发器名称已被占用,因此未更改保护设置。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.config_write_failed":`数据库已更改,但 OpenCodex 无法保存保护设置。请先修复配置存储,然后运行“修复保护”。`},"zh-TW":{compact:`壓縮`,compactComplete:`压缩完成(逻辑 / 磁盘回收)`,pagesUnit:`頁`,compactPartial:`压缩部分完成(逻辑 / 磁盘回收)`,confirmCompact:`確認壓縮`,cancel:`取消`,inspectionOnly:`僅檢查`,externalSqliteHome:`外部 SQLite 儲存空間`,inspectionUnavailable:`診斷記錄檢查目前無法使用。`,metricsSkippedLarge:`已略過列指標:資料庫超過 {threshold},掃描會阻塞代理。`,protection:`保護`,compat:`相容模式`,quiet:`靜默模式`,disable:`停用保護`,repair:`修復保護`,applying:`正在套用保護…`,"error.generic":`無法變更 Codex 日誌保護。`,"error.codex_running":`變更 Codex 日誌保護前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未變更保護設定。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援保護功能。`,"error.trigger_collision":`保留的 Log Guard 觸發器名稱已被使用,因此未變更保護設定。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.config_write_failed":`資料庫已變更,但 OpenCodex 無法儲存保護設定。請先修復設定儲存空間,再執行「修復保護」。`},ru:{compact:`Сжать`,compactComplete:`Сжатие завершено (логически / освобождено на диске)`,pagesUnit:`страниц`,compactPartial:`Сжатие частичное (логически / освобождено на диске)`,confirmCompact:`Подтвердить сжатие`,cancel:`Отмена`,inspectionOnly:`Только проверка`,externalSqliteHome:`Внешнее хранилище SQLite`,inspectionUnavailable:`Проверка диагностических журналов недоступна.`,metricsSkippedLarge:`Метрики строк пропущены: база больше {threshold}, и её сканирование заблокировало бы прокси.`,protection:`Защита`,compat:`Совместимость`,quiet:`Тихий режим`,disable:`Отключить защиту`,repair:`Восстановить защиту`,applying:`Применение защиты…`,"error.generic":`Не удалось изменить защиту журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением защиты журналов.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Защита не изменена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает защиту.`,"error.trigger_collision":`Зарезервированное имя триггера Log Guard уже используется. Защита не изменена.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.config_write_failed":`База была изменена, но OpenCodex не смог сохранить настройку защиты. Исправьте хранилище конфигурации и затем запустите восстановление.`},ja:{compact:`圧縮`,compactComplete:`圧縮完了(論理 / ディスク解放)`,pagesUnit:`ページ`,compactPartial:`圧縮は部分的に完了(論理 / ディスク解放)`,confirmCompact:`圧縮を確認`,cancel:`キャンセル`,inspectionOnly:`検査のみ`,externalSqliteHome:`外部 SQLite ストレージ`,inspectionUnavailable:`診断ログの検査を利用できません。`,metricsSkippedLarge:`行メトリクスをスキップしました。データベースが {threshold} を超えており、走査するとプロキシが停止します。`,protection:`保護`,compat:`互換モード`,quiet:`静音モード`,disable:`保護を無効化`,repair:`保護を修復`,applying:`保護を適用中…`,"error.generic":`Codex ログ保護を変更できませんでした。`,"error.codex_running":`ログ保護を変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、保護は変更されませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマでは保護機能を使用できません。`,"error.trigger_collision":`予約済みの Log Guard トリガー名が既に使用されています。保護は変更されませんでした。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.config_write_failed":`データベースは変更されましたが、OpenCodex は保護設定を保存できませんでした。設定ストレージを修正してから保護を修復してください。`},tr:{compact:`Sıkıştır`,compactComplete:`Sikistirma tamamlandi (mantiksal / diskte geri kazanilan)`,pagesUnit:`sayfa`,compactPartial:`Sikistirma kismi (mantiksal / diskte geri kazanilan)`,confirmCompact:`Sıkıştırmayı onayla`,cancel:`İptal`,inspectionOnly:`Yalnızca inceleme`,externalSqliteHome:`Harici SQLite depolaması`,inspectionUnavailable:`Tanılama günlüğü incelemesi kullanılamıyor.`,metricsSkippedLarge:`Satır ölçümleri atlandı: veritabanı {threshold} sınırının üzerinde ve taranması proxy’yi kilitler.`,protection:`Koruma`,compat:`Uyumluluk`,quiet:`Sessiz`,disable:`Korumayı devre dışı bırak`,repair:`Korumayı onar`,applying:`Koruma uygulanıyor…`,"error.generic":`Codex günlük koruması değiştirilemedi.`,"error.codex_running":`Günlük korumasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Koruma değiştirilmedi.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması koruma için desteklenmiyor.`,"error.trigger_collision":`Ayrılmış bir Log Guard tetikleyici adı zaten kullanılıyor. Koruma değiştirilmedi.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.config_write_failed":`Veritabanı değişti ancak OpenCodex koruma ayarını kaydedemedi. Yapılandırma depolamasını düzeltip ardından korumayı onarın.`}};function hh(e,t){return mh[e][t]}var gh={en:{applying:`Applying Log Guard change…`,"error.generic":`Could not update Codex log storage.`,"error.codex_running":`Quit Codex before changing Codex log storage.`,"error.process_enumeration_failed":`Could not verify that Codex is stopped. The Log Guard operation was not started.`,"error.busy":`The Codex logs database is busy. Quit Codex and try again.`,"error.unsupported_schema":`This Codex logs schema is not supported for this operation.`,"error.unsafe_path":`The Codex logs database path failed the safety check.`,"error.database_error":`Could not update the Codex logs database.`,"error.auto_vacuum_not_incremental":`This Codex logs database is not configured for incremental vacuum, so space cannot be reclaimed without a full rebuild.`,"error.integrity_check_failed":`The Codex logs database failed its integrity check. No space was reclaimed.`},de:{applying:`Log-Guard-Änderung wird angewendet…`,"error.generic":`Der Codex-Protokollspeicher konnte nicht aktualisiert werden.`,"error.codex_running":`Beende Codex, bevor du den Codex-Protokollspeicher änderst.`,"error.process_enumeration_failed":`Es konnte nicht sicher festgestellt werden, dass Codex beendet ist. Der Log-Guard-Vorgang wurde nicht gestartet.`,"error.busy":`Die Codex-Protokolldatenbank ist belegt. Beende Codex und versuche es erneut.`,"error.unsupported_schema":`Dieses Schema der Codex-Protokolldatenbank wird für diesen Vorgang nicht unterstützt.`,"error.unsafe_path":`Der Pfad der Codex-Protokolldatenbank hat die Sicherheitsprüfung nicht bestanden.`,"error.database_error":`Die Codex-Protokolldatenbank konnte nicht aktualisiert werden.`,"error.auto_vacuum_not_incremental":`Diese Codex-Protokolldatenbank ist nicht fuer inkrementelles Vacuum konfiguriert; ohne vollstaendigen Neuaufbau kann kein Speicher freigegeben werden.`,"error.integrity_check_failed":`Die Integritaetspruefung der Codex-Protokolldatenbank ist fehlgeschlagen. Es wurde kein Speicher freigegeben.`},fr:{applying:`Application de la modification Log Guard…`,"error.generic":`Impossible de mettre à jour le stockage des journaux Codex.`,"error.codex_running":`Quittez Codex avant de modifier le stockage des journaux Codex.`,"error.process_enumeration_failed":`Impossible de vérifier que Codex est arrêté. L’opération Log Guard n’a pas été lancée.`,"error.busy":`La base de données des journaux Codex est occupée. Quittez Codex et réessayez.`,"error.unsupported_schema":`Ce schéma de journaux Codex n’est pas pris en charge pour cette opération.`,"error.unsafe_path":`Le chemin de la base de données des journaux Codex a échoué au contrôle de sécurité.`,"error.database_error":`Impossible de mettre à jour la base de données des journaux Codex.`,"error.auto_vacuum_not_incremental":`Cette base de donnees de journaux Codex n'est pas configuree pour le vacuum incrementiel : l'espace ne peut pas etre recupere sans reconstruction complete.`,"error.integrity_check_failed":`La verification d'integrite de la base de donnees de journaux Codex a echoue. Aucun espace n'a ete recupere.`},ko:{applying:`Log Guard 변경 적용 중…`,"error.generic":`Codex 로그 저장소를 업데이트하지 못했습니다.`,"error.codex_running":`Codex 로그 저장소를 변경하기 전에 Codex를 종료하세요.`,"error.process_enumeration_failed":`Codex가 종료되었는지 확인할 수 없어 Log Guard 작업을 시작하지 않았습니다.`,"error.busy":`Codex 로그 데이터베이스가 사용 중입니다. Codex를 종료한 뒤 다시 시도하세요.`,"error.unsupported_schema":`이 Codex 로그 스키마는 이 작업을 지원하지 않습니다.`,"error.unsafe_path":`Codex 로그 데이터베이스 경로가 안전성 검사를 통과하지 못했습니다.`,"error.database_error":`Codex 로그 데이터베이스를 업데이트하지 못했습니다.`,"error.auto_vacuum_not_incremental":`이 Codex 로그 데이터베이스는 증분 정리로 구성되어 있지 않아, 전체 재구축 없이는 공간을 회수할 수 없습니다.`,"error.integrity_check_failed":`Codex 로그 데이터베이스 무결성 검사에 실패했습니다. 공간이 회수되지 않았습니다.`},zh:{applying:`正在应用 Log Guard 更改…`,"error.generic":`无法更新 Codex 日志存储。`,"error.codex_running":`更改 Codex 日志存储前请先退出 Codex。`,"error.process_enumeration_failed":`无法确认 Codex 已停止,因此未启动 Log Guard 操作。`,"error.busy":`Codex 日志数据库正忙。请退出 Codex 后重试。`,"error.unsupported_schema":`此 Codex 日志数据库结构不支持此操作。`,"error.unsafe_path":`Codex 日志数据库路径未通过安全检查。`,"error.database_error":`无法更新 Codex 日志数据库。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},"zh-TW":{applying:`正在套用 Log Guard 變更…`,"error.generic":`無法更新 Codex 日誌儲存空間。`,"error.codex_running":`變更 Codex 日誌儲存空間前請先退出 Codex。`,"error.process_enumeration_failed":`無法確認 Codex 已停止,因此未啟動 Log Guard 操作。`,"error.busy":`Codex 日誌資料庫忙碌中。請退出 Codex 後重試。`,"error.unsupported_schema":`此 Codex 日誌資料庫結構不支援此操作。`,"error.unsafe_path":`Codex 日誌資料庫路徑未通過安全檢查。`,"error.database_error":`無法更新 Codex 日誌資料庫。`,"error.auto_vacuum_not_incremental":`此 Codex 日志数据库未配置增量清理,因此不完整重建就无法回收空间。`,"error.integrity_check_failed":`Codex 日志数据库完整性检查失败,未回收任何空间。`},ru:{applying:`Применение изменения Log Guard…`,"error.generic":`Не удалось обновить хранилище журналов Codex.`,"error.codex_running":`Закройте Codex перед изменением хранилища журналов Codex.`,"error.process_enumeration_failed":`Не удалось убедиться, что Codex остановлен. Операция Log Guard не запущена.`,"error.busy":`База журналов Codex занята. Закройте Codex и повторите попытку.`,"error.unsupported_schema":`Эта схема базы журналов Codex не поддерживает эту операцию.`,"error.unsafe_path":`Путь к базе журналов Codex не прошёл проверку безопасности.`,"error.database_error":`Не удалось обновить базу журналов Codex.`,"error.auto_vacuum_not_incremental":`Эта база данных журналов Codex не настроена на инкрементальную очистку, поэтому освободить место без полной перестройки невозможно.`,"error.integrity_check_failed":`Проверка целостности базы данных журналов Codex не пройдена. Место не освобождено.`},ja:{applying:`Log Guard の変更を適用中…`,"error.generic":`Codex ログストレージを更新できませんでした。`,"error.codex_running":`Codex ログストレージを変更する前に Codex を終了してください。`,"error.process_enumeration_failed":`Codex が停止していることを確認できなかったため、Log Guard 操作を開始しませんでした。`,"error.busy":`Codex ログデータベースが使用中です。Codex を終了して再試行してください。`,"error.unsupported_schema":`この Codex ログスキーマではこの操作を使用できません。`,"error.unsafe_path":`Codex ログデータベースのパスが安全性チェックに失敗しました。`,"error.database_error":`Codex ログデータベースを更新できませんでした。`,"error.auto_vacuum_not_incremental":`この Codex ログ データベースは増分バキューム用に構成されていないため、完全な再構築なしに領域を解放できません。`,"error.integrity_check_failed":`Codex ログ データベースの整合性チェックに失敗しました。領域は解放されていません。`},tr:{applying:`Log Guard değişikliği uygulanıyor…`,"error.generic":`Codex günlük depolaması güncellenemedi.`,"error.codex_running":`Codex günlük depolamasını değiştirmeden önce Codex'i kapatın.`,"error.process_enumeration_failed":`Codex'in kapalı olduğu doğrulanamadı. Log Guard işlemi başlatılmadı.`,"error.busy":`Codex günlük veritabanı meşgul. Codex'i kapatıp yeniden deneyin.`,"error.unsupported_schema":`Bu Codex günlük şeması bu işlem için desteklenmiyor.`,"error.unsafe_path":`Codex günlük veritabanı yolu güvenlik denetimini geçemedi.`,"error.database_error":`Codex günlük veritabanı güncellenemedi.`,"error.auto_vacuum_not_incremental":`Bu Codex gunluk veritabani artimli vacuum icin yapilandirilmamis; tam yeniden olusturma olmadan alan geri kazanilamaz.`,"error.integrity_check_failed":`Codex gunluk veritabani butunluk denetiminden gecemedi. Alan geri kazanilmadi.`}};function _h(e,t){return gh[e][t]}var vh={en:{schema:{compatible:`Compatible`,missing:`Database not found`,unreadable:`Database unavailable`,unsupported:`Unsupported`},protection:{off:`Off`,active:`Active`,drifted:`Needs repair`,unsupported:`Unsupported`,unknown:`Unknown`},mode:{off:`Off`,compat:`Compatibility`,quiet:`Quiet`,collision:`Unknown`}},de:{schema:{compatible:`Kompatibel`,missing:`Datenbank nicht gefunden`,unreadable:`Datenbank nicht lesbar`,unsupported:`Nicht unterstützt`},protection:{off:`Aus`,active:`Aktiv`,drifted:`Reparatur erforderlich`,unsupported:`Nicht unterstützt`,unknown:`Unbekannt`},mode:{off:`Aus`,compat:`Kompatibilität`,quiet:`Leise`,collision:`Unbekannt`}},fr:{schema:{compatible:`Compatible`,missing:`Base de données introuvable`,unreadable:`Base de données indisponible`,unsupported:`Non pris en charge`},protection:{off:`Désactivée`,active:`Active`,drifted:`Réparation requise`,unsupported:`Non prise en charge`,unknown:`Inconnue`},mode:{off:`Désactivé`,compat:`Compatibilité`,quiet:`Silencieux`,collision:`Inconnu`}},ko:{schema:{compatible:`호환됨`,missing:`데이터베이스 없음`,unreadable:`데이터베이스를 읽을 수 없음`,unsupported:`지원되지 않음`},protection:{off:`꺼짐`,active:`활성`,drifted:`복구 필요`,unsupported:`지원되지 않음`,unknown:`알 수 없음`},mode:{off:`꺼짐`,compat:`호환 모드`,quiet:`조용한 모드`,collision:`알 수 없음`}},zh:{schema:{compatible:`兼容`,missing:`未找到数据库`,unreadable:`无法读取数据库`,unsupported:`不受支持`},protection:{off:`关闭`,active:`已启用`,drifted:`需要修复`,unsupported:`不受支持`,unknown:`未知`},mode:{off:`关闭`,compat:`兼容模式`,quiet:`静默模式`,collision:`未知`}},"zh-TW":{schema:{compatible:`相容`,missing:`找不到資料庫`,unreadable:`無法讀取資料庫`,unsupported:`不支援`},protection:{off:`關閉`,active:`已啟用`,drifted:`需要修復`,unsupported:`不支援`,unknown:`未知`},mode:{off:`關閉`,compat:`相容模式`,quiet:`靜默模式`,collision:`未知`}},ru:{schema:{compatible:`Совместимо`,missing:`База не найдена`,unreadable:`База недоступна`,unsupported:`Не поддерживается`},protection:{off:`Выключено`,active:`Активно`,drifted:`Требуется восстановление`,unsupported:`Не поддерживается`,unknown:`Неизвестно`},mode:{off:`Выключено`,compat:`Совместимость`,quiet:`Тихий режим`,collision:`Неизвестно`}},ja:{schema:{compatible:`互換`,missing:`データベースが見つかりません`,unreadable:`データベースを読み取れません`,unsupported:`未対応`},protection:{off:`オフ`,active:`有効`,drifted:`修復が必要`,unsupported:`未対応`,unknown:`不明`},mode:{off:`オフ`,compat:`互換モード`,quiet:`静音モード`,collision:`不明`}},tr:{schema:{compatible:`Uyumlu`,missing:`Veritabanı bulunamadı`,unreadable:`Veritabanı okunamıyor`,unsupported:`Desteklenmiyor`},protection:{off:`Kapalı`,active:`Etkin`,drifted:`Onarım gerekli`,unsupported:`Desteklenmiyor`,unknown:`Bilinmiyor`},mode:{off:`Kapalı`,compat:`Uyumluluk`,quiet:`Sessiz`,collision:`Bilinmiyor`}}};function yh(e,t){return vh[e].schema[t]}function bh(e,t){return vh[e].protection[t]}function xh(e,t){return vh[e].mode[t]}var Sh=``,Ch={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 wh(e,t){let n=Ch[e.key];return n?t(n):e.label}function Th(e,t){return e===void 0?`—`:new Date(e).toLocaleDateString(t)}function Eh(e,t,n){return e.rows===void 0?`—`:e.rows===null?n(`storage.rows.unknown`):e.rows.toLocaleString(t)}function Dh(e,t){switch(t){case`codex_running`:return _h(e,`error.codex_running`);case`process_enumeration_failed`:return _h(e,`error.process_enumeration_failed`);case`busy`:return _h(e,`error.busy`);case`unsupported_schema`:return _h(e,`error.unsupported_schema`);case`trigger_collision`:return hh(e,`error.trigger_collision`);case`unsafe_path`:return _h(e,`error.unsafe_path`);case`database_error`:return _h(e,`error.database_error`);case`auto_vacuum_not_incremental`:return _h(e,`error.auto_vacuum_not_incremental`);case`integrity_check_failed`:return _h(e,`error.integrity_check_failed`);case`config_write_failed`:return hh(e,`error.config_write_failed`);default:return _h(e,`error.generic`)}}function Oh({report:e,locale:t,t:n,busy:r,error:i,compaction:a,onAction:o}){let s=e.metrics,c=e.capabilities.protection.state===`unsupported`||e.capabilities.reclaim.state===`unsupported`,l=e.protection,u=r||e.capabilities.protection.state!==`supported`,d=l!==void 0&&e.capabilities.reclaim.state===`supported`&&(s?.reclaimableBytes??0)>0,[f,p]=(0,_.useState)(!1);return(0,J.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:n(`storage.bucket.logs_db`)}),(0,J.jsxs)(`dl`,{className:`stw-kv`,children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`dash.status`)}),(0,J.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(0,J.jsx)(`code`,{children:yh(t,e.schema.state)}),c&&e.schema.state===`unsupported`?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,J.jsx)(`code`,{children:hh(t,`inspectionOnly`)})]}):null]})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.bucket.logs_db`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(e.files.databaseBytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`WAL`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(e.files.walBytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`SHM`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(e.files.shmBytes,t)})]}),s&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:s.totalRows.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`TRACE`})}),(0,J.jsxs)(`dd`,{className:`stw-kv-mono`,children:[(s.traceShare*100).toFixed(1),`%`]})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`freelist`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(s.reclaimableBytes,t)})]})]}),!s&&e.metricsSkipped&&(0,J.jsxs)(`div`,{className:`stw-kv-row`,"data-testid":`log-guard-metrics-skipped`,children:[(0,J.jsx)(`dt`,{children:n(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`muted`,children:hh(t,`metricsSkippedLarge`).replace(`{threshold}`,ph(e.metricsSkipped.thresholdBytes,t))})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:(0,J.jsx)(`code`,{children:`sqlite_home`})}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:(0,J.jsx)(`code`,{children:e.externalSqliteHome?hh(t,`externalSqliteHome`):`CODEX_HOME`})})]})]}),l&&(0,J.jsxs)(`div`,{className:`stw-section`,"data-testid":`log-guard-protection`,children:[(0,J.jsx)(`h4`,{className:`stw-section-title`,children:hh(t,`protection`)}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`span`,{className:`muted`,children:(0,J.jsx)(`code`,{children:bh(t,l.state)})}),(0,J.jsxs)(`span`,{className:`stw-kv-mono`,children:[(0,J.jsx)(`code`,{children:xh(t,l.desiredMode)}),l.observedMode===l.desiredMode?null:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`span`,{"aria-hidden":`true`,children:` · `}),(0,J.jsx)(`code`,{children:xh(t,l.observedMode)})]})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-compat`,disabled:u,"aria-pressed":l.desiredMode===`compat`,onClick:()=>o({action:`protect`,mode:`compat`}),children:hh(t,`compat`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-protect-quiet`,disabled:u,"aria-pressed":l.desiredMode===`quiet`,onClick:()=>o({action:`protect`,mode:`quiet`}),children:hh(t,`quiet`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-unprotect`,disabled:u||l.desiredMode===`off`,onClick:()=>o({action:`unprotect`}),children:hh(t,`disable`)}),l.state===`drifted`&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-repair`,disabled:u,onClick:()=>o({action:`repair`}),children:hh(t,`repair`)}),r&&(0,J.jsx)(`span`,{className:`muted`,role:`status`,children:_h(t,`applying`)})]}),i&&(0,J.jsx)(`p`,{className:`err`,role:`alert`,children:i})]}),d&&(0,J.jsx)(`div`,{className:`stw-section`,"data-testid":`log-guard-reclaim`,children:(0,J.jsx)(`div`,{className:`storage-policy-actions`,children:f?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"data-testid":`log-guard-compact-confirm`,disabled:r,onClick:()=>{p(!1),o({action:`compact`})},children:hh(t,`confirmCompact`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:r,onClick:()=>p(!1),children:hh(t,`cancel`)})]}):(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"data-testid":`log-guard-compact`,disabled:r,onClick:()=>p(!0),children:hh(t,`compact`)})})}),a&&(0,J.jsx)(`div`,{className:`stw-section`,children:(0,J.jsx)(`p`,{className:`stw-kv-mono`,role:`status`,"data-testid":`log-guard-compact-result`,children:a})}),s&&s.topTargets.length>0&&(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h4`,{className:`stw-section-title`,children:(0,J.jsx)(`code`,{children:`target`})}),s.topTargets.slice(0,5).map(e=>(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.target,children:(0,J.jsx)(`code`,{children:e.target})}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:e.rows.toLocaleString(t)})]},e.target))]}),(0,J.jsx)(`p`,{className:`stw-hint`,children:(0,J.jsxs)(`code`,{children:[`immutable=1 · snapshot=`,e.snapshot]})})]})}function kh({locale:e,t}){return(0,J.jsxs)(`div`,{className:`stw-section`,"data-testid":`codex-log-guard-unavailable`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:t(`storage.bucket.logs_db`)}),(0,J.jsx)(`p`,{className:`stw-hint`,children:hh(e,`inspectionUnavailable`)})]})}function Ah({report:e,locale:t,logGuardBusy:n=!1,onLogGuardAction:r}){let i=Q(),[a,o]=(0,_.useState)(null),[s,c]=(0,_.useState)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),h=(0,_.useMemo)(()=>e.buckets.toSorted((e,t)=>t.bytes-e.bytes),[e.buckets]),g=h.find(e=>e.key===a)??null,v=s?.generation===e.generatedAt?s.report:e.codexLogs??null,y=d?.generation===e.generatedAt?d.message:null,b=p?.generation===e.generatedAt?p.summary:null,x=n||l,S=(0,_.useMemo)(()=>{let t=[];for(let n of e.buckets)for(let e of n.largest??[])t.push({...e,bucketKey:n.key});return t.sort((e,t)=>t.bytes-e.bytes).slice(0,10)},[e.buckets]),C=(0,_.useMemo)(()=>new Map(e.buckets.map(e=>[e.key,e])),[e.buckets]);return(0,J.jsxs)(`div`,{className:`storage-workspace-root`,children:[(0,J.jsxs)(`aside`,{className:`storage-workspace-rail`,"aria-label":i(`storage.section.buckets`),children:[(0,J.jsxs)(`div`,{className:`storage-workspace-rail-header`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-title`,children:i(`storage.section.buckets`)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-count`,children:h.length})]}),(0,J.jsx)(`div`,{className:`storage-workspace-rail-list`,children:h.length===0?(0,J.jsx)(`span`,{className:`storage-workspace-rail-empty`,children:i(`storage.empty`)}):h.map(e=>(0,J.jsxs)(`button`,{type:`button`,className:`storage-workspace-rail-row${a===e.key?` storage-workspace-rail-row--selected`:``}`,onClick:()=>o(t=>t===e.key?null:e.key),"aria-current":a===e.key?`true`:void 0,children:[(0,J.jsxs)(`span`,{className:`storage-workspace-rail-primary`,children:[(0,J.jsx)(`span`,{className:`storage-workspace-rail-name`,children:wh(e,i)}),(0,J.jsx)(`span`,{className:`storage-workspace-rail-size`,children:ph(e.bytes,t)})]}),(0,J.jsxs)(`span`,{className:`storage-workspace-rail-meta`,children:[e.fileCount.toLocaleString(t),` `,i(`storage.col.files`).toLowerCase()]})]},e.key))})]}),(0,J.jsx)(`section`,{className:`storage-workspace-main`,"aria-label":g?wh(g,i):i(`storage.section.largest`),children:g?(0,J.jsxs)(`div`,{className:`stw-detail`,children:[(0,J.jsx)(`div`,{className:`stw-detail-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`stw-detail-back`,onClick:()=>o(null),children:[(0,J.jsx)(Se,{className:`stw-detail-back-chevron`,"aria-hidden":`true`}),i(`modal.back`)]})}),(0,J.jsxs)(`div`,{className:`stw-detail-body`,children:[(0,J.jsx)(`h2`,{className:`stw-detail-title`,children:wh(g,i)}),(0,J.jsxs)(`dl`,{className:`stw-kv`,children:[(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.size`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:ph(g.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.files`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:g.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.oldest`)}),(0,J.jsx)(`dd`,{children:Th(g.oldest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.newest`)}),(0,J.jsx)(`dd`,{children:Th(g.newest,t)})]}),(0,J.jsxs)(`div`,{className:`stw-kv-row`,children:[(0,J.jsx)(`dt`,{children:i(`storage.col.rows`)}),(0,J.jsx)(`dd`,{className:`stw-kv-mono`,children:Eh(g,t,i)})]})]}),(g.largest?.length??0)>0&&(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:i(`storage.section.largest`)}),g.largest.map(e=>(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:ph(e.bytes,t)})]},e.path))]})]})]}):(0,J.jsxs)(`div`,{className:`stw-overview`,children:[(0,J.jsxs)(`div`,{className:`stw-summary`,children:[(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:i(`storage.card.total`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:ph(e.total.bytes,t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:i(`storage.card.files`)}),(0,J.jsx)(`div`,{className:`stw-summary-value`,children:e.total.fileCount.toLocaleString(t)})]}),(0,J.jsxs)(`div`,{className:`stw-summary-card`,children:[(0,J.jsx)(`div`,{className:`stw-summary-label`,children:i(`storage.card.home`)}),(0,J.jsx)(`div`,{className:`stw-summary-value mono stw-home-path`,title:e.codexHome,children:e.codexHome})]})]}),v?(0,J.jsx)(Oh,{report:v,locale:t,t:i,busy:x,error:y,compaction:b,onAction:n=>{if(r){r(n);return}if(l)return;let i=e.generatedAt;(async()=>{u(!0),f(null),n.action===`compact`&&m(null);try{let e=n.action===`protect`?`protect`:n.action,r={method:`POST`,...n.action===`protect`?{headers:{"content-type":`application/json`},body:JSON.stringify({mode:n.mode})}:{}},a=await fetch(`${Sh}/api/storage/codex-logs/${e}`,r);if(!a.ok){let e=await a.json().catch(()=>({}));f({generation:i,message:Dh(t,e.error)});return}if(n.action===`compact`){let e=(await a.json().catch(()=>null))?.report;if(e){let n=ph(e.logicalBytesReclaimed??0,t),r=ph(e.physicalDatabaseBytesReclaimed??0,t),a=e.complete?hh(t,`compactComplete`):hh(t,`compactPartial`),o=e.pagesReclaimed??0,s=!e.complete&&e.stopReason?` (${e.stopReason})`:``;m({generation:i,summary:[`${a}${s}`,`${o.toLocaleString(t)} ${hh(t,`pagesUnit`)}`,`${n} / ${r}`].join(` — `)})}try{let e=await fetch(`${Sh}/api/storage/codex-logs`);if(e.ok){let t=await e.json();c({generation:i,report:t})}}catch{}return}let o=await a.json();c({generation:i,report:o})}catch{f({generation:i,message:_h(t,`error.generic`)})}finally{u(!1)}})()}}):e.codexLogsError===`inspect_failed`?(0,J.jsx)(kh,{locale:t,t:i}):null,S.length>0?(0,J.jsxs)(`div`,{className:`stw-section`,children:[(0,J.jsx)(`h3`,{className:`stw-section-title`,children:i(`storage.section.largest`)}),S.map(e=>{let n=C.get(e.bucketKey);return(0,J.jsxs)(`div`,{className:`stw-file-row`,children:[(0,J.jsx)(`span`,{className:`stw-file-path`,title:e.path,children:e.path}),n&&(0,J.jsx)(`span`,{className:`stw-file-bucket`,children:wh(n,i)}),(0,J.jsx)(`span`,{className:`stw-file-size`,children:ph(e.bytes,t)})]},`${e.bucketKey}:${e.path}`)})]}):(0,J.jsxs)(`p`,{className:`stw-hint`,children:[(0,J.jsx)(ce,{style:{width:14,height:14,verticalAlign:`text-bottom`,marginRight:6},"aria-hidden":`true`}),i(`storage.workspace.selectBucket`)]})]})})]})}var jh=1024**3,Mh=[10,25,50],Nh=(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 Ph({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(Nh(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:ph(a.bytes,t)})),r()}catch(e){v(Nh(e,n(`storage.cleanup.cleanupFailed`)))}finally{p(!1)}}};return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.cleanup.help`)}),(0,J.jsxs)(`div`,{className:`storage-manual-panel__controls`,children:[(0,J.jsxs)(`label`,{className:`storage-manual-panel__slider`,children:[(0,J.jsx)(`span`,{className:`muted mono`,style:{minWidth:`3.5rem`,fontVariantNumeric:`tabular-nums`},children:n(`storage.cleanup.percent`,{percent:String(i)})}),(0,J.jsx)(`input`,{type:`range`,min:1,max:100,value:i,onChange:e=>a(Number(e.target.value)),disabled:f,style:{flex:1,minWidth:0},"aria-label":n(`storage.cleanup.slider`)})]}),(0,J.jsx)(`div`,{className:`storage-manual-panel__presets`,children:Mh.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm${i===e?` active`:``}`,disabled:f,onClick:()=>a(e),children:w(e)},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:f,onClick:()=>void T(),children:n(`storage.cleanup.preview`)})]}),m&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:m}),g&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},children:g}),c&&o&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-cleanup-confirm-title`,onClick:()=>!f&&S(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-cleanup-confirm-title`,children:n(`storage.cleanup.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.cleanup.confirmBody`,{count:String(o.count),size:ph(o.bytes,t),percent:String(o.percent)})}),o.candidates.length>0&&(0,J.jsxs)(`ul`,{className:`mono muted`,style:{maxHeight:160,overflow:`auto`,fontSize:`var(--text-caption)`},children:[o.candidates.slice(0,8).map(e=>(0,J.jsx)(`li`,{children:e.relPath},e.relPath)),o.count>8&&(0,J.jsx)(`li`,{children:n(`storage.cleanup.moreFiles`,{n:String(Math.max(0,o.count-8))})})]}),(0,J.jsxs)(`label`,{style:{display:`flex`,gap:8,alignItems:`center`,marginTop:12},children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:u,disabled:f,onChange:e=>d(e.target.checked)}),(0,J.jsx)(`span`,{children:n(`storage.cleanup.permanent`)})]}),(0,J.jsx)(`p`,{className:`muted`,style:{marginTop:8,fontSize:`var(--text-caption)`},children:n(u?`storage.cleanup.permanentWarn`:`storage.cleanup.quarantineNote`)}),g&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:g}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:y,type:`button`,className:`btn btn-ghost`,disabled:f,onClick:()=>S(),children:n(`storage.cleanup.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:u?`btn btn-danger`:`btn`,disabled:f||o.count===0,onClick:()=>void E(),children:n(u?`storage.cleanup.confirmPermanent`:`storage.cleanup.confirmQuarantine`)})]})]})})]})}function Fh({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=ol(`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:ph(a.bytes,t)})),r()}catch(e){p(Nh(e,n(`storage.trash.restoreFailed`)))}finally{s(!1)}}},w=e=>{let n=e.quarantinedAt??Number(e.epoch.split(`-`)[0]);return!Number.isFinite(n)||n<=0?`—`:new Date(n).toLocaleString(t)},T=e=>e===`permanent`?n(`storage.trash.mode.permanent`):e===`quarantine`?n(`storage.trash.mode.quarantine`):`—`;return(0,J.jsxs)(`section`,{className:`storage-cleanup-pane storage-quarantine-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-manual-panel__help`,children:n(`storage.trash.help`)}),u&&(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:u}),f&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:f}),b.showError&&!c&&(0,J.jsx)(`p`,{className:`storage-manual-panel__status`,style:{color:`var(--red)`},role:`alert`,children:b.error instanceof Error?b.error.message:n(`storage.trash.listFailed`)}),b.refreshing&&!b.showSkeleton&&(0,J.jsx)(ll,{live:!b.showError,children:n(`storage.trash.loading`)}),b.showSkeleton?(0,J.jsx)(cl,{label:n(`storage.trash.loading`),rows:2}):x.length===0?(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)}):(0,J.jsx)(`div`,{className:`tbl-wrap storage-manual-panel__table`,children:(0,J.jsxs)(`table`,{className:`tbl`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:n(`storage.trash.col.when`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.files`)}),(0,J.jsx)(`th`,{className:`num`,children:n(`storage.trash.col.size`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.mode`)}),(0,J.jsx)(`th`,{children:n(`storage.trash.col.id`)}),(0,J.jsx)(`th`,{})]})}),(0,J.jsx)(`tbody`,{children:x.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{className:`muted`,children:w(e)}),(0,J.jsx)(`td`,{className:`num`,children:e.fileCount}),(0,J.jsx)(`td`,{className:`num mono`,children:ph(e.bytes,t)}),(0,J.jsx)(`td`,{className:`muted`,children:T(e.mode)}),(0,J.jsx)(`td`,{className:`mono`,style:{fontSize:`var(--text-caption)`},children:e.id}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:o,onClick:()=>{p(null),l(e)},children:n(`storage.trash.restore`)})})]},e.id))})]})}),c&&(0,J.jsx)(`div`,{className:`modal-overlay`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`storage-trash-confirm-title`,onClick:()=>!o&&v(),children:(0,J.jsxs)(`div`,{className:`modal-card`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(`h3`,{id:`storage-trash-confirm-title`,children:n(`storage.trash.confirmTitle`)}),(0,J.jsx)(`p`,{children:n(`storage.trash.confirmBody`,{count:String(c.fileCount),size:ph(c.bytes,t),id:c.id})}),f&&(0,J.jsx)(`p`,{style:{marginTop:12,color:`var(--red)`},children:f}),(0,J.jsxs)(`div`,{className:`dialog-actions`,style:{marginTop:16},children:[(0,J.jsx)(`button`,{ref:m,type:`button`,className:`btn btn-ghost`,disabled:o,onClick:()=>v(),children:n(`storage.trash.cancel`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn`,disabled:o,onClick:()=>void C(),children:n(`storage.trash.confirmRestore`)})]})]})})]})}function Ih(e){let{job:t,...n}=e;return n}function Lh(e){let t=String(Math.max(0,Math.round(e.trigger.archivedBytesOver/jh*100)/100));return e.target.reduceToBytes===void 0?{policy:Ih(e),thresholdGb:t,targetMode:`percent`,percent:String(Math.min(100,Math.max(1,Math.floor(e.target.removeOldestPercent??25)))),reduceGb:`4`}:{policy:Ih(e),thresholdGb:t,targetMode:`reduce`,percent:`25`,reduceGb:String(Math.max(0,Math.round(e.target.reduceToBytes/jh*100)/100))}}async function Rh(e){await new Promise(t=>window.setTimeout(t,e))}function zh({apiBase:e,locale:t,t:n,onDone:r}){let i=`ocx.storage.cleanup-policy.v1:${e}`,a=fr(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=Lh(e);c(t.policy),D(t.thresholdGb),x(t.targetMode),C(t.percent),T(t.reduceGb),o.current=!0,gr(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*jh)}}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*jh)},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 Rh(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=Ih(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.ok&&f.metadataPersistenceError?(y(n(`storage.policy.metadataSaveWarning`)),f.removed!==void 0&&r()):f.skipped===`under_threshold`?g(n(`storage.policy.skippedUnder`)):f.skipped===`nothing_selected`?g(n(`storage.policy.skippedEmpty`)):f.deferred===`codex_busy`||f.error===`codex_busy`?y(n(`storage.cleanup.err.codex_busy`)):f.ok?(g(f.mode===`permanent`?n(`storage.policy.donePermanent`,{count:String(f.removed??0),size:ph(f.freedBytes??0,t)}):n(`storage.policy.doneQuarantine`,{count:String(f.removed??0),size:ph(f.freedBytes??0,t)})),r()):y(n(`storage.policy.runFailed`))}catch(e){if(a.aborted||e instanceof DOMException&&e.name===`AbortError`)return;y(n(`storage.policy.runFailed`))}finally{O.current===i&&(O.current=null),a.aborted||m(!1)}},z=e=>e===void 0?n(`storage.policy.never`):new Date(e).toLocaleString(t);return l&&!s?(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.loading`)})}):s?(0,J.jsxs)(`section`,{className:`storage-cleanup-pane`,children:[(0,J.jsx)(`p`,{className:`muted storage-policy-help`,children:n(`storage.policy.help`)}),(0,J.jsx)(`div`,{className:`storage-policy-enable`,children:(0,J.jsxs)(`div`,{className:`storage-policy-enable-row`,children:[(0,J.jsx)(`button`,{type:`button`,className:`toggle${s.enabled?` on`:``}`,disabled:d||p,"aria-pressed":s.enabled,"aria-label":n(`storage.policy.enabled`),title:n(`storage.policy.enabledHint`),onClick:()=>void L({enabled:!s.enabled}),children:(0,J.jsx)(`span`,{className:`toggle-knob`})}),(0,J.jsx)(`span`,{children:n(`storage.policy.enabled`)})]})}),(0,J.jsxs)(`div`,{className:`storage-policy-fields`,children:[(0,J.jsxs)(`div`,{className:`field storage-policy-trigger`,children:[(0,J.jsx)(`label`,{className:`field-label`,htmlFor:`storage-policy-threshold`,children:n(`storage.policy.trigger`)}),(0,J.jsxs)(`div`,{className:`storage-policy-trigger-row`,children:[(0,J.jsx)(`span`,{className:`storage-policy-trigger-hint`,children:n(`storage.policy.threshold`)}),(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-threshold`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:E,disabled:d||p,"aria-label":n(`storage.policy.threshold`),onFocus:()=>P(!0),onChange:e=>{N(),D(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(So,{disabled:d||p,incrementLabel:n(`storage.policy.thresholdInc`),decrementLabel:n(`storage.policy.thresholdDec`),onIncrement:()=>{N(),D(xo(E,.1,0,1e4,.1))},onDecrement:()=>{N(),D(xo(E,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`fieldset`,{className:`field storage-policy-target`,children:[(0,J.jsx)(`legend`,{className:`field-label`,children:n(`storage.policy.target`)}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`percent`,disabled:d||p,onChange:()=>{N(),x(`percent`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetPercent`)}),b===`percent`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-percent`,className:`input mono codex-auto-switch-input`,type:`number`,min:1,max:100,step:1,inputMode:`numeric`,value:S,disabled:d||p,"aria-label":n(`storage.policy.targetPercent`),onFocus:()=>P(!0),onChange:e=>{N(),C(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`%`}),(0,J.jsx)(So,{disabled:d||p,incrementLabel:n(`storage.policy.percentInc`),decrementLabel:n(`storage.policy.percentDec`),onIncrement:()=>{N(),C(xo(S,1,1,100))},onDecrement:()=>{N(),C(xo(S,-1,1,100))}})]})]}),(0,J.jsxs)(`label`,{className:`storage-policy-target-row`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`storage-policy-target`,checked:b===`reduce`,disabled:d||p,onChange:()=>{N(),x(`reduce`)}}),(0,J.jsx)(`span`,{className:`storage-policy-target-label`,children:n(`storage.policy.targetReduce`)}),b===`reduce`&&(0,J.jsxs)(`span`,{className:`codex-auto-switch-input-wrap`,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(P(!1),L())},children:[(0,J.jsx)(`input`,{id:`storage-policy-reduce`,className:`input mono codex-auto-switch-input`,type:`number`,min:0,step:.1,inputMode:`decimal`,value:w,disabled:d||p,"aria-label":n(`storage.policy.targetReduce`),onFocus:()=>P(!0),onChange:e=>{N(),T(e.target.value)},onKeyDown:e=>{e.nativeEvent.isComposing||d||p||e.key===`Enter`&&(e.preventDefault(),L())}}),(0,J.jsx)(`span`,{className:`codex-auto-switch-unit`,"aria-hidden":`true`,children:`GiB`}),(0,J.jsx)(So,{disabled:d||p,incrementLabel:n(`storage.policy.reduceInc`),decrementLabel:n(`storage.policy.reduceDec`),onIncrement:()=>{N(),T(xo(w,.1,0,1e4,.1))},onDecrement:()=>{N(),T(xo(w,-.1,0,1e4,.1))}})]})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-selects`,children:[(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-schedule`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.schedule`)}),(0,J.jsxs)(`select`,{id:`storage-policy-schedule`,className:`input`,value:s.schedule,disabled:d||p,onChange:e=>{let t=e.target.value;L({schedule:t})},children:[(0,J.jsx)(`option`,{value:`manual`,children:n(`storage.policy.schedule.manual`)}),(0,J.jsx)(`option`,{value:`startup`,children:n(`storage.policy.schedule.startup`)}),(0,J.jsx)(`option`,{value:`daily`,children:n(`storage.policy.schedule.daily`)}),(0,J.jsx)(`option`,{value:`weekly`,children:n(`storage.policy.schedule.weekly`)})]})]}),(0,J.jsxs)(`label`,{className:`field`,htmlFor:`storage-policy-mode`,children:[(0,J.jsx)(`span`,{className:`field-label`,children:n(`storage.policy.mode`)}),(0,J.jsxs)(`select`,{id:`storage-policy-mode`,className:`input`,value:s.mode,disabled:d||p,onChange:e=>{let t=e.target.value;L({mode:t})},children:[(0,J.jsx)(`option`,{value:`quarantine`,children:n(`storage.policy.mode.quarantine`)}),(0,J.jsx)(`option`,{value:`permanent`,children:n(`storage.policy.mode.permanent`)})]})]})]}),s.mode===`permanent`&&(0,J.jsx)(`p`,{className:`err storage-policy-warn`,role:`status`,children:n(`storage.policy.permanentWarn`)})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta`,children:[(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.lastRun`)}),(0,J.jsxs)(`span`,{className:`storage-policy-meta-value`,children:[z(s.lastRun?.at),s.lastRun?` · ${n(`storage.policy.lastRunDetail`,{count:String(s.lastRun.removed),size:ph(s.lastRun.freedBytes,t)})}`:``]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-meta-item`,children:[(0,J.jsx)(`span`,{className:`muted`,children:n(`storage.policy.nextRun`)}),(0,J.jsx)(`span`,{className:`storage-policy-meta-value`,children:z(s.nextRun)})]})]}),(0,J.jsxs)(`div`,{className:`storage-policy-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:d||p,onClick:()=>void L(),children:n(`storage.policy.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,disabled:d||p,onClick:()=>void R(),children:n(p?`storage.policy.running`:`storage.policy.runNow`)}),(0,J.jsx)(`span`,{className:`storage-policy-actions__status${v?` is-error`:``}`,role:v?`alert`:`status`,"aria-live":`polite`,children:v??h??``})]})]}):(0,J.jsx)(`section`,{className:`storage-cleanup-pane`,children:v&&(0,J.jsx)(`p`,{className:`err`,role:`alert`,children:v})})}function Bh({apiBase:e,locale:t,t:n,archivedCount:r,showQuarantine:i,trashReloadToken:a,onDone:o,onTrashEntriesChange:s}){let[c,l]=(0,_.useState)(`policy`),u=(0,_.useRef)(null),d=(0,_.useRef)(null),f=[{id:`policy`,label:n(`storage.cleanupCard.tab.policy`),ref:u},{id:`quarantine`,label:n(`storage.cleanupCard.tab.quarantine`),ref:d}],p=e=>{l(e),window.requestAnimationFrame(()=>(e===`policy`?u:d).current?.focus())},m=e=>{e.key===`ArrowLeft`||e.key===`ArrowRight`?(e.preventDefault(),p(c===`policy`?`quarantine`:`policy`)):e.key===`Home`?(e.preventDefault(),p(`policy`)):e.key===`End`&&(e.preventDefault(),p(`quarantine`))};return(0,J.jsxs)(`section`,{className:`panel storage-cleanup-card`,"aria-labelledby":`storage-cleanup-card-title`,children:[(0,J.jsx)(`div`,{className:`page-tabs storage-cleanup-card__tabs`,role:`tablist`,"aria-label":n(`storage.cleanupCard.tabs`),children:f.map(({id:e,label:t,ref:n})=>(0,J.jsx)(`button`,{type:`button`,role:`tab`,ref:n,id:`storage-cleanup-tab-${e}`,"aria-selected":c===e,"aria-controls":`storage-cleanup-panel-${e}`,tabIndex:c===e?0:-1,className:`page-tab${c===e?` page-tab--active`:``}`,onKeyDown:m,onClick:()=>p(e),children:t},e))}),(0,J.jsx)(`h3`,{id:`storage-cleanup-card-title`,className:`panel-title`,children:n(`storage.cleanupCard.title`)}),(0,J.jsxs)(`div`,{className:`storage-cleanup-card__stack`,children:[(0,J.jsxs)(`div`,{id:`storage-cleanup-panel-policy`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-policy`,className:`storage-cleanup-card__body storage-cleanup-policy-split`,"data-active":c===`policy`?`true`:`false`,"aria-hidden":c!==`policy`,...c===`policy`?{}:{inert:!0},children:[(0,J.jsx)(zh,{apiBase:e,locale:t,t:n,onDone:o}),(0,J.jsxs)(`aside`,{className:`storage-cleanup-manual`,"aria-labelledby":`storage-cleanup-manual-title`,children:[(0,J.jsx)(`h4`,{id:`storage-cleanup-manual-title`,className:`storage-cleanup-manual__title`,children:n(`storage.cleanup.title`)}),r>0?(0,J.jsx)(Ph,{apiBase:e,locale:t,t:n,onDone:o}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.cleanup.noArchives`)})]})]}),(0,J.jsx)(`div`,{id:`storage-cleanup-panel-quarantine`,role:`tabpanel`,"aria-labelledby":`storage-cleanup-tab-quarantine`,className:`storage-cleanup-card__body`,"data-active":c===`quarantine`?`true`:`false`,"aria-hidden":c!==`quarantine`,...c===`quarantine`?{}:{inert:!0},children:i?(0,J.jsx)(Fh,{apiBase:e,locale:t,t:n,onDone:o,reloadToken:a,onEntriesChange:s}):(0,J.jsx)(`p`,{className:`muted storage-manual-panel__status`,children:n(`storage.trash.empty`)})})]})]})}function Vh({apiBase:e}){let{t,locale:n}=ct(),r=`ocx.storage.report.v1:${e}`,i=fr(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 gr(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=ol(`storage-report:${e}`,[e],f,{isEmpty:e=>e.total.fileCount===0&&e.error===void 0}),m=p.state,h=m.data??i,g=m.refreshing||m.showSkeleton&&!h,v=p.refresh,y=(0,_.useCallback)(()=>{o(null),l.current=!0,v(),c(e=>e+1)},[v]),b=(0,_.useCallback)(t=>{d({apiBase:e,settled:!0,hasEntries:t.length>0})},[e]),x=u.apiBase===e&&u.settled,S=u.apiBase===e&&u.hasEntries,C=h?.error!==void 0,w=!g&&!m.showError&&!C&&h.total.fileCount===0&&x&&!S,T=h?.buckets.find(e=>e.key===`archived_sessions`)?.fileCount??0,E=!!h&&!C,D=E&&(h.total.fileCount>0||!x||S);return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsx)(`h2`,{id:`storage-page-title`,children:t(`storage.title`)}),(0,J.jsxs)(`div`,{className:`storage-page-head-actions`,children:[(0,J.jsx)(`span`,{className:`storage-page-head-feedback`,role:`status`,"aria-live":`polite`,children:a??``}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:g,onClick:()=>void y(),children:[(0,J.jsx)(fe,{}),` `,t(`storage.refresh`)]})]})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`storage.subtitle`)}),h&&h.error===void 0&&(0,J.jsxs)(`p`,{className:`storage-page-meta`,children:[(0,J.jsx)(`code`,{className:`mono storage-page-meta__home`,title:h.codexHome,children:h.codexHome}),(0,J.jsx)(`span`,{className:`storage-page-meta__sep`,"aria-hidden":`true`,children:`·`}),(0,J.jsxs)(`span`,{children:[t(`storage.snapshot.lastScan`),`:`,` `,new Date(h.generatedAt).toLocaleString(n)]})]}),m.showSkeleton&&!h?(0,J.jsx)(cl,{label:t(`storage.loading`),rows:5}):m.kind===`failed-cold`&&!h?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:m.error instanceof Error?m.error.message:t(`storage.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>v(),children:t(`common.retry`)})]}):C?(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)})}):(0,J.jsxs)(J.Fragment,{children:[m.showError&&(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:t(`storage.error`)}),w?(0,J.jsx)(Ot,{title:t(`storage.empty`)}):h&&h.total.fileCount>0&&(0,J.jsx)(Ah,{report:h,locale:n})]}),h&&h.error===void 0&&m.refreshing&&!m.showSkeleton&&(0,J.jsx)(ll,{live:!m.showError,children:t(`storage.loading`)}),E&&(0,J.jsx)(Bh,{apiBase:e,locale:n,t,archivedCount:T,showQuarantine:D,trashReloadToken:s,onDone:()=>void y(),onTrashEntriesChange:b})]})}var Hh=`/api/codex-auth/features/default-mode-request-user-input`;function Uh({apiBase:e}){let t=Q(),[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,n=Ln(15e3);try{let i=await fetch(`${e}${Hh}`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(f.current||t!==m.current)return;p.current=o.enabled===!0,r(p.current),a(!0),l(!1)}catch{!f.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=Vn(()=>{h()},3e4);return()=>{window.clearTimeout(e),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}${Hh}`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({enabled:n})}),o=await Pt(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,J.jsxs)(`div`,{className:`card card-row codex-request-user-input-card`,style:{marginTop:16},"aria-busy":o||!i&&!c||void 0,children:[(0,J.jsxs)(`div`,{className:`codex-request-user-input-copy`,children:[(0,J.jsx)(`strong`,{children:t(`codexAuth.requestUserInput`)}),(0,J.jsx)(`div`,{className:`card-sub`,role:c?`alert`:void 0,children:t(c?`codexAuth.requestUserInputLoadFailed`:`codexAuth.requestUserInputDesc`)}),(0,J.jsx)(`code`,{className:`mono codex-request-user-input-config`,children:`[features]
80
80
  default_mode_request_user_input = true`})]}),(0,J.jsxs)(`div`,{className:`codex-request-user-input-controls`,children:[c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},children:t(`common.retry`)}),(0,J.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,J.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,J.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 Wh({apiBase:e}){let t=Q(),[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,n=Ln(15e3);try{let i=await fetch(`${e}/api/settings`,{signal:n.signal});if(!i.ok)throw Error(`load`);let o=await i.json();if(p.current||t!==m.current)return;if(typeof o.codexAccountPickerEnabled!=`boolean`)throw Error(`shape`);f.current=o.codexAccountPickerEnabled,r(o.codexAccountPickerEnabled),a(!0),l(!1)}catch{!p.current&&t===m.current&&l(!0)}finally{n.clear()}},[e]);(0,_.useEffect)(()=>{let e=window.setTimeout(()=>{h()},0),t=Vn(()=>{h()},3e4);return()=>{window.clearTimeout(e),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 Pt(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,J.jsxs)(`div`,{className:`card card-row codex-account-picker-card`,"aria-busy":o||!i&&!v||void 0,children:[(0,J.jsxs)(`div`,{className:`codex-account-picker-copy`,children:[(0,J.jsx)(`strong`,{children:t(`codexAuth.accountPickerTitle`)}),(0,J.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,J.jsx)(`div`,{className:`card-sub faint`,children:t(`codexAuth.accountPickerCompatibility`)}),i&&c&&(0,J.jsx)(`div`,{className:`card-sub faint`,role:`status`,children:t(`codexAuth.accountPickerRefreshFailed`)})]}),(0,J.jsxs)(`div`,{className:`codex-account-picker-controls`,children:[c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{h()},disabled:o,children:t(`common.retry`)}),i&&(0,J.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,J.jsx)(`span`,{className:`toggle-knob`})})]}),u&&(0,J.jsx)(`div`,{className:`codex-account-picker-feedback is-${u.tone}`,role:u.tone===`err`?`alert`:`status`,"aria-atomic":`true`,children:u.message})]})}function Gh(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 Kh({state:e,busy:t,onEnable:n}){let r=Q();return(0,J.jsxs)(`div`,{className:`panel openai-account-mode-banner`,style:{marginBottom:16},children:[(0,J.jsxs)(`div`,{className:`row`,children:[(0,J.jsx)(`strong`,{children:r(`codexAuth.accountModeTitle`)}),e===null?(0,J.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot openai-account-mode-banner__badge-slot--pending`,"aria-hidden":`true`,children:r(`codexAuth.accountModePool`)}):e===`pool`?(0,J.jsx)(`span`,{className:`badge badge-accent openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModePool`)}):e===`direct`?(0,J.jsx)(`span`,{className:`badge badge-green openai-account-mode-banner__badge-slot`,children:r(`codexAuth.accountModeDirect`)}):null]}),e===null&&(0,J.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc openai-account-mode-banner__desc--pending`,"aria-hidden":`true`,children:`\xA0`}),e===`pool`&&(0,J.jsx)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:r(`codexAuth.accountModePoolDesc`)}),e===`direct`&&(0,J.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.accountModeDirectDesc`),` `,(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>pt(`providers`),children:r(`codexAuth.openProviders`)})]}),(e===`absent`||e===`disabled`)&&(0,J.jsxs)(`div`,{className:`row`,style:{alignItems:`center`,marginTop:8},children:[(0,J.jsx)(`p`,{className:`card-sub`,style:{flex:1,margin:0},children:r(`codexAuth.openaiUnavailableDesc`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:t,onClick:n,children:r(t?`codexAuth.enablingOpenai`:`codexAuth.enableOpenai`)})]}),e===`invalid`&&(0,J.jsxs)(`p`,{className:`card-sub openai-account-mode-banner__desc`,children:[r(`codexAuth.openaiMissing`),` `,(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>pt(`providers`),children:r(`codexAuth.openProviders`)})]})]})}function qh(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 Jh({apiBase:e}){let t=Q(),n=`ocx.codex-auth.config.v1:${e}`,r=fr(n),[i,a]=(0,_.useState)(()=>r?.bannerState??null),[o,s]=(0,_.useState)(()=>r?.accountModeState??null),c=(0,_.useRef)(null),[l,u]=(0,_.useState)(!1),[d,f]=(0,_.useState)(``),p=(0,_.useCallback)(async()=>{let t=Ln(15e3);try{let r=await fetch(`${e}/api/config`,{signal:t.signal});if(!r.ok)throw Error(String(r.status));let i=await r.json(),o=zs(qh(i));if(o===`absent`||o===`disabled`||o===`invalid`){a(o);let e=o===`disabled`?`disabled`:`absent`;s(e),gr(n,{bannerState:o,accountModeState:e});return}let c=Gh(i);a(c),s(c),gr(n,{bannerState:c,accountModeState:c})}catch{}finally{t.clear()}},[e,n]);(0,_.useEffect)(()=>{c.current!==e&&(c.current=e,Promise.resolve().then(()=>{p()}));let t=Vn(()=>{p()},3e4);return()=>{t()}},[e,p]);let m=async()=>{u(!0),f(``);try{if(i!==`absent`&&i!==`disabled`)return;await Ks(e,i),await p()}catch(e){e instanceof Gs?f(t(e.i18nKey)):f(e instanceof Error?e.message:t(`prov.saveFailed`))}finally{u(!1)}};return(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(_s,{apiBase:e,accountModeState:o,banner:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Kh,{state:i,busy:l,onEnable:()=>{m()}}),d&&(0,J.jsx)(`div`,{className:`notice notice-err`,role:`alert`,children:d})]}),advancedExtras:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Wh,{apiBase:e}),(0,J.jsx)(Uh,{apiBase:e})]})})})}var Yh={"base-instructions":`codexSet.layer.base-instructions`,"model-switch":`codexSet.layer.model-switch`,personality:`codexSet.layer.personality`,"context-window-guidance":`codexSet.layer.context-window-guidance`,realtime:`codexSet.layer.realtime`,"agents-md":`codexSet.layer.agents-md`,permissions:`codexSet.layer.permissions`,collaboration:`codexSet.layer.collaboration`,environment:`codexSet.layer.environment`,"environments-instructions":`codexSet.layer.environments-instructions`,apps:`codexSet.layer.apps`,plugins:`codexSet.layer.plugins`,tools:`codexSet.layer.tools`,skills:`codexSet.layer.skills`,"multi-agent-mode":`codexSet.layer.multi-agent-mode`,"git-attribution":`codexSet.layer.git-attribution`},Xh={"base-instructions":`codexSet.about.base-instructions`,"model-switch":`codexSet.about.model-switch`,personality:`codexSet.about.personality`,"context-window-guidance":`codexSet.about.context-window-guidance`,realtime:`codexSet.about.realtime`,"agents-md":`codexSet.about.agents-md`,permissions:`codexSet.about.permissions`,collaboration:`codexSet.about.collaboration`,environment:`codexSet.about.environment`,"environments-instructions":`codexSet.about.environments-instructions`,apps:`codexSet.about.apps`,plugins:`codexSet.about.plugins`,tools:`codexSet.about.tools`,skills:`codexSet.about.skills`,"multi-agent-mode":`codexSet.about.multi-agent-mode`,"git-attribution":`codexSet.about.git-attribution`},Zh={"model-switch":`codexSet.condition.model-switch`,realtime:`codexSet.condition.realtime`,"agents-md":`codexSet.condition.agents-md`,plugins:`codexSet.condition.plugins`,"git-attribution":`codexSet.condition.git-attribution`},Qh={base:`codexSet.class.base`,"config-toggle":`codexSet.class.config-toggle`,"feature-gated":`codexSet.class.feature-gated`,"runtime-conditional":`codexSet.class.runtime-conditional`,"extension-unknown":`codexSet.class.extension-unknown`};function $h({descriptor:e,toggle:t,bytes:n,transitionOnly:r=!1,busy:i,writesRefused:a,onToggle:o,onSelectBase:s,baseSelection:c,onOpen:l}){let u=Q(),d=Yh[e.id],f=d?u(d):e.id,p=Zh[e.id],m=t?.defaultedUserValue??e.default??!0,h=c?.kind==="default";return(0,J.jsxs)(`li`,{className:`codex-set-prompt__row`,"data-layer-id":e.id,"data-layer-class":e.class,children:[(0,J.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:e.order===null?`·`:e.order+1}),(0,J.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>l(e.id),children:f}),e.key&&(0,J.jsx)(`code`,{className:`codex-set-prompt__key`,children:e.key}),n!==null&&n>0&&(0,J.jsx)(`span`,{className:`codex-set-prompt__bytes`,title:u(`codexSet.dialog.sourceBytes`,{bytes:n}),children:n>=1024?Math.round(n/1024)+` KB`:n+` B`}),e.class===`base`&&s?(0,J.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${h?`on`:``}`,"aria-checked":h,"aria-label":f,disabled:i||a||c?.kind===`external`,onClick:()=>{s(!h)},children:(0,J.jsx)(`span`,{className:`toggle-knob`})}):e.class===`config-toggle`?(0,J.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${m?`on`:``}`,"aria-checked":m,"aria-label":f,disabled:i||a,onClick:()=>{o(e.id,!m)},children:(0,J.jsx)(`span`,{className:`toggle-knob`})}):e.class===`feature-gated`?(0,J.jsxs)(`span`,{className:`codex-set-prompt__note`,children:[u(`codexSet.row.featureGated`),` `,(0,J.jsx)(`button`,{type:`button`,className:`link-btn`,onClick:()=>pt(`integrations/codex`),children:u(`codexSet.row.openFeatures`)})]}):(0,J.jsx)(`span`,{className:`codex-set-prompt__note codex-set-prompt__note--locked`,children:u(r?`codexSet.row.onChange`:p||`codexSet.row.alwaysOn`)})]})}function eg({descriptor:e,toggle:t,text:n,busy:r,onToggle:i,onClose:a}){let o=Q(),s=(0,_.useRef)(null),c=`codex-set-layer-dialog-`+e.id;(0,_.useEffect)(()=>{let e=s.current,t=document.activeElement;return e&&!e.open&&e.showModal(),()=>{e?.open&&e.close(),t&&typeof t.focus==`function`&&t.focus()}},[]);let l=(0,_.useCallback)(e=>{e.preventDefault(),a()},[a]),u=Qh[e.class],d=Yh[e.id],f=Xh[e.id],p=Zh[e.id];return(0,J.jsxs)(`dialog`,{ref:s,className:`modal-overlay`,"aria-labelledby":c,onCancel:l,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":o(`common.close`),tabIndex:-1,onClick:a}),(0,J.jsxs)(`div`,{className:`modal-card codex-set-layer-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:c,children:d?o(d):e.id}),e.class===`config-toggle`&&t&&(0,J.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${t.defaultedUserValue?`on`:``}`,"aria-checked":t.defaultedUserValue,"aria-label":d?o(d):e.id,disabled:r,onClick:()=>{i(e.id,!t.defaultedUserValue)},children:(0,J.jsx)(`span`,{className:`toggle-knob`})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:a,children:o(`common.close`)})]}),(0,J.jsx)(`p`,{className:`muted small`,children:o(f||`codexSet.dialog.unknownLayer`)}),(0,J.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.class`)}),(0,J.jsx)(`span`,{children:o(u)})]}),e.key&&(0,J.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.key`)}),(0,J.jsx)(`code`,{className:`api-code`,children:e.key}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>{navigator.clipboard?.writeText(e.key??``)},children:o(`codexSet.dialog.copyKey`)})]}),e.class===`config-toggle`&&t&&(0,J.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.fileValue`)}),(0,J.jsx)(`span`,{children:t.userFileValue===null?o(`codexSet.dialog.absentDefault`,{value:String(t.default)}):o(`codexSet.dialog.setValue`,{value:String(t.userFileValue),fallback:String(t.default)})})]}),e.class===`runtime-conditional`&&p&&(0,J.jsx)(`p`,{className:`muted small`,children:o(p)}),n?.reason===`ok`&&n.text?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`codex-set-layer-dialog__line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:o(`codexSet.dialog.sourceText`)}),(0,J.jsx)(`span`,{className:`muted small`,children:o(`codexSet.dialog.sourceBytes`,{bytes:n.bytes})})]}),(0,J.jsx)(`pre`,{className:`api-code codex-set-layer-dialog__text`,children:n.text})]}):(0,J.jsx)(`p`,{className:`muted small codex-set-layer-dialog__no-text`,children:n?.reason===`empty-source`?o(`codexSet.dialog.emptySource`,{path:n.sourcePath??``}):n?.reason===`not-rendered`?o(`codexSet.dialog.notRendered`):n?.reason===`not-exposed`?o(`codexSet.dialog.notExposed`):o(`codexSet.dialog.textUnavailable`)})]})]})}function tg({layer:e,index:t,total:n,busy:r,onToggle:i,onEdit:a,onDelete:o,onMove:s}){let c=Q();return(0,J.jsxs)(`li`,{className:`codex-set-prompt__row codex-set-custom__row`,"data-custom-id":e.id,onKeyDown:i=>{!i.altKey||r||(i.key===`ArrowUp`&&t>0?(i.preventDefault(),s(e.id,-1)):i.key===`ArrowDown`&&t<n-1&&(i.preventDefault(),s(e.id,1)))},children:[(0,J.jsx)(`span`,{className:`codex-set-prompt__pos`,"aria-hidden":`true`,children:t+1}),(0,J.jsx)(`button`,{type:`button`,className:`link-btn codex-set-prompt__name`,onClick:()=>a(e.id),children:e.title}),(0,J.jsxs)(`span`,{className:`codex-set-custom__reorder`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveUp`,{title:e.title}),disabled:t===0||r,onClick:()=>s(e.id,-1),children:`↑`}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":c(`codexSet.custom.moveDown`,{title:e.title}),disabled:t===n-1||r,onClick:()=>s(e.id,1),children:`↓`})]}),(0,J.jsx)(`button`,{type:`button`,role:`switch`,className:`toggle ${e.enabled?`on`:``}`,"aria-checked":e.enabled,"aria-label":e.title,disabled:r,onClick:()=>i(e.id,!e.enabled),children:(0,J.jsx)(`span`,{className:`toggle-knob`})}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm codex-set-custom__delete`,"aria-label":c(`codexSet.custom.delete`,{title:e.title}),disabled:r,onClick:()=>o(e.id),children:`×`})]})}var ng=8192,rg=[{rule:`identity`,level:`warn`,messageKey:`codexSet.lint.identity`,pattern:/you\s+are\s+(claude|grok|gemini|gpt-|chatgpt)/gi},{rule:`foreign-tool`,level:`warn`,messageKey:`codexSet.lint.foreignTool`,pattern:/\b(Read|Edit|Write|Bash|Glob|Grep)\s+tool\b/g},{rule:`placeholder`,level:`warn`,messageKey:`codexSet.lint.placeholder`,pattern:/\$\{\{[\s\S]*?\}\}/g},{rule:`apply-patch`,level:`warn`,messageKey:`codexSet.lint.applyPatch`,pattern:/apply_patch\s+(?:is|must|should|means|works)/gi},{rule:`approval-vocab`,level:`warn`,messageKey:`codexSet.lint.approvalVocab`,pattern:/\b(always-approve|ask mode|acceptEdits)\b/gi},{rule:`environment`,level:`warn`,messageKey:`codexSet.lint.environment`,pattern:/\b(your (?:cwd|working directory) is|today's date is|you have no network access|you are running on (?:macos|linux|windows))/gi}];function ig(e){let t=0;for(let n of e){let e=n.codePointAt(0);t+=e<128?1:e<2048?2:e<65536?3:4}return t}function ag(e){let t=[];for(let n of rg){let r=new RegExp(n.pattern.source,n.pattern.flags);for(let i=r.exec(e);i!==null;i=r.exec(e))t.push({level:n.level,rule:n.rule,messageKey:n.messageKey,span:[i.index,i.index+i[0].length]}),i[0].length===0&&(r.lastIndex+=1)}return ig(e)>ng&&t.push({level:`info`,rule:`size`,messageKey:`codexSet.lint.size`}),t.sort((e,t)=>(e.span?.[0]??1/0)-(t.span?.[0]??1/0))}var og=65536;function sg(e){let t=0;for(let n of e){let e=n.codePointAt(0);t+=e<128?1:e<2048?2:e<65536?3:4}return t}function cg(e){return e.replace(/\r\n/g,`
81
81
  `).replace(/\r/g,`
82
82
  `).replace(/\t/g,` `)}function lg(e){let t=0;for(let n of e){let e=n.codePointAt(0);if(n!==`
@@ -109,4 +109,4 @@ default_mode_request_user_input = true`})]}),(0,J.jsxs)(`div`,{className:`codex-
109
109
  }'`;return(0,J.jsxs)(`section`,{className:`panel api-panel awi-usage-panel`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:n(`api.workspace.usageExamples`)}),(0,J.jsxs)(`div`,{className:`awi-usage-panel-body`,children:[(0,J.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,J.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageChatTitle`)}),(0,J.jsx)(Ig,{text:i})]}),(0,J.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,J.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageResponsesTitle`)}),(0,J.jsx)(Ig,{text:a})]}),t&&(0,J.jsxs)(`div`,{className:`awi-usage-example`,children:[(0,J.jsx)(`h4`,{className:`awi-usage-example-title`,children:n(`api.usageMessagesTitle`)}),(0,J.jsx)(Ig,{text:o})]})]})]})}var Hg=[`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`],Ug={opencode:`api.clientConfig.clientOpencode`,pi:`api.clientConfig.clientPi`,omp:`api.clientConfig.clientOmp`,hermes:`api.clientConfig.clientHermes`,openclaw:`api.clientConfig.clientOpenclaw`,kimi:`api.clientConfig.clientKimi`,gajae:`api.clientConfig.clientGajae`,dsh:`api.clientConfig.clientDsh`,mcode:`api.clientConfig.clientMcode`,zcode:`api.clientConfig.clientZcode`,prime:`api.clientConfig.clientPrime`},Wg={opencode:`/provider-icons/opencode.svg`,pi:`/provider-icons/pi.svg`};function Gg({client:e,apiBase:t,onOpenDetails:n,onCopy:r,onDownload:i}){let a=Q(),[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(Ug[e]),g=Wg[e],v=f?.text??``,y=(0,_.useCallback)(t=>{f&&n(e,f,v,t.currentTarget)},[e,f,v,n]);return(0,J.jsxs)(`li`,{className:`awi-clientconfig-row`,children:[(0,J.jsx)(`span`,{className:`awi-clientconfig-mark`,"aria-hidden":`true`,children:g?(0,J.jsx)(`img`,{src:g,alt:``,width:20,height:20}):(0,J.jsx)(`span`,{className:`awi-clientconfig-monogram`,children:h.slice(0,1)})}),(0,J.jsxs)(`span`,{className:`awi-clientconfig-identity`,children:[(0,J.jsx)(`span`,{className:`awi-clientconfig-name`,children:h}),(0,J.jsx)(`span`,{className:`muted text-label awi-clientconfig-meta`,children:m?a(`api.clientConfig.loading`):p||!f?(0,J.jsx)(`span`,{role:`alert`,children:a(`api.clientConfig.rowError`,{client:h})}):a(`api.clientConfig.rowMeta`,{destination:f.destination,count:f.modelCount})})]}),(0,J.jsx)(`span`,{className:`awi-clientconfig-row-actions`,children:p&&!m?(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>s(e=>e+1),children:a(`common.retry`)}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":a(`api.clientConfig.copyAria`,{client:h}),disabled:!f,onClick:()=>{f&&r(e,v)},children:a(`api.clientConfig.copy`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,"aria-label":a(`api.clientConfig.downloadAria`,{client:h}),disabled:!f,onClick:()=>{f&&i(e,f,v)},children:a(`api.clientConfig.download`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,"aria-label":a(`api.clientConfig.detailsAria`,{client:h}),disabled:!f,onClick:y,children:a(`api.clientConfig.details`)})]})})]})}function Kg({client:e,envelope:t,json:n,hasKeys:r,onClose:i,onCopy:a,onDownload:o}){let s=Q(),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,J.jsxs)(`dialog`,{ref:c,className:`modal-overlay`,"aria-labelledby":l,onCancel:u,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":s(`common.close`),tabIndex:-1,onClick:i}),(0,J.jsxs)(`div`,{className:`modal-card awi-clientconfig-dialog`,onClick:e=>e.stopPropagation(),role:`document`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:l,children:s(Ug[e])}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:i,children:s(`common.close`)})]}),(0,J.jsx)(`pre`,{className:`api-code api-example-pre awi-clientconfig-json`,tabIndex:0,role:`group`,"aria-label":s(`api.clientConfig.jsonLabel`,{client:s(Ug[e])}),children:n}),(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-count`,children:s(`api.clientConfig.modelCount`,{count:t.modelCount})}),t.modelsWithoutLimits>0&&(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-degraded`,children:s(`api.clientConfig.missingLimits`,{count:t.modelsWithoutLimits,total:t.modelCount})}),!r&&(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-nokey`,children:s(`api.clientConfig.noKeyYet`,{env:t.apiKeyEnv})}),(0,J.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.destination`)}),(0,J.jsx)(Ig,{text:t.destination})]}),(0,J.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:s(`api.clientConfig.envHint`)}),(0,J.jsx)(Ig,{text:t.exportHint})]}),(0,J.jsx)(`p`,{className:`muted small awi-clientconfig-merge`,children:s(`api.clientConfig.mergeWarning`)}),(0,J.jsx)(`p`,{className:`muted text-label awi-clientconfig-where-title`,children:s(`api.clientConfig.whereDisclosure`)}),(0,J.jsx)(`p`,{className:`muted small`,children:s(`api.clientConfig.whereBody`)}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,onClick:a,children:s(`api.clientConfig.copy`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:o,children:s(`api.clientConfig.download`)})]})]})]})}function qg({apiBase:e,baseUrl:t,hasKeys:n}){let r=Q(),[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(Ug[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,J.jsxs)(`section`,{className:`panel api-panel awi-clientconfig-panel`,children:[(0,J.jsx)(`div`,{className:`api-panel-head awi-clientconfig-head`,children:(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`api.clientConfig.title`)})}),(0,J.jsx)(`ul`,{className:`awi-clientconfig-rows`,"aria-label":r(`api.clientConfig.rowsLabel`),children:Hg.map(t=>(0,J.jsx)(Gg,{client:t,apiBase:e,onOpenDetails:f,onCopy:(e,t)=>{l(e,t,!0)},onDownload:u},t))}),(0,J.jsxs)(`div`,{className:`awi-clientconfig-line`,children:[(0,J.jsx)(`span`,{className:`muted text-label`,children:r(`api.baseUrl`)}),(0,J.jsx)(Ig,{text:t})]}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:o}),i&&(0,J.jsx)(Kg,{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 Jg({keys:e,keysLoading:t,keysLoadFailed:n,attributionSince:r,localeTag:i,busy:a,onSelect:o}){let s=Q();return(0,J.jsxs)(`div`,{className:`panel api-panel awi-keylist-panel`,"aria-busy":t,children:[(0,J.jsx)(`div`,{className:`api-panel-head`,children:(0,J.jsx)(`h3`,{className:`panel-title`,children:t?s(`api.activeKeysLoading`):s(`api.activeKeys`,{count:e.length})})}),t?(0,J.jsx)(`div`,{className:`api-active-keys-skeleton`,role:`status`,"aria-label":s(`common.loading`)}):e.length===0?(0,J.jsx)(`p`,{className:`muted small`,children:s(n?`api.keysLoadFailed`:`api.noKeys`)}):(0,J.jsx)(`div`,{className:`tbl-wrap`,children:(0,J.jsxs)(`table`,{className:`tbl awi-keylist-table`,children:[(0,J.jsx)(`thead`,{children:(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`th`,{children:s(`api.colName`)}),(0,J.jsx)(`th`,{children:s(`api.colKey`)}),(0,J.jsx)(`th`,{children:s(`api.attribution.requests7d`)}),(0,J.jsx)(`th`,{children:s(`api.attribution.lastUsed`)})]})}),(0,J.jsx)(`tbody`,{children:e.map(e=>(0,J.jsxs)(`tr`,{children:[(0,J.jsx)(`td`,{children:(0,J.jsx)(`button`,{type:`button`,className:`awi-keylist-name`,disabled:a,onClick:()=>o(e.id),children:e.name})}),(0,J.jsx)(`td`,{children:(0,J.jsx)(`code`,{children:e.prefix})}),(0,J.jsx)(`td`,{children:r?e.usage.ambiguous?s(`api.attribution.railAmbiguous`):e.usage.requests7d.toLocaleString(i):s(`api.attribution.unavailable`)}),(0,J.jsx)(`td`,{children:!r||e.usage.ambiguous?`—`:e.usage.lastUsedAt?Ng(e.usage.lastUsedAt,i):s(`api.attribution.neverUsed`)})]},e.id))})]})})]})}function Yg({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=Q(),[R,z]=(0,_.useState)(null),[B,V]=(0,_.useState)(!1),[H,U]=(0,_.useState)(!1),[W,ee]=(0,_.useState)(!1),[G,K]=(0,_.useState)(!1),[q,Y]=(0,_.useState)(``),[te,ne]=(0,_.useState)(!1),[re,ie]=(0,_.useState)(!1),[ae,oe]=(0,_.useState)(!1),X=R?e.find(e=>e.id===R)??null:null,se=W||te,ce=(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]),le=()=>{V(!1),U(!1)},ue=()=>{z(null),le(),K(!1),ie(!1),oe(!1)};(0,_.useEffect)(()=>{if(!B)return;let e=window.setTimeout(()=>U(!0),300);return()=>window.clearTimeout(e)},[B]);let de=()=>{X&&V(!0)},fe=async()=>{if(!(!X||!H||W)){ee(!0),oe(!1);try{await k(X.id)?(le(),z(null)):oe(!0)}finally{ee(!1)}}},pe=()=>{X&&(Y(X.name),ie(!1),K(!0))},me=async()=>{if(!X||te)return;let e=q.trim();if(!e||e===X.name){K(!1);return}ne(!0),ie(!1);try{await A(X.id,e)?K(!1):ie(!0)}finally{ne(!1)}};return(0,J.jsxs)(`div`,{className:`apikeys-workspace-shell`,children:[!X&&(0,J.jsx)(lp,{scope:`api`,items:ce,ariaLabel:L(`api.workspace.sections`)}),(0,J.jsx)(`div`,{className:`apikeys-workspace-root`,children:(0,J.jsx)(`section`,{className:`apikeys-workspace-main`,"aria-label":L(`api.workspace.details`),children:X?(0,J.jsxs)(`div`,{className:`awi-detail`,children:[(0,J.jsx)(`div`,{className:`awi-detail-toolbar`,children:(0,J.jsxs)(`button`,{type:`button`,className:`awi-back`,onClick:ue,disabled:se,children:[(0,J.jsx)(Se,{className:`awi-back-chevron`,"aria-hidden":`true`}),L(`modal.back`)]})}),(0,J.jsxs)(`div`,{className:`awi-detail-body`,children:[(0,J.jsxs)(`div`,{className:`awi-detail-head`,children:[(0,J.jsx)(`h2`,{className:`awi-detail-title`,children:X.name}),(0,J.jsx)(`span`,{className:`awi-detail-actions`,children:B?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm awi-confirm-delete`,onClick:()=>{fe()},disabled:!H||W,children:[(0,J.jsx)(he,{}),` `,L(W?`api.key.deleting`:`api.confirm`)]},`confirm-delete`),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:le,disabled:W,children:L(`common.cancel`)})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:pe,disabled:G,children:L(`api.key.rename`)},`rename`),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-danger btn-sm`,onClick:de,"aria-label":L(`api.deleteAria`),children:[(0,J.jsx)(he,{}),` `,L(`api.workspace.deleteKey`)]},`request-delete`)]})})]}),B&&(0,J.jsx)(`p`,{className:`muted awi-delete-hint`,children:L(`api.workspace.deleteConfirm`)}),ae&&(0,J.jsx)(`p`,{className:`awi-delete-error`,role:`alert`,children:L(`api.deleteFailed`)}),G&&(0,J.jsxs)(`div`,{className:`awi-rename`,children:[(0,J.jsx)(`label`,{className:`awi-rename-label`,htmlFor:`awi-key-name`,children:L(`api.key.name`)}),(0,J.jsx)(`input`,{id:`awi-key-name`,className:`input`,type:`text`,value:q,maxLength:64,disabled:te,onChange:e=>Y(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),me())}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:()=>{me()},disabled:te,children:L(te?`api.key.renaming`:`api.key.saveName`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>K(!1),disabled:te,children:L(`common.cancel`)}),re&&(0,J.jsx)(`p`,{className:`awi-rename-error`,role:`alert`,children:L(`api.key.renameFailed`)})]}),(0,J.jsxs)(`div`,{className:`awi-section`,children:[(0,J.jsx)(`h3`,{className:`awi-section-title`,children:L(`api.workspace.keyDetails`)}),(0,J.jsxs)(`dl`,{className:`awi-kv`,children:[(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.workspace.keyPrefix`)}),(0,J.jsx)(`dd`,{children:(0,J.jsx)(`code`,{children:X.prefix})})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.colCreated`)}),(0,J.jsx)(`dd`,{children:Ng(X.createdAt,l)})]})]})]}),(0,J.jsxs)(`div`,{className:`awi-section`,children:[(0,J.jsx)(`h3`,{className:`awi-section-title`,children:L(`api.attribution.title`)}),n?X.usage.ambiguous?(0,J.jsx)(`p`,{className:`muted`,children:L(`api.attribution.ambiguous`)}):(0,J.jsxs)(`dl`,{className:`awi-kv`,children:[(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.attribution.requests7d`)}),(0,J.jsx)(`dd`,{children:X.usage.requests7d.toLocaleString(l)})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(r?`api.attribution.totalRequestsAvailable`:`api.attribution.totalRequests`)}),(0,J.jsx)(`dd`,{children:X.usage.totalRequests.toLocaleString(l)})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(`api.attribution.lastUsed`)}),(0,J.jsx)(`dd`,{children:X.usage.lastUsedAt?Ng(X.usage.lastUsedAt,l):L(`api.attribution.neverUsed`)})]}),(0,J.jsxs)(`div`,{className:`awi-kv-row`,children:[(0,J.jsx)(`dt`,{children:L(r?`api.attribution.sinceAvailable`:`api.attribution.since`)}),(0,J.jsx)(`dd`,{children:Ng(n,l)})]})]}):(0,J.jsx)(`p`,{className:`muted`,children:L(`api.attribution.unavailableDetail`)})]})]})]}):(0,J.jsx)(`div`,{className:`awi-overview`,children:(0,J.jsxs)(`div`,{className:`awi-overview-section`,children:[(0,J.jsxs)(`div`,{id:op(`api`,`keys`),className:`awi-section-anchor`,children:[(0,J.jsx)(zg,{keys:e,keysLoading:a,keysLoadFailed:o,newName:u,creating:d,newKey:f,copied:p,confirmDelete:null,localeTag:l,showKeyList:!1,onNewNameChange:T,onCreate:E,onDismissNewKey:D,onCopyKey:O,onConfirmDelete:()=>{},onCancelDelete:()=>{},onDelete:()=>{}}),(0,J.jsx)(Jg,{keys:e,keysLoading:a,keysLoadFailed:o,attributionSince:n,localeTag:l,busy:se,onSelect:e=>{z(e),le(),K(!1),ie(!1),oe(!1)}})]}),(0,J.jsx)(`div`,{id:op(`api`,`connect`),className:`awi-section-anchor`,children:(0,J.jsx)(qg,{apiBase:t,baseUrl:s.baseUrl,hasKeys:e.length>0})}),(0,J.jsx)(`div`,{id:op(`api`,`endpoints`),className:`awi-section-anchor`,children:(0,J.jsx)(Rg,{endpoints:s,claudeCodeEnabled:c,authMatrix:i})}),(0,J.jsx)(`div`,{id:op(`api`,`models`),className:`awi-section-anchor`,children:(0,J.jsx)(Bg,{filteredModels:m,modelsLoading:h,modelsRefreshing:g,modelsLoadFailed:v,modelCount:y,hasModelData:b,modelQuery:x,copiedModelId:S,modelTests:C,claudeCodeEnabled:c,onModelQueryChange:j,onCopyModelId:M,onTestModel:N,onRetryModels:P,canTestModels:w,sourceLabel:F,protocolLabel:I})}),(0,J.jsx)(`div`,{id:op(`api`,`examples`),className:`awi-section-anchor`,children:(0,J.jsx)(Vg,{endpoints:s,claudeCodeEnabled:c})})]})})})})]})}var Xg=[],Zg=15e3;function Qg(e){let t=e.replace(/\/$/,``);if(!t)return jg;try{return new URL(t).host?Mg(`${t}/v1/responses`):jg}catch{return jg}}function $g(e){return!e||!Ag(e.authMatrix)||!Array.isArray(e.keys)||e.keys.some(e=>!e||!Og(e.usage))?null:e}function e_({apiBase:e,active:t=!0}){let{t:n,locale:r}=ct(),i=et.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=mr(a),u=mr(o),d=$g(l?.data??null),f=u?.data??null,[p,m]=(0,_.useState)(null),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(null),[b,x]=(0,_.useState)({}),[S,C]=(0,_.useState)(``),[w,T]=(0,_.useState)(!1),[E,D]=(0,_.useState)(null),[O,k]=(0,_.useState)(!1),A=(0,_.useRef)(!1),j=(0,_.useCallback)(async t=>{let r=await Ft(await fetch(`${e}/api/keys`,{signal:t}));if(!r||!Ag(r.authMatrix))throw Error(n(`api.keysLoadFailed`));let i=r.keys??[];if(i.some(e=>!Og(e.usage)))throw Error(n(`api.keysLoadFailed`));let o=i,s=Mg(r.endpoint??``),c={keys:o,endpoints:{baseUrl:r.baseUrl??s.baseUrl,responses:r.responsesEndpoint??r.endpoint??jg.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 hr(a,c),c},[e,a,n]),M=(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=>Eg(e)).sort((e,t)=>Dg(e).localeCompare(Dg(t)));return hr(o,s),s},[e,o,n]),N=ol(s,[e],j,{isEmpty:e=>e.keys.length===0,initialData:d??void 0,initialDataCachedAt:l?.cachedAt??null,staleAfterMs:6e4,enabled:t}),P=ol(c,[e],M,{isEmpty:e=>e.length===0,initialData:f??void 0,initialDataCachedAt:u?.cachedAt??null,staleAfterMs:6e4,enabled:t}),F=N.state,I=P.state,L=F.data??d,R=I.data??f??Xg,z=L?.keys??[],B=L?.endpoints??Qg(e),V=L?.claudeCodeEnabled??!0,H=L?.attributionSince,U=L?.historyTruncated===!0,W=L?.authMatrix??[],ee=N.refresh,G=P.refresh,K=(0,_.useMemo)(()=>{let e=h.trim().toLowerCase();return e?R.filter(t=>Dg(t).toLowerCase().includes(e)||t.displayName.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):R},[h,R]),q=async t=>{if(A.current)return!1;A.current=!0,T(!0),m(null);try{let r=t??S,i=await Pt(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?(m(n(`api.createFailed`)),!1):(D(i.key),C(``),ee(),!0)}catch{return m(n(`api.createFailed`)),!1}finally{A.current=!1,T(!1)}},Y=async t=>{m(null);let n=Ln(Zg);try{return(await fetch(`${e}/api/keys`,{method:`DELETE`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:t}),signal:n.signal})).ok?(ee(),!0):!1}catch{return!1}finally{n.clear()}},te=async(t,n)=>{m(null);let r=Ln(Zg);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?(ee(),!0):!1}catch{return!1}finally{r.clear()}},ne=async()=>{if(E){m(null);try{await navigator.clipboard.writeText(E),k(!0),window.setTimeout(()=>k(!1),2e3)}catch{k(!1),m(n(`api.key.copyFailed`))}}},re=async e=>{try{await navigator.clipboard.writeText(e),y(e),window.setTimeout(()=>y(t=>t===e?null:t),2e3)}catch{}},ie=e=>e.native?n(`api.sourceNative`):e.provider===`combo`?n(`api.sourceCombo`):e.custom?n(`api.sourceCustom`):Dn(e.provider,n),ae=e=>n(e===`responses`?`api.protocolResponses`:e===`messages`?`api.protocolMessages`:`api.protocolChatCompletions`),oe=(e,t)=>e===`responses`?{url:B.responses,body:{model:t,input:`ping`,max_output_tokens:1,stream:!1}}:e===`messages`?{url:B.messages,body:{model:t,max_tokens:1,messages:[{role:`user`,content:`ping`}]}}:{url:B.chatCompletions,body:{model:t,messages:[{role:`user`,content:`ping`}],max_tokens:1,stream:!1}},X=(e,t,n)=>x(r=>({...r,[e]:{...r[e],[t]:n}})),se=async(e,t)=>{if(!E)return;let r=Dg(e),i=oe(t,r);X(r,t,{state:`testing`});try{let e=await fetch(i.url,{method:`POST`,headers:{"Content-Type":`application/json`,"x-opencodex-api-key":E},body:JSON.stringify(i.body)});if(!e.ok){let n=await e.text();X(r,t,{state:`error`,detail:n.slice(0,160)||String(e.status)});return}X(r,t,{state:`ok`})}catch(e){X(r,t,{state:`error`,detail:e instanceof Error?e.message:n(`api.testFailed`)})}},ce=n(`api.subtitle`).split(`{authHeader}`);return(0,J.jsxs)(`section`,{className:`api-page`,"aria-busy":F.refreshing||I.refreshing||void 0,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:n(`api.title`)})}),(0,J.jsxs)(`p`,{className:`page-sub`,children:[ce[0],(0,J.jsx)(`code`,{children:`x-opencodex-api-key`}),ce[1]]}),p&&(0,J.jsx)($,{tone:`err`,children:p}),F.showError&&L&&(0,J.jsx)($,{tone:`err`,children:n(`api.keysLoadFailed`)}),F.showSkeleton&&!L?(0,J.jsx)(cl,{label:n(`api.activeKeysLoading`),rows:4}):F.kind===`failed-cold`&&!L?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)($,{tone:`err`,children:F.error instanceof Error?F.error.message:n(`api.keysLoadFailed`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>ee(),children:n(`common.retry`)})]}):(0,J.jsx)(J.Fragment,{children:(0,J.jsx)(Yg,{keys:z,apiBase:e,attributionSince:H,historyTruncated:U,authMatrix:W,keysLoading:!1,keysLoadFailed:F.showError,endpoints:B,claudeCodeEnabled:V,localeTag:i,newName:S,creating:w,newKey:E,copied:O,filteredModels:K,modelsLoading:I.showSkeleton&&!I.data&&!f,modelsRefreshing:I.refreshing&&I.showError&&(I.data!==void 0||f!==null),modelsLoadFailed:I.showError,modelCount:R.length,hasModelData:I.data!==void 0||f!==null,modelQuery:h,copiedModelId:v,modelTests:b,onNewNameChange:C,onCreate:()=>{q()},onDismissNewKey:()=>D(null),onCopyKey:()=>{ne()},onDelete:Y,onRename:te,onModelQueryChange:g,onCopyModelId:e=>{re(e)},onTestModel:(e,t)=>{se(e,t)},onRetryModels:()=>{G({forceLoading:!0})},canTestModels:E!==null,sourceLabel:ie,protocolLabel:ae})})]})}function t_(e,t){let n=(e??[]).map(e=>({value:e,label:il(e)}));return[{value:``,label:t},...n]}function n_(e){let t=e.autoConnectSupported===!0;return{autoConnectSupported:t,systemEnv:t&&e.systemEnv===!0}}function r_(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)try{return crypto.randomUUID()}catch{}let e=new Uint8Array(16);if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`)crypto.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var i_=829800;function a_(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`}var o_=[`ANTHROPIC_MODEL`,`ANTHROPIC_DEFAULT_OPUS_MODEL`,`ANTHROPIC_DEFAULT_SONNET_MODEL`,`ANTHROPIC_DEFAULT_HAIKU_MODEL`,`ANTHROPIC_DEFAULT_FABLE_MODEL`];function s_(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=o_.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??829800}`]:[],...i,`claude`].join(`
110
110
  `)}function c_(e){return e?e.backend??`auto`:`inherit`}function l_(e,t){if(t!==`inherit`)return t===`auto`?{...e,backend:void 0}:{...e,backend:t}}function u_(e,t){return{...e,model:t}}function d_(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 f_({label:e,checked:t,onChange:n,disabled:r=!1,describedBy:i}){return(0,J.jsxs)(`label`,{className:`toggle`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:t,disabled:r,"aria-label":e,"aria-describedby":i,onChange:e=>n(e.target.checked)}),(0,J.jsx)(`span`,{className:`slider`,"aria-hidden":`true`})]})}function p_({supported:e,checked:t,onChange:n}){let r=Q(),i=e?void 0:`claude-system-env-unsupported`;return(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:r(`claude.systemEnv`)}),e?(0,J.jsx)(`span`,{className:`desc`,children:r(`claude.systemEnvDesc`)}):(0,J.jsx)(`span`,{className:`desc`,id:i,children:(0,J.jsx)(ut,{k:`claude.systemEnvUnsupported`,cmd:`ocx claude`})}),e&&t&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:r(`claude.systemEnvWarn`)})]}),(0,J.jsx)(f_,{label:r(`claude.systemEnv`),checked:e&&t,disabled:!e,describedBy:i,onChange:n})]})}function m_({value:e,tierHaikuModel:t,options:n,onChange:r}){let i=Q(),a=t??e;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:i(`claude.smallFastModelAccurateHint`)}),(0,J.jsx)(Dt,{value:e,options:n,onChange:r,label:i(`claude.smallFastModel`),style:{maxWidth:420}}),a===``&&(0,J.jsx)(`p`,{className:`notice-warn`,role:`status`,style:{marginTop:8},children:i(`claude.smallFastModelNativeWarning`)})]})}function h_(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 g_({state:e,autoCompactOptions:t,availableModels:n,onStateChange:r}){let i=Q();return(0,J.jsxs)(`div`,{className:`card`,style:{overflow:`hidden`},children:[(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.authMode`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.authModeHint`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(Dt,{value:e.authMode,options:[{value:`auto`,label:i(`claude.authModeAuto`)},{value:`subscription`,label:i(`claude.authModeSubscription`)},{value:`proxy`,label:i(`claude.authModeProxy`)}],onChange:t=>r({...e,authMode:t}),label:i(`claude.authMode`),style:{minWidth:220},align:`right`,portal:!0})})]}),e.authModeOrigin&&(0,J.jsxs)(`div`,{className:`claude-effective-auth${e.authModeOrigin===`auto-unknown`?` warn`:``}`,role:`status`,children:[(0,J.jsx)(`span`,{className:`claude-effective-auth-label`,children:i(`claude.effectiveMode.label`)}),(0,J.jsxs)(`span`,{children:[e.authModeOrigin===`manual`?i(`claude.effectiveMode.manual`,{mode:e.markerMode===`proxy`?i(`claude.authModeProxy`):i(`claude.authModeSubscription`)}):e.authModeOrigin===`auto-present`?i(`claude.effectiveMode.autoPresent`,{source:h_(e.authFoundBy,i)}):e.authModeOrigin===`auto-absent`?i(`claude.effectiveMode.autoAbsent`):i(`claude.effectiveMode.autoUnknown`),e.admissionKeyActive===!0?` ${i(`claude.effectiveMode.admissionKey`)}`:``]})]}),(0,J.jsx)(p_,{supported:e.autoConnectSupported,checked:e.systemEnv,onChange:t=>r({...e,systemEnv:t})}),(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.fastMode`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.fastModeDesc`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(Dt,{value:e.fastMode===null?`auto`:e.fastMode?`on`:`off`,options:[{value:`auto`,label:i(`claude.fastAuto`)},{value:`on`,label:i(`claude.fastOn`)},{value:`off`,label:i(`claude.fastOff`)}],onChange:t=>r({...e,fastMode:t===`auto`?null:t===`on`}),label:i(`claude.fastMode`),style:{minWidth:140},align:`right`,portal:!0})})]}),(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.autoContext`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.autoContextDesc`)}),e.maxContextTokens!==null&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--muted)`},children:i(`claude.autoContextInert`)})]}),(0,J.jsx)(f_,{label:i(`claude.autoContext`),checked:e.autoContext,onChange:t=>r({...e,autoContext:t})})]}),e.autoContext&&(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.autoCompactWindow`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.autoCompactWindowDesc`)}),e.autoCompactWindow!==null&&(0,J.jsx)(`span`,{className:`desc`,style:{color:`var(--red)`},children:i(`claude.autoCompactWindowWarn`)})]}),(0,J.jsx)(`div`,{className:`setting-controls`,children:(0,J.jsx)(Dt,{value:e.autoCompactWindow===null?``:String(e.autoCompactWindow),options:t,onChange:t=>r({...e,autoCompactWindow:t===``?null:Number(t)}),label:i(`claude.autoCompactWindow`),style:{minWidth:130},align:`right`,portal:!0})})]}),(0,J.jsxs)(`div`,{className:`setting-row`,children:[(0,J.jsxs)(`div`,{className:`setting-label`,children:[(0,J.jsx)(`span`,{className:`title`,children:i(`claude.injectAgents`)}),(0,J.jsx)(`span`,{className:`desc`,children:i(`claude.injectAgentsDesc`)})]}),(0,J.jsx)(f_,{label:i(`claude.injectAgents`),checked:e.injectAgents,onChange:t=>r({...e,injectAgents:t})})]}),[`webSearchSidecar`,`visionSidecar`].map(t=>{let a=e[t],o=t===`webSearchSidecar`?`claude.webSearchSidecar`:`claude.visionSidecar`,s=t===`webSearchSidecar`?`claude.webSearchSidecarHint`:`claude.visionSidecarHint`,c=`claude-sidecar-models-${t}`;return(0,J.jsxs)(`div`,{className:`setting-row`,style:{alignItems:`flex-start`},children:[(0,J.jsxs)(`div`,{className:`setting-label setting-copy`,style:{flex:1},children:[(0,J.jsx)(`span`,{className:`title`,children:i(o)}),(0,J.jsx)(`span`,{className:`desc`,children:i(s)})]}),(0,J.jsxs)(`div`,{className:`setting-controls`,style:{display:`flex`,gap:8},children:[(0,J.jsx)(Dt,{value:c_(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]:l_(a,n)})},label:i(`dash.sidecarBackend`),portal:!0}),(0,J.jsx)(`input`,{className:`input mono`,value:a?.model??``,onChange:n=>{r({...e,[t]:u_(a,n.target.value)})},placeholder:i(`claude.sidecarModelPlaceholder`),disabled:!a,list:a?c:void 0,"aria-label":i(`dash.sidecarModel`),style:{minWidth:210},autoComplete:`off`}),a&&(0,J.jsx)(`datalist`,{id:c,children:n.map(e=>(0,J.jsx)(`option`,{value:e},e))})]})]},t)})]})}function __({manualEnv:e}){let t=Q();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:(0,J.jsx)(ut,{k:`claude.quickstartHint`,cmd:`ocx claude`})}),(0,J.jsx)(`pre`,{className:`mono card`,style:{padding:`10px 14px`,overflowX:`auto`,margin:0},children:`ocx claude`}),(0,J.jsxs)(`details`,{style:{margin:`10px 0 0`},children:[(0,J.jsx)(`summary`,{className:`muted text-label`,style:{cursor:`pointer`,padding:`2px 2px`},children:t(`claude.manualEnv`)}),(0,J.jsx)(`pre`,{className:`mono card text-label`,style:{padding:`10px 14px`,overflowX:`auto`,margin:`6px 0 0`},children:e})]})]})}function v_({rows:e,onRowsChange:t}){let n=Q();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`muted text-label`,style:{margin:`0 0 8px`},children:n(`claude.modelMapHint`)}),(0,J.jsx)(`div`,{className:`stack`,style:{gap:8},children:e.map((r,i)=>(0,J.jsxs)(`div`,{className:`row`,style:{gap:8},children:[(0,J.jsx)(`input`,{className:`input mono`,value:r.from,placeholder:n(`claude.mapFrom`),"aria-label":n(`claude.mapFrom`),onChange:n=>t(e.map((e,t)=>t===i?{...e,from:n.target.value}:e)),style:{flex:1}}),(0,J.jsx)(`span`,{className:`muted`,"aria-hidden":!0,children:`→`}),(0,J.jsx)(`input`,{className:`input mono`,value:r.to,placeholder:n(`claude.mapTo`),"aria-label":n(`claude.mapTo`),onChange:n=>t(e.map((e,t)=>t===i?{...e,to:n.target.value}:e)),style:{flex:1}}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-icon btn-sm`,onClick:()=>t(e.filter((e,t)=>t!==i)),"aria-label":n(`claude.removeMapping`),style:{color:`var(--red)`},children:(0,J.jsx)(ue,{})})]},r.id))}),(0,J.jsx)(`div`,{style:{marginTop:8},children:(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>t([...e,{id:r_(),from:``,to:``}]),children:[(0,J.jsx)(de,{}),` `,n(`claude.addMapping`)]})})]})}var y_=`etc`;function b_(e){let t=new Map;for(let n of e){let e=/\(([^)]+)\)\s*$/.exec(n.display_name),r=e?e[1]:y_,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t)}function x_({aliases:e}){let t=Q();return(0,J.jsxs)(`div`,{className:`claude-aliases`,children:[(0,J.jsx)(`p`,{className:`muted text-label claude-aliases-hint`,children:t(`claude.aliasesHint`)}),e.length===0?(0,J.jsx)(`div`,{className:`muted text-label`,children:t(`claude.none`)}):(0,J.jsx)(`div`,{className:`claude-aliases-scroll`,children:b_(e).map(([e,n])=>(0,J.jsxs)(`div`,{className:`claude-aliases-group`,children:[(0,J.jsxs)(`div`,{className:`claude-aliases-group-label`,children:[e===y_?t(`claude.aliasProviderOther`):e,(0,J.jsx)(`span`,{className:`claude-aliases-group-count`,children:n.length})]}),(0,J.jsx)(`div`,{className:`claude-aliases-chips`,children:n.map(e=>(0,J.jsxs)(`span`,{className:`claude-aliases-chip`,children:[(0,J.jsx)(`code`,{className:`claude-aliases-chip-id`,children:e.id}),e.display_name?(0,J.jsx)(`span`,{className:`claude-aliases-chip-name`,children:e.display_name}):null]},e.id))})]},e))})]})}function S_({apiBase:e,active:t=!0}){let n=Q(),{locale:r}=ct(),i=et.find(e=>e.code===r)?.htmlLang??`en`,a=`ocx.claude-code.v1:${e}`,o=`claude-code:${e}`,s=(0,_.useMemo)(()=>mr(a),[a]),c=s?.data??null,[l,u]=(0,_.useState)(()=>c?.state??null),[d,f]=(0,_.useState)(()=>c?.rows??[]),[p,m]=(0,_.useState)(!!c),[h,g]=(0,_.useState)(``),[v,y]=(0,_.useState)(!1),[b,x]=(0,_.useState)(`settings`),[S,C]=(0,_.useState)(!1),w=(0,_.useRef)(!1),T=(0,_.useCallback)(async t=>{let r=await Pt(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`,...n_(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:r_(),from:e,to:String(t)})),s={state:i,rows:o};if(t.aborted)throw Error(`Claude Code request aborted`);return u(i),f(o),m(!0),hr(a,s),s},[e,a,n]),E=ol(o,[e],T,{isEmpty:()=>!1,enabled:t,initialData:c??void 0,initialDataCachedAt:s?.cachedAt??null,staleAfterMs:6e4}),D=E.state,O=D.data??c,k=l??O?.state??null,A=p?d:O?.rows??d,j=(0,_.useMemo)(()=>t_(k?.available,n(`claude.smallFastModelUnsetOption`)),[k?.available,n]),M=(0,_.useMemo)(()=>{let e=[1e5,2e5,25e4,3e5,35e4,4e5,5e5,6e5,75e4,i_,9e5,1e6].sort((e,t)=>e-t),t=k?.autoCompactWindow??null,r=t!==null&&!e.includes(t)?[...e,t].sort((e,t)=>e-t):e;return[{value:``,label:n(`claude.autoCompactDefault`,{value:a_(i_,i)})},...r.map(e=>({value:String(e),label:a_(e,i)}))]},[k?.autoCompactWindow,n,i]),N=async()=>{if(!k||w.current)return;w.current=!0,C(!0),g(``);let t=!k.enabled;try{await Pt(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:t})}),n(`claude.saveFailed`)),u({...k,enabled:t}),E.refresh()}catch(e){y(!1),g(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}finally{w.current=!1,C(!1)}},P=async()=>{if(!k)return;g(``);let t={};for(let e of A)e.from.trim()&&e.to.trim()&&(t[e.from.trim()]=e.to.trim());try{await Pt(await fetch(`${e}/api/claude-code`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:k.enabled,authMode:k.authMode,systemEnv:k.systemEnv,fastMode:k.fastMode,autoContext:k.autoContext,autoCompactWindow:k.autoCompactWindow,injectAgents:k.injectAgents,smallFastModel:k.smallFastModel,modelMap:t,webSearchSidecar:d_(k.webSearchSidecar),visionSidecar:d_(k.visionSidecar)})}),n(`claude.saveFailed`)),y(!0),g(n(`claude.saved`)),E.refresh()}catch(e){y(!1),g(e instanceof Error&&e.message?e.message:n(`claude.networkError`))}};if(D.kind===`disabled`&&!O)return null;if(D.showSkeleton&&!O)return(0,J.jsx)(cl,{label:n(`claude.loading`),rows:3});if(D.kind===`failed-cold`){let e=D.error instanceof Error?D.error.message:n(`claude.loadFail`);return(0,J.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[(0,J.jsx)($,{tone:`err`,children:e}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>E.refresh(),children:n(`common.retry`)})]})}if(!k)return null;let F=[{id:`settings`,label:n(`claude.workspace.settings`),body:(0,J.jsx)(g_,{state:k,autoCompactOptions:M,availableModels:k.available??[],onStateChange:u})},{id:`quickstart`,label:n(`claude.quickstart`),body:(0,J.jsx)(__,{manualEnv:s_(k)})},{id:`smallFast`,label:n(`claude.smallFastModel`),body:(0,J.jsx)(m_,{value:k.smallFastModel,tierHaikuModel:k.tierModels?.haiku,options:j,onChange:e=>u({...k,smallFastModel:e})})},{id:`modelMap`,label:n(`claude.modelMap`),meta:String(A.length),body:(0,J.jsx)(v_,{rows:A,onRowsChange:e=>{m(!0),f(e)}})},{id:`aliases`,label:n(`claude.aliases`),meta:String(k.aliases.length),body:(0,J.jsx)(x_,{aliases:k.aliases})}],I=F.find(e=>e.id===b)??F[0],L=b===`settings`||b===`smallFast`||b===`modelMap`;return(0,J.jsxs)(`div`,{className:`claudecode-workspace-shell`,children:[h&&(0,J.jsx)($,{tone:v?`ok`:`err`,children:h}),D.showError&&(0,J.jsx)($,{tone:`err`,children:n(`claude.loadFail`)}),k&&(0,J.jsxs)(`div`,{className:`claudecode-connection-head`,children:[(0,J.jsx)(`span`,{id:`claudecode-connection-label`,children:n(`claude.enabledLabel`)}),(0,J.jsx)(Tt,{on:k.enabled,onClick:()=>void N(),disabled:S,label:n(`claude.toggleAria`)})]}),(0,J.jsxs)(`div`,{className:`claudecode-workspace-root`,children:[(0,J.jsx)(`aside`,{className:`claudecode-workspace-rail`,"aria-label":n(`claude.pageTitle`),children:(0,J.jsx)(`div`,{className:`claudecode-workspace-rail-list`,children:F.map(e=>(0,J.jsx)(`button`,{type:`button`,className:`claudecode-workspace-rail-row${b===e.id?` claudecode-workspace-rail-row--selected`:``}`,onClick:()=>x(e.id),"aria-current":b===e.id?`true`:void 0,children:(0,J.jsx)(`span`,{className:`claudecode-workspace-rail-name`,children:e.label})},e.id))})}),(0,J.jsxs)(`section`,{className:`claudecode-workspace-main`,"aria-label":I.label,children:[(0,J.jsxs)(`div`,{className:`ccw-main-head`,children:[(0,J.jsxs)(`h3`,{className:`ccw-main-title`,children:[I.label,I.meta==null?null:(0,J.jsx)(`span`,{className:`count`,children:I.meta})]}),(0,J.jsx)(`div`,{className:`claudecode-workspace-save`,"data-visible":L?`true`:`false`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,disabled:!L,tabIndex:L?0:-1,"aria-hidden":!L,onClick:()=>{P()},children:n(`common.save`)})})]}),(0,J.jsx)(`div`,{className:`ccw-body`,children:I.body})]})]})]})}function C_(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 w_(e){return new Set(Object.keys(e))}function T_(e,t){return t!==null&&e===t}function E_(e){return e||(typeof localStorage>`u`?void 0:localStorage)}function D_(e){return{read(t){let n=E_(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=E_(n);if(r)try{r.setItem(e,JSON.stringify([...t]))}catch{}}}}function O_(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}var k_=[`opus`,`fable`,`sonnet`,`haiku`],A_=D_(`ocx.claudeDesktop.collapsedFamilies.v2`),j_={opus:`claudeDesktop.family.opus`,fable:`claudeDesktop.family.fable`,sonnet:`claudeDesktop.family.sonnet`,haiku:`claudeDesktop.family.haiku`};function M_(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 N_(e){let t={...e.profile.assignments};for(let n of e.models){let e=t[n.route]??n.assignment;t[n.route]={family:k_.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 P_(e,t){return e&&typeof e==`object`&&`error`in e&&typeof e.error==`string`?e.error:t}function F_(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 I_(e){return mr(e)?.data??null}function L_(e){return mr(e)?.cachedAt??null}function R_(e){let t=I_(e);return{held:t,data:t?.data??null,profile:t?.profile??null,savedProfile:t?.profile?M_(t.profile):null,destinations:t?.data?Object.fromEntries(t.data.models.map(e=>[e.route,t.profile.assignments[e.route]?.family??`opus`])):{}}}function z_({apiBase:e,active:t=!0,onPortChange:n}){let{t:r,locale:i}=ct(),a=et.find(e=>e.code===i)?.htmlLang,o=`ocx.claude-desktop.v1:${e}`,s=`claude-desktop:${e}`,c=(0,_.useMemo)(()=>R_(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)(()=>A_.read()??new Set(k_)),[O,k]=(0,_.useState)({}),A=(0,_.useRef)(null),j=(0,_.useCallback)(async t=>{let n=await Pt(await fetch(`${e}/api/claude-desktop`,{signal:t}),r(`claudeDesktop.loadFail`));if(!n||!(`profile`in n)||!(`models`in n))throw Error(P_(n,r(`claudeDesktop.loadFail`)));let i=N_(n),a={data:n,profile:i};if(t.aborted)throw Error(`Claude Desktop request aborted`);if(u(i),f(M_(i)),m(Object.fromEntries(n.models.map(e=>[e.route,i.assignments[e.route]?.family??`opus`]))),A_.read()===null){let e=Object.fromEntries(k_.map(e=>[e,0]));for(let t of n.models)e[i.assignments[t.route]?.family??`opus`]+=1;D(w_(e))}return hr(o,a),a},[e,o,r,m,u,f]),M=ol(s,[e],j,{isEmpty:()=>!1,enabled:t,initialData:c.held??void 0,initialDataCachedAt:L_(o),staleAfterMs:6e4}),N=M.state,P=N.data??(c.data&&c.profile?{data:c.data,profile:c.profile}:null),F=P?.data??null,I=l??P?.profile??null,L=d??P?.profile??null,R=P?Object.fromEntries(P.data.models.map(e=>[e.route,P.profile.assignments[e.route]?.family??`opus`])):{},z=Object.keys(p).length>0?p:R;(0,_.useEffect)(()=>{if(n){if(typeof F?.port==`number`){n(F.port);return}N.kind===`failed-cold`&&n(null)}},[F?.port,N.kind,n]);let B=(0,_.useMemo)(()=>I!==null&&L!==null&&JSON.stringify(I)!==JSON.stringify(L),[I,L]),V=(0,_.useMemo)(()=>{let e=Object.fromEntries(k_.map(e=>[e,[]]));if(!F||!I)return e;for(let t of F.models)e[I.assignments[t.route]?.family??`opus`].push(t);return e},[F,I]),H=(0,_.useMemo)(()=>{let e={};for(let t of k_){let n=V[t].filter(e=>e.available).map(e=>e.route).sort(),r=I?.defaults[t]??null;e[t]=r&&n.includes(r)?r:n[0]??null}return e},[V,I]),U=`ocx.claude-desktop.status.v1:${e}`,W=`claude-desktop-status:${e}`,ee=mr(U),G=ol(W,[e],async t=>{let n=await Ft(await fetch(`${e}/api/claude-desktop/status`,{signal:t}));if(!n)throw Error(`Claude Desktop status unavailable`);return hr(U,n),n},{isEmpty:()=>!1,pollMs:5e3,enabled:t,initialData:ee?.data??void 0}),K=G.state,q=K.data??ee?.data??null,Y=K.showError,te=(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(j_[t])})))},ne=e=>{let t=O_(E,e);A_.write(t),D(t)},re=async t=>{if(!(!I||b)){x(`save`),g(null);try{await Pt(await fetch(`${e}/api/claude-desktop`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({profile:I})}),r(`claudeDesktop.saveFailed`)),f(M_(I)),t?(x(`apply`),(await Pt(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`))),G.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=N_({...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&&te(n,t)};if(N.kind===`disabled`&&!P)return null;if(N.showSkeleton&&!P)return(0,J.jsx)(cl,{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,J.jsxs)(`div`,{className:`claude-desktop-error`,children:[(0,J.jsx)($,{tone:`err`,children:e}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>M.refresh(),children:r(`claudeDesktop.retry`)})]})}return!F||!I?null:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`div`,{className:`claude-desktop-toolbar`,children:(0,J.jsxs)(`div`,{className:`claude-profile-tools`,children:[(0,J.jsx)(`input`,{ref:A,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>void ae(e)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>A.current?.click(),children:r(`claudeDesktop.importJson`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:ie,children:r(`claudeDesktop.exportJson`)})]})}),(0,J.jsxs)(`div`,{className:`claude-status-bar ${Y&&!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&&!Y||void 0,children:[(0,J.jsx)(`span`,{className:`claude-status-dot`}),(0,J.jsx)(`span`,{children:Y&&!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,J.jsxs)(`span`,{className:`claude-status-health`,children:[r(`claudeDesktop.health.lastRequest`),`:`,` `,new Date(q.health.lastRequestAt).toLocaleTimeString(a)]}),q&&q.health.requestCount>0&&(0,J.jsx)(`span`,{className:`claude-status-health`,children:r(`claudeDesktop.health.stats`,{count:q.health.requestCount,errors:q.health.errorCount})})]}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:v}),h&&(0,J.jsx)($,{tone:h.tone,children:h.text}),N.showError&&(0,J.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),Y&&q&&(0,J.jsx)($,{tone:`err`,children:r(`claudeDesktop.loadFail`)}),(0,J.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,J.jsx)(`span`,{className:`claude-dirty${B?` active`:``}`,children:r(B?`claudeDesktop.unsaved`:`claudeDesktop.upToDate`)}),(0,J.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!B||b!==null,onClick:()=>void re(!1),children:r(b===`save`?`claudeDesktop.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:b!==null,onClick:()=>void re(!0),children:b===`apply`?r(`claudeDesktop.applying`):b===`save`?r(`claudeDesktop.saving`):q?.desiredEnabled===!1?r(`claudeDesktop.enableApply`):r(`claudeDesktop.saveApply`)})]})]}),F.models.length===0&&(0,J.jsx)(Ot,{title:r(`claudeDesktop.emptyTitle`),children:r(`claudeDesktop.emptyHint`)}),(0,J.jsx)(`div`,{className:`ocx-group-stack`,"aria-label":r(`claudeDesktop.assignmentsLabel`),children:k_.map(e=>{let t=V[e],n=C_(t,S[e]??``,w[e]??6),i=E.has(e),a=H[e];return(0,J.jsxs)(`section`,{className:`ocx-group${i?` collapsed`:``}`,"aria-labelledby":`claude-lane-${e}`,onDragOver:e=>e.preventDefault(),onDrop:t=>oe(t,e),children:[(0,J.jsxs)(`header`,{className:`ocx-group-head${i?``:` open`}`,children:[(0,J.jsx)(`h3`,{id:`claude-lane-${e}`,className:`ocx-group-heading`,children:(0,J.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!i,"aria-controls":`claude-lane-body-${e}`,onClick:()=>ne(e),children:[(0,J.jsx)(Se,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:i?`none`:`rotate(90deg)`}}),(0,J.jsx)(`span`,{className:`ocx-group-name`,children:r(j_[e])}),(0,J.jsx)(`span`,{className:`ocx-group-count`,children:r(t.length===1?`claudeDesktop.modelCountOne`:`claudeDesktop.modelCountMany`,{count:t.length})}),a&&(0,J.jsx)(`code`,{className:`claude-lane-default`,title:a,children:a})]})}),t.length>0&&I.defaults[e]===null&&(0,J.jsx)(`span`,{className:`claude-default-needed`,children:r(`claudeDesktop.chooseDefault`)}),a&&a!==I.defaults[e]&&(0,J.jsx)(`span`,{className:`claude-default-needed`,title:a,children:r(`claudeDesktop.temporaryDefault`)})]}),!i&&(0,J.jsxs)(`div`,{id:`claude-lane-body-${e}`,children:[n.showSearch&&(0,J.jsx)(`input`,{className:`input claude-lane-search`,type:`search`,placeholder:r(`models.search`),"aria-label":r(`models.search`),value:S[e]??``,onChange:t=>{let n=t.target.value;C(t=>({...t,[e]:n})),T(t=>({...t,[e]:6}))}}),(0,J.jsxs)(`div`,{className:`claude-lane-models`,children:[t.length===0?(0,J.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneEmpty`)}):n.noMatch?(0,J.jsx)(`div`,{className:`claude-lane-empty`,children:r(`claudeDesktop.laneNoMatch`)}):n.shown.map(t=>{let n=I.assignments[t.route],i=F_(t.contextWindow,r),a=z[t.route]??`opus`,o=O[t.route]??T_(t.route,H[e]);return(0,J.jsxs)(`article`,{className:`claude-model-card${o?` open`:``}`,draggable:t.available,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t.route)},children:[(0,J.jsxs)(`button`,{type:`button`,className:`claude-model-summary`,"aria-expanded":o,"aria-controls":`claude-model-body-${t.route}`,onClick:()=>k(e=>({...e,[t.route]:!o})),children:[(0,J.jsx)(Se,{className:`ocx-chevron`,width:12,height:12,"aria-hidden":`true`,style:{transform:o?`rotate(90deg)`:`none`}}),(0,J.jsxs)(`span`,{className:`claude-model-names`,children:[(0,J.jsx)(`strong`,{title:t.label,children:t.label}),(0,J.jsx)(`code`,{title:t.route,children:t.route})]}),i&&(0,J.jsx)(`span`,{className:`claude-model-context`,children:i}),!i&&(0,J.jsx)(`span`,{className:`claude-model-context claude-model-context-unknown`,children:r(`claudeDesktop.contextUnknown`)}),t.supports1m===!0&&(0,J.jsx)(`span`,{className:`claude-1m-chip`,children:r(`claudeDesktop.supports1m`)}),t.effortSupported===!1&&(0,J.jsx)(`span`,{className:`claude-effort-badge off`,children:r(`claudeDesktop.effort.displayOnly`)}),t.effortSupported===!0&&(0,J.jsx)(`span`,{className:`claude-effort-badge on`,children:r(`claudeDesktop.effort.supported`)}),I.defaults[e]===t.route&&(0,J.jsx)(`span`,{className:`claude-row-default`,children:r(`claudeDesktop.defaultBadge`)}),(0,J.jsx)(`span`,{className:`badge ${t.available?`badge-green`:`badge-muted`}`,children:t.available?r(`claudeDesktop.available`):r(`claudeDesktop.unavailable`)})]}),o&&(0,J.jsxs)(`div`,{className:`claude-model-body`,id:`claude-model-body-${t.route}`,children:[H[e]===t.route&&I.defaults[e]!==t.route&&(0,J.jsx)(`span`,{className:`claude-effective-default`,children:r(`claudeDesktop.temporaryDefault`)}),(0,J.jsxs)(`div`,{className:`claude-field`,children:[(0,J.jsx)(`span`,{children:r(`claudeDesktop.alias`)}),(0,J.jsx)(`code`,{className:`claude-alias`,title:n.alias,children:n.alias})]}),(0,J.jsxs)(`label`,{className:`claude-default-radio`,children:[(0,J.jsx)(`input`,{type:`radio`,name:`default-${e}`,checked:I.defaults[e]===t.route,disabled:!t.available,onChange:()=>u(n=>n&&{...n,defaults:{...n.defaults,[e]:t.route}})}),r(`claudeDesktop.useAsDefault`,{family:r(j_[e])})]}),(0,J.jsxs)(`div`,{className:`claude-move-row`,children:[(0,J.jsx)(`label`,{htmlFor:`move-${t.route}`,children:r(`claudeDesktop.moveTo`)}),(0,J.jsx)(`select`,{id:`move-${t.route}`,className:`input`,value:a,disabled:!t.available,onChange:e=>m(n=>({...n,[t.route]:e.target.value})),children:k_.map(e=>(0,J.jsx)(`option`,{value:e,children:r(j_[e])},e))}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,disabled:!t.available||a===e,onClick:()=>te(t.route,a),children:r(`claudeDesktop.move`)})]})]})]},t.route)}),n.hidden>0&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm claude-lane-more`,onClick:()=>T(t=>({...t,[e]:(t[e]??6)+6})),children:r(`models.showMore`,{n:n.hidden})})]})]})]},e)})})]})}var B_=`integrations/claude`,V_=`integrations/claude/desktop`;function H_(e=typeof window<`u`?window.location.hash:``){return dt(e)===V_?`desktop`:`code`}function U_(e){let t=fr(`ocx.claude-desktop.v1:${e}`);return typeof t?.data?.port==`number`?t.data.port:null}function W_({apiBase:e,active:t=!0}){let[n,r]=(0,_.useState)(H_),i=Q(),a=(0,_.useRef)(null),o=(0,_.useRef)(null),s=U_(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(H_());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let p=e=>{pt(e===`desktop`?V_:B_),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,J.jsxs)(`section`,{className:`claude-page`,children:[(0,J.jsxs)(`div`,{className:`claude-page-intro`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:i(n===`code`?`claude.pageTitle`:`claudeDesktop.title`)})}),n===`code`?(0,J.jsx)(`p`,{className:`page-sub`,children:i(`claude.subtitle`)}):(0,J.jsx)(`p`,{className:`page-sub`,children:u==null?i(d?`claudeDesktop.loadFail`:`claudeDesktop.loading`):i(`claudeDesktop.subtitle`,{port:u})})]}),(0,J.jsxs)(`div`,{className:`claude-tabs`,role:`tablist`,"aria-label":i(`claude.tabsLabel`),children:[(0,J.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,J.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,J.jsx)(`div`,{id:`claude-code-panel`,role:`tabpanel`,"aria-labelledby":`claude-code-tab`,hidden:n!==`code`,children:(0,J.jsx)(S_,{apiBase:e,active:t&&n===`code`},e)}),(0,J.jsx)(`div`,{id:`claude-desktop-panel`,role:`tabpanel`,"aria-labelledby":`claude-desktop-tab`,hidden:n!==`desktop`,children:(0,J.jsx)(z_,{apiBase:e,active:t&&n===`desktop`,onPortChange:f},e)})]})}function G_(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 K_=D_(`ocx.grok.collapsedGroups.v2`),q_=[{id:`native`,tkey:`grok.groupNative`},{id:`routed`,tkey:`grok.groupRouted`}],J_=new Set(q_.map(e=>e.id));function Y_(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 X_({apiBase:e,active:t=!0}){let n=Q(),r=`ocx.grok.status.v1:${e}`,i=mr(r),a=i?.data??null,[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(()=>K_.read()??new Set(J_)),[u,d]=(0,_.useState)(null),[f,p]=(0,_.useState)(null),[m,h]=(0,_.useState)(``),g=(0,_.useCallback)(async t=>{let i=await Pt(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 hr(r,a),a},[e,r,n]),v=`grok-status:${e}`,y=ol(v,[e],g,{isEmpty:()=>!1,initialData:a??void 0,initialDataCachedAt:i?.cachedAt??null,staleAfterMs:6e4,enabled:t}),{state:b}=y,x=y.refresh,S=b.data??a,C=(0,_.useMemo)(()=>new Set(S?.excluded??[]),[S]),w=o??C,T=(0,_.useMemo)(()=>o!==null&&(o.size!==C.size||[...o].some(e=>!C.has(e))),[o,C]),E=(0,_.useMemo)(()=>new Map((S?.models??[]).map(e=>[e.id,e.alias])),[S]),D=e=>{let t=O_(c,e);K_.write(t),l(t)},O=e=>{let t=e?new Set(q_.map(e=>e.id)):new Set;K_.write(t),l(t)},k=(e,t)=>{s(n=>{let r=new Set(n??C);return t?r.delete(e):r.add(e),r})},A=async t=>{if(!u){d(`save`),p(null);try{await Pt(await fetch(`${e}/api/grok/selection`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({excluded:[...w]})}),n(`grok.saveFailed`));let i=[...w];if(S&&K(v,{...S,excluded:i}),s(null),t){d(`apply`);let t=await fetch(`${e}/api/grok/apply`,{method:`POST`});if(!t.ok){let e=await t.json().catch(()=>({}));throw Error(e.message??e.error??n(`grok.applyFailed`))}let r=await t.json().catch(()=>({}));r.skippedReason?(p({tone:`err`,text:r.message??n(`grok.applySkipped`)}),h(r.message??n(`grok.applySkipped`))):(p({tone:`ok`,text:n(`grok.savedApplied`)}),h(n(`grok.savedApplied`))),await x()}else p({tone:`ok`,text:n(`grok.saved`)}),h(n(`grok.saved`)),S&&hr(r,{...S,excluded:i})}catch(e){let t=e instanceof Error?e.message:n(`grok.saveFailed`);p({tone:`err`,text:t}),h(t)}finally{d(null)}}};if(b.showSkeleton&&!S)return(0,J.jsx)(`section`,{className:`grok-page`,children:(0,J.jsx)(cl,{label:n(`grok.loading`),rows:4})});if(b.kind===`failed-cold`){let e=b.error instanceof Error?b.error.message:n(`grok.loadFail`);return(0,J.jsxs)(`section`,{className:`grok-page`,children:[(0,J.jsx)(`div`,{className:`alert alert-err`,role:`alert`,children:e}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>x(),children:n(`common.retry`)})]})}return(0,J.jsxs)(`section`,{className:`grok-page`,"aria-busy":b.refreshing||void 0,children:[(0,J.jsx)(`h2`,{className:`page-title`,children:n(`grok.title`)}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`grok.subtitle`)}),(0,J.jsx)(`div`,{className:`sr-only`,"aria-live":`polite`,"aria-atomic":`true`,children:m}),f&&(0,J.jsx)($,{tone:f.tone,children:f.text}),b.showError&&(0,J.jsx)($,{tone:`err`,children:n(`grok.loadFail`)}),S&&S.candidates.length>0&&(0,J.jsxs)(`div`,{className:`claude-profile-bar`,children:[(0,J.jsx)(`span`,{className:`claude-dirty${T?` active`:``}`,children:n(T?`grok.unsaved`:`grok.upToDate`)}),(0,J.jsxs)(`div`,{className:`claude-save-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:!T||u!==null,onClick:()=>void A(!1),children:n(u===`save`?`grok.saving`:`common.save`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:!T||u!==null,onClick:()=>void A(!0),children:n(u===`apply`?`grok.applying`:u===`save`?`grok.saving`:`grok.saveApply`)})]})]}),S?.present?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`grok-endpoint`,children:[(0,J.jsx)(`span`,{children:n(`grok.endpoint`)}),(0,J.jsx)(`code`,{children:S.baseUrl??`—`})]}),(0,J.jsx)(`p`,{className:`page-sub`,children:(0,J.jsx)(`code`,{children:S.configPath})})]}):(0,J.jsxs)(Ot,{title:n(`grok.notConfiguredTitle`),children:[n(`grok.notConfiguredHint`),(0,J.jsx)(`br`,{}),(0,J.jsx)(`code`,{children:S?.configPath})]}),S&&S.candidates.length>0&&(0,J.jsxs)(`div`,{className:`ocx-group-stack`,children:[(0,J.jsxs)(`div`,{className:`row`,style:{gap:6,margin:`2px 0 10px`},children:[(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!0),disabled:u!==null,children:[(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`}),` `,n(`models.collapseAll`)]}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm text-caption`,onClick:()=>O(!1),disabled:u!==null,children:[(0,J.jsx)(Se,{width:12,height:12,"aria-hidden":`true`,style:{transform:`rotate(90deg)`}}),` `,n(`models.expandAll`)]})]}),q_.map(e=>{let t=G_(S.candidates,E,w,e.id);if(t.total===0)return null;let r=c.has(e.id);return(0,J.jsxs)(`section`,{className:`ocx-group${r?` collapsed`:``}`,"aria-labelledby":`grok-group-${e.id}`,children:[(0,J.jsx)(`header`,{className:`ocx-group-head${r?``:` open`}`,children:(0,J.jsx)(`h3`,{id:`grok-group-${e.id}`,className:`ocx-group-heading`,children:(0,J.jsxs)(`button`,{type:`button`,className:`ocx-group-toggle`,"aria-expanded":!r,"aria-controls":`grok-group-body-${e.id}`,onClick:()=>D(e.id),children:[(0,J.jsx)(Se,{className:`ocx-chevron`,width:14,height:14,"aria-hidden":`true`,style:{transform:r?`none`:`rotate(90deg)`}}),(0,J.jsx)(`span`,{className:`ocx-group-name`,children:n(e.tkey)}),(0,J.jsx)(`span`,{className:`ocx-group-count`,children:n(`grok.enabledCount`,{on:t.enabled,total:t.total})})]})})}),!r&&(0,J.jsx)(`div`,{id:`grok-group-body-${e.id}`,className:`grok-model-list`,children:t.rows.map(e=>(0,J.jsxs)(`div`,{className:`grok-model-row`,children:[(0,J.jsx)(Tt,{on:e.enabled,onClick:()=>k(e.id,!e.enabled),disabled:u!==null,label:n(`grok.toggleModel`,{id:e.id})}),(0,J.jsxs)(`span`,{className:`grok-model-names`,children:[(0,J.jsx)(`strong`,{title:e.id,children:e.id}),(0,J.jsx)(`code`,{title:e.alias??void 0,children:e.alias??`—`})]}),(0,J.jsx)(`span`,{className:`claude-model-context`,children:Y_(e.contextWindow,n)})]},e.id))})]},e.id)})]})]})}var Z_={"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`},Q_={"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 $_({state:e,installed:t,id:n}){let r=Q(),i=e===`unknown`||e===`not-installed`||t?e:`not-installed`;return(0,J.jsx)(`span`,{id:n,className:Q_[i],"data-integration-state":i,children:r(Z_[i])})}function ev({copyKey:e,vars:t}){let n=Q()(e,t),r=t?.path;if(!r||!n.includes(r))return(0,J.jsx)(`p`,{children:n});let[i,...a]=n.split(r);return(0,J.jsxs)(`p`,{children:[i,(0,J.jsx)(`code`,{children:r}),a.join(r)]})}function tv({copy:e,onConfirm:t,onClose:n}){let r=Q(),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,J.jsx)(ev,{copyKey:e.changesKey,vars:e.vars},`changes`),(0,J.jsx)(ev,{copyKey:e.breakageKey,vars:e.vars},`breakage`),(0,J.jsx)(ev,{copyKey:e.undoKey,vars:e.vars},`undo`)];return e.sideEffectKey&&f.push((0,J.jsx)(ev,{copyKey:e.sideEffectKey,vars:e.vars},`side-effect`)),(0,J.jsxs)(`dialog`,{ref:i,className:`modal-overlay`,"aria-labelledby":l,onCancel:u,children:[(0,J.jsx)(`button`,{type:`button`,className:`modal-backdrop-dismiss`,"aria-label":r(`common.close`),tabIndex:-1,onClick:()=>{a||n()}}),(0,J.jsxs)(`div`,{className:`modal-card integration-consequence-dialog`,role:`document`,children:[(0,J.jsxs)(`div`,{className:`modal-head`,children:[(0,J.jsx)(`h3`,{id:l,children:r(e.titleKey,e.vars)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:n,disabled:a,children:r(`common.close`)})]}),(0,J.jsx)(`div`,{className:`integration-consequence-body`,children:f}),s&&(0,J.jsx)($,{tone:`err`,children:s}),(0,J.jsx)(`div`,{className:`modal-actions`,children:(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,onClick:()=>void d(),disabled:a,children:r(e.confirmKey)})})]})]})}var nv=[`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`],rv=new Set([`not_installed`,`conflict`,`unsafe`,`non_loopback`,`drift_requires_confirm`,`snapshot_expired`,`write_failed`]),iv=new Set([`integration_unsafe`,`integration_conflict`,`integration_drift_confirmation_required`,`integration_snapshot_expired`,`integration_mutation_failed`]),av=new Set([`absent`,`current`,`stale`,`conflict`,`unsafe`]);function ov(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sv(e){return!ov(e)||!rv.has(String(e.reason))?!1:typeof e.error==`string`&&iv.has(String(e.code))&&nv.includes(e.clientId)&&av.has(String(e.state))&&typeof e.message==`string`}var cv=class extends Error{refusal;status;body;constructor(e,t){let n=sv(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 lv(e){try{let t=await e.json();return ov(t)?t:{}}catch{return{}}}async function uv(e){if(!e.ok)throw new cv(e.status,await lv(e));let t=await Ft(e);if(t==null)throw new cv(e.status,{});return t}async function dv(e,t){return uv(await fetch(`${e}/api/client-integrations`,{signal:t}))}async function fv(e,t,n){return uv(await fetch(`${e}/api/client-integrations/${encodeURIComponent(t)}`,{signal:n}))}async function pv(e,t,n){let r=t?`?client=${encodeURIComponent(t)}`:``;return uv(await fetch(`${e}/api/client-integrations/journal${r}`,{signal:n}))}async function mv(e,t,n,r){return uv(await fetch(`${e}/api/client-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}async function hv(e,t,n=!1,r){return uv(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 gv(e){try{let t=await e;return t.ok?await Ft(t)??null:null}catch{return null}}async function _v(e,t){let n=await gv(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 vv(e,t){let n=await fetch(`${e}/api/keys`,{signal:t});if(!n.ok)throw Error(`/api/keys responded ${n.status}`);let r=await Ft(n);if(!r||!Array.isArray(r.keys))throw Error(`/api/keys returned an unexpected body`);return r.keys.length}async function yv(e,t){let n=await gv(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 bv(e,t){let n=await gv(fetch(`${e}/api/claude-desktop/status`,{signal:t}));return!n||typeof n.desiredEnabled!=`boolean`||typeof n.installed!=`boolean`||typeof n.observedKind!=`string`?null:{desiredEnabled:n.desiredEnabled,installed:n.installed,observedKind:n.observedKind,applied:n.applied===!0,stale:n.stale===!0,drift:n.drift===!0,driftReason:typeof n.driftReason==`string`?n.driftReason:null,activeProfile:typeof n.activeProfile==`boolean`?n.activeProfile:null,appliedAt:typeof n.appliedAt==`string`?n.appliedAt:null}}async function xv(e,t){let n=await gv(fetch(`${e}/api/grok`,{signal:t}));return n?{present:n.present===!0,models:Array.isArray(n.models)?n.models:[]}:null}var Sv=new Set([`claude`,`grok`,`codex`,`claude-desktop`]),Cv=new Set([`native_integration_refused`,`native_integration_failed`]),wv=new Set([`not_installed`,`orphaned_marker`,`home_mismatch`,`config_busy`,`write_failed`,`metadata_unreadable`,`cleanup_incomplete`,`desired_state_changed`]);function Tv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ev(e){return Tv(e)?typeof e.error==`string`&&Cv.has(String(e.code))&&Sv.has(String(e.clientId))&&wv.has(String(e.reason))&&typeof e.message==`string`:!1}var Dv=class extends Error{refusal;status;body;constructor(e,t){let n=Ev(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 Ov(e){try{let t=await e;return t.ok?await Ft(t)??null:null}catch{return null}}async function kv(e){try{let t=await e.json();return Tv(t)?t:{}}catch{return{}}}async function Av(e){if(!e.ok)throw new Dv(e.status,await kv(e));let t=await Ft(e);if(t==null)throw new Dv(e.status,{});return t}function jv(e,t){return Ov(fetch(`${e}/api/native-integrations`,{signal:t}))}async function Mv(e,t,n,r){return Av(await fetch(`${e}/api/native-integrations/${encodeURIComponent(t)}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({enabled:n}),signal:r}))}var Nv={integration_mutation_busy:`integrations.error.busy`};function Pv(e){return e instanceof cv?e.refusal:null}function Fv(e){return e instanceof Dv?e.refusal:null}function Iv(e){return e===`conflict`?`integrations.error.conflict`:e===`unsafe`?`integrations.error.unsafe`:e===`non_loopback`?`integrations.error.nonLoopback`:`integrations.error.generic`}var Lv=new Set([`non_loopback`]);function Rv(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 zv(e,t,n,r){let i=Fv(t);if(i)return Rv(e,i,r);let a=Pv(t);if(!a){let r=Nv[t instanceof cv?String(t.body.code??``):``];return r?e(r):t instanceof Error&&t.message?t.message:n??e(`integrations.error.generic`)}let o=Lv.has(a.reason)?e(Iv(a.reason),{client:a.clientId}):a.message||e(Iv(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(Iv(a.reason))} ${o}`:o}function Bv({apiBase:e,row:t,onClose:n,onRestored:r}){let i=Q(),[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 hv(e,t.opId,a),r(),n()}catch(e){if(Pv(e)?.reason===`drift_requires_confirm`){o(!0),c(!1);return}u(zv(i,e)),c(!1)}}};return(0,J.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,J.jsxs)(`div`,{className:`modal-card integration-restore-dialog`,children:[(0,J.jsx)(`div`,{className:`modal-head`,children:(0,J.jsx)(`h3`,{id:`integration-restore-title`,children:i(a?`integrations.restore.driftTitle`:`integrations.restore.title`)})}),(0,J.jsx)(`div`,{className:`modal-desc`,children:i(a?`integrations.restore.driftBody`:`integrations.restore.body`)}),(0,J.jsx)(`p`,{className:`integration-path`,children:t.configPath}),l&&(0,J.jsx)($,{tone:`err`,children:l}),(0,J.jsxs)(`div`,{className:`modal-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:n,disabled:s,children:i(`common.cancel`)}),(0,J.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 Vv={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,prime:`integrations.tab.prime`};function Hv(e){return e===`current`||e===`stale`}function Uv(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 Wv(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 Gv(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 Kv(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=Gv(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 qv(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(!i)return e.applied===!0||e.driftReason===`desired_off_gateway_selected`?{...r,state:`stale`,installed:e.installed===!0,applied:!0,toggleOn:!1,detailKey:`integrations.detail.desktopDesiredOffCleanupPending`}:{...r,state:`absent`,installed:e.installed===!0,applied:!1,toggleOn:!1,detailKey:`integrations.detail.desktopDesiredOff`};if(e.applied!==!0)return{...r,state:`absent`,installed:e.installed===!0,applied:!1,toggleOn:i,detailKey:`integrations.detail.desktopDesiredOnNotApplied`};let a=e.stale===!0||e.activeProfile===!1;return{...r,state:a?`stale`:`current`,installed:!0,applied:!0,toggleOn:i,detailKey:e.activeProfile===!1?`integrations.detail.desktopNotServed`:a?`integrations.detail.desktopStale`:`integrations.detail.desktopCurrent`}}function Jv(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 Yv(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=Jv(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 Xv(e){return{id:e.clientId,hash:`integrations/${e.clientId}`,labelKey:Vv[e.clientId],state:e.installed?e.state:`not-installed`,installed:e.installed,applied:e.installed&&Hv(e.state),detail:e.configPath,detailKey:null,detailVars:null,toggle:e.clientId,toggleBlocked:null,togglePath:e.configPath,status:e}}function Zv(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=[Uv(e.codex),Kv(e.claude,t,e.nativeSettled),qv(e.claudeDesktop,e.native?.find(e=>e.clientId===`claude-desktop`),e.nativeSettled),Yv(e.grok,n,e.nativeSettled)];for(let t of nv){let n=r.get(t);if(n){i.push(Xv(n));continue}e.clientsSettled||i.push({id:t,hash:`integrations/${t}`,labelKey:Vv[t],state:`unknown`,installed:!1,applied:!1,detail:null,detailKey:null,detailVars:null,toggle:null,toggleBlocked:null,togglePath:null,status:null})}return{keysRow:Wv(e.keyPhase,e.keyCount),rows:i}}function Qv(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 $v={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`},ey={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`},ty={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`};function ny(e){return e.state===`current`||e.state===`stale`}function ry({row:e,pending:t,result:n,onOpen:r,onToggle:i}){let a=Q(),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`)?zv(a,new Dv(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,J.jsxs)(`li`,{className:`integration-card`,"data-client":e.id,children:[(0,J.jsxs)(`div`,{className:`integration-card-head`,children:[(0,J.jsx)(`h4`,{children:(0,J.jsx)(`button`,{type:`button`,className:`integration-card-link`,onClick:r,children:a(e.labelKey)})}),(0,J.jsx)($_,{state:e.state,installed:e.installed})]}),o&&(0,J.jsx)(`p`,{className:e.detail?`integration-path`:`integration-meta`,children:o}),n?.tone===`err`&&(0,J.jsx)($,{tone:`err`,children:n.text}),n?.tone===`ok`&&(0,J.jsx)($,{tone:`ok`,children:n.text}),(0,J.jsxs)(`div`,{className:`integration-card-actions`,children:[e.toggle&&i&&(0,J.jsxs)(`div`,{className:`integration-toggle-control`,children:[(0,J.jsx)(Tt,{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,J.jsx)(`p`,{className:`integration-toggle-blocked`,children:c})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:r,tabIndex:-1,children:a(`integrations.action.settings`)})]})]})}function iy({apiBase:e,active:t=!0}){let n=Q(),[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 dv(e,t)).clients,[e]),h=(0,_.useCallback)(async t=>(await pv(e,void 0,t)).operations,[e]),g=(0,_.useCallback)(t=>_v(e,t),[e]),v=(0,_.useCallback)(t=>vv(e,t),[e]),y=(0,_.useCallback)(t=>yv(e,t),[e]),b=(0,_.useCallback)(t=>bv(e,t),[e]),x=(0,_.useCallback)(t=>xv(e,t),[e]),S=(0,_.useCallback)(async t=>(await jv(e,t))?.clients??null,[e]),C=ol(`integration-states:${e}`,[e],m,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.states.v1:${e}`}),w=ol(`integration-journal-all:${e}`,[e],h,{isEmpty:e=>e.length===0,enabled:t,sessionCacheKey:`ocx.integrations.journal.v1:${e}`}),T=ol(`integration-codex:${e}`,[e],g,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.codex.v1:${e}`}),E=ol(`integration-keys:${e}`,[e],v,{isEmpty:()=>!1,enabled:t,sessionCacheKey:`ocx.integrations.keys.v1:${e}`}),D=ol(`integration-claude:${e}`,[e],y,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude.v1:${e}`}),O=ol(`integration-claude-desktop:${e}`,[e],b,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.claude-desktop.v1:${e}`}),k=ol(`integration-grok:${e}`,[e],x,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.grok.v1:${e}`}),A=ol(`integration-native:${e}`,[e],S,{isEmpty:e=>e===null,enabled:t,sessionCacheKey:`ocx.integrations.native.v1:${e}`}),j=C.state.data??[],M=w.state.data??[],N=j.filter(ny),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:z,rows:B}=Zv({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}),V=Qv(B),H=()=>{C.refresh(),w.refresh(),T.refresh(),E.refresh(),D.refresh(),O.refresh(),k.refresh(),A.refresh()},U=async()=>{if(r||N.length===0)return;let t=[n(`integrations.bulk.title`),n(`integrations.bulk.body`)].join(`
111
111
 
112
- `);if(!confirm(t))return;i(!0),o(null);let a=[];for(let t of N)try{await mv(e,t.clientId,!1)}catch(e){a.push(`${t.clientId}: ${zv(n,e)}`)}let s=!1;try{s=(await dv(e)).clients.some(ny)}catch{a.push(n(`integrations.error.stale`))}s&&a.length===0&&a.push(n(`integrations.error.stale`)),H(),i(!1),o(a.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})})},W=M[0]?.at,[ee,G]=(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})},Y=async(t,r)=>{if(!ee&&t.toggle){G(t.id),q(t.id,null);try{if(t.status)await mv(e,t.status.clientId,r),H();else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await Mv(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:zv(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&K()}finally{G(null)}}},te=(e,t)=>{if(e.status||t||e.id===`claude`||e.toggle===null){Y(e,t);return}let n=document.activeElement;p.current=n?.tagName===`BUTTON`?n:null,f(e)};return(0,J.jsxs)(`section`,{className:`integrations-overview`,children:[(0,J.jsxs)(`div`,{className:`integration-summary`,children:[(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,J.jsx)(`strong`,{children:V.detected})]}),(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,J.jsx)(`strong`,{children:V.applied})]}),(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,J.jsx)(`strong`,{children:V.stale})]}),V.unknown>0&&(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,J.jsx)(`strong`,{children:V.unknown})]}),(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,J.jsx)(`strong`,{children:W?new Date(W).toLocaleString():n(`integrations.status.unknown`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void U(),disabled:r||N.length===0,children:n(`integrations.summary.disableAll`)})]}),(0,J.jsx)(ay,{row:z}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`integrations.onboarding`)}),C.state.kind===`failed-cold`&&(0,J.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),C.state.kind===`failed-with-stale`&&(0,J.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),a&&(0,J.jsx)($,{tone:a.tone,children:a.text}),B.length===0?C.state.kind===`failed-cold`?null:(0,J.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,J.jsx)(`ul`,{className:`integration-cards`,children:B.map(e=>(0,J.jsx)(ry,{row:e,pending:ee!==null,result:l[e.id]??null,onOpen:()=>pt(e.hash),onToggle:e.toggle?()=>te(e,!(e.toggleOn??e.applied)):null},e.id))}),F&&P.length===0&&(0,J.jsxs)(`div`,{className:`integration-empty`,children:[(0,J.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,J.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,J.jsx)(`h4`,{children:n(`integrations.rollback.title`)}),M.length===0?(0,J.jsxs)(`div`,{className:`integration-empty`,children:[(0,J.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,J.jsx)(`ul`,{className:`integration-history`,children:M.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`integration-history-kind`,children:n(ty[e.kind])}),(0,J.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,J.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,J.jsx)(`span`,{className:`badge badge-muted`,children:n(`integrations.action.snapshotExpired`)}):(0,J.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,J.jsx)(Bv,{apiBase:e,row:s,onClose:()=>c(null),onRestored:H}),d&&(0,J.jsx)(tv,{copy:{...d.toggle===`claude-desktop`?ey:$v,vars:{path:d.togglePath??``}},onClose:()=>f(null),onConfirm:async()=>{await Y(d,!1),f(null)}})]})}function ay({row:e}){let t=Q(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,J.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,J.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,J.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,J.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>pt(e.hash),children:t(`integrations.action.manageKeys`)})]})}var oy={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,omp:`integrations.semantics.omp`,hermes:`integrations.semantics.hermes`,openclaw:`integrations.semantics.openclaw`,kimi:`integrations.semantics.kimi`,gajae:`integrations.semantics.gajae`,dsh:`integrations.semantics.dsh`,mcode:`integrations.semantics.mcode`,zcode:`integrations.semantics.zcode`,prime:`integrations.semantics.prime`},sy={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,prime:`integrations.tab.prime`},cy={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`};function ly({apiBase:e,client:t,active:n=!0}){let r=Q(),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),u=(0,_.useCallback)(n=>fv(e,t,n),[e,t]),d=(0,_.useCallback)(async n=>(await pv(e,t,n)).operations,[e,t]),f=ol(`integration-state:${e}:${t}`,[e,t],u,{isEmpty:()=>!1,enabled:n,sessionCacheKey:`ocx.integrations.state.v1:${e}:${t}`}),p=ol(`integration-journal:${e}:${t}`,[e,t],d,{isEmpty:e=>e.length===0,enabled:n,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${t}`}),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 mv(e,t,n),g()}catch(e){s(zv(r,e))}finally{a(!1)}}},y=()=>void v(!(m&&(m.state===`current`||m.state===`stale`)));if(!m)return(0,J.jsx)(`section`,{className:`integration-client-page`,children:f.state.kind===`failed-cold`?(0,J.jsx)($,{tone:`err`,children:r(`integrations.error.load`)}):(0,J.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,J.jsxs)(`section`,{className:`integration-client-page`,children:[(0,J.jsxs)(`div`,{className:`integration-client-head`,children:[(0,J.jsx)(`h3`,{children:r(sy[t])}),(0,J.jsx)($_,{state:m.state,installed:m.installed,id:`integration-state-${t}`}),(0,J.jsx)(Tt,{on:b,onClick:y,disabled:x||i,label:r(b?`integrations.action.disable`:`integrations.action.apply`)})]}),m.state===`stale`&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void v(!0),disabled:i,children:r(`integrations.action.refresh`)}),(0,J.jsx)(`p`,{className:`page-sub`,children:r(oy[t])}),(0,J.jsx)(`p`,{className:`integration-path`,children:m.configPath}),m.appliedAt&&(0,J.jsxs)(`p`,{className:`integration-meta`,children:[r(`integrations.status.appliedAt`),`: `,new Date(m.appliedAt).toLocaleString()]}),m.retentionDegraded&&(0,J.jsx)($,{tone:`err`,children:r(`integrations.retention.degraded`)}),o&&(0,J.jsx)($,{tone:`err`,children:o}),(0,J.jsx)(`h4`,{children:r(`integrations.rollback.title`)}),h.length===0?(0,J.jsx)(`p`,{className:`page-sub`,children:r(`integrations.rollback.empty`)}):(0,J.jsx)(`ul`,{className:`integration-history`,children:h.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`integration-history-kind`,children:r(cy[e.kind])}),(0,J.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,J.jsx)(`span`,{className:`badge badge-muted`,children:r(`integrations.action.snapshotExpired`)}):(0,J.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,J.jsx)(Bv,{apiBase:e,row:c,onClose:()=>l(null),onRestored:g})]})}var uy=[{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`},{id:`zcode`,hash:`integrations/zcode`,labelKey:`integrations.tab.zcode`},{id:`prime`,hash:`integrations/prime`,labelKey:`integrations.tab.prime`}],dy=new Set([`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`]);function fy(e=window.location.hash){let t=dt(e);return t===`integrations/claude/desktop`?`claude`:uy.find(e=>e.hash===t)?.id??`overview`}function py(e){return`integrations-tab-${e}`}function my(e){return`integrations-panel-${e}`}function hy({apiBase:e}){let t=Q(),[n,r]=(0,_.useState)(fy),[i,a]=(0,_.useState)(()=>new Set([fy()])),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(fy());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let c=(e,t)=>{let n=uy.find(t=>t.id===e);n&&(pt(n.hash),s(e),t&&window.requestAnimationFrame(()=>{o.current.get(e)?.focus({preventScroll:!0})}))},l=e=>{let t=uy.findIndex(e=>e.id===n),r=null;e.key===`ArrowLeft`?r=(t-1+uy.length)%uy.length:e.key===`ArrowRight`?r=(t+1)%uy.length:e.key===`Home`?r=0:e.key===`End`&&(r=uy.length-1),r!==null&&(e.preventDefault(),c(uy[r].id,!0))};return(0,J.jsxs)(`section`,{className:`integrations-page`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.integrations`)})}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`integrations.subtitle`)}),(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`integrations.tabsLabel`),children:uy.map(e=>(0,J.jsx)(`button`,{ref:t=>{t?o.current.set(e.id,t):o.current.delete(e.id)},type:`button`,role:`tab`,id:py(e.id),"aria-selected":n===e.id,"aria-controls":my(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))}),uy.map(r=>{if(!i.has(r.id))return null;let a=n===r.id;return(0,J.jsxs)(`div`,{role:`tabpanel`,id:my(r.id),"aria-labelledby":py(r.id),hidden:!a,children:[r.id===`overview`&&(0,J.jsx)(iy,{apiBase:e,active:a}),r.id===`keys`&&(0,J.jsx)(e_,{apiBase:e,active:a}),r.id===`codex`&&(0,J.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,J.jsx)(`h3`,{id:`codex-integration-title`,children:t(`integrations.codex.title`)}),(0,J.jsx)(`p`,{children:t(`integrations.codex.body`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>pt(`startup`),children:t(`integrations.codex.openService`)})]}),r.id===`claude`&&(0,J.jsx)(W_,{apiBase:e,active:a}),r.id===`grok`&&(0,J.jsx)(X_,{apiBase:e,active:a}),dy.has(r.id)&&(0,J.jsx)(ly,{apiBase:e,client:r.id,active:a})]},r.id)})]})}function gy(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 _y={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},vy={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},yy={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function by({ok:e,yes:t,no:n}){return(0,J.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function xy({failed:e,data:t}){let{t:n}=ct(),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`?_e:le,a=t.routingKind===`opencodex-local`?`startup.routing.proxy`:t.routingKind===`custom-local`?`startup.routing.customLocal`:t.routingKind===`custom-remote`?`startup.routing.customRemote`:t.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,J.jsx)(`div`,{className:`startup-hero-icon`,children:(0,J.jsx)(i,{})}),(0,J.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,J.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:_y[t.status])}),(0,J.jsx)(`h3`,{children:n(e?`startup.error`:vy[t.status])}),(0,J.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(_r(t)):n(`startup.safeDetail`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,J.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,J.jsx)(`div`,{className:`value`,children:n(yy[t.protection])})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,J.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function Sy({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=ct(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,J.jsxs)(`section`,{className:`panel startup-details`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,J.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.service`)}),(0,J.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(by,{ok:e.serviceViable,yes:o(`startup.viable`),no:o(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-service`),children:o(r===`install-service`?`startup.installing`:`startup.install`)}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-service`,{repair:!0}),children:o(r===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.shim`)}),(0,J.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(by,{ok:e.shimHealthy&&e.autostartEnabled,yes:o(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:o(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-shim`),children:o(r===`install-shim`?`startup.installing`:`startup.install`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-shim`,{repair:!0}),children:o(r===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),i&&(0,J.jsx)(`div`,{className:`notice ${i.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:i.kind===`success`?i.action===`install-service`?o(i.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):o(i.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${o(`startup.installFailed`)} ${i.detail??``}`})]})}function Cy({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=ct();return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,J.jsx)(we,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,J.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,J.jsx)(by,{ok:e.running&&!e.stale,yes:a(`startup.tray.running`),no:a(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,J.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`install`),children:a(`startup.tray.install`)}),!t&&!n&&e?.installed&&!e.stale&&!e.running&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`start`),children:a(`startup.tray.start`)}),!t&&!n&&e?.running&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:()=>i(`stop`),children:a(`startup.tray.stop`)}),!t&&!n&&e&&(e.installed||e.stale)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:r,onClick:()=>{window.confirm(a(`startup.tray.uninstall`))&&i(`uninstall`)},children:a(`startup.tray.uninstall`)})]}),(n||e?.stale)&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function wy({data:e,copied:t,onCopy:n}){let{t:r}=ct(),i=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,J.jsx)(X,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,J.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,J.jsx)(`code`,{children:i})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(i),children:r(t===i?`startup.copied`:`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,J.jsx)(`code`,{children:e.commands.installShim})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installShim),children:t===e.commands.installShim?r(`startup.copied`):r(`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,J.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.restoreNative),children:t===e.commands.restoreNative?r(`startup.copied`):r(`startup.copy`)})]})]}),e.status===`at-risk`&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,J.jsx)(we,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var Ty=`ocx.startup.page.v1:`;function Ey(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function Dy(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=Ey([`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 Oy({apiBase:e}){let{t}=ct(),n=`${Ty}${e}`,r=(0,_.useMemo)(()=>fr(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,_.useRef)(0);(0,_.useEffect)(()=>()=>{D.current+=1},[e]);let O=(0,_.useCallback)(async r=>{let i=++D.current,a=E.current;a||(u(!0),T(!0));try{let a=fetch(`${e}/api/settings`,{signal:r}).then(async e=>e.ok?await e.json():null).catch(()=>null),o=await fetch(`${e}/api/startup-health`,{signal:r});if(!o.ok)throw Error(`fetch failed`);let s=await o.json();y(e=>e?.kind===`error`&&(s.status===`native`&&e.forLocalRouting===!0||(e.action===`install-service`?s.serviceViable:s.shimInstalled&&s.shimHealthy))?null:e),E.current=!0;let l=fr(n);gr(n,{data:s,warning:l?.warning??null,fix:l?.fix??null,tray:l?.tray??null});let d=s.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(!gy(t))throw Error(`invalid tray status`);return{tray:t,error:!1}}).catch(()=>({tray:null,error:!0})):Promise.resolve({tray:null,error:!1});return Promise.all([a,d]).then(([e,a])=>{if(r.aborted||i!==D.current)return;let o=s.platform===`win32`?a.tray:null;if(s.platform===`win32`?(c(o),m(a.error)):(c(null),m(!1)),u(!1),T(!1),e){let r=Dy(e.codexRuntime,t,s.platform);x(r.warning),C(r.fix),gr(n,{data:s,warning:r.warning,fix:r.fix,tray:o});return}let l=fr(n);gr(n,{data:s,warning:l?.warning??null,fix:l?.fix??null,tray:o})}),s}catch(e){throw r.aborted?e:(a||(c(null),m(!0),x(null),C(null)),T(!1),u(!1),e)}},[e,n,t]),k=ol(i,[e],O,{isEmpty:()=>!1,initialData:r?.data??void 0}),A=k.state,j=k.refresh,M=A.data??r?.data??null,N=A.refreshing,P=!!M?.diagnosticStale||A.showError;(0,_.useEffect)(()=>{if(!M?.diagnosticStale)return;let e=window.setTimeout(j,2e3);return()=>window.clearTimeout(e)},[M,j]);let F=async e=>{try{await navigator.clipboard.writeText(e),o(e),window.setTimeout(()=>o(t=>t===e?null:t),1600)}catch{o(null)}},I=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(!gy(r.status))throw Error(`invalid tray action status`);c(r.status),m(!1)}catch{c(null),m(!0)}finally{f(!1)}},L=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}),j()}catch(e){y({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e),forLocalRouting:M?.localRoutingDependency===!0})}finally{g(null)}};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{children:t(`startup.title`)}),(0,J.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,J.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>pt(`dashboard`),children:t(`startup.backToDashboard`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j(),disabled:N,children:[(0,J.jsx)(fe,{}),` `,t(`startup.refresh`)]})]})]}),A.showSkeleton&&!M?(0,J.jsx)(cl,{label:t(`startup.loading`),rows:5}):A.kind===`failed-cold`?(0,J.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,J.jsx)($,{tone:`err`,children:A.error instanceof Error?A.error.message:t(`startup.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j(),children:t(`common.retry`)})]}):M?(0,J.jsxs)(J.Fragment,{children:[A.showError&&(0,J.jsx)($,{tone:`err`,children:t(`startup.error`)}),P&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(w||b)&&(0,J.jsx)(`div`,{className:`startup-runtime-notice-slot${w&&!b?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":w&&!b?!0:void 0,children:b&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,J.jsx)(`p`,{className:`startup-runtime-notice__text`,children:b}),S&&(0,J.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,J.jsx)(`code`,{children:S}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void F(S),children:t(a===S?`startup.copied`:`startup.copy`)})]})]})}),(0,J.jsx)(xy,{failed:P,data:M}),(0,J.jsx)(Sy,{data:M,failed:P,loading:N,installBusy:h,installResult:v,onInstall:(e,t)=>{L(e,t)}}),M.platform===`win32`&&(0,J.jsx)(Cy,{tray:s,trayLoading:l,trayError:p,trayBusy:d,onTrayAction:e=>{I(e)}}),(0,J.jsx)(wy,{data:M,copied:a,onCopy:e=>{F(e)}})]}):null]})}var ky=3e5,Ay=6e5,jy=`https://github.com/lidge-jun/opencodex`;async function My(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Ny({apiBase:e,onOpenUpdate:t}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=G(`sidebar-star:${e}`,[e],t=>My(`${e}/api/github/star`,t),{pollMs:ky}),c=G(`sidebar-update-badge:${e}`,[e],t=>My(`${e}/api/update/badge`,t),{pollMs:Ay}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??jy,f=u===`starred`,p=c.data,m=p?.updateAvailable===!0,h=p?.latestVersion??null,g=()=>window.open(d,`_blank`,`noopener,noreferrer`),v=async()=>{if(!(f||r)){if(u===`unauthenticated`){g();return}i(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){o({state:`starred`,basedOn:l});return}n?.state&&o({state:n.state,basedOn:l}),g()}catch{g()}finally{i(!1),s.refresh()}}},y=n(f?`sidebar.starred`:u===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),b=m&&h?n(`sidebar.updateAvailable`,{version:h}):n(`sidebar.checkUpdate`);return(0,J.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,J.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,J.jsx)(Ce,{}),` `,n(`common.github`)]}),(0,J.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`sidebar-orb${f?` sidebar-orb--starred`:``}`,onClick:()=>{v()},disabled:r||f,"aria-label":y,"aria-pressed":f,title:y,children:(0,J.jsx)(Ie,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,J.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,J.jsx)(Z,{"aria-hidden":`true`}),m&&(0,J.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Py=`opencodex-admin-token-dialog`,Fy=`OpenCodex`;function Iy(e,t=it()){let n=Ze[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=Py,o.className=`modal-overlay`,o.setAttribute(`aria-labelledby`,`${Py}-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=`${Py}-title`,l.textContent=r,c.append(l);let u=document.createElement(`div`),d=document.createElement(`label`);d.className=`field-label`,d.htmlFor=`${Py}-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=Fy,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=`${Py}-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 Ly=!1,Ry=null,zy=null,By=!1,Vy=Iy,Hy=`/opencodex-session`,Uy=`/api/settings`,Wy=1e4,Gy=15e3;function Ky(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 qy=`opencodex-api-token`,Jy=null,Yy=null,Xy=null;function Zy(){return Jy}function Qy(e){Jy=e}function $y(){Jy=null,Yy=null,Xy=null}function eb(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function tb(){rb(eb(`opencodex-session-token`),eb(`opencodex-session-csrf`),eb(`opencodex-session-origin`))}function nb(e){e!=null&&Zy()===e&&$y()}function rb(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(Jy=e,Yy=t,Xy=n,!0)}function ib(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 ab(){if(!zy)return{kind:`failed`};let e=Ln(Wy);try{let t=await zy(Hy,{cache:`no-store`,signal:e.signal});if(!t.ok)return t.status>=400&&t.status<500?{kind:`unavailable`}:{kind:`failed`};let n=await t.text(),r=rb(ib(n,`opencodex-session-token`),ib(n,`opencodex-session-csrf`),ib(n,`opencodex-session-origin`)),i=Zy();return r&&i?{kind:`minted`,token:i}:{kind:`unavailable`}}catch{return{kind:`failed`}}finally{e.clear()}}async function ob(e){if(!zy)return`unavailable`;try{let[t,n]=cb(Uy,{cache:`no-store`},e),r=await zy(t,n);return r.status===401?`rejected`:r.ok?`accepted`:`unavailable`}catch{return`unavailable`}}function sb(){try{sessionStorage.removeItem(qy)}catch{}}function cb(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),Xy&&Yy&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,Xy);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,Yy)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function lb(e,t){if(By||t?.aborted)return null;if(!Ry){let t=(async()=>{if(By)return null;let t=Zy();if(t&&t!==e)return t;let n,r=await Promise.race([ab(),new Promise(e=>{n=setTimeout(()=>e({kind:`failed`}),Gy)})]).finally(()=>clearTimeout(n));if(r.kind===`minted`)return r.token;if(r.kind===`failed`)return null;let i=await Vy(ob);return i?(Qy(i),i):(By=!0,null)})().finally(()=>{Ry===t&&(Ry=null)});Ry=t}if(!t)return Ry;let n,r=new Promise(e=>{n=()=>e(null),t.addEventListener(`abort`,n,{once:!0})});return Promise.race([Ry,r]).finally(()=>{n&&t.removeEventListener(`abort`,n)})}function ub(){if(Ly)return;Ly=!0,sb(),tb();let e=window.fetch.bind(window);zy=e,window.fetch=async(t,n)=>{if(!Ky(t))return e(t,n);let r=n?.signal??(t instanceof Request?t.signal:void 0),i=Zy(),[a,o]=i?cb(t,n,i):[t,n],s=await e(a,o);if(s.status!==401)return s;let c=Zy();if(c&&c!==i){let[r,i]=cb(t,n,c),a=await e(r,i);if(a.status!==401)return a;nb(c)}else nb(i);let l=await lb(i,r??void 0);if(!l)return s;let[u,d]=cb(t,n,l),f=await e(u,d);return f.status===401&&nb(l),f}}var db=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`logs`,`usage`,`storage`,`codex-set`,`integrations`]);function fb(e){let t=dt(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:t===`codex-auth`?`codex-set`:t===`combos`||t===`routing`||t===`lab`?`models`:t===`api`||t===`claude`||t===`grok`?`integrations`:db.has(t)?t:`dashboard`}var pb=[`dashboard/providers`,`dashboard/models`],mb=[`models/combos`,`models/routing`,`models/compatibility`],hb=[`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`,`integrations/mcode`,`integrations/zcode`,`integrations/prime`];function gb(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`codex-set`&&e===`codex-set/prompt`||t===`models`&&mb.includes(e)||t===`dashboard`&&(e===`dashboard/update`||pb.includes(e))||t===`integrations`&&hb.includes(e)}function _b(e){let t=fb(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`codex-auth`||e.startsWith(`codex-auth/`)?{page:`codex-set`,replaceTo:`codex-set`}:e===`combos`||e.startsWith(`combos/`)?{page:`models`,replaceTo:`models/combos`}:e===`routing`||e.startsWith(`routing/`)?{page:`models`,replaceTo:`models/routing`}:e===`lab`||e.startsWith(`lab/`)?{page:`models`,replaceTo:`models/compatibility`}:e===`api`?{page:`integrations`,replaceTo:`integrations/keys`}:e===`claude`?{page:`integrations`,replaceTo:`integrations/claude`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:gb(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var vb=[`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 yb(){try{for(let e of vb)localStorage.removeItem(e)}catch{}}function bb(){let[e,t]=(0,_.useState)(fb);(0,_.useEffect)(()=>{yb()},[]);let n=(0,_.useCallback)(e=>{let n=_b(e);n.replaceTo&&ft(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(dt(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=_b(dt(window.location.hash));n.replaceTo&&ft(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{pt(n?`${e}/${n}`:e),t(e)}}}var xb=15e3;function Sb(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 Cb(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function wb(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=xb,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 Cb(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:Sb(o,a.status,i)}:{accepted:!0}}ub();var Tb={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-set":`nav.codexSet`,integrations:`nav.integrations`},Eb=``,Db=`ocx-theme`,Ob=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:te},{id:`codex-set`,tkey:`nav.codexSet`,Icon:Ee},{id:`providers`,tkey:`nav.providers`,Icon:ne},{id:`models`,tkey:`nav.models`,Icon:re},{id:`subagents`,tkey:`nav.subagents`,Icon:ie},{id:`logs`,tkey:`nav.logs`,Icon:ae},{id:`usage`,tkey:`nav.usage`,Icon:se},{id:`storage`,tkey:`nav.storage`,Icon:ce},{id:`integrations`,tkey:`nav.integrations`,Icon:Ne}],kb={light:Ae,dark:je,system:Me},Ab={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function jb(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 Mb(){let e=localStorage.getItem(Db);return e===`light`||e===`dark`?e:`system`}function Nb(){let{page:e,navigateToPage:t}=bb(),[n,r]=(0,_.useState)(Cf);(0,_.useEffect)(()=>{let e=()=>r(Cf());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[i,a]=(0,_.useState)(Mb),{locale:o,setLocale:s}=ct(),c=Q(),[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(Db)):(e.setAttribute(`data-theme`,i),localStorage.setItem(Db,i))},[i]);let m=G(`app-healthz:${Eb}`,[],async e=>{let t=await fetch(`${Eb}/healthz`,{signal:e});return t.ok?jb(await t.json()):null},{pollMs:3e4}),h=()=>a(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),g=kb[i],v=m.data??`2.36.0-preview.20260830`,[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}=$c(Eb,{onSettled:()=>S(e=>e+1)}),T=async()=>{if(!confirm(c(`dash.stopConfirm`)))return;b(!0);let e=await wb(Eb,{formatFailure:e=>c(`dash.stopFailed`,{status:String(e)})});e.accepted||(b(!1),alert(e.message))},E=(0,J.jsxs)(`div`,{className:`brand`,children:[(0,J.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":c(`app.logoAria`)}),(0,J.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,J.jsxs)(`span`,{className:`ver`,children:[`v`,v]})]});return(0,J.jsxs)(`div`,{className:`app`,children:[(0,J.jsxs)(`header`,{className:`mobile-topbar`,inert:l,children:[(0,J.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,J.jsx)(oe,{})}),E,(0,J.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(0,J.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,J.jsx)(we,{})}),(0,J.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{w()},disabled:C,"aria-label":c(`dash.codexRestart`),title:c(`dash.codexRestart`),children:(0,J.jsx)(fe,{})})]})]}),l&&(0,J.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>u(!1),"aria-hidden":`true`}),(0,J.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${l?` open`:``}`,ref:f,tabIndex:-1,children:[(0,J.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,J.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>u(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,J.jsx)(ue,{})})]}),(0,J.jsx)(`nav`,{children:Ob.map(n=>{let{id:r,tkey:i,Icon:a}=n,o=r===e;return(0,J.jsx)(`div`,{className:`nav-entry`,children:(0,J.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,J.jsx)(a,{}),` `,c(i)]})},r)})}),(0,J.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,J.jsxs)(`div`,{className:`lang-toggle`,children:[(0,J.jsx)(Ne,{"aria-hidden":!0}),(0,J.jsx)(Dt,{value:o,options:et.map(e=>({value:e.code,label:Qe(e.code)})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,J.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:h,"aria-label":`${c(`theme.label`)}: ${c(Ab[i])}`,title:`${c(`theme.label`)}: ${c(Ab[i])}`,children:[(0,J.jsx)(g,{}),` `,(0,J.jsx)(`span`,{className:`mode`,children:c(Ab[i])})]}),(0,J.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,J.jsx)(`span`,{className:`sidebar-action-label`,children:c(`dash.actions`)}),(0,J.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[(0,J.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,J.jsx)(we,{})}),(0,J.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,J.jsx)(fe,{})})]})]}),(0,J.jsx)(Ny,{apiBase:Eb,onOpenUpdate:()=>{u(!1),t(`dashboard`,`update`)}})]})]}),(0,J.jsx)(`main`,{className:`main`,inert:l,children:(0,J.jsx)(`div`,{className:`main-inner${e===`models`&&n===`combos`?` main-inner--combos`:``}`,children:(0,J.jsxs)(ul,{pageName:c(Tb[e]),title:c(`errorBoundary.title`),message:c(`errorBoundary.message`),detailsLabel:c(`errorBoundary.details`),reloadLabel:c(`errorBoundary.reload`),children:[e===`dashboard`&&(0,J.jsx)(Kr,{apiBase:Eb}),e===`startup`&&(0,J.jsx)(Oy,{apiBase:Eb}),e===`providers`&&(0,J.jsx)(Bc,{apiBase:Eb}),e===`models`&&(0,J.jsx)(ip,{apiBase:Eb,restartEpoch:x},Eb),e===`subagents`&&(0,J.jsx)(gp,{apiBase:Eb},Eb),e===`logs`&&(0,J.jsx)(Um,{apiBase:Eb}),e===`usage`&&(0,J.jsx)(dh,{apiBase:Eb}),e===`storage`&&(0,J.jsx)(Vh,{apiBase:Eb}),e===`codex-set`&&(0,J.jsx)(wg,{apiBase:Eb}),e===`integrations`&&(0,J.jsx)(hy,{apiBase:Eb})]},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,J.jsx)(_.StrictMode,{children:(0,J.jsx)(lt,{children:(0,J.jsx)(Nb,{})})}));
112
+ `);if(!confirm(t))return;i(!0),o(null);let a=[];for(let t of N)try{await mv(e,t.clientId,!1)}catch(e){a.push(`${t.clientId}: ${zv(n,e)}`)}let s=!1;try{s=(await dv(e)).clients.some(ny)}catch{a.push(n(`integrations.error.stale`))}s&&a.length===0&&a.push(n(`integrations.error.stale`)),H(),i(!1),o(a.length===0?{tone:`ok`,text:n(`integrations.bulk.success`)}:{tone:`err`,text:n(`integrations.bulk.partial`,{clients:a.join(`; `)})})},W=M[0]?.at,[ee,G]=(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})},Y=async(t,r)=>{if(!ee&&t.toggle){G(t.id),q(t.id,null);try{if(t.status)await mv(e,t.status.clientId,r),H();else if(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`){let i=await Mv(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:zv(n,e,void 0,t.togglePath??void 0)}),(t.toggle===`claude`||t.toggle===`grok`||t.toggle===`codex`||t.toggle===`claude-desktop`)&&K()}finally{G(null)}}},te=(e,t)=>{if(e.status||t||e.id===`claude`||e.toggle===null){Y(e,t);return}let n=document.activeElement;p.current=n?.tagName===`BUTTON`?n:null,f(e)};return(0,J.jsxs)(`section`,{className:`integrations-overview`,children:[(0,J.jsxs)(`div`,{className:`integration-summary`,children:[(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.detected`)}),(0,J.jsx)(`strong`,{children:V.detected})]}),(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.applied`)}),(0,J.jsx)(`strong`,{children:V.applied})]}),(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.stale`)}),(0,J.jsx)(`strong`,{children:V.stale})]}),V.unknown>0&&(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.state.unknown`)}),(0,J.jsx)(`strong`,{children:V.unknown})]}),(0,J.jsxs)(`div`,{className:`integration-summary-cell`,children:[(0,J.jsx)(`span`,{className:`integration-summary-label`,children:n(`integrations.summary.lastChange`)}),(0,J.jsx)(`strong`,{children:W?new Date(W).toLocaleString():n(`integrations.status.unknown`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void U(),disabled:r||N.length===0,children:n(`integrations.summary.disableAll`)})]}),(0,J.jsx)(ay,{row:z}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`integrations.onboarding`)}),C.state.kind===`failed-cold`&&(0,J.jsx)($,{tone:`err`,children:n(`integrations.error.load`)}),C.state.kind===`failed-with-stale`&&(0,J.jsx)($,{tone:`err`,children:n(`integrations.error.stale`)}),a&&(0,J.jsx)($,{tone:a.tone,children:a.text}),B.length===0?C.state.kind===`failed-cold`?null:(0,J.jsx)(`p`,{className:`page-sub`,children:n(`common.loading`)}):(0,J.jsx)(`ul`,{className:`integration-cards`,children:B.map(e=>(0,J.jsx)(ry,{row:e,pending:ee!==null,result:l[e.id]??null,onOpen:()=>pt(e.hash),onToggle:e.toggle?()=>te(e,!(e.toggleOn??e.applied)):null},e.id))}),F&&P.length===0&&(0,J.jsxs)(`div`,{className:`integration-empty`,children:[(0,J.jsx)(`h4`,{children:n(`integrations.empty.title`)}),(0,J.jsx)(`p`,{children:n(`integrations.empty.body`)})]}),(0,J.jsx)(`h4`,{children:n(`integrations.rollback.title`)}),M.length===0?(0,J.jsxs)(`div`,{className:`integration-empty`,children:[(0,J.jsx)(`p`,{children:n(`integrations.rollback.empty`)}),(0,J.jsx)(`p`,{className:`page-sub`,children:n(`integrations.rollback.emptyBody`)})]}):(0,J.jsx)(`ul`,{className:`integration-history`,children:M.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`integration-history-kind`,children:n(ty[e.kind])}),(0,J.jsx)(`span`,{className:`integration-history-client`,children:e.clientId}),(0,J.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,J.jsx)(`span`,{className:`badge badge-muted`,children:n(`integrations.action.snapshotExpired`)}):(0,J.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,J.jsx)(Bv,{apiBase:e,row:s,onClose:()=>c(null),onRestored:H}),d&&(0,J.jsx)(tv,{copy:{...d.toggle===`claude-desktop`?ey:$v,vars:{path:d.togglePath??``}},onClose:()=>f(null),onConfirm:async()=>{await Y(d,!1),f(null)}})]})}function ay({row:e}){let t=Q(),n=e.detailKey?t(e.detailKey,e.detailVars??void 0):null;return(0,J.jsxs)(`div`,{className:`integration-api-keys-row`,"data-client":`keys`,"data-key-state":e.state,children:[(0,J.jsxs)(`div`,{className:`integration-api-keys-copy`,children:[(0,J.jsx)(`h4`,{children:t(e.labelKey)}),n&&(0,J.jsx)(`p`,{className:`integration-meta`,children:n})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>pt(e.hash),children:t(`integrations.action.manageKeys`)})]})}var oy={opencode:`integrations.semantics.opencode`,pi:`integrations.semantics.pi`,omp:`integrations.semantics.omp`,hermes:`integrations.semantics.hermes`,openclaw:`integrations.semantics.openclaw`,kimi:`integrations.semantics.kimi`,gajae:`integrations.semantics.gajae`,dsh:`integrations.semantics.dsh`,mcode:`integrations.semantics.mcode`,zcode:`integrations.semantics.zcode`,prime:`integrations.semantics.prime`},sy={opencode:`integrations.tab.opencode`,pi:`integrations.tab.pi`,omp:`integrations.tab.omp`,hermes:`integrations.tab.hermes`,openclaw:`integrations.tab.openclaw`,kimi:`integrations.tab.kimi`,gajae:`integrations.tab.gajae`,dsh:`integrations.tab.dsh`,mcode:`integrations.tab.mcode`,zcode:`integrations.tab.zcode`,prime:`integrations.tab.prime`},cy={apply:`integrations.kind.apply`,disable:`integrations.kind.disable`,refresh:`integrations.kind.refresh`,restore:`integrations.kind.restore`};function ly({apiBase:e,client:t,active:n=!0}){let r=Q(),[i,a]=(0,_.useState)(!1),[o,s]=(0,_.useState)(null),[c,l]=(0,_.useState)(null),u=(0,_.useCallback)(n=>fv(e,t,n),[e,t]),d=(0,_.useCallback)(async n=>(await pv(e,t,n)).operations,[e,t]),f=ol(`integration-state:${e}:${t}`,[e,t],u,{isEmpty:()=>!1,enabled:n,sessionCacheKey:`ocx.integrations.state.v1:${e}:${t}`}),p=ol(`integration-journal:${e}:${t}`,[e,t],d,{isEmpty:e=>e.length===0,enabled:n,sessionCacheKey:`ocx.integrations.client-journal.v1:${e}:${t}`}),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 mv(e,t,n),g()}catch(e){s(zv(r,e))}finally{a(!1)}}},y=()=>void v(!(m&&(m.state===`current`||m.state===`stale`)));if(!m)return(0,J.jsx)(`section`,{className:`integration-client-page`,children:f.state.kind===`failed-cold`?(0,J.jsx)($,{tone:`err`,children:r(`integrations.error.load`)}):(0,J.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,J.jsxs)(`section`,{className:`integration-client-page`,children:[(0,J.jsxs)(`div`,{className:`integration-client-head`,children:[(0,J.jsx)(`h3`,{children:r(sy[t])}),(0,J.jsx)($_,{state:m.state,installed:m.installed,id:`integration-state-${t}`}),(0,J.jsx)(Tt,{on:b,onClick:y,disabled:x||i,label:r(b?`integrations.action.disable`:`integrations.action.apply`)})]}),m.state===`stale`&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>void v(!0),disabled:i,children:r(`integrations.action.refresh`)}),(0,J.jsx)(`p`,{className:`page-sub`,children:r(oy[t])}),(0,J.jsx)(`p`,{className:`integration-path`,children:m.configPath}),m.appliedAt&&(0,J.jsxs)(`p`,{className:`integration-meta`,children:[r(`integrations.status.appliedAt`),`: `,new Date(m.appliedAt).toLocaleString()]}),m.retentionDegraded&&(0,J.jsx)($,{tone:`err`,children:r(`integrations.retention.degraded`)}),o&&(0,J.jsx)($,{tone:`err`,children:o}),(0,J.jsx)(`h4`,{children:r(`integrations.rollback.title`)}),h.length===0?(0,J.jsx)(`p`,{className:`page-sub`,children:r(`integrations.rollback.empty`)}):(0,J.jsx)(`ul`,{className:`integration-history`,children:h.map(e=>(0,J.jsxs)(`li`,{children:[(0,J.jsx)(`span`,{className:`integration-history-kind`,children:r(cy[e.kind])}),(0,J.jsx)(`span`,{className:`integration-history-at`,children:new Date(e.at).toLocaleString()}),e.snapshot===`expired`?(0,J.jsx)(`span`,{className:`badge badge-muted`,children:r(`integrations.action.snapshotExpired`)}):(0,J.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,J.jsx)(Bv,{apiBase:e,row:c,onClose:()=>l(null),onRestored:g})]})}var uy=[{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`},{id:`zcode`,hash:`integrations/zcode`,labelKey:`integrations.tab.zcode`},{id:`prime`,hash:`integrations/prime`,labelKey:`integrations.tab.prime`}],dy=new Set([`opencode`,`pi`,`omp`,`hermes`,`openclaw`,`kimi`,`gajae`,`dsh`,`mcode`,`zcode`,`prime`]);function fy(e=window.location.hash){let t=dt(e);return t===`integrations/claude/desktop`?`claude`:uy.find(e=>e.hash===t)?.id??`overview`}function py(e){return`integrations-tab-${e}`}function my(e){return`integrations-panel-${e}`}function hy({apiBase:e}){let t=Q(),[n,r]=(0,_.useState)(fy),[i,a]=(0,_.useState)(()=>new Set([fy()])),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(fy());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let c=(e,t)=>{let n=uy.find(t=>t.id===e);n&&(pt(n.hash),s(e),t&&window.requestAnimationFrame(()=>{o.current.get(e)?.focus({preventScroll:!0})}))},l=e=>{let t=uy.findIndex(e=>e.id===n),r=null;e.key===`ArrowLeft`?r=(t-1+uy.length)%uy.length:e.key===`ArrowRight`?r=(t+1)%uy.length:e.key===`Home`?r=0:e.key===`End`&&(r=uy.length-1),r!==null&&(e.preventDefault(),c(uy[r].id,!0))};return(0,J.jsxs)(`section`,{className:`integrations-page`,children:[(0,J.jsx)(`div`,{className:`page-head`,children:(0,J.jsx)(`h2`,{children:t(`nav.integrations`)})}),(0,J.jsx)(`p`,{className:`page-sub`,children:t(`integrations.subtitle`)}),(0,J.jsx)(`div`,{className:`page-tabs`,role:`tablist`,"aria-label":t(`integrations.tabsLabel`),children:uy.map(e=>(0,J.jsx)(`button`,{ref:t=>{t?o.current.set(e.id,t):o.current.delete(e.id)},type:`button`,role:`tab`,id:py(e.id),"aria-selected":n===e.id,"aria-controls":my(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))}),uy.map(r=>{if(!i.has(r.id))return null;let a=n===r.id;return(0,J.jsxs)(`div`,{role:`tabpanel`,id:my(r.id),"aria-labelledby":py(r.id),hidden:!a,children:[r.id===`overview`&&(0,J.jsx)(iy,{apiBase:e,active:a}),r.id===`keys`&&(0,J.jsx)(e_,{apiBase:e,active:a}),r.id===`codex`&&(0,J.jsxs)(`section`,{className:`integration-native-page`,"aria-labelledby":`codex-integration-title`,children:[(0,J.jsx)(`h3`,{id:`codex-integration-title`,children:t(`integrations.codex.title`)}),(0,J.jsx)(`p`,{children:t(`integrations.codex.body`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,onClick:()=>pt(`startup`),children:t(`integrations.codex.openService`)})]}),r.id===`claude`&&(0,J.jsx)(W_,{apiBase:e,active:a}),r.id===`grok`&&(0,J.jsx)(X_,{apiBase:e,active:a}),dy.has(r.id)&&(0,J.jsx)(ly,{apiBase:e,client:r.id,active:a})]},r.id)})]})}function gy(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 _y={native:`startup.status.native`,protected:`startup.status.protected`,"at-risk":`startup.status.atRisk`},vy={native:`startup.summary.native`,protected:`startup.summary.protected`,"at-risk":`startup.summary.atRisk`},yy={service:`startup.protection.service`,shim:`startup.protection.shim`,none:`startup.protection.none`};function by({ok:e,yes:t,no:n}){return(0,J.jsx)(`span`,{className:`badge ${e?`badge-green`:`badge-amber`}`,children:e?t:n})}function xy({failed:e,data:t}){let{t:n}=ct(),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`?_e:le,a=t.routingKind===`opencodex-local`?`startup.routing.proxy`:t.routingKind===`custom-local`?`startup.routing.customLocal`:t.routingKind===`custom-remote`?`startup.routing.customRemote`:t.routingKind===`unknown`?`startup.routing.unknown`:`startup.routing.native`;return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`section`,{className:`panel startup-hero ${r}`,"aria-live":`polite`,children:[(0,J.jsx)(`div`,{className:`startup-hero-icon`,children:(0,J.jsx)(i,{})}),(0,J.jsxs)(`div`,{className:`startup-hero-copy`,children:[(0,J.jsx)(`span`,{className:`badge ${e||t.status===`at-risk`?`badge-amber`:`badge-green`}`,children:n(e?`startup.status.atRisk`:_y[t.status])}),(0,J.jsx)(`h3`,{children:n(e?`startup.error`:vy[t.status])}),(0,J.jsx)(`p`,{children:e?n(`startup.staleData`):t.status===`at-risk`?n(_r(t)):n(`startup.safeDetail`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-state-grid`,children:[(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.routing`)}),(0,J.jsx)(`div`,{className:`value`,children:n(a)})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.restartProtection`)}),(0,J.jsx)(`div`,{className:`value`,children:n(yy[t.protection])})]}),(0,J.jsxs)(`section`,{className:`stat`,children:[(0,J.jsx)(`div`,{className:`label`,children:n(`startup.preference`)}),(0,J.jsx)(`div`,{className:`value`,children:n(t.autostartEnabled?`startup.enabled`:`startup.disabled`)})]})]})]})}function Sy({data:e,failed:t,loading:n=!1,installBusy:r,installResult:i,onInstall:a}){let{t:o}=ct(),s=e.serviceSupported&&e.serviceInstalled&&e.serviceStale&&!e.serviceConflict,c=e.shimInstalled&&!e.shimHealthy,l=r!==null||t||n;return(0,J.jsxs)(`section`,{className:`panel startup-details`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:o(`startup.details`)}),(0,J.jsx)(`span`,{className:`muted mono`,children:e.platform})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.service`)}),(0,J.jsx)(`span`,{children:o(`startup.serviceHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(by,{ok:e.serviceViable,yes:o(`startup.viable`),no:o(e.serviceConflict?`startup.conflict`:e.serviceStale?`startup.stale`:e.serviceInstalled?`startup.unhealthy`:e.serviceSupported?`startup.notInstalled`:`startup.unsupported`)}),e.serviceSupported&&!e.serviceInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-service`),children:o(r===`install-service`?`startup.installing`:`startup.install`)}),s&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.service`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-service`,{repair:!0}),children:o(r===`install-service`?`startup.repairing`:`startup.repair`)})]})]}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:o(`startup.shim`)}),(0,J.jsx)(`span`,{children:o(`startup.shimHint`)})]}),(0,J.jsxs)(`div`,{className:`startup-detail-actions`,children:[(0,J.jsx)(by,{ok:e.shimHealthy&&e.autostartEnabled,yes:o(e.shimCoverage===`cli-only`?`startup.cliOnly`:`startup.healthy`),no:o(e.shimInstalled?e.shimHealthy&&!e.autostartEnabled?`startup.installedDisabled`:`startup.stale`:`startup.notInstalled`)}),!e.shimInstalled&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.install`)}`,disabled:l,onClick:()=>a(`install-shim`),children:o(r===`install-shim`?`startup.installing`:`startup.install`)}),c&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary btn-sm`,"aria-label":`${o(`startup.shim`)} - ${o(`startup.repair`)}`,disabled:l,onClick:()=>a(`install-shim`,{repair:!0}),children:o(r===`install-shim`?`startup.repairing`:`startup.repair`)})]})]}),i&&(0,J.jsx)(`div`,{className:`notice ${i.kind===`success`?`notice-ok`:`notice-warn`} startup-action-notice`,role:`status`,"aria-live":`polite`,children:i.kind===`success`?i.action===`install-service`?o(i.repair?`startup.serviceRepaired`:`startup.serviceInstalled`):o(i.repair?`startup.shimRepaired`:`startup.shimInstalled`):`${o(`startup.installFailed`)} ${i.detail??``}`})]})}function Cy({tray:e,trayLoading:t,trayError:n,trayBusy:r,onTrayAction:i}){let{t:a}=ct();return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:a(`startup.tray.title`)}),(0,J.jsx)(we,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:a(`startup.tray.hint`)}),(0,J.jsxs)(`div`,{className:`startup-detail-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:a(`startup.tray.login`)}),(0,J.jsx)(`span`,{children:a(`startup.tray.notProtection`)})]}),t||n||!e?(0,J.jsx)(`span`,{className:`badge badge-amber`,children:a(t?`startup.tray.loading`:`startup.tray.unavailable`)}):(0,J.jsx)(by,{ok:e.running&&!e.stale,yes:a(`startup.tray.running`),no:a(e.stale?`startup.tray.stale`:e.installed?`startup.tray.stopped`:`startup.tray.notInstalled`)})]}),(0,J.jsxs)(`div`,{className:`startup-tray-buttons`,children:[!t&&!n&&e&&!e.installed&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`install`),children:a(`startup.tray.install`)}),!t&&!n&&e?.installed&&!e.stale&&!e.running&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-primary`,disabled:r,onClick:()=>i(`start`),children:a(`startup.tray.start`)}),!t&&!n&&e?.running&&!e.stale&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost`,disabled:r,onClick:()=>i(`stop`),children:a(`startup.tray.stop`)}),!t&&!n&&e&&(e.installed||e.stale)&&(0,J.jsx)(`button`,{type:`button`,className:`btn btn-danger`,disabled:r,onClick:()=>{window.confirm(a(`startup.tray.uninstall`))&&i(`uninstall`)},children:a(`startup.tray.uninstall`)})]}),(n||e?.stale)&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-tray-error`,role:`alert`,children:a(`startup.tray.error`)})]})}function wy({data:e,copied:t,onCopy:n}){let{t:r}=ct(),i=e.serviceInstalled&&!e.serviceConflict?e.commands.repairService:e.commands.installService;return(0,J.jsxs)(`section`,{className:`panel startup-actions`,children:[(0,J.jsxs)(`div`,{className:`panel-head`,children:[(0,J.jsx)(`h3`,{className:`panel-title`,children:r(`startup.recovery`)}),(0,J.jsx)(X,{})]}),(0,J.jsx)(`p`,{className:`muted`,children:r(`startup.recoveryHint`)}),(0,J.jsxs)(`div`,{className:`startup-command-list`,children:[e.serviceSupported&&(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.service`)}),(0,J.jsx)(`code`,{children:i})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(i),children:r(t===i?`startup.copied`:`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.shim`)}),(0,J.jsx)(`code`,{children:e.commands.installShim})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.installShim),children:t===e.commands.installShim?r(`startup.copied`):r(`startup.copy`)})]}),(0,J.jsxs)(`div`,{className:`startup-command-row`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:r(`startup.command.native`)}),(0,J.jsx)(`code`,{children:e.commands.restoreNative})]}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>n(e.commands.restoreNative),children:t===e.commands.restoreNative?r(`startup.copied`):r(`startup.copy`)})]})]}),e.status===`at-risk`&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-action-notice`,role:`alert`,children:[(0,J.jsx)(we,{}),` `,r(`startup.recommended`,{cmd:e.recommendedCommand??e.commands.installService})]})]})}var Ty=`ocx.startup.page.v1:`;function Ey(e,t){let n=t===`win32`?`; `:` && `;return e.join(n)}function Dy(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=Ey([`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 Oy({apiBase:e}){let{t}=ct(),n=`${Ty}${e}`,r=(0,_.useMemo)(()=>fr(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,_.useRef)(0);(0,_.useEffect)(()=>()=>{D.current+=1},[e]);let O=(0,_.useCallback)(async r=>{let i=++D.current,a=E.current;a||(u(!0),T(!0));try{let a=fetch(`${e}/api/settings`,{signal:r}).then(async e=>e.ok?await e.json():null).catch(()=>null),o=await fetch(`${e}/api/startup-health`,{signal:r});if(!o.ok)throw Error(`fetch failed`);let s=await o.json();y(e=>e?.kind===`error`&&(s.status===`native`&&e.forLocalRouting===!0||(e.action===`install-service`?s.serviceViable:s.shimInstalled&&s.shimHealthy))?null:e),E.current=!0;let l=fr(n);gr(n,{data:s,warning:l?.warning??null,fix:l?.fix??null,tray:l?.tray??null});let d=s.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(!gy(t))throw Error(`invalid tray status`);return{tray:t,error:!1}}).catch(()=>({tray:null,error:!0})):Promise.resolve({tray:null,error:!1});return Promise.all([a,d]).then(([e,a])=>{if(r.aborted||i!==D.current)return;let o=s.platform===`win32`?a.tray:null;if(s.platform===`win32`?(c(o),m(a.error)):(c(null),m(!1)),u(!1),T(!1),e){let r=Dy(e.codexRuntime,t,s.platform);x(r.warning),C(r.fix),gr(n,{data:s,warning:r.warning,fix:r.fix,tray:o});return}let l=fr(n);gr(n,{data:s,warning:l?.warning??null,fix:l?.fix??null,tray:o})}),s}catch(e){throw r.aborted?e:(a||(c(null),m(!0),x(null),C(null)),T(!1),u(!1),e)}},[e,n,t]),k=ol(i,[e],O,{isEmpty:()=>!1,initialData:r?.data??void 0}),A=k.state,j=k.refresh,M=A.data??r?.data??null,N=A.refreshing,P=!!M?.diagnosticStale||A.showError;(0,_.useEffect)(()=>{if(!M?.diagnosticStale)return;let e=window.setTimeout(j,2e3);return()=>window.clearTimeout(e)},[M,j]);let F=async e=>{try{await navigator.clipboard.writeText(e),o(e),window.setTimeout(()=>o(t=>t===e?null:t),1600)}catch{o(null)}},I=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(!gy(r.status))throw Error(`invalid tray action status`);c(r.status),m(!1)}catch{c(null),m(!0)}finally{f(!1)}},L=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}),j()}catch(e){y({kind:`error`,action:t,repair:n?.repair===!0,detail:e instanceof Error?e.message:String(e),forLocalRouting:M?.localRoutingDependency===!0})}finally{g(null)}};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`page-head`,children:[(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`h2`,{children:t(`startup.title`)}),(0,J.jsx)(`p`,{className:`page-sub startup-page-sub`,children:t(`startup.subtitle`)})]}),(0,J.jsxs)(`div`,{className:`startup-page-head-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>pt(`dashboard`),children:t(`startup.backToDashboard`)}),(0,J.jsxs)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j(),disabled:N,children:[(0,J.jsx)(fe,{}),` `,t(`startup.refresh`)]})]})]}),A.showSkeleton&&!M?(0,J.jsx)(cl,{label:t(`startup.loading`),rows:5}):A.kind===`failed-cold`?(0,J.jsxs)(`div`,{className:`startup-page-notice`,children:[(0,J.jsx)($,{tone:`err`,children:A.error instanceof Error?A.error.message:t(`startup.error`)}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>j(),children:t(`common.retry`)})]}):M?(0,J.jsxs)(J.Fragment,{children:[A.showError&&(0,J.jsx)($,{tone:`err`,children:t(`startup.error`)}),P&&(0,J.jsx)(`div`,{className:`notice notice-warn startup-page-notice`,role:`alert`,children:t(`startup.staleData`)}),(w||b)&&(0,J.jsx)(`div`,{className:`startup-runtime-notice-slot${w&&!b?` startup-runtime-notice-slot--pending`:``}`,"aria-hidden":w&&!b?!0:void 0,children:b&&(0,J.jsxs)(`div`,{className:`notice notice-warn startup-page-notice startup-runtime-notice`,role:`status`,children:[(0,J.jsx)(`p`,{className:`startup-runtime-notice__text`,children:b}),S&&(0,J.jsxs)(`div`,{className:`startup-runtime-notice__fix`,children:[(0,J.jsx)(`code`,{children:S}),(0,J.jsx)(`button`,{type:`button`,className:`btn btn-ghost btn-sm`,onClick:()=>void F(S),children:t(a===S?`startup.copied`:`startup.copy`)})]})]})}),(0,J.jsx)(xy,{failed:P,data:M}),(0,J.jsx)(Sy,{data:M,failed:P,loading:N,installBusy:h,installResult:v,onInstall:(e,t)=>{L(e,t)}}),M.platform===`win32`&&(0,J.jsx)(Cy,{tray:s,trayLoading:l,trayError:p,trayBusy:d,onTrayAction:e=>{I(e)}}),(0,J.jsx)(wy,{data:M,copied:a,onCopy:e=>{F(e)}})]}):null]})}var ky=3e5,Ay=6e5,jy=`https://github.com/lidge-jun/opencodex`;async function My(e,t){let n=await fetch(e,{signal:t});return n.ok?await n.json():null}function Ny({apiBase:e,onOpenUpdate:t}){let n=Q(),[r,i]=(0,_.useState)(!1),[a,o]=(0,_.useState)(null),s=G(`sidebar-star:${e}`,[e],t=>My(`${e}/api/github/star`,t),{pollMs:ky}),c=G(`sidebar-update-badge:${e}`,[e],t=>My(`${e}/api/update/badge`,t),{pollMs:Ay}),l=s.data?.state??null,u=a!==null&&a.basedOn===l?a.state:l??`not-starred`,d=s.data?.url??jy,f=u===`starred`,p=c.data,m=p?.updateAvailable===!0,h=p?.latestVersion??null,g=()=>window.open(d,`_blank`,`noopener,noreferrer`),v=async()=>{if(!(f||r)){if(u===`unauthenticated`){g();return}i(!0);try{let t=await fetch(`${e}/api/github/star`,{method:`POST`}),n=t.ok?await t.json():null;if(n?.ok===!0){o({state:`starred`,basedOn:l});return}n?.state&&o({state:n.state,basedOn:l}),g()}catch{g()}finally{i(!1),s.refresh()}}},y=n(f?`sidebar.starred`:u===`unauthenticated`?`sidebar.starUnauthenticated`:`sidebar.star`),b=m&&h?n(`sidebar.updateAvailable`,{version:h}):n(`sidebar.checkUpdate`);return(0,J.jsxs)(`div`,{className:`sidebar-github-row`,children:[(0,J.jsxs)(`a`,{className:`sidebar-link sidebar-github-link`,href:d,target:`_blank`,rel:`noreferrer`,children:[(0,J.jsx)(Ce,{}),` `,n(`common.github`)]}),(0,J.jsxs)(`div`,{className:`sidebar-github-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`sidebar-orb${f?` sidebar-orb--starred`:``}`,onClick:()=>{v()},disabled:r||f,"aria-label":y,"aria-pressed":f,title:y,children:(0,J.jsx)(Ie,{"aria-hidden":`true`,...f?{fill:`currentColor`}:{}})}),(0,J.jsxs)(`button`,{type:`button`,className:`sidebar-orb${m?` sidebar-orb--update`:``}`,onClick:t,"aria-label":b,title:b,children:[(0,J.jsx)(Z,{"aria-hidden":`true`}),m&&(0,J.jsx)(`span`,{className:`sidebar-orb-dot`,"aria-hidden":`true`})]})]})]})}var Py=`opencodex-admin-token-dialog`,Fy=`OpenCodex`;function Iy(e,t=it()){let n=Ze[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=Py,o.className=`modal-overlay`,o.setAttribute(`aria-labelledby`,`${Py}-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=`${Py}-title`,l.textContent=r,c.append(l);let u=document.createElement(`div`),d=document.createElement(`label`);d.className=`field-label`,d.htmlFor=`${Py}-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=Fy,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=`${Py}-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 Ly=!1,Ry=null,zy=null,By=!1,Vy=Iy,Hy=`/opencodex-session`,Uy=`/api/settings`,Wy=1e4,Gy=15e3;function Ky(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 qy=`opencodex-api-token`,Jy=null,Yy=null,Xy=null;function Zy(){return Jy}function Qy(e){Jy=e}function $y(){Jy=null,Yy=null,Xy=null}function eb(e){let t=document.querySelector(`meta[name="${e}"]`),n=t?.content.trim()||null;return t?.remove(),n}function tb(){rb(eb(`opencodex-session-token`),eb(`opencodex-session-csrf`),eb(`opencodex-session-origin`))}function nb(e){e!=null&&Zy()===e&&$y()}function rb(e,t,n){return!e?.startsWith(`ocx_session_`)||!t||n!==window.location.origin?!1:(Jy=e,Yy=t,Xy=n,!0)}function ib(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 ab(){if(!zy)return{kind:`failed`};let e=Ln(Wy);try{let t=await zy(Hy,{cache:`no-store`,signal:e.signal});if(!t.ok)return t.status>=400&&t.status<500?{kind:`unavailable`}:{kind:`failed`};let n=await t.text(),r=rb(ib(n,`opencodex-session-token`),ib(n,`opencodex-session-csrf`),ib(n,`opencodex-session-origin`)),i=Zy();return r&&i?{kind:`minted`,token:i}:{kind:`unavailable`}}catch{return{kind:`failed`}}finally{e.clear()}}async function ob(e){if(!zy)return`unavailable`;try{let[t,n]=cb(Uy,{cache:`no-store`},e),r=await zy(t,n);return r.status===401?`rejected`:r.ok?`accepted`:`unavailable`}catch{return`unavailable`}}function sb(){try{sessionStorage.removeItem(qy)}catch{}}function cb(e,t,n){let r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));if(r.set(`X-OpenCodex-API-Key`,n),Xy&&Yy&&n.startsWith(`ocx_session_`)){r.set(`X-OpenCodex-GUI-Origin`,Xy);let n=(t?.method??(e instanceof Request?e.method:`GET`)).toUpperCase();n!==`GET`&&n!==`HEAD`&&r.set(`X-OpenCodex-CSRF-Token`,Yy)}return e instanceof Request?[new Request(e,{headers:r}),t?{...t,headers:r}:void 0]:[e,{...t,headers:r}]}async function lb(e,t){if(By||t?.aborted)return null;if(!Ry){let t=(async()=>{if(By)return null;let t=Zy();if(t&&t!==e)return t;let n,r=await Promise.race([ab(),new Promise(e=>{n=setTimeout(()=>e({kind:`failed`}),Gy)})]).finally(()=>clearTimeout(n));if(r.kind===`minted`)return r.token;if(r.kind===`failed`)return null;let i=await Vy(ob);return i?(Qy(i),i):(By=!0,null)})().finally(()=>{Ry===t&&(Ry=null)});Ry=t}if(!t)return Ry;let n,r=new Promise(e=>{n=()=>e(null),t.addEventListener(`abort`,n,{once:!0})});return Promise.race([Ry,r]).finally(()=>{n&&t.removeEventListener(`abort`,n)})}function ub(){if(Ly)return;Ly=!0,sb(),tb();let e=window.fetch.bind(window);zy=e,window.fetch=async(t,n)=>{if(!Ky(t))return e(t,n);let r=n?.signal??(t instanceof Request?t.signal:void 0),i=Zy(),[a,o]=i?cb(t,n,i):[t,n],s=await e(a,o);if(s.status!==401)return s;let c=Zy();if(c&&c!==i){let[r,i]=cb(t,n,c),a=await e(r,i);if(a.status!==401)return a;nb(c)}else nb(i);let l=await lb(i,r??void 0);if(!l)return s;let[u,d]=cb(t,n,l),f=await e(u,d);return f.status===401&&nb(l),f}}var db=new Set([`dashboard`,`startup`,`providers`,`models`,`subagents`,`logs`,`usage`,`storage`,`codex-set`,`integrations`]);function fb(e){let t=dt(e??(typeof window<`u`?window.location.hash:``)).split(`/`)[0];return t===`debug`?`logs`:t===`codex-auth`?`codex-set`:t===`combos`||t===`routing`||t===`lab`?`models`:t===`api`||t===`claude`||t===`grok`?`integrations`:db.has(t)?t:`dashboard`}var pb=[`dashboard/providers`,`dashboard/models`],mb=[`models/combos`,`models/routing`,`models/compatibility`],hb=[`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`,`integrations/mcode`,`integrations/zcode`,`integrations/prime`];function gb(e,t){return e===t||t===`logs`&&e===`logs/debug`||t===`codex-set`&&e===`codex-set/prompt`||t===`models`&&mb.includes(e)||t===`dashboard`&&(e===`dashboard/update`||pb.includes(e))||t===`integrations`&&hb.includes(e)}function _b(e){let t=fb(e);return e===`debug`||e.startsWith(`debug/`)?{page:`logs`,replaceTo:`logs/debug`}:e===`codex-auth`||e.startsWith(`codex-auth/`)?{page:`codex-set`,replaceTo:`codex-set`}:e===`combos`||e.startsWith(`combos/`)?{page:`models`,replaceTo:`models/combos`}:e===`routing`||e.startsWith(`routing/`)?{page:`models`,replaceTo:`models/routing`}:e===`lab`||e.startsWith(`lab/`)?{page:`models`,replaceTo:`models/compatibility`}:e===`api`?{page:`integrations`,replaceTo:`integrations/keys`}:e===`claude`?{page:`integrations`,replaceTo:`integrations/claude`}:e===`grok`?{page:`integrations`,replaceTo:`integrations/grok`}:e===`providers/workspace`?{page:`providers`,replaceTo:`providers`}:gb(e,t)?{page:t,replaceTo:null}:{page:t,replaceTo:t}}var vb=[`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 yb(){try{for(let e of vb)localStorage.removeItem(e)}catch{}}function bb(){let[e,t]=(0,_.useState)(fb);(0,_.useEffect)(()=>{yb()},[]);let n=(0,_.useCallback)(e=>{let n=_b(e);n.replaceTo&&ft(n.replaceTo),t(n.page)},[]);return(0,_.useEffect)(()=>{let e=()=>{n(dt(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=_b(dt(window.location.hash));n.replaceTo&&ft(n.replaceTo),n.page!==e&&t(n.page)},[e]),{page:e,setPageState:t,navigateToPage:(e,n)=>{pt(n?`${e}/${n}`:e),t(e)}}}var xb=15e3;function Sb(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 Cb(e){return(e instanceof DOMException||e instanceof Error)&&e.name===`AbortError`}async function wb(e,t={}){let{fetchFn:n=fetch,timeoutMs:r=xb,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 Cb(e),{accepted:!0}}let o=await a.json().catch(()=>null);return!a.ok||o?.success===!1?{accepted:!1,message:Sb(o,a.status,i)}:{accepted:!0}}ub();var Tb={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-set":`nav.codexSet`,integrations:`nav.integrations`},Eb=``,Db=`ocx-theme`,Ob=[{id:`dashboard`,tkey:`nav.dashboard`,Icon:te},{id:`codex-set`,tkey:`nav.codexSet`,Icon:Ee},{id:`providers`,tkey:`nav.providers`,Icon:ne},{id:`models`,tkey:`nav.models`,Icon:re},{id:`subagents`,tkey:`nav.subagents`,Icon:ie},{id:`logs`,tkey:`nav.logs`,Icon:ae},{id:`usage`,tkey:`nav.usage`,Icon:se},{id:`storage`,tkey:`nav.storage`,Icon:ce},{id:`integrations`,tkey:`nav.integrations`,Icon:Ne}],kb={light:Ae,dark:je,system:Me},Ab={light:`theme.light`,dark:`theme.dark`,system:`theme.system`};function jb(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 Mb(){let e=localStorage.getItem(Db);return e===`light`||e===`dark`?e:`system`}function Nb(){let{page:e,navigateToPage:t}=bb(),[n,r]=(0,_.useState)(Cf);(0,_.useEffect)(()=>{let e=()=>r(Cf());return window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e),()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e)}},[]);let[i,a]=(0,_.useState)(Mb),{locale:o,setLocale:s}=ct(),c=Q(),[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(Db)):(e.setAttribute(`data-theme`,i),localStorage.setItem(Db,i))},[i]);let m=G(`app-healthz:${Eb}`,[],async e=>{let t=await fetch(`${Eb}/healthz`,{signal:e});return t.ok?jb(await t.json()):null},{pollMs:3e4}),h=()=>a(e=>e===`light`?`dark`:e===`dark`?`system`:`light`),g=kb[i],v=m.data??`2.37.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}=$c(Eb,{onSettled:()=>S(e=>e+1)}),T=async()=>{if(!confirm(c(`dash.stopConfirm`)))return;b(!0);let e=await wb(Eb,{formatFailure:e=>c(`dash.stopFailed`,{status:String(e)})});e.accepted||(b(!1),alert(e.message))},E=(0,J.jsxs)(`div`,{className:`brand`,children:[(0,J.jsx)(`span`,{className:`brand-logo`,role:`img`,"aria-label":c(`app.logoAria`)}),(0,J.jsx)(`span`,{className:`name`,children:`opencodex`}),(0,J.jsxs)(`span`,{className:`ver`,children:[`v`,v]})]});return(0,J.jsxs)(`div`,{className:`app`,children:[(0,J.jsxs)(`header`,{className:`mobile-topbar`,inert:l,children:[(0,J.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,J.jsx)(oe,{})}),E,(0,J.jsxs)(`div`,{className:`mobile-topbar-actions`,children:[(0,J.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,J.jsx)(we,{})}),(0,J.jsx)(`button`,{type:`button`,className:`sidebar-orb`,onClick:()=>{w()},disabled:C,"aria-label":c(`dash.codexRestart`),title:c(`dash.codexRestart`),children:(0,J.jsx)(fe,{})})]})]}),l&&(0,J.jsx)(`div`,{className:`drawer-scrim`,onClick:()=>u(!1),"aria-hidden":`true`}),(0,J.jsxs)(`aside`,{id:`app-sidebar`,className:`sidebar${l?` open`:``}`,ref:f,tabIndex:-1,children:[(0,J.jsxs)(`div`,{className:`drawer-head`,children:[E,(0,J.jsx)(`button`,{type:`button`,className:`menu-toggle drawer-close`,onClick:()=>u(!1),"aria-label":c(`nav.closeMenu`),title:c(`nav.closeMenu`),children:(0,J.jsx)(ue,{})})]}),(0,J.jsx)(`nav`,{children:Ob.map(n=>{let{id:r,tkey:i,Icon:a}=n,o=r===e;return(0,J.jsx)(`div`,{className:`nav-entry`,children:(0,J.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,J.jsx)(a,{}),` `,c(i)]})},r)})}),(0,J.jsxs)(`div`,{className:`sidebar-foot`,children:[(0,J.jsxs)(`div`,{className:`lang-toggle`,children:[(0,J.jsx)(Ne,{"aria-hidden":!0}),(0,J.jsx)(Dt,{value:o,options:et.map(e=>({value:e.code,label:Qe(e.code)})),onChange:e=>s(e),label:c(`lang.label`),placement:`right`,portal:!1,style:{flex:1,minWidth:0,width:`100%`}})]}),(0,J.jsxs)(`button`,{type:`button`,className:`theme-toggle`,onClick:h,"aria-label":`${c(`theme.label`)}: ${c(Ab[i])}`,title:`${c(`theme.label`)}: ${c(Ab[i])}`,children:[(0,J.jsx)(g,{}),` `,(0,J.jsx)(`span`,{className:`mode`,children:c(Ab[i])})]}),(0,J.jsxs)(`div`,{className:`sidebar-action-row`,children:[(0,J.jsx)(`span`,{className:`sidebar-action-label`,children:c(`dash.actions`)}),(0,J.jsxs)(`div`,{className:`sidebar-action-orbs`,children:[(0,J.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,J.jsx)(we,{})}),(0,J.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,J.jsx)(fe,{})})]})]}),(0,J.jsx)(Ny,{apiBase:Eb,onOpenUpdate:()=>{u(!1),t(`dashboard`,`update`)}})]})]}),(0,J.jsx)(`main`,{className:`main`,inert:l,children:(0,J.jsx)(`div`,{className:`main-inner${e===`models`&&n===`combos`?` main-inner--combos`:``}`,children:(0,J.jsxs)(ul,{pageName:c(Tb[e]),title:c(`errorBoundary.title`),message:c(`errorBoundary.message`),detailsLabel:c(`errorBoundary.details`),reloadLabel:c(`errorBoundary.reload`),children:[e===`dashboard`&&(0,J.jsx)(Kr,{apiBase:Eb}),e===`startup`&&(0,J.jsx)(Oy,{apiBase:Eb}),e===`providers`&&(0,J.jsx)(Bc,{apiBase:Eb}),e===`models`&&(0,J.jsx)(ip,{apiBase:Eb,restartEpoch:x},Eb),e===`subagents`&&(0,J.jsx)(gp,{apiBase:Eb},Eb),e===`logs`&&(0,J.jsx)(Um,{apiBase:Eb}),e===`usage`&&(0,J.jsx)(dh,{apiBase:Eb}),e===`storage`&&(0,J.jsx)(Vh,{apiBase:Eb}),e===`codex-set`&&(0,J.jsx)(wg,{apiBase:Eb}),e===`integrations`&&(0,J.jsx)(hy,{apiBase:Eb})]},e)})})]})}g.createRoot(document.getElementById(`root`)).render((0,J.jsx)(_.StrictMode,{children:(0,J.jsx)(lt,{children:(0,J.jsx)(Nb,{})})}));