diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 0c5a5d24ab5..7afa8a38843 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -787,3 +787,11 @@ El enfriamiento por combo es independiente del de cuenta y persiste con expiraci Los destinos RunTurn retienen razonamiento previo hasta un segundo: una finalización max_output_tokens sin salida dentro del plazo permite otro destino sin enfriar al sano. Al vencer o aparecer salida, se compromete y transmite lo retenido. También puede avanzar incomplete sin razón, adapter_eof, missing_terminal_event o upstream_stall_timeout antes de salida. `end_turn: false` o `incomplete_details.retryable` false conserva el destino. `pause_turn` Anthropic es pausa larga y sigue como `incomplete` con max_output_tokens, sin alternativa. Content_filter, razones semánticas explícitas, null explícito y límites tras salida son terminales. Si todos acaban así sin salida y sin exceso de contexto confirmado, se devuelve el último HTTP 200 incomplete con su uso, no 502. JSON nativo no streaming no se inspecciona. Los metadatos de tasa de Codex WebSocket no son salida; tras salida o límite de buffer nunca se reproduce en otro destino. Un rechazo estructurado de esfuerzo puede bajar una posición publicada cada vez en el mismo destino mientras quede presupuesto. Incluye `{"code":"invalid-argument","error":"Invalid reasoning effort."}` y las formas reconocidas de unsupported_value. Si ninguna sirve, solo formas de compatibilidad reconocidas avanzan sin enfriarlo; conserva el 400 si no quedan envíos. No convierte none ni generaliza a errores inválidos arbitrarios. Rechazos de política, cancelación o salida ya comprometida nunca se reproducen. Si un destino enfriado fija la recuperación más próxima, mensaje y Retry-After muestran el mismo plazo, por ejemplo `(retry in ~2m)`; Messages usa la misma espera. + +## Combos sugeridos + +Si los ajustes cambian antes de guardar una sugerencia, Combos actualiza las sugerencias y muestra un mensaje. Al guardar, se comprueban las exclusiones y el consentimiento de gasto vigentes. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. + +El proxy aplica estas reglas en cada guardado. El panel puede mostrar brevemente una acción que el proxy rechaza, por ejemplo justo después de cambiar los ajustes en otra pestaña o con la CLI. En ese caso, el proxy responde con HTTP 409 y el espacio de trabajo vuelve a cargar los ajustes guardados y los combos para que las tarjetas coincidan con lo que permite el proxy. + +En el espacio de trabajo de combos, **Generar** abre un borrador de conmutación por error para un modelo disponible en varios proveedores. **Añadir al combo** ofrece destinos que faltan en un combo existente. Las tarjetas descartadas quedan ocultas en este navegador. Usa **Excluir un proveedor…** para filtrar ambos tipos de sugerencias. El proxy guarda la selección como `comboSuggestionExcludedProviders` en `config.json`. Los miembros existentes se conservan. Todos los destinos sugeridos pueden generar cargos, incluso los canales de suscripción, como Codex con créditos comprados, Grok con Extra Usage y Kimi Code con Extra Usage. Para guardar un borrador, marca **Permitir destinos de pago**. Para añadir destinos, habilita primero los destinos de pago en el combo existente. El proxy guarda todos los destinos sugeridos con `metered: true`. El control de exclusión sigue disponible tras descartar todas las tarjetas. Al cambiar una exclusión, las acciones de sugerencias quedan deshabilitadas hasta que el panel vuelva a cargar los ajustes guardados, aunque se pierda la respuesta del guardado. Si no se pueden cargar los ajustes de sugerencias, selecciona **Reintentar**. Si los ajustes guardados cambian antes de que guardes una sugerencia, el espacio de trabajo actualiza las tarjetas según las exclusiones y el permiso de pago vigentes. Si **Añadir al combo** está deshabilitado, ejecuta `ocx combo update --allow-metered-targets on` y sustituye `` por el identificador del combo guardado. La siguiente actualización del combo habilita la acción si hay destinos aptos para añadir. diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index 0a2478fd9d9..ba6633dba9c 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -218,8 +218,11 @@ Las instantáneas de sesión incluyen `resumable`. Se vuelve cierto sólo despu | --- | --- | --- | | `GET /api/combos` | Lista de combos normalizados y sus ID de modelo público | El trabajo del catálogo puede devolver `catalog_busy` | | `PUT /api/combos` | Crea, sustituye o renombra un combo. | 400 si el identificador, destino, configuración o cambio de nombre son inválidos, o hay una colisión ordinaria; un 400 de validación también identifica el primer campo superior inválido en `field`, por ejemplo `targets` o `decisionProvider`. 409 si hay colisión con el espacio de nombres de una cuenta Codex. | +| `POST /api/combo-suggestions/save` | Guarda pares de proveedor y modelo sugeridos con `{ id, mode, targets }` y modo `"create"` o `"append"` | 400 solicitud inválida; 403 si falta una sesión de panel válida; 409 si el consentimiento, las exclusiones, la disponibilidad o el estado del combo impiden guardar. La creación requiere `allowMeteredTargets: true` en la solicitud y lo guarda en el combo. La ampliación rechaza ese campo y exige el consentimiento guardado en el combo. Todos los destinos sugeridos se guardan con `metered: true` porque incluso los canales de suscripción pueden cobrar créditos o uso adicional. Al añadir sugerencias, el servidor aplica el nivel de mayor coste entre la configuración activa y la guardada. Trata los destinos existentes marcados explícitamente como medidos como destinos de pago por uso y conserva el orden relativo de los destinos existentes. | | `DELETE /api/combos?id=...` | Eliminar un combo y borrar su estado de selección/enfriamiento | 400 id ausente; 404 combo desconocido | +Las tres operaciones de sugerencias (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions` y `POST /api/combo-suggestions/save`) requieren una sesión de panel iniciada mediante el acceso local, una identidad de Tailscale verificada o el emparejamiento. Las credenciales de administrador y las sesiones recordadas reciben un 403. + Consulte [Combos](/es/guides/combos/) para conocer las estrategias de destino, los tiempos de reutilización, los alias y los fallos de enrutamiento. diff --git a/docs-site/src/content/docs/fr/guides/combos.md b/docs-site/src/content/docs/fr/guides/combos.md index 43c8488cf42..12bfa5a240f 100644 --- a/docs-site/src/content/docs/fr/guides/combos.md +++ b/docs-site/src/content/docs/fr/guides/combos.md @@ -387,3 +387,7 @@ Exception aux erreurs 400 terminales : l'enveloppe opaque d'OpenRouter (`Provide ## Réservation d’une tentative de récupération Une tentative de récupération activée par `cooldownReprobe: { enabled: true }` appartient uniquement à la requête qui l’a réservée ; les autres requêtes restent soumises aux délais de refroidissement enregistrés. La réservation est conservée pendant l’attente et la sélection JEV. Une cible redevenue utilisable pendant l’attente peut être réessayée si son délai enregistré n’a pas changé. Un nouvel enregistrement annule la réservation de cette cible. Un succès ne supprime que le délai inchangé de la cible ayant répondu ; les cibles non essayées et les nouveaux échecs conservent leurs délais. La désactivation du fournisseur, les quotas, l’admissibilité de la requête et l’annulation restent vérifiés. Voir les [réglages et limites](/guides/combos/#retry-all-cooled-targets-opt-in). + +## Combos suggérés + +Dans l’espace Combos, générez un brouillon de basculement pour un modèle partagé ou ajoutez une cible manquante à un combo existant. Les cartes ignorées restent masquées dans ce navigateur. Excluez des fournisseurs des suggestions via `comboSuggestionExcludedProviders` dans `config.json`. Les membres existants sont conservés. Les cibles facturées à l’usage suivent les règles de consentement. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 9b7f49fa5ce..7a8ba582177 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1213,3 +1213,11 @@ waits and JEV selection. A target that becomes usable again during a wait can st be retried if its cooldown has not changed. A newer cooldown cancels that target's reservation. Success clears only the unchanged cooldown of the target that answered; untried targets and newer failures keep their cooldowns. + +## Suggested combos + +When settings change before a suggestion is saved, Combos refreshes the suggestions and displays a message. Saving checks the current exclusions and spend consent. + +The proxy enforces these rules on every save. The dashboard can briefly show an action that the proxy then refuses, for example right after settings change in another tab or through the CLI. The proxy answers with HTTP 409, and the workspace reloads the saved settings and combos so the cards match what the proxy allows. + +In the Combos workspace, **Generate** opens a failover draft for a model served by multiple providers. **Add to combo** offers missing targets for an existing combo. Dismissed cards stay hidden in this browser. Use **Exclude providers…** to filter both kinds of suggestions. The proxy stores your selection as `comboSuggestionExcludedProviders` in `config.json`. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. Every suggested target can incur paid usage, including subscription channels such as Codex with purchased credits, Grok with Extra Usage, and Kimi Code with Extra Usage. To save a draft, check **Allow paid targets**. To append, first enable paid targets in the existing combo. The proxy saves every suggested target as `metered: true`. The exclusion control stays available after dismissing all cards. Changing an exclusion disables suggestion actions until the dashboard reloads the saved settings, even if the save response is lost. If suggestion settings fail to load, select **Retry**. If saved settings change before you save a suggestion, the workspace refreshes the cards using the current exclusions and paid-target consent. If **Add to combo** is disabled, run `ocx combo update --allow-metered-targets on`, replacing `` with the saved combo ID. The next combo refresh makes the action available when there are eligible targets to add. diff --git a/docs-site/src/content/docs/ja/guides/combos.md b/docs-site/src/content/docs/ja/guides/combos.md index b86d67b61b4..4b683759838 100644 --- a/docs-site/src/content/docs/ja/guides/combos.md +++ b/docs-site/src/content/docs/ja/guides/combos.md @@ -285,3 +285,7 @@ ocx combo remove --yes ## クールダウン回復の予約 `cooldownReprobe: { enabled: true }` で有効にした回復試行は、予約したリクエストだけに属し、他のリクエストには保存済みのクールダウンが引き続き適用されます。予約はクールダウン待機と JEV 選択を経ても維持されます。待機中に再び利用可能になったターゲットは、クールダウンが変わっていなければ再試行できますが、新しいクールダウンの記録はそのターゲットの予約を無効にします。成功時は応答したターゲットの変更されていないクールダウンだけを解除し、未試行のターゲットや新しい失敗のクールダウンは残します。プロバイダーの無効化、クォータ、リクエストの適格性、キャンセルの確認は引き続き有効です。[設定と制限](/guides/combos/#retry-all-cooled-targets-opt-in)を参照してください。 + +## おすすめのコンボ + +コンボ画面では、複数のプロバイダーが提供するモデルのフェイルオーバー案を作成したり、既存コンボに候補を追加したりできます。閉じたカードはこのブラウザーで非表示になります。除外設定は `config.json` の `comboSuggestionExcludedProviders` に保存されます。既存のメンバーは保持され、従量課金の候補には同意の規則が適用されます。 diff --git a/docs-site/src/content/docs/ko/guides/combos.md b/docs-site/src/content/docs/ko/guides/combos.md index 53589443fda..95170207d6b 100644 --- a/docs-site/src/content/docs/ko/guides/combos.md +++ b/docs-site/src/content/docs/ko/guides/combos.md @@ -301,3 +301,7 @@ opencodex 인스턴스에 기록했는지 확인하세요. ## 쿨다운 복구 예약 `cooldownReprobe: { enabled: true }`로 활성화한 복구 시도는 이를 예약한 요청에만 속하며, 다른 요청에는 저장된 쿨다운이 계속 적용됩니다. 예약은 쿨다운 대기와 JEV 선택을 거쳐 유지됩니다. 대기 중 다시 사용 가능해진 대상은 기존 쿨다운이 바뀌지 않았다면 재시도할 수 있지만, 새 쿨다운 기록은 그 대상의 예약을 무효화합니다. 성공하면 응답한 대상의 변경되지 않은 쿨다운만 해제하며, 시도하지 않은 대상과 새로운 실패의 쿨다운은 유지합니다. 공급자 비활성화, 할당량, 요청 적격성 및 취소 검사는 계속 적용됩니다. [설정과 제한](/guides/combos/#retry-all-cooled-targets-opt-in)을 참고하세요. + +## 추천 콤보 + +콤보 화면에서 여러 공급자가 제공하는 모델의 장애 조치 초안을 만들거나 기존 콤보에 빠진 대상을 추가할 수 있습니다. 닫은 카드는 이 브라우저에서 숨겨집니다. 제외한 공급자는 `config.json`의 `comboSuggestionExcludedProviders`에 저장됩니다. 기존 구성원은 유지되며, 종량제 대상에는 사용 동의 규칙이 적용됩니다. diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 97941a8f94a..e2941c9fcf2 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -247,8 +247,11 @@ completes. | --- | --- | --- | | `GET /api/combos` | List normalized combos and their public model ids | Catalog work can return `catalog_busy` | | `PUT /api/combos` | Create, replace, or rename one combo | 400 invalid id, target, config, rename, or ordinary collision (a combo validation 400 also names the first invalid top-level field in `field`, for example `targets` or `decisionProvider`); 409 Codex-account namespace collision | +| `POST /api/combo-suggestions/save` | Save suggested provider/model pairs using `{ id, mode, targets }` with mode `"create"` or `"append"` | 400 invalid request; 403 without an eligible dashboard session; 409 when consent, exclusions, provider availability, or combo state prevents the save. Create requires `allowMeteredTargets: true` in the request and stores it on the combo. Append rejects that field and requires stored combo consent. All suggested targets are saved with `metered: true` because even subscription channels may bill paid credits or extra usage. When appending suggestions, the server uses the more costly tier from the active and saved configurations. It treats existing targets explicitly marked as metered as pay-per-use and preserves the relative order of existing targets. | | `DELETE /api/combos?id=...` | Delete one combo and clear its selection/cooldown state | 400 missing id; 404 unknown combo | +All three suggestion operations (`GET /api/combo-suggestions`, `PUT /api/combo-suggestions`, and `POST /api/combo-suggestions/save`) require a dashboard session issued through local bootstrap, verified Tailscale identity, or pairing. Admin credentials and remembered sessions receive a 403. + See [Combos](/guides/combos/) for target strategies, cooldowns, aliases, and routing failures. ### Codex prompt layers diff --git a/docs-site/src/content/docs/ru/guides/combos.md b/docs-site/src/content/docs/ru/guides/combos.md index a76f46e2bbc..b8dbc2afd4d 100644 --- a/docs-site/src/content/docs/ru/guides/combos.md +++ b/docs-site/src/content/docs/ru/guides/combos.md @@ -345,3 +345,7 @@ CLI и дашборд показывают точное сообщение ва ## Резервирование восстановления после cooldown Попытка восстановления, включённая через `cooldownReprobe: { enabled: true }`, принадлежит только зарезервировавшему её запросу; для других запросов сохранённые cooldown продолжают действовать. Резервирование сохраняется при ожидании cooldown и выборе JEV. Если цель снова становится доступной во время ожидания, её можно повторно попробовать, пока запись cooldown не изменилась. Новая запись отменяет резервирование этой цели. Успех снимает только неизменённый cooldown ответившей цели; для непроверенных целей и новых сбоев cooldown сохраняется. Проверки отключения провайдера, квоты, допустимости запроса и отмены остаются в силе. См. [настройки и ограничения](/guides/combos/#retry-all-cooled-targets-opt-in). + +## Предложения комбо + +В рабочей области комбо можно создать черновик для переключения между поставщиками общей модели или добавить недостающую цель в существующее комбо. Закрытые карточки остаются скрытыми в этом браузере. Список исключений сохраняется в `comboSuggestionExcludedProviders` в `config.json`. Состав существующих комбо сохраняется, а для целей с оплатой по факту действуют правила согласия. diff --git a/docs-site/src/content/docs/tr/guides/combos.md b/docs-site/src/content/docs/tr/guides/combos.md index 8890281219b..0d3db6efc2f 100644 --- a/docs-site/src/content/docs/tr/guides/combos.md +++ b/docs-site/src/content/docs/tr/guides/combos.md @@ -426,3 +426,7 @@ Sonlandırıcı 400 hatalarının dar bir istisnası vardır: OpenRouter'ın opa ## Soğuma kurtarma rezervasyonu `cooldownReprobe: { enabled: true }` ile etkinleştirilen kurtarma denemesi yalnızca onu ayıran isteğe aittir; diğer istekler kayıtlı soğuma sürelerine uymaya devam eder. Rezervasyon, soğuma beklemesi ve JEV seçimi boyunca korunur. Bekleme sırasında yeniden kullanılabilir olan hedef, soğuma kaydı değişmediyse tekrar denenebilir. Yeni bir soğuma kaydı o hedefin rezervasyonunu geçersiz kılar. Başarı yalnızca yanıt veren hedefin değişmemiş soğuma kaydını kaldırır; denenmeyen hedefler ve yeni hatalar soğuma kayıtlarını korur. Sağlayıcının devre dışı olması, kota, istek uygunluğu ve iptal kontrolleri geçerliliğini korur. [Ayarlar ve sınırlar](/guides/combos/#retry-all-cooled-targets-opt-in) bölümüne bakın. + +## Önerilen kombolar + +Kombolar çalışma alanında, birden çok sağlayıcının sunduğu model için yük devretme taslağı oluşturabilir veya mevcut komboya eksik hedef ekleyebilirsiniz. Kapatılan kartlar bu tarayıcıda gizli kalır. Hariç tutulan sağlayıcılar `config.json` dosyasındaki `comboSuggestionExcludedProviders` alanına kaydedilir. Mevcut üyeler korunur ve kullanıma göre ücretlendirilen hedeflere onay kuralları uygulanır. diff --git a/docs-site/src/content/docs/zh-cn/guides/combos.md b/docs-site/src/content/docs/zh-cn/guides/combos.md index 4b2316f031f..37ce5bd95ec 100644 --- a/docs-site/src/content/docs/zh-cn/guides/combos.md +++ b/docs-site/src/content/docs/zh-cn/guides/combos.md @@ -315,3 +315,7 @@ combo id 不存在。响应是 HTTP 404,类型为 `invalid_request_error`。 ## 冷却恢复预约 通过 `cooldownReprobe: { enabled: true }` 启用的恢复尝试只属于预约它的请求;其他请求仍受已保存的冷却限制。预约会在冷却等待和 JEV 选择期间保留。目标在等待期间重新可用时,只要其冷却记录没有变化,就仍可重试;新的冷却记录会使该目标的预约失效。成功后,只清除实际响应目标未改变的冷却记录;未尝试的目标和新的失败仍保留冷却。提供方禁用、配额、请求资格和取消检查仍然生效。请参阅[设置与限制](/guides/combos/#retry-all-cooled-targets-opt-in)。 + +## 推荐组合 + +在组合工作区,可为多个提供商共享的模型生成故障转移草稿,或向现有组合添加缺少的目标。关闭的卡片会在当前浏览器中隐藏。排除的提供商保存在 `config.json` 的 `comboSuggestionExcludedProviders` 中。现有成员会保留,按量计费的建议目标遵循授权规则。 diff --git a/docs-site/src/content/docs/zh-tw/guides/combos.md b/docs-site/src/content/docs/zh-tw/guides/combos.md index 8e38a59bf00..96b1eea7ffc 100644 --- a/docs-site/src/content/docs/zh-tw/guides/combos.md +++ b/docs-site/src/content/docs/zh-tw/guides/combos.md @@ -309,3 +309,7 @@ Combo id 未知。回應為 HTTP 404 並帶 type `invalid_request_error`。執 ## 冷卻復原預約 透過 `cooldownReprobe: { enabled: true }` 啟用的復原嘗試只屬於預約它的請求;其他請求仍受已儲存的冷卻限制。預約會在冷卻等待與 JEV 選擇期間保留。目標在等待期間重新可用時,只要其冷卻紀錄沒有變更,就仍可重試;新的冷卻紀錄會使該目標的預約失效。成功後,只清除實際回應目標未變更的冷卻紀錄;未嘗試的目標與新的失敗仍保留冷卻。供應商停用、配額、請求資格與取消檢查仍然生效。請參閱[設定與限制](/guides/combos/#retry-all-cooled-targets-opt-in)。 + +## 建議組合 + +在組合工作區,可以為多個供應商共用的模型產生容錯移轉草稿,或將缺少的目標加入現有組合。關閉的卡片會在目前的瀏覽器中隱藏。排除的供應商儲存在 `config.json` 的 `comboSuggestionExcludedProviders` 中。現有成員會保留,按量計費的建議目標遵循授權規則。 diff --git a/gui/src/combo-suggestions.ts b/gui/src/combo-suggestions.ts new file mode 100644 index 00000000000..26bfdabc5df --- /dev/null +++ b/gui/src/combo-suggestions.ts @@ -0,0 +1,202 @@ +/** + * Combo suggestions for the Combos overview: models that two or more providers serve under the + * same name, offered as a ready-made failover combo, and existing combos that a provider serving + * their model is missing from. Pure: no React, no fetch, no storage. + * + * The idea of merging one model across providers by a normalized name follows Magpie's found + * groups (`internal/catalog/samemodel.go`, MIT, Copyright (c) 2026 yetone). No code is taken + * from it. Unlike Magpie, a snapshot date stays part of the name (two snapshots can differ in + * capability) and a trailing reasoning-effort suffix is dropped. + */ +import { COMBO_ID_RE, emptyDraft, newComboTarget, type ComboItem } from "./combo-workspace-data"; +import { channelTier, EFFORT_SUFFIX, normalizeModelName, TIER_RANK, type ChannelTier, type SuggestionProvider } from "../../src/combos/suggestion-channel"; +export { channelTier, normalizeModelName, type ChannelTier, type SuggestionProvider }; + + +export interface SuggestionModel { + provider: string; + id: string; +} + +export interface SuggestedMember { + provider: string; + model: string; + tier: ChannelTier; + /** Lowest remaining percent across the provider's reported windows for this model. */ + remainingPercent?: number; +} + +export type ComboSuggestion = + | { + kind: "create"; + /** Dismissal key, stable across reloads. */ + key: string; + /** Normalized model name the members share. */ + model: string; + /** Free combo id for the draft. */ + comboId: string; + members: SuggestedMember[]; + /** At least one member is listed in the model catalog rather than hidden from it. */ + listed: boolean; + } + | { + kind: "extend"; + key: string; + model: string; + comboId: string; + /** Providers serving the combo's model that the combo does not route to yet. */ + members: SuggestedMember[]; + }; + +/** The id spelled as the provider writes it, minus prefix and effort suffix: the combo id candidate. */ +function spelling(id: string): string { + const bare = id.trim().slice(id.trim().lastIndexOf("/") + 1).toLowerCase(); + return bare.replace(EFFORT_SUFFIX, ""); +} + +/** Tier first; within a tier more quota left first, unknown quota after; then catalog order. */ +export function orderMembers(members: readonly SuggestedMember[]): SuggestedMember[] { + return members + .map((member, index) => ({ member, index })) + .sort((a, b) => { + const tier = TIER_RANK[a.member.tier] - TIER_RANK[b.member.tier]; + if (tier !== 0) return tier; + const left = a.member.remainingPercent ?? -1; + const right = b.member.remainingPercent ?? -1; + return right - left || a.index - b.index; + }) + .map(({ member }) => member); +} + +/** The combo is about one model: its id names it, or every member serves it. */ +function comboModel(combo: ComboItem): string | undefined { + const byId = normalizeModelName(combo.id); + const names = new Set(combo.targets.map((target) => normalizeModelName(target.model))); + if (names.size === 1) return [...names][0]; + return names.has(byId) ? byId : undefined; +} + +/** `base`, else `base-2`, `base-3`, … that no combo id or alias already takes (case-insensitive). */ +export function freeComboId(base: string, combos: readonly ComboItem[]): string { + const taken = new Set(combos.flatMap((combo) => [combo.id, combo.alias ?? ""]).map((id) => id.toLowerCase())); + base = base.slice(0, 64); + if (!COMBO_ID_RE.test(base)) base = "suggested-combo"; + if (!taken.has(base.toLowerCase())) return base; + for (let n = 2; ; n++) { + const suffix = `-${n}`; + const candidate = base.slice(0, 64 - suffix.length) + suffix; + if (!taken.has(candidate.toLowerCase())) return candidate; + } +} + +export interface SuggestionInput { + combos: readonly ComboItem[]; + /** Catalog rows, combos excluded, hidden rows included: hiding a model only hides it from pickers. */ + models: readonly SuggestionModel[]; + /** `provider/model` keys hidden from the model catalog (`disabledModels`). */ + hiddenModels?: ReadonlySet; + providers: readonly SuggestionProvider[]; + remainingPercent?: (provider: string, model: string) => number | undefined; + dismissed?: ReadonlySet; + /** Providers the operator left out of suggestions: they join no suggested combo. */ + excludedProviders?: ReadonlySet; +} + +export function suggestionKey(kind: ComboSuggestion["kind"], model: string, comboId?: string): string { + return kind === "create" ? `create:${model}` : `extend:${comboId}:${model}`; +} + +export function buildComboSuggestions(input: SuggestionInput): ComboSuggestion[] { + const providers = new Map(input.providers.map((provider) => [provider.name, provider])); + /** model name → provider → that provider's id for it (the shortest spelling wins). */ + const byModel = new Map>(); + for (const row of input.models) { + const provider = providers.get(row.provider); + if (!provider || provider.disabled || provider.hiddenFromPicker || input.excludedProviders?.has(row.provider)) continue; + const name = normalizeModelName(row.id); + if (!name) continue; + const served = byModel.get(name) ?? new Map(); + const current = served.get(row.provider); + if (current === undefined || row.id.length < current.length) served.set(row.provider, row.id); + byModel.set(name, served); + } + + const member = (provider: string, model: string): SuggestedMember => { + const remaining = input.remainingPercent?.(provider, model); + return { + provider, + model, + tier: channelTier(providers.get(provider)!, model), + ...(remaining !== undefined ? { remainingPercent: remaining } : {}), + }; + }; + + const covering = new Map(); + for (const combo of input.combos) { + const name = comboModel(combo); + if (name !== undefined && !covering.has(name)) covering.set(name, combo); + } + + const creates: Array = []; + const extends_: Array = []; + for (const [name, served] of byModel) { + const combo = covering.get(name); + const eligible = [...served].map(([p, m]) => member(p, m)); + // An existing combo takes any eligible provider it is missing, even the only one left once + // its own members are excluded; a new combo needs two providers to fail over between. + if (combo) { + const routed = new Set(combo.targets.filter((target) => normalizeModelName(target.model) === name).map((target) => target.provider)); + const missing = eligible.filter(({ provider }) => !routed.has(provider)); + const key = suggestionKey("extend", name, combo.id); + if (missing.length === 0 || input.dismissed?.has(key)) continue; + extends_.push({ kind: "extend", key, model: name, comboId: combo.id, members: orderMembers(missing) }); + continue; + } + if (eligible.length < 2) continue; + const key = suggestionKey("create", name); + if (input.dismissed?.has(key)) continue; + const spellings = eligible.map(({ model }) => spelling(model)); + const counts = new Map(); + for (const value of spellings) counts.set(value, (counts.get(value) ?? 0) + 1); + const preferred = spellings.reduce((best, value) => (counts.get(value)! > counts.get(best)! ? value : best)); + creates.push({ + kind: "create", + key, + model: name, + comboId: freeComboId(COMBO_ID_RE.test(preferred) ? preferred : name, input.combos), + members: orderMembers(eligible), + listed: eligible.some(({ provider, model }) => !input.hiddenModels?.has(`${provider}/${model}`)), + }); + } + creates.sort((a, b) => Number(b.listed) - Number(a.listed) || b.members.length - a.members.length || a.model.localeCompare(b.model)); + extends_.sort((a, b) => a.comboId.localeCompare(b.comboId)); + // A model nobody lists in the catalog is usually an older version: after the hints for live combos. + return [...creates.filter((s) => s.listed), ...extends_, ...creates.filter((s) => !s.listed)]; +} + +/** The failover combo a create suggestion saves, members in the order given. */ +export function suggestionDraft(comboId: string, members: readonly SuggestedMember[]): ComboItem { + return { + ...emptyDraft(comboId), + allowMeteredTargets: true, + targets: members.map(({ provider, model }) => newComboTarget({ provider, model, metered: true })), + }; +} + +/** + * The combo with each suggested member placed before the first of its own members in a lower + * tier (a subscription goes ahead of pay-per-use keys), else last. Its own members keep their order. + */ +export function extendedCombo( + combo: ComboItem, + members: readonly SuggestedMember[], + tierOf: (provider: string, model: string) => ChannelTier, +): ComboItem { + if (combo.allowMeteredTargets !== true) return combo; + const targets = [...combo.targets]; + for (const entry of members) { + const at = targets.findIndex((target) => TIER_RANK[tierOf(target.provider, target.model)] > TIER_RANK[entry.tier]); + targets.splice(at < 0 ? targets.length : at, 0, newComboTarget({ provider: entry.provider, model: entry.model, metered: true })); + } + return { ...combo, targets }; +} diff --git a/gui/src/combo-workspace-data.ts b/gui/src/combo-workspace-data.ts index 5654f2bd81d..95bf17567f5 100644 --- a/gui/src/combo-workspace-data.ts +++ b/gui/src/combo-workspace-data.ts @@ -106,6 +106,7 @@ export function intersectComboEfforts( } export interface ComboTarget { + metered?: boolean; provider: string; model: string; weight?: number; @@ -127,6 +128,7 @@ let comboTargetKeySeq = 0; export function newComboTarget(partial: Partial = {}): ComboTarget { return { + ...(partial.metered === true ? { metered: true } : {}), provider: partial.provider ?? "", model: partial.model ?? "", ...(partial.weight !== undefined ? { weight: partial.weight } : {}), @@ -174,6 +176,7 @@ export interface ComboItem { decisionTimeoutMs?: number | null; /** `jev` only: undefined preserves an omitted setting; null explicitly turns the pin off. */ sessionPin?: JevSessionPinConfig | null; + allowMeteredTargets?: boolean; targets: ComboTarget[]; } @@ -295,6 +298,7 @@ export function parseComboList(payload: unknown): ComboItem[] { targets.push(newComboTarget({ provider, model, + metered: tr.metered === true, ...(weight !== undefined ? { weight } : {}), ...(reasoningEfforts !== undefined ? { reasoningEfforts } : {}), ...(typeof tr.modelProfile === "string" ? { modelProfile: tr.modelProfile } : {}), @@ -311,6 +315,7 @@ export function parseComboList(payload: unknown): ComboItem[] { : comboPublicModelId(id, normalizeAlias(r.alias)), alias: normalizeAlias(r.alias), nativeAlias: r.nativeAlias === true, + ...(r.allowMeteredTargets === true ? { allowMeteredTargets: true } : {}), displayName: normalizeAlias(r.displayName), strategy: normalizeStrategy(r.strategy), stickyLimit: normalizeStickyLimit(r.stickyLimit), diff --git a/gui/src/components/ComboWorkspace.tsx b/gui/src/components/ComboWorkspace.tsx index 32ac369178b..a774a4c63be 100644 --- a/gui/src/components/ComboWorkspace.tsx +++ b/gui/src/components/ComboWorkspace.tsx @@ -37,6 +37,7 @@ export default function ComboWorkspace({ addDecisionProvider, onCloseAdd, onCreated, + renderSuggestions, }: ComboWorkspaceProps) { const t = useT(); const providerMap = useMemo( @@ -130,6 +131,8 @@ export default function ComboWorkspace({ }; return ( + <> + {renderSuggestions?.(detailDirty ? activeId : null)}