diff --git a/AGENTS.md b/AGENTS.md index 9b56dfb..e85f4e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,7 @@ - `src/workspace.ts` — artifact workspace: per-main-session `/.switchman//-/` folders (SESSION.md / dispatches.jsonl / media/; config `workspace.*`). - `src/provider-config.ts`, `src/types.ts` — provider/model metadata, routing config, option types. - `src/lang-config.ts` — project language preference (settings.json + AGENTS.md marker, ask directive, [LANG] line, question capture). +- `src/setup-gate.ts` — setup completion predicate + gate copy (all 6 task pools + capability rank must be configured; task dispatch denied until then); wired in index.ts (task deny, [SETUP] directive, banner segment), guided wizard in tui.tsx. - `scripts/` — codegen (`gen-shells`, `gen-capability-default`, `gen-version`), build helpers, mode switcher. - `test/` — bun test suites; treat as the behavioral contract (update together with behavior changes). diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a932bc..f953dbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes describe user-visible behavior; implementation details remain in the technical specification and commit history. +## [1.2.0] - 2026-09-19 + +### Added + +- **Setup hard gate + guided wizard (`/switchman-setup` / `/switchman-setup-chat`)** — unconfigured task pools no longer fall back to "all models": task dispatch is denied in main sessions until every one of the six task pools (`economy`/`mechanical`/`main`/`hard`/`vision`/`review`) has at least one selected model **and** the capability ranking has at least one entry. The guided wizard covers the whole matrix in one pass: **TUI (`/switchman-setup`)** — a resumable intro (Start jumps to the first unfinished step), one multi-select dialog per pool in lane order (Enter toggles, capability tier per row, select-all/clear-all/back; the per-pool confirm persists immediately, minimum one model), a sequential strongest-first ranking pick over exactly the union of the selected models (minimum one), and a done screen with the per-pool summary, ranking order, and any providers still flagged restartRequired; **conversational fallback (`/switchman-setup-chat`)** — the same flow in chat (state overview → per-pool multi-select questions → ranking → CLI persist → verify), for when the TUI plugin surface is unavailable. While setup is incomplete, main sessions carry a `[SETUP]` directive each turn and every task denial relays the remedy; dispatched shells and internal sessions are exempt and there is no waiver flag. The gate rides on the language gate — until the project language preference is configured, the language ask stays the single blocking voice. The wizard writes the same hot-reloaded `pool-config.json`/`capability-rank.json` as the manual overrides, so the gate opens the moment the last file is saved — no restart (a restart only registers brand-new providers). New module `src/setup-gate.ts`; sidebar notice and `[LIMITS]` banner segment report the missing state. +- **Render-time i18n (11 locales)** — sidebar chrome, pool/rank/handover dialogs, status-log notices, and config-CLI copy now localize at render time via a new i18n core (`src/i18n.ts`); locale chain: project language → global `ui.lang` → terminal env (`LC_ALL`/`LANG`) → English, with an English/key fallback that never throws. The six-lane sidebar labels localize display-only (runtime `LANE_ORDER`, pool-config keys, and protocol stay English) with CJK-aware column padding; model-facing protocol copy stays byte-stable English so capture anchors (`[ROUTES]`/`[WATERMARK]`/`[LANG]` lines) never drift. + +### Changed + +- **Real-fail isolation window shortened 30 min → 5 min** — a shell whose probe passes but whose actual delegation fails (in-memory, per-combo isolation) now auto-unlocks after 5 minutes instead of 30: these states are usually transient vendor blips, and a 30-minute head-of-chain lockout starved lanes far longer than the failure warranted. Rate-limit self-heal keeps its dedicated 10-min TTL; endpoint-class config errors keep the 6h TTL; restart still clears everything. +- **Model rank scoped to the task-pool universe with pool-lane priority ordering** — `/modelRank` now ranks exactly the pool-selected universe: rankable rows are scoped to it, an empty universe gates set/add with guidance (the TUI offers a jump to `/poolConfig`), and non-pool entries (with their anchored scores) are auto-pruned on every rank write. The manual rank becomes the absolute ordering key on pool lanes — it beats tier grouping, effort partitions, and family preference — and pool members are exempt from capability-level floors. The `[LIMITS]` banner surfaces the rankable universe. +- **Economy lane effort preference raised to medium→high→low→minimal** — a medium-less flash model (e.g. glm-5.3-flash) now takes its high face as the economy chain head instead of being pinned to low; `off` stays the lane-tail fallback partition. +- **Self-read budget defragmented (tolerance band, headroom grants, continuation merge)** — reads within R* + deny-retry overhead (~400 tok) now pass outright (denying them costs more than the overshoot saved); per-call grants are sized from the remaining turn headroom (max 2× R*) so demonstrated-range reads land one-shot; bounded continuations of the last granted window merge into one completion shot even past the spent turn budget. Protocol §5, config comments, and dispatch-gate tests are synced to the new semantics. + ## [1.1.0] - 2026-09-15 ### Added diff --git a/README.de.md b/README.de.md new file mode 100644 index 0000000..fb840dd --- /dev/null +++ b/README.de.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | **Deutsch** | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) + +> **Du nutzt auch zcode?** Wirf einen Blick auf [zcode-switchman](https://github.com/mrzturn/zcode-switchman) — ein Schwesterprojekt desselben Autors, das dieselbe Orchestrierung für zcode-Nutzer bereitstellt. + +> Kontext auf dem Tacho. Aufgaben verteilen sich von selbst. + +![opencode-switchman — the context water level drives the switchman and throws the route](docs/assets/hero.svg) + +> Interaktive Demo-Präsentation: [opencode-switchman in Aktion](https://mrzturn.github.io/opencode-switchman/) + +Ein Orchestrierungs-Plugin für [OpenCode](https://opencode.ai). Es tut zwei Dinge — und tut sie richtig gut: + +**1. Kontext-Pegelstandskontrolle.** Der Kontext deiner Session wird in jeder Runde gemessen. Lesevorgänge laufen gegen ein Budget pro Runde, sodass das Modell nicht im Stillen das ganze Repo schlürfen kann; Soft-/Hard-/Force-Wassermarken lösen erst Hinweise aus, dann Aufräumen, dann eine automatische Übergabe mit Backup und Komprimierung; jeder abgeschickte Subagent trägt sein eigenes hartes Limit. Der Kontext hört auf, sich wie ein Schneeball aufzublähen — eine Session kann den ganzen Tag laufen, ohne dass Tokens von der eigenen History aufgefressen werden. + +**2. Automatisierte Entscheidungs-Delegation.** Dein primäres Modell wird zum Dispatcher: Es profiliert jede Aufgabe und delegiert sie an Subagent-Shells über sechs kognitive Spuren (economy / mechanical / main / hard / vision / review). Das Plugin erzwingt deterministische Gates, gewichtetes Modell-Scoring und selbstheilende Fehlerisolierung und protokolliert jede Routing-Entscheidung. + +Darüber hinaus: + +- **Mehrere Modelle oder Abos? Dieses Plugin wurde genau dafür gebaut.** GitHub Copilot, GLM Coding Plan, DeepSeek — oder jeder andere opencode-Provider — werden als ein einziger Pool orchestriert: kontingentbewusste Reihenfolge, Vermeidung von Spitzenfenstern, erzwungenes Review über Modellfamilien hinweg. +- **Nur ein Modell? Trotzdem lohnt es sich.** Die Kontextkontrolle und das smarte Dispatching allein halten ein einzelnes Modell unbegrenzt nutzbar — egal wie lange die Session läuft, der Kontext bläht sich nie auf. + +## Installation + +Ein Befehl — deckt die Erstinstallation und spätere Updates ab. Danach opencode neu starten. + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +oder + +```bash +npx -y opencode-switchman@latest +``` + +oder + +```bash +bunx opencode-switchman@latest +``` + +Beide Wege schreiben den `plugin`-Eintrag in deiner opencode-Konfiguration auf die exakte neueste Version um und räumen veraltete Caches weg. Manuelle npm-Installation, Build aus dem Quellcode und der Hinweis „Warum exakte Versionen": [Installationsdetails](./docs/reference.md#installation). + +Lieber alles delegieren? Lass deine KI die Installation erledigen — füge diesen Prompt in die KI deiner Wahl ein: + +<details open> +<summary><strong>KI-gestützter Installations-Prompt</strong></summary> + +```text +Bitte installiere und konfiguriere das opencode-switchman-Plugin für mein opencode, strikt nach seinen offiziellen Anweisungen. + +Offizielle Quellen (maßgeblich, nicht aus dem Gedächtnis raten): +- GitHub-Repo: https://github.com/mrzturn/opencode-switchman +- npm-Paket: https://www.npmjs.com/package/opencode-switchman +Lies den Abschnitt „Installation" in der README des Repos und befolge ihn exakt. + +Schritte: +1. Installiere die auf npm veröffentlichte neueste Version: führe `npx -y opencode-switchman@latest` aus (oder `bunx opencode-switchman@latest`) — es schreibt den `plugin`-Eintrag in meiner opencode-Konfiguration auf die exakte neueste Version um (es funktioniert auch in der `opencode.json` auf Projektebene, falls ich diese verwende). +2. Vervollständige die funktionale Konfiguration: alle Plugin-Einstellungen liegen in der eigenständigen `opencode-switchman.jsonc` in meinem opencode-Konfigurationsverzeichnis, die beim ersten Start automatisch mit Standardwerten und Inline-Kommentaren erzeugt wird; prüfe sie gegen meine Provider (z. B. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) und passe sie bei Bedarf an. +3. Verifiziere, dass opencode das Plugin lädt, startet und ausführt: führe `/switchman-doctor` in opencode aus für einen lokalen Diagnosebericht ohne Zugangsdaten und behebe jeden gemeldeten Fehler; starte opencode dann neu und bestätige, dass das Plugin tatsächlich geladen wurde — das Log sollte `[opencode-switchman] injected N model shells (agents)` enthalten und der System-Prompt meines primären Modells sollte den aktuellen `[ROUTES]/[WATERMARK]/[LIMITS]`-Bannerblock tragen. + +Erkläre keinen Erfolg, bevor alle drei Schritte bestanden sind; berichte, was du geändert hast, und zeige die Verifikationsnachweise. +``` + +</details> + +**Voraussetzungen**: [opencode](https://opencode.ai), CLI/TUI empfohlen (Dialoge, Seitenleiste und Banner sind dort am umfangreichsten; die Desktop-App teilt dieselbe Konfiguration und denselben Zustand). Jeder Provider funktioniert; Copilot / GLM / DeepSeek erhalten zusätzlich kontingentbewusstes Routing. Zugangsdaten werden ausschließlich lesend aus opencodes eigener Auth gelesen — das Plugin speichert niemals Secrets. + +## Schnellstart + +Sechs Schritte. Komplette Anleitung mit Screenshots: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). + +1. **Provider verbinden** — `/connect` in der TUI: Copilot-OAuth, DeepSeek-API-Key; GLM Coding Plan landet als benutzerdefinierter Provider `zhipuai-coding-plan` in der `opencode.json`. +2. **Modelle auswählen, die an der Orchestrierung teilnehmen** — `/models`, dann `ctrl+f` zum Favorisieren (Desktop-App: Schalter unter „Modelle verwalten"). +3. **`/switchman-setup`** *(einmalig erforderlich)* — der geführte Assistent deckt die gesamte Matrix in einem Durchgang ab: wähle für jeden der sechs Task-Pools mindestens ein Modell aus (economy / mechanical / main / hard / vision / review) und ordne die gewählten Modelle dann vom stärksten zum schwächsten. Keine TUI? `/switchman-setup-chat` führt denselben geführten Ablauf im Chat aus. Bis zum Abschluss des Setups ist Task-Dispatching hart blockiert — unkonfigurierte Pools fallen nicht mehr auf „alle Modelle" zurück. Gespeicherte Konfiguration wird per Hot-Reload übernommen; ein Neustart ist nur nötig, um völlig neue Provider zu registrieren. +4. **Feintuning** *(optional)* — **`/modelRank`** stimmt das Fähigkeits-Ranking von Hand ab und **`/poolConfig`** kuratiert die Kandidatenlisten pro Pool in TUI-Dialogen (`-chat`-Varianten im Chat); manuelle Einträge überschreiben überall die anfänglichen Standardwerte. +5. **Kontext-Befehle** + - **`/handover`** — sichert die Session und komprimiert sie selbst. Nutze sie, wenn die `[WATERMARK:SESSION]`-Zeile groß wird oder die Aufgabe einen guten Stopp-Punkt erreicht, statt auf die automatische Übergabe zu warten. + - **`/ctx-pause`** — schaltet die Lese-Limits dieser Session und die Auto-Übergabe aus. Nutze sie, wenn du viele große Dateien auf einmal lesen musst und Tokens auszugeben dir nichts ausmacht; die Messung läuft weiter. + - **`/ctx-resume`** — schaltet die Limits wieder ein. Nutze sie, sobald das intensive Lesen erledigt ist; ein Neustart von opencode hat denselben Effekt. +6. **Neu starten und prüfen** — kontrolliere das `[ROUTES]`/`[LIMITS]`-Banner und das `switchman`-Panel in der Seitenleiste; führe `/switchman-doctor` aus, falls etwas ungewöhnlich wirkt. Danach nutze opencode einfach wie gewohnt. + +## Was du bekommst + +**Kernfunktionen** + +- **Kontext-Pegelstandskontrolle** — Live-Messung der Session (`[WATERMARK:SESSION]`), Soft-/Hard-/Force-Schwellenwerte, ein Lese-Budget pro Runde, das übermäßige Lesevorgänge automatisch begrenzt, ein hartes Limit mit Zusammenfassung und Abbruch für jeden Subagenten sowie eine automatische Übergabe (vollständiges Backup-Fork + Komprimierung) auf Force-Level. +- **Automatisierte Entscheidungs-Delegation** — ein mitgeliefertes Dispatcher-Protokoll macht dein primäres Modell zum Dispatcher; sechs kognitive Spuren leiten Arbeit an das richtige Modell mit dem richtigen Aufwand; sechs deterministische Gates prüfen jede Delegation; Ausfälle lösen Circuit-Breaker und Isolierung aus, und das System heilt sich selbst. + +**Extras** + +- **Multi-Abo-Orchestrierung** — kontingentbewusstes Routing über Copilot / GLM / DeepSeek hinweg (jeder Provider nimmt teil), Ausweichen bei Spitzenfenstern, abrechnungsbewusstes Scoring, erzwungenes Review über Modellfamilien hinweg. +- **Manuelle Steuerung** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **Sichtbarkeit** — Live-Banner mit vier Zeilen in jedem System-Prompt, TUI-Seitenleisten-Panel, tmux-Pane-Spiegelung, ein Artefakt-Arbeitsbereich pro Session und ein Audit-Log jeder Routing-Entscheidung. + +Vollständige Optionstabelle, Architektur und Interna: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). + +## Dokumentation + +- Schnellstart (illustriert): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- Vollständiges Handbuch (Konfiguration, Befehle, Architektur): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- Technische Spezifikation (Verträge / Algorithmen / Praxistest-Notizen): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- Versionshinweise: [CHANGELOG.md](./CHANGELOG.md) + +## Roadmap + +Kurzfristig: Kontingent-Unterstützung für weitere Provider — mehr Abo-Pläne und Pay-as-you-go-Pools über Copilot / GLM / DeepSeek hinaus. Falls dein Provider noch nicht abgedeckt ist, [öffne ein Issue](https://github.com/mrzturn/opencode-switchman/issues): Die reale Nutzung entscheidet, was als Nächstes gebaut wird. Vorschläge und Fehlerberichte sind gleichermaßen willkommen. + +## Unterstütze den Autor + +Dieses Plugin ist Open Source und kostenlos nutzbar — und das bleibt auch so. Am Leben zu halten ist es trotzdem nicht gratis: Die Pflege und das Testen der Adapter-Kompatibilität über Provider hinweg bedeuten, mehrere Abos zu halten und sie einzeln durchzudebuggen — jede Runde kostet echtes Geld. + +Wenn das Plugin dir wirklich geholfen hat und dein Budget es erlaubt, spendiere mir einen Kaffee. Danke — von Herzen. + +👇 + +<details> +<summary>☕ Hier klicken 【Dem Autor einen Kaffee ausgeben】</summary> + +| Alipay | WeChat Pay | Mit WeChat scannen und ihm ein Like geben | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="Alipay QR code" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="WeChat Pay QR code" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="WeChat scan-to-like QR code" /> | + +</details> + +## Lizenz + +[MIT](./LICENSE) diff --git a/README.es.md b/README.es.md new file mode 100644 index 0000000..73b1dec --- /dev/null +++ b/README.es.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | **Español** | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) + +> **¿También usas zcode?** Echa un vistazo a [zcode-switchman](https://github.com/mrzturn/zcode-switchman) — un proyecto hermano de código abierto del mismo autor que lleva la misma orquestación a los usuarios de zcode. + +> El contexto, bajo medición. Las tareas se despachan solas. + +![opencode-switchman — the context water level drives the switchman and throws the route](docs/assets/hero.svg) + +> Demo interactiva: [opencode-switchman en acción](https://mrzturn.github.io/opencode-switchman/) + +Un plugin de orquestación para [OpenCode](https://opencode.ai). Hace dos cosas, y las hace bien: + +**1. Control de nivel de agua del contexto.** El contexto de tu sesión se mide en cada turno. Las lecturas se rigen por un presupuesto por turno, así que el modelo no puede beberse el repositorio entero en silencio; las marcas de agua soft / hard / force disparan avisos, luego el cierre, y después un handover automático con backup y compactación; cada subagente despachado lleva su propio tope duro. El contexto deja de hacer bola de nieve: una sesión puede funcionar todo el día sin que su historial se devore los tokens. + +**2. Despacho automatizado de decisiones.** Tu modelo principal se convierte en despachador: perfila cada tarea y la delega a shells de subagentes en seis carriles cognitivos (economy / mechanical / main / hard / vision / review). El plugin aplica compuertas deterministas, puntuación ponderada de modelos y aislamiento de fallos con autorreparación, y registra cada decisión de enrutamiento. + +Además: + +- **¿Varios modelos o varias suscripciones? Este plugin se hizo para ti.** GitHub Copilot, GLM Coding Plan, DeepSeek — o cualquier proveedor de opencode — se orquestan como un solo pool: orden consciente de cuota, evitación de ventanas pico y revisión cruzada entre familias obligatoria. +- **¿Un solo modelo? Sigue valiendo la pena.** El control de contexto y el despacho inteligente, por sí solos, mantienen un modelo utilizable indefinidamente — no importa cuánto corra la sesión, el contexto nunca se desborda. + +## Instalación + +Un solo comando: cubre la primera instalación y las actualizaciones posteriores. Reinicia opencode después. + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +o + +```bash +npx -y opencode-switchman@latest +``` + +o + +```bash +bunx opencode-switchman@latest +``` + +Cualquiera de las dos vías reescribe la entrada `plugin` de tu configuración de opencode a la última versión exacta y poda las cachés obsoletas. Instalación manual con npm, compilación desde el código fuente y la nota sobre "por qué versiones exactas": [Detalles de instalación](./docs/reference.md#installation). + +¿Prefieres no complicarte? Deja que tu IA haga la instalación — pega este prompt en la IA que estés usando: + +<details open> +<summary><strong>Prompt de instalación asistida por IA</strong></summary> + +```text +Por favor, instala y configura el plugin opencode-switchman en mi opencode, siguiendo estrictamente sus instrucciones oficiales. + +Fuentes oficiales (autoritativas, no las deduzcas de memoria): +- Repositorio de GitHub: https://github.com/mrzturn/opencode-switchman +- Paquete npm: https://www.npmjs.com/package/opencode-switchman +Lee la sección "Installation" del README del repositorio y síguela al pie de la letra. + +Pasos: +1. Instala la última versión publicada en npm: ejecuta `npx -y opencode-switchman@latest` (o `bunx opencode-switchman@latest`) — reescribe la entrada `plugin` de mi configuración de opencode a la última versión exacta (también funciona en el `opencode.json` a nivel de proyecto, si es lo que uso). +2. Completa la configuración funcional: todos los ajustes del plugin viven en el archivo independiente `opencode-switchman.jsonc` dentro de mi directorio de configuración de opencode, autogenerado con valores por defecto y comentarios en línea en el primer arranque; revísalo contra mis proveedores (p. ej. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) y ajústalo según sea necesario. +3. Verifica que opencode cargue, arranque y ejecute el plugin: ejecuta `/switchman-doctor` dentro de opencode para obtener un informe de diagnóstico local sin credenciales y corrige cada error que reporte; luego reinicia opencode y confirma que el plugin realmente se cargó — el log debe contener `[opencode-switchman] injected N model shells (agents)` y el system prompt de mi modelo principal debe llevar el bloque de banner vivo `[ROUTES]/[WATERMARK]/[LIMITS]`. + +No declares éxito hasta que los tres pasos pasen; informa de lo que cambiaste y muestra la evidencia de la verificación. +``` + +</details> + +**Requisitos previos**: [opencode](https://opencode.ai), se recomienda CLI/TUI (los diálogos, la barra lateral y los banners lucen mejor ahí; la app de escritorio comparte la misma configuración y el mismo estado). Sirve cualquier proveedor; Copilot / GLM / DeepSeek además obtienen enrutamiento consciente de cuota. Las credenciales se leen en modo solo lectura desde la autenticación propia de opencode — el plugin nunca almacena secretos. + +## Inicio rápido + +Seis pasos. Guía completa con capturas: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). + +1. **Conecta proveedores** — `/connect` en la TUI: OAuth de Copilot, API key de DeepSeek; GLM Coding Plan va en `opencode.json` como proveedor personalizado `zhipuai-coding-plan`. +2. **Elige los modelos que entran en la orquestación** — `/models` y luego `ctrl+f` para marcar favoritos (app de escritorio: interruptores de "Manage models"). +3. **`/switchman-setup`** *(necesario una sola vez)* — el asistente guiado cubre toda la matriz de una pasada: selección múltiple de al menos un modelo para cada uno de los seis pools de tareas (economy / mechanical / main / hard / vision / review) y, después, ordena los modelos elegidos del más fuerte al más débil. ¿Sin TUI? `/switchman-setup-chat` ejecuta el mismo flujo guiado en el chat. Hasta que la configuración se complete, el despacho de tareas queda bloqueado en firme — los pools sin configurar ya no usan por defecto "todos los modelos". La configuración guardada se recarga en caliente; reiniciar solo hace falta para registrar proveedores totalmente nuevos. +4. **Ajuste fino** *(opcional)* — **`/modelRank`** afina a mano el ranking de capacidades y **`/poolConfig`** curta las listas de candidatos por pool en diálogos de la TUI (variantes `-chat` en el chat); las entradas manuales sobrescriben los valores iniciales por defecto en todas partes. +5. **Comandos de contexto** + - **`/handover`** — respalda la sesión y compacta tú mismo. Úsalo cuando la línea `[WATERMARK:SESSION]` crece demasiado o la tarea llega a un buen punto de pausa, en lugar de esperar el handover automático. + - **`/ctx-pause`** — apaga los límites de lectura y el auto-handover de esta sesión. Úsalo cuando necesites leer muchos archivos grandes de golpe y no te importe gastar tokens; la medición sigue corriendo. + - **`/ctx-resume`** — vuelve a encender los límites. Úsalo en cuanto termine la lectura pesada; reiniciar opencode tiene el mismo efecto. +6. **Reinicia y verifica** — revisa el banner `[ROUTES]`/`[LIMITS]` y el panel `switchman` de la barra lateral; ejecuta `/switchman-doctor` si algo se ve raro. Luego usa opencode con normalidad. + +## Qué obtienes + +**Núcleo** + +- **Control de nivel de agua del contexto** — medición en vivo de la sesión (`[WATERMARK:SESSION]`), umbrales soft/hard/force, un presupuesto de lectura por turno que acota automáticamente las lecturas demasiado ávidas, un tope duro con resumen-y-terminación para cada subagente y un handover automático (fork con backup completo + compactación) en el nivel force. +- **Despacho automatizado de decisiones** — un protocolo de despacho incluido convierte tu modelo principal en despachador; seis carriles cognitivos llevan el trabajo al modelo correcto con el esfuerzo adecuado; seis compuertas deterministas revisan cada despacho; los fallos disparan breakers y aislamiento, y el sistema se repara solo. + +**Extras** + +- **Orquestación multi-suscripción** — enrutamiento consciente de cuota entre Copilot / GLM / DeepSeek (cualquier proveedor participa), cesión en ventanas pico, puntuación consciente de facturación y revisión cruzada entre familias obligatoria. +- **Anulaciones manuales** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **Visibilidad** — banner vivo de cuatro líneas en cada system prompt, panel en la barra lateral de la TUI, espejo en paneles de tmux, workspace de artefactos por sesión y un log de auditoría de cada decisión de enrutamiento. + +Tabla completa de opciones, arquitectura e internals: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). + +## Documentación + +- Inicio rápido (ilustrado): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- Manual completo (configuración, comandos, arquitectura): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- Especificación técnica (contratos / algoritmos / notas de pruebas de campo): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- Notas de versión: [CHANGELOG.md](./CHANGELOG.md) + +## Hoja de ruta + +A corto plazo: soporte de cuota para más proveedores — más planes de suscripción y pools de pago por uso más allá de Copilot / GLM / DeepSeek. Si tu proveedor aún no está cubierto, [abre un issue](https://github.com/mrzturn/opencode-switchman/issues): el uso real decide qué se construye después. Sugerencias y reportes de bugs son igual de bienvenidos. + +## Apoya al autor + +Este plugin es de código abierto y de uso libre, y seguirá siéndolo. Mantenerlo con vida, sin embargo, no es gratis: dar soporte y probar la compatibilidad de adaptadores entre proveedores implica mantener varias suscripciones y depurarlas una por una — cada ronda cuesta dinero real. + +Si el plugin te ha ayudado de verdad y tu presupuesto lo permite, invítame a un café. Gracias — de corazón. + +👇 + +<details> +<summary>☕ Haz clic aquí 【Invita un café al autor】</summary> + +| Alipay | WeChat Pay | Escanea con WeChat para darle un like | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="Alipay QR code" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="WeChat Pay QR code" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="WeChat scan-to-like QR code" /> | + +</details> + +## Licencia + +[MIT](./LICENSE) diff --git a/README.fr.md b/README.fr.md new file mode 100644 index 0000000..911cc24 --- /dev/null +++ b/README.fr.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | **Français** | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) + +> **Vous utilisez aussi zcode ?** Découvrez [zcode-switchman](https://github.com/mrzturn/zcode-switchman) — un projet open source frère du même auteur, qui apporte la même orchestration aux utilisateurs de zcode. + +> Le contexte au compteur. Les tâches se dispatchent toutes seules. + +![opencode-switchman — the context water level drives the switchman and throws the route](docs/assets/hero.svg) + +> Diaporama de démonstration interactive : [opencode-switchman en action](https://mrzturn.github.io/opencode-switchman/) + +Un plugin d'orchestration pour [OpenCode](https://opencode.ai). Il fait deux choses, et les fait bien : + +**1. Contrôle du niveau d'eau du contexte.** Le contexte de votre session est mesuré à chaque tour. Les lectures sont soumises à un budget par tour, si bien que le modèle ne peut pas discrètement avaler tout le dépôt ; les watermarks soft / hard / force déclenchent d'abord des conseils, puis une clôture, puis un handover automatique (sauvegarde + compactage) ; chaque sous-agent dispatché embarque son propre plafond strict. Le contexte ne fait plus boule de neige — une session peut tourner toute la journée sans que ses tokens soient dévorés par son propre historique. + +**2. Dispatch décisionnel automatisé.** Votre modèle principal devient un dispatcher : il profile chaque tâche et la délègue à des shells de sous-agents répartis sur six couloirs cognitifs (economy / mechanical / main / hard / vision / review). Le plugin impose des gates déterministes, un score pondéré des modèles et une isolation des pannes auto-réparatrice, et journalise chaque décision de routage. + +Et par-dessus le marché : + +- **Plusieurs modèles ou abonnements ? Ce plugin a été conçu pour vous.** GitHub Copilot, GLM Coding Plan, DeepSeek — ou n'importe quel fournisseur opencode — sont orchestrés comme un seul pool : ordonnancement conscient des quotas, évitement des fenêtres de pointe, review forcée inter-familles. +- **Un seul modèle ? Ça vaut quand même le coup.** Le contrôle du contexte et le dispatch intelligent suffisent à garder un modèle unique utilisable indéfiniment — aussi longue que soit la session, le contexte ne gonfle jamais. + +## Installation + +Une seule commande — gère la première installation comme les mises à jour ultérieures. Redémarrez opencode ensuite. + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +ou + +```bash +npx -y opencode-switchman@latest +``` + +ou + +```bash +bunx opencode-switchman@latest +``` + +Les deux chemins réécrivent l'entrée `plugin` de votre configuration opencode vers la dernière version exacte et purgent les caches obsolètes. Installation npm manuelle, build depuis les sources et la note « pourquoi des versions exactes » : [Détails d'installation](./docs/reference.md#installation). + +Vous préférez ne rien faire ? Laissez votre IA faire l'installation — collez ce prompt dans l'IA que vous utilisez : + +<details open> +<summary><strong>Prompt d'installation assistée par IA</strong></summary> + +```text +Veuillez installer et configurer le plugin opencode-switchman pour mon opencode, en suivant strictement ses instructions officielles. + +Sources officielles (faire foi, ne pas deviner de mémoire) : +- Dépôt GitHub : https://github.com/mrzturn/opencode-switchman +- Paquet npm : https://www.npmjs.com/package/opencode-switchman +Lisez la section « Installation » du README du dépôt et suivez-la à la lettre. + +Étapes : +1. Installez la dernière version publiée sur npm : exécutez `npx -y opencode-switchman@latest` (ou `bunx opencode-switchman@latest`) — cela réécrit l'entrée `plugin` de ma configuration opencode vers la dernière version exacte (cela fonctionne aussi dans le `opencode.json` au niveau du projet si c'est ce que j'utilise). +2. Terminez la configuration fonctionnelle : tous les réglages du plugin vivent dans le fichier autonome `opencode-switchman.jsonc` de mon répertoire de configuration opencode, généré automatiquement avec des valeurs par défaut et des commentaires en ligne au premier démarrage ; vérifiez-le par rapport à mes fournisseurs (par ex. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) et ajustez si besoin. +3. Vérifiez que tout est correct pour qu'opencode se charge, démarre et exécute le plugin : lancez `/switchman-doctor` dans opencode pour obtenir un rapport de diagnostic local sans identifiants et corrigez chaque erreur signalée ; puis redémarrez opencode et confirmez que le plugin est réellement chargé — le journal doit contenir `[opencode-switchman] injected N model shells (agents)` et le prompt système de mon modèle principal doit porter le bloc de bannière `[ROUTES]/[WATERMARK]/[LIMITS]` à jour. + +Ne déclarez pas la réussite tant que les trois étapes ne sont pas passées ; rapportez ce que vous avez modifié et montrez les preuves de vérification. +``` + +</details> + +**Prérequis** : [opencode](https://opencode.ai), CLI/TUI recommandée (dialogues, panneau latéral et bannières y sont les plus riches ; l'application de bureau partage la même configuration et le même état). N'importe quel fournisseur fonctionne ; Copilot / GLM / DeepSeek bénéficient en plus du routage conscient des quotas. Les identifiants sont lus en lecture seule depuis l'auth d'opencode — le plugin ne stocke jamais de secrets. + +## Démarrage rapide + +Six étapes. Guide complet illustré : **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). + +1. **Connectez les fournisseurs** — `/connect` dans la TUI : OAuth Copilot, clé API DeepSeek ; le GLM Coding Plan se configure dans `opencode.json` comme fournisseur personnalisé `zhipuai-coding-plan`. +2. **Choisissez les modèles qui rejoignent l'orchestration** — `/models` puis `ctrl+f` pour mettre en favori (application de bureau : interrupteurs « Manage models »). +3. **`/switchman-setup`** *(obligatoire une fois)* — l'assistant guidé couvre toute la matrice en une passe : multi-sélection d'au moins un modèle pour chacun des six pools de tâches (economy / mechanical / main / hard / vision / review), puis classement des modèles sélectionnés du plus fort au plus faible. Pas de TUI ? `/switchman-setup-chat` déroule le même parcours guidé en chat. Jusqu'à la fin de la configuration, le dispatch de tâches est carrément bloqué — les pools non configurés ne basculent plus par défaut sur « tous les modèles ». La configuration enregistrée se recharge à chaud ; un redémarrage n'est nécessaire que pour enregistrer des fournisseurs tout neufs. +4. **Réglage fin** *(optionnel)* — **`/modelRank`** ajuste à la main le classement de capacités et **`/poolConfig`** cuisine les listes de candidats par pool dans des dialogues TUI (variantes `-chat` en chat) ; les entrées manuelles priment partout sur les valeurs par défaut initiales. +5. **Commandes de contexte** + - **`/handover`** — sauvegardez la session et compactez-la vous-même. À utiliser quand la ligne `[WATERMARK:SESSION]` grossit ou que la tâche atteint un bon point d'arrêt, au lieu d'attendre le handover automatique. + - **`/ctx-pause`** — coupez les limites de lecture et le handover automatique de cette session. À utiliser quand vous devez lire d'un coup beaucoup de gros fichiers et que dépenser les tokens ne vous fait pas peur ; la mesure continue de tourner. + - **`/ctx-resume`** — remettez les limites en route. À faire dès que les lourdes lectures sont terminées ; redémarrer opencode produit le même effet. +6. **Redémarrez et vérifiez** — contrôlez la bannière `[ROUTES]`/`[LIMITS]` et le panneau `switchman` de la barre latérale ; lancez `/switchman-doctor` si quelque chose cloche. Ensuite, utilisez opencode normalement. + +## Ce que vous y gagnez + +**L'essentiel** + +- **Contrôle du niveau d'eau du contexte** — mesure en direct de la session (`[WATERMARK:SESSION]`), seuils soft/hard/force, budget de lecture par tour qui borne automatiquement les lectures trop gourmandes, plafond strict avec résumé-puis-arrêt pour chaque sous-agent, et handover automatique (fork de sauvegarde complet + compactage) au niveau force. +- **Dispatch décisionnel automatisé** — un protocole de dispatcher embarqué transforme votre modèle principal en dispatcher ; six couloirs cognitifs aiguillent le travail vers le bon modèle au bon niveau d'effort ; six gates déterministes contrôlent chaque dispatch ; les échecs déclenchent des disjoncteurs et une isolation, et le système se répare tout seul. + +**En supplément** + +- **Orchestration multi-abonnements** — routage conscient des quotas sur Copilot / GLM / DeepSeek (tout fournisseur peut participer), cédure aux fenêtres de pointe, score sensible à la facturation, review inter-familles imposée. +- **Overrides manuels** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **Visibilité** — bannière live de quatre lignes dans chaque prompt système, panneau latéral TUI, miroir tmux, espace de travail d'artefacts par session et journal d'audit de chaque décision de routage. + +Table complète des options, architecture et fonctionnement interne : [docs/reference.md](./docs/reference.md) (中文 : [docs/reference.zh.md](./docs/reference.zh.md)). + +## Documentation + +- Quick start (illustré) : [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- Manuel complet (config, commandes, architecture) : [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- Spécification technique (contrats / algorithmes / notes de terrain) : [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- Notes de version : [CHANGELOG.md](./CHANGELOG.md) + +## Feuille de route + +À court terme : le support des quotas pour davantage de fournisseurs — davantage de plans d'abonnement et de pools à l'usage au-delà de Copilot / GLM / DeepSeek. Si votre fournisseur n'est pas encore couvert, [ouvrez une issue](https://github.com/mrzturn/opencode-switchman/issues) : l'usage réel décide de ce qui sera construit ensuite. Suggestions et rapports de bugs sont tout aussi bienvenus. + +## Soutenir l'auteur + +Ce plugin est open source et gratuit, et il le restera. Le maintenir en vie ne l'est pas, pourtant : soutenir et tester la compatibilité des adaptateurs chez les fournisseurs suppose de détenir plusieurs abonnements et de les déboguer un par un — chaque cycle coûte de l'argent réel. + +Si le plugin vous a vraiment aidé et que votre budget le permet, offrez-moi un café. Merci — sincèrement. + +👇 + +<details> +<summary>☕ Cliquez ici 【Offrir un café à l'auteur】</summary> + +| Alipay | WeChat Pay | Scannez avec WeChat pour lui témoigner votre soutien | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="QR code Alipay" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="QR code WeChat Pay" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="QR code scan-to-like WeChat" /> | + +</details> + +## Licence + +[MIT](./LICENSE) diff --git a/README.it.md b/README.it.md new file mode 100644 index 0000000..505799f --- /dev/null +++ b/README.it.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | **Italiano** | [Português](./README.pt.md) | [Русский](./README.ru.md) + +> **Usi anche zcode?** Dai un'occhiata a [zcode-switchman](https://github.com/mrzturn/zcode-switchman) — un progetto open source gemello, dello stesso autore, che porta la stessa orchestrazione agli utenti di zcode. + +> Il contesto ha un contatore. I task si dispacciano da soli. + +![opencode-switchman — il livello dell'acqua del contesto guida lo switchman e traccia la rotta](docs/assets/hero.svg) + +> Demo interattiva: [opencode-switchman in azione](https://mrzturn.github.io/opencode-switchman/) + +Un plugin di orchestrazione per [OpenCode](https://opencode.ai). Fa due cose, e le fa bene: + +**1. Controllo del livello del contesto.** Il contesto della tua sessione viene misurato a ogni turno. Le letture girano su un budget per turno, così il modello non può divorarsi l'intero repo in silenzio; le soglie soft / hard / force attivano prima un consiglio, poi il wrap-up, infine un handover automatico con backup e compattazione; ogni subagent dispacciato porta con sé il proprio hard cap. Il contesto smette di valicare — una sessione può girare tutto il giorno senza che i token vengano divorati dalla propria storia. + +**2. Dispatch automatico delle decisioni.** Il tuo modello primario diventa un dispatcher: profila ogni task e lo delega a shell subagent su sei corsie cognitive (economy / mechanical / main / hard / vision / review). Il plugin impone gate deterministici, punteggi pesati per modello e isolamento auto-riparante dei guasti, e registra ogni decisione di routing. + +E in più: + +- **Più modelli o abbonamenti? Questo plugin è fatto per te.** GitHub Copilot, GLM Coding Plan, DeepSeek — o qualsiasi provider opencode — vengono orchestrati come un unico pool: ordinamento consapevole delle quote, evitamento delle finestre di picco, review cross-family forzata. +- **Un solo modello? Vale comunque la pena.** Il controllo del contesto e il dispatch intelligente da soli mantengono un singolo modello usabile all'infinito — per quanto lunga sia la sessione, il contesto non esplode mai. + +## Installazione + +Un solo comando — copre prima installazione e aggiornamenti successivi. Riavvia opencode dopo. + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +oppure + +```bash +npx -y opencode-switchman@latest +``` + +oppure + +```bash +bunx opencode-switchman@latest +``` + +Entrambi i percorsi riscrivono la voce `plugin` nella tua configurazione opencode sulla versione esatta più recente e ripuliscono le cache stantie. Installazione npm manuale, build dai sorgenti e la nota sul «perché versioni esatte»: [Dettagli di installazione](./docs/reference.md#installation). + +Preferisci non toccare nulla? Lascia fare alla tua IA — incolla questo prompt nell'IA che stai usando: + +<details open> +<summary><strong>Prompt di installazione assistita dall'IA</strong></summary> + +```text +Installa e configura il plugin opencode-switchman per il mio opencode, seguendo rigorosamente le istruzioni ufficiali. + +Fonti ufficiali (autoritative, non indovinare a memoria): +- Repo GitHub: https://github.com/mrzturn/opencode-switchman +- Pacchetto npm: https://www.npmjs.com/package/opencode-switchman +Leggi la sezione "Installazione" del README del repo e seguila esattamente. + +Passaggi: +1. Installa l'ultima versione pubblicata su npm: esegui `npx -y opencode-switchman@latest` (o `bunx opencode-switchman@latest`) — riscrive la voce `plugin` nella mia configurazione opencode sulla versione esatta più recente (funziona anche nell'`opencode.json` di progetto, se è quello che uso). +2. Completa la configurazione funzionale: tutte le impostazioni del plugin vivono nel file autonomo `opencode-switchman.jsonc` nella directory di configurazione di opencode, generato automaticamente con default e commenti inline al primo avvio; controllalo rispetto ai miei provider (es. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) e adattalo se serve. +3. Verifica che opencode carichi, avvii ed esegua il plugin: esegui `/switchman-doctor` dentro opencode per un rapporto diagnostico locale senza credenziali e correggi ogni errore riportato; poi riavvia opencode e conferma che il plugin sia effettivamente caricato — il log deve contenere `[opencode-switchman] injected N model shells (agents)` e il system prompt del mio modello primario deve portare il blocco banner live `[ROUTES]/[WATERMARK]/[LIMITS]`. + +Non dichiarare successo finché tutti e tre i passaggi non passano; riporta cosa hai modificato e mostra le evidenze di verifica. +``` + +</details> + +**Prerequisiti**: [opencode](https://opencode.ai), consigliata la CLI/TUI (finestre di dialogo, sidebar e banner sono lì al massimo; l'app desktop condivide stessa configurazione e stato). Qualsiasi provider funziona; Copilot / GLM / DeepSeek ottengono in più il routing consapevole delle quote. Le credenziali sono lette in sola lettura dall'autenticazione di opencode — il plugin non archivia mai segreti. + +## Inizio rapido + +Sei passi. Guida completa con screenshot: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). + +1. **Connetti i provider** — `/connect` nella TUI: OAuth per Copilot, API key per DeepSeek; GLM Coding Plan va in `opencode.json` come provider personalizzato `zhipuai-coding-plan`. +2. **Scegli i modelli che entrano nell'orchestrazione** — `/models` poi `ctrl+f` per aggiungere ai preferiti (app desktop: interruttori in "Gestisci modelli"). +3. **`/switchman-setup`** *(obbligatorio una volta)* — la procedura guidata copre l'intera matrice in un colpo solo: multi-selezione di almeno un modello per ciascuno dei sei task pool (economy / mechanical / main / hard / vision / review), poi ordina i modelli selezionati dal più forte al più debole. Niente TUI? `/switchman-setup-chat` esegue lo stesso flusso guidato in chat. Fino al completamento della configurazione, il dispatch dei task è bloccato — i pool non configurati non ricadono più su «tutti i modelli». La configurazione salvata si ricarica a caldo; serve un riavvio solo per registrare provider del tutto nuovi. +4. **Messa a punto** *(opzionale)* — **`/modelRank`** regola a mano la classifica di capacità e **`/poolConfig`** cura le liste candidate per pool nelle finestre TUI (varianti `-chat` in chat); le voci manuali sovrascrivono i default iniziali ovunque. +5. **Comandi di contesto** + - **`/handover`** — fai tu il backup della sessione e la compattazione. Usalo quando la riga `[WATERMARK:SESSION]` cresce o il task raggiunge un buon punto di arresto, invece di aspettare l'handover automatico. + - **`/ctx-pause`** — disattiva i limiti di lettura e l'handover automatico di questa sessione. Usalo quando devi leggere molti file grandi in una volta e non ti dispiace spendere token; la misurazione continua. + - **`/ctx-resume`** — riattiva i limiti. Usalo appena finita la lettura pesante; riavviare opencode ha lo stesso effetto. +6. **Riavvia e verifica** — controlla il banner `[ROUTES]`/`[LIMITS]` e il pannello `switchman` nella sidebar; esegui `/switchman-doctor` se qualcosa non torna. Poi usa opencode normalmente. + +## Cosa ottieni + +**Nucleo** + +- **Controllo del livello del contesto** — misurazione live della sessione (`[WATERMARK:SESSION]`), soglie soft/hard/force, un budget di lettura per turno che limita da solo le letture troppo avide, un hard cap con riepilogo-e-terminazione per ogni subagent, e un handover automatico (fork di backup completo + compattazione) al livello force. +- **Dispatch automatico delle decisioni** — un protocollo dispatcher incluso trasforma il tuo modello primario in un dispatcher; sei corsie cognitive instradano il lavoro al modello giusto con lo sforzo giusto; sei gate deterministici controllano ogni dispatch; i guasti azionano breaker e isolamento, e il sistema si ripara da sé. + +**Extra** + +- **Orchestrazione multi-abbonamento** — routing consapevole delle quote tra Copilot / GLM / DeepSeek (qualsiasi provider partecipa), cedenza nelle finestre di picco, punteggio consapevole della fatturazione, review cross-family imposta. +- **Override manuali** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **Visibilità** — banner live di quattro righe in ogni system prompt, pannello sidebar TUI, mirroring dei riquadri tmux, workspace di artefatti per sessione, e un log di audit di ogni decisione di routing. + +Tabella completa delle opzioni, architettura e interni: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). + +## Documentazione + +- Inizio rapido (illustrato): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- Manuale completo (configurazione, comandi, architettura): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- Specifica tecnica (contratti / algoritmi / note sul campo): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- Note di rilascio: [CHANGELOG.md](./CHANGELOG.md) + +## Roadmap + +Brevi termine: supporto quote per più provider — più piani in abbonamento e pool pay-as-you-go oltre Copilot / GLM / DeepSeek. Se il tuo provider non è ancora coperto, [apri una issue](https://github.com/mrzturn/opencode-switchman/issues): l'uso reale decide cosa viene costruito dopo. Suggerimenti e bug report sono ugualmente benvenuti. + +## Sostieni l'autore + +Questo plugin è open source e gratuito, e lo resterà. Tenerlo in vita però non è gratis: supportare e testare la compatibilità degli adattatori tra provider significa mantenere più abbonamenti e fare debug uno per uno — ogni giro costa denaro vero. + +Se il plugin ti è stato davvero d'aiuto e il tuo budget lo permette, offrimi un caffè. Grazie — sinceramente. + +👇 + +<details> +<summary>☕ Clicca qui 【Offri un caffè all'autore】</summary> + +| Alipay | WeChat Pay | Scansiona con WeChat e lascia un like | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="Codice QR Alipay" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="Codice QR WeChat Pay" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="Codice QR Wechat scan-to-like" /> | + +</details> + +## Licenza + +[MIT](./LICENSE) diff --git a/README.ja.md b/README.ja.md new file mode 100644 index 0000000..6ebee21 --- /dev/null +++ b/README.ja.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | **日本語** | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) + +> **zcode も使っているなら**、同じ作者による姉妹オープンソースプロジェクト [zcode-switchman](https://github.com/mrzturn/zcode-switchman) をチェック — 同じオーケストレーションを zcode ユーザーに届けている。 + +> コンテキストはメーター管理。タスクは自らディスパッチされる。 + +![opencode-switchman — the context water level drives the switchman and throws the route](docs/assets/hero.svg) + +> インタラクティブなデモスライド: [opencode-switchman in action](https://mrzturn.github.io/opencode-switchman/) + +[OpenCode](https://opencode.ai) 向けオーケストレーションプラグイン。やることは 2 つ、どちらも確実に仕上げる: + +**1. コンテキスト水位制御。** セッションのコンテキストを毎ターン計測。読み込みはターンごとの予算内で走るため、モデルがリポジトリ全体を黙って飲み込むことはない。soft / hard / force の各ウォーターマークが、まず助言、次に締め、そして自動のバックアップ&コンパクト化ハンドオーバーを発火させる。ディスパッチされた各サブエージェントも固有のハード上限を担う。コンテキストの雪だるま化はここで止まる — セッションは丸一日回り続けても、トークンが自らの履歴に食い潰されることはない。 + +**2. 自動ディシジョンディスパッチ。** プライマリモデルはディスパッチャーに変わる: 各タスクをプロファイリングし、6 つの認知レーン (economy / mechanical / main / hard / vision / review) にわたるサブエージェントシェルへ委譲する。プラグインは決定論的ゲート、重み付きモデルスコアリング、自己修復型の障害分離を強制し、すべてのルーティング判断を記録する。 + +さらに: + +- **モデルもサブスクリプションも複数? このプラグインはまさにそのために作られた。** GitHub Copilot、GLM Coding Plan、DeepSeek — あるいは任意の opencode プロバイダー — が 1 つのプールとしてオーケストレーションされる: クォータを考慮した順序付け、ピーク時間帯の回避、強制クロスファミリーレビュー。 +- **モデルが 1 つだけ? それでも導入する価値はある。** コンテキスト制御とスマートディスパッチだけでも、単一モデルを無期限に使い続けられる — セッションがどれだけ長引いても、コンテキストが肥大化することはない。 + +## インストール + +コマンドは 1 つ — 初回インストールも以後の更新もこれで完結。実行後は opencode を再起動する。 + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +または + +```bash +npx -y opencode-switchman@latest +``` + +または + +```bash +bunx opencode-switchman@latest +``` + +どちらの方法でも、opencode 設定の `plugin` エントリが正確な最新バージョンに書き換わり、古いキャッシュは削除される。手動 npm インストール、ソースからのビルド、「バージョン固定なのはなぜか」の注記: [インストールの詳細](./docs/reference.md#installation)。 + +手間をかけたくないなら、AI にインストールを任せる — 以下のプロンプトを利用中の AI に貼り付ける: + +<details open> +<summary><strong>AI 支援インストール用プロンプト</strong></summary> + +```text +私の opencode に opencode-switchman プラグインをインストールし、設定してください。公式の手順に厳密に従うこと。 + +公式ソース (必ずこちらを正とすること。記憶からの推測はしない): +- GitHub リポジトリ: https://github.com/mrzturn/opencode-switchman +- npm パッケージ: https://www.npmjs.com/package/opencode-switchman +リポジトリ README の「Installation」セクションを読み、そこに書かれた通りに実行すること。 + +手順: +1. npm で公開されている最新版をインストール: `npx -y opencode-switchman@latest` (または `bunx opencode-switchman@latest`) を実行 — 私の opencode 設定の `plugin` エントリが正確な最新バージョンに書き換わる (私が使っているのがプロジェクト直下の `opencode.json` であれば、そちらにも同様に有効)。 +2. 機能設定を完了させる: プラグイン設定はすべて、opencode 設定ディレクトリ内の独立した `opencode-switchman.jsonc` に置かれ、初回起動時にデフォルト値とインラインコメント付きで自動生成される。私のプロバイダー (`zhipuai-coding-plan` / `deepseek` / `github-copilot` など) と突き合わせ、必要に応じて調整すること。 +3. opencode がプラグインをロードし、起動して動作させられることを検証する: opencode 内で `/switchman-doctor` を実行し、資格情報不要のローカル診断レポートを取得して、報告されたエラーをすべて修正する; その後 opencode を再起動し、プラグインが実際にロードされたことを確認する — ログに `[opencode-switchman] injected N model shells (agents)` が含まれ、プライマリモデルのシステムプロンプトに生きた `[ROUTES]/[WATERMARK]/[LIMITS]` バナーブロックが載っているはず。 + +3 つの手順すべてが通るまで成功と宣言しないこと。変更した内容を報告し、検証の証拠を見せること。 +``` + +</details> + +**前提条件**: [opencode](https://opencode.ai)。CLI/TUI 推奨 (ダイアログ、サイドバー、バナーの表示が最も充実。デスクトップアプリも同じ設定と状態を共有する)。プロバイダーはどれでも動作し、Copilot / GLM / DeepSeek はさらにクォータ対応ルーティングの対象になる。認証情報は opencode 自身の auth から読み取り専用で取得 — プラグインがシークレットを保存することはない。 + +## クイックスタート + +ステップは 6 つ。スクリーンショット付きの完全ウォークスルー: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md)。 + +1. **プロバイダーを接続** — TUI で `/connect`: Copilot OAuth、DeepSeek API キー。GLM Coding Plan は `zhipuai-coding-plan` カスタムプロバイダーとして `opencode.json` に記載する。 +2. **オーケストレーションに参加するモデルを選ぶ** — `/models` を開いて `ctrl+f` でお気に入り登録 (デスクトップアプリは「Manage models」トグル)。 +3. **`/switchman-setup`** *(必須・初回のみ)* — ガイド付きウィザードがマトリクス全体を一巡でカバー: 6 つのタスクプール (economy / mechanical / main / hard / vision / review) のそれぞれに対し最低 1 つのモデルを選択し、選んだモデルを強い順にランク付けする。TUI が使えない環境なら `/switchman-setup-chat` がチャット上で同じガイドフローを実行する。セットアップが完了するまでタスクディスパッチはハードブロック — 未設定のプールが「全モデル」にフォールバックすることはもうない。保存済みの設定はホットリロードされ、再起動が必要なのは全く新しいプロバイダーの登録時のみ。 +4. **微調整** *(任意)* — **`/modelRank`** で能力ランキングを手動調整、**`/poolConfig`** でプール別の候補リストを TUI ダイアログ内で編集する (チャットでは `-chat` 版)。手動エントリは初期デフォルトをどこでも上書きする。 +5. **コンテキストコマンド** + - **`/handover`** — セッションをバックアップし、自分で圧縮する。`[WATERMARK:SESSION]` 行が大きくなってきたとき、あるいはタスクが良い区切りに差しかかったとき、自動ハンドオーバーを待たずに使う。 + - **`/ctx-pause`** — このセッションの読み込み制限と自動ハンドオーバーを止める。大量の大きなファイルを一気に読みたいとき、トークン消費を気にしないときに使う。計測自体は継続する。 + - **`/ctx-resume`** — 制限を再度有効にする。重い読み込みが終わり次第すぐ使う。opencode の再起動でも同じ効果が得られる。 +6. **再起動して検証** — `[ROUTES]`/`[LIMITS]` バナーとサイドバーの `switchman` パネルを確認する; 引っかかる点があれば `/switchman-doctor` を実行。あとは opencode を普通に使うだけ。 + +## 得られるもの + +**コア** + +- **コンテキスト水位制御** — セッションのライブ計測 (`[WATERMARK:SESSION]`)、soft/hard/force の各しきい値、食い気味の読み込みを自動で上限内に収めるターン別読み込み予算、各サブエージェントに課される要約して終了のハード上限、そして force レベルでの自動ハンドオーバー (完全バックアップフォーク + 圧縮)。 +- **自動ディシジョンディスパッチ** — 同梱のディスパッチャープロトコルがプライマリモデルをディスパッチャーへ変える; 6 つの認知レーンが作業を適切なモデル・適切な負荷へルーティングする; 6 つの決定論的ゲートが全ディスパッチを検査する; 障害はブレーカーと分離を作動させ、システムは自己修復する。 + +**拡張機能** + +- **マルチサブスクリプションオーケストレーション** — Copilot / GLM / DeepSeek にまたがるクォータ対応ルーティング (どのプロバイダーでも参加可)、ピーク時間帯の譲り合い、課金を考慮したスコアリング、クロスファミリーレビューの強制。 +- **手動オーバーライド** — `/switchman-setup`、`/poolConfig`、`/modelRank`、`/expert`、`/handover`、`/ctx-pause`、`/ctx-resume`、`/switchman-doctor`、`/switchman-update`。 +- **可視性** — すべてのシステムプロンプトに載るライブ 4 行バナー、TUI サイドバーパネル、tmux ペインのミラーリング、セッション単位の成果物ワークスペース、全ルーティング判断の監査ログ。 + +オプション一覧、アーキテクチャ、内部構造の全体: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md))。 + +## ドキュメント + +- クイックスタート (図解付き): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- 完全マニュアル (設定、コマンド、アーキテクチャ): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- 技術仕様 (契約 / アルゴリズム / 実運用テストメモ): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- リリースノート: [CHANGELOG.md](./CHANGELOG.md) + +## ロードマップ + +直近の計画: より多くのプロバイダーへのクォータ対応 — Copilot / GLM / DeepSeek 以外のサブスクリプションプランと従量課金プールの拡充。まだ対応のないプロバイダーを使っているなら [issue を立ててほしい](https://github.com/mrzturn/opencode-switchman/issues): 次に何を作るかは実際の使用が決める。提案もバグ報告も同じく歓迎。 + +## 作者を支援する + +このプラグインはオープンソースで無料、これからもそのままだ。ただし維持にはコストが伴う: プロバイダー横断のアダプタ互換性の保守とテストには複数のサブスクリプション契約と一件ずつのデバッグが必要 — 一巡するごとに実際の金が消えていく。 + +プラグインが本当に役に立ったと感じたら、予算の許す範囲でコーヒーを一杯おごってほしい。感謝を — 心から。 + +👇 + +<details> +<summary>☕ ここをクリック 【作者にコーヒーをおごる】</summary> + +| Alipay | WeChat Pay | WeChat でスキャンして拍手を送る | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="Alipay QRコード" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="WeChat Pay QRコード" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="WeChat スキャン拍手 QRコード" /> | + +</details> + +## ライセンス + +[MIT](./LICENSE) diff --git a/README.ko.md b/README.ko.md new file mode 100644 index 0000000..f675df2 --- /dev/null +++ b/README.ko.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | **한국어** | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) + +> **zcode도 함께 사용 중이신가요?** 같은 저자의 자매 오픈소스 프로젝트 [zcode-switchman](https://github.com/mrzturn/zcode-switchman)을 확인해 보세요 — zcode 사용자에게 동일한 오케스트레이션을 제공합니다. + +> 컨텍스트는 계기판으로 관리하고, 작업은 스스로 디스패치합니다. + +![opencode-switchman — 컨텍스트 수위가 switchman을 움직이고 경로를 전환합니다](docs/assets/hero.svg) + +> 인터랙티브 데모: [opencode-switchman in action](https://mrzturn.github.io/opencode-switchman/) + +[OpenCode](https://opencode.ai)용 오케스트레이션 플러그인입니다. 두 가지 일을 하며, 둘 다 잘 해냅니다: + +**1. 컨텍스트 수위 제어.** 세션의 컨텍스트를 매 턴 측정합니다. 읽기는 턴별 예산 안에서 수행되므로 모델이 몰래 리포지토리 전체를 들이켤 수 없고, soft / hard / force 수위선이 순서대로 조언 → 마무리 → 자동 백업·압축 핸드오버를 트리거합니다. 디스패치되는 모든 서브에이전트에도 각자의 하드 상한이 부여됩니다. 컨텍스트는 더 이상 눈덩이처럼 불어나지 않습니다 — 세션이 하루 종일 돌아도 토큰이 자기 히스토리에 잡아먹히는 일이 없습니다. + +**2. 자동 의사결정 디스패칭.** 메인 모델이 디스패처로 변신합니다: 각 작업의 성격을 분석해 6개 인지 레인(economy / mechanical / main / hard / vision / review)의 서브에이전트 셸에 위임합니다. 플러그인은 결정론적 게이트와 가중치 기반 모델 스코어링, 자가 치유형 장애 격리를 강제하고 모든 라우팅 결정을 기록합니다. + +여기에 더해: + +- **모델·구독이 여러 개? 바로 그 상황을 위해 만들어진 플러그인.** GitHub Copilot, GLM Coding Plan, DeepSeek — 그 밖의 모든 opencode 프로바이더까지 — 하나의 풀로 묶어 오케스트레이션: 할당량 인지 정렬, 피크 시간대 회피, 교차 계열 리뷰 강제. +- **모델이 하나뿐이라도? 여전히 가치 있음.** 컨텍스트 제어와 스마트 디스패치만으로 단일 모델도 무기한 사용 가능 — 세션이 아무리 길어져도 컨텍스트는 부풀지 않음. + +## 설치 + +명령 한 줄 — 최초 설치와 이후 업데이트를 모두 처리합니다. 실행 후 opencode를 재시작하세요. + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +또는 + +```bash +npx -y opencode-switchman@latest +``` + +또는 + +```bash +bunx opencode-switchman@latest +``` + +어느 경로든 opencode 설정의 `plugin` 항목을 정확한 최신 버전으로 재작성하고 오래된 캐시를 정리합니다. 수동 npm 설치, 소스에서 직접 빌드, "왜 정확한 버전으로 고정하는가" 노트: [설치 상세](./docs/reference.md#installation). + +손대기 싫다면? 설치를 AI에게 맡기세요 — 사용 중인 AI에 이 프롬프트를 붙여넣으세요: + +<details open> +<summary><strong>AI 설치 위임 프롬프트</strong></summary> + +```text +제 opencode에 opencode-switchman 플러그인을 설치·설정해 주세요. 공식 안내를 엄격히 따라 주세요. + +공식 출처 (권위 있는 자료입니다. 기억으로 추측하지 말 것): +- GitHub 저장소: https://github.com/mrzturn/opencode-switchman +- npm 패키지: https://www.npmjs.com/package/opencode-switchman +저장소 README의 "Installation" 섹션을 읽고 그대로 따르세요. + +단계: +1. npm에 게시된 최신 버전 설치: `npx -y opencode-switchman@latest`(또는 `bunx opencode-switchman@latest`) 실행 — 제 opencode 설정의 `plugin` 항목을 정확한 최신 버전으로 재작성합니다(제가 프로젝트 수준 `opencode.json`을 사용한다면 거기에서도 동일하게 동작함). +2. 기능 설정 완료: 플러그인 설정은 전부 제 opencode 설정 디렉터리의 단독 파일 `opencode-switchman.jsonc`에 들어 있으며, 첫 시작 시 기본값과 인라인 주석이 포함된 채 자동 생성됩니다. 제 프로바이더(예: `zhipuai-coding-plan` / `deepseek` / `github-copilot`)에 맞는지 확인하고 필요한 만큼 조정하세요. +3. opencode가 플러그인을 로드·기동·실행하는지 검증: opencode 안에서 `/switchman-doctor`를 실행해 크리덴셜 없이 도는 로컬 진단 리포트를 받고, 보고된 모든 오류를 수정하세요. 그다음 opencode를 재시작해 플러그인이 실제로 로드됐는지 확인하세요 — 로그에 `[opencode-switchman] injected N model shells (agents)`가 있어야 하고, 메인 모델의 시스템 프롬프트에 라이브 `[ROUTES]/[WATERMARK]/[LIMITS]` 배너 블록이 붙어 있어야 합니다. + +세 단계가 모두 통과하기 전까지는 성공을 선언하지 마세요. 무엇을 변경했는지 보고하고 검증 증거를 보여주세요. +``` + +</details> + +**전제 조건**: [opencode](https://opencode.ai), CLI/TUI 권장(대화상자, 사이드바, 배너가 가장 풍부하게 표시됩니다; 데스크톱 앱도 동일한 설정과 상태를 공유합니다). 어떤 프로바이더든 동작하며, Copilot / GLM / DeepSeek은 추가로 할당량 인지 라우팅의 혜택을 받습니다. 크리덴셜은 opencode 자체 인증에서 읽기 전용으로만 사용 — 플러그인은 시크릿을 절대 저장하지 않습니다. + +## 빠른 시작 + +6단계. 스크린샷이 있는 전체 워크스루: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). + +1. **프로바이더 연결** — TUI에서 `/connect`: Copilot OAuth, DeepSeek API 키; GLM Coding Plan은 `zhipuai-coding-plan` 커스텀 프로바이더로 `opencode.json`에 등록. +2. **오케스트레이션에 참여할 모델 선택** — `/models` 실행 후 `ctrl+f`로 즐겨찾기(데스크톱 앱: "Manage models" 토글). +3. **`/switchman-setup`** *(한 번은 필수)* — 가이드 마법사가 매트릭스 전체를 한 번에: 6개 작업 풀(economy / mechanical / main / hard / vision / review) 각각에 모델을 최소 하나 이상 다중 선택한 뒤, 선택한 모델을 강한 순으로 랭킹. TUI가 없나요? `/switchman-setup-chat`이 채팅에서 동일한 가이드 흐름을 실행. 설정이 완료될 때까지 작업 디스패치는 하드 차단 — 미설정 풀이 더 이상 "all models"로 기본 설정되지 않음. 저장된 설정은 핫 리로드되며, 재시작은 완전히 새로운 프로바이더 등록 시에만 필요. +4. **미세 조정** *(선택)* — **`/modelRank`**로 능력 랭킹을 직접 다듬고 **`/poolConfig`**로 풀별 후보 목록을 TUI 대화상자에서 큐레이션(채팅에서는 `-chat` 변형 사용); 수동 항목은 모든 곳에서 초기 기본값보다 우선. +5. **컨텍스트 명령** + - **`/handover`** — 세션을 백업하고 직접 압축. `[WATERMARK:SESSION]` 줄이 커지고 있거나 작업이 적절한 중단점에 도달했을 때, 자동 핸드오버를 기다리는 대신 사용. + - **`/ctx-pause`** — 이 세션의 읽기 제한과 자동 핸드오버를 끔. 대용량 파일을 한꺼번에 많이 읽어야 하고 토큰 소모를 감수할 수 있을 때 사용; 측정 자체는 계속 실행됨. + - **`/ctx-resume`** — 제한을 다시 켬. 무거운 읽기가 끝나는 즉시 사용; opencode 재시작도 같은 효과. +6. **재시작 및 검증** — `[ROUTES]`/`[LIMITS]` 배너와 사이드바의 `switchman` 패널 확인; 뭔가 어긋나 보이면 `/switchman-doctor` 실행. 이후에는 평소처럼 opencode를 사용하면 됨. + +## 얻을 수 있는 것 + +**코어** + +- **컨텍스트 수위 제어** — 실시간 세션 측정(`[WATERMARK:SESSION]`), soft/hard/force 임계값, 탐적인 읽기를 자동으로 상한 처리하는 턴별 읽기 예산, 모든 서브에이전트에 적용되는 요약 후 종료 방식의 하드 상한, 그리고 force 수위에서 발동하는 자동 핸드오버(전체 백업 포크 + 압축). +- **자동 의사결정 디스패칭** — 번들된 디스패처 프로토콜이 메인 모델을 디스패처로 바꿈; 6개 인지 레인이 작업을 알맞은 모델에 알맞은 노력으로 라우팅; 6개의 결정론적 게이트가 모든 디스패치를 검사; 장애가 서킷 브레이커와 격리를 발동하고 시스템은 스스로 회복. + +**부가 기능** + +- **멀티 구독 오케스트레이션** — Copilot / GLM / DeepSeek에 걸친 할당량 인지 라우팅(모든 프로바이더 참여 가능), 피크 시간대 양보, 과금 인지 스코어링, 교차 계열 리뷰 강제. +- **수동 오버라이드** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **가시성** — 모든 시스템 프롬프트에 실시간으로 뜨는 4줄 배너, TUI 사이드바 패널, tmux 패인 미러링, 세션별 아티팩트 워크스페이스, 모든 라우팅 결정의 감사 로그. + +전체 옵션 표, 아키텍처, 내부 동작: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). + +## 문서 + +- 빠른 시작(그림 포함): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- 전체 매뉴얼(설정, 명령, 아키텍처): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- 기술 명세(계약 / 알고리즘 / 실전 테스트 노트): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- 릴리스 노트: [CHANGELOG.md](./CHANGELOG.md) + +## 로드맵 + +근시일 내: 더 많은 프로바이더의 할당량 지원 — Copilot / GLM / DeepSeek 이외의 더 많은 구독 플랜과 종량제 풀. 아직 지원되지 않는 프로바이더가 있다면 [이슈를 열어 주세요](https://github.com/mrzturn/opencode-switchman/issues): 실제 사용이 다음에 지어질 기능을 결정합니다. 제안과 버그 리포트도 언제나 환영합니다. + +## 제작자 지원하기 + +이 플러그인은 오픈소스이며 무료로 사용할 수 있고, 앞으로도 그럴 것입니다. 다만 유지에는 비용이 듭니다: 프로바이더별 어댑터 호환성을 지원하고 테스트하려면 여러 구독을 보유하고 하나씩 디버깅해야 합니다 — 매 차례 실제 돈이 들어갑니다. + +플러그인이 정말 도움이 됐고 예산에 여유가 있다면 커피 한 잔 사주세요. 진심으로 감사합니다. + +👇 + +<details> +<summary>☕ 여기를 클릭 【제작자에게 커피 한 잔】</summary> + +| Alipay | WeChat Pay | WeChat으로 스캔해 응원 전하기 | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="Alipay QR code" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="WeChat Pay QR code" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="WeChat scan-to-like QR code" /> | + +</details> + +## 라이선스 + +[MIT](./LICENSE) diff --git a/README.md b/README.md index fb39c1b..ca61a01 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # opencode-switchman -**English** | [中文](./README.zh.md) +**English** | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) > **Also using zcode?** Check out [zcode-switchman](https://github.com/mrzturn/zcode-switchman) — a sibling open-source project by the same author that brings the same orchestration to zcode users. @@ -74,8 +74,8 @@ Six steps. Full walkthrough with screenshots: **[docs/quick-start.md](./docs/qui 1. **Connect providers** — `/connect` in the TUI: Copilot OAuth, DeepSeek API key; GLM Coding Plan goes into `opencode.json` as the `zhipuai-coding-plan` custom provider. 2. **Pick the models that join orchestration** — `/models` then `ctrl+f` to favorite (desktop app: "Manage models" toggles). -3. **`/modelRank`** *(recommended)* — open the TUI dialog and hand-tune your own capability ranking; manual entries override the initial defaults everywhere. -4. **`/poolConfig`** *(recommended)* — curate per-pool candidate lists in the TUI dialog, overriding the initial defaults for the six task pools. +3. **`/switchman-setup`** *(required once)* — the guided wizard covers the whole matrix in one pass: multi-select at least one model for each of the six task pools (economy / mechanical / main / hard / vision / review), then rank the selected models strongest-first. No TUI? `/switchman-setup-chat` runs the same guided flow in chat. Until setup completes, task dispatch is hard-blocked — unconfigured pools no longer default to "all models". Saved config hot-reloads; a restart is only needed to register brand-new providers. +4. **Fine-tune** *(optional)* — **`/modelRank`** hand-tunes the capability ranking and **`/poolConfig`** curates per-pool candidate lists in TUI dialogs (`-chat` variants in chat); manual entries override the initial defaults everywhere. 5. **Context commands** - **`/handover`** — back up the session and compact it yourself. Use it when the `[WATERMARK:SESSION]` line is getting large or the task hits a good stopping point, instead of waiting for the automatic handover. - **`/ctx-pause`** — turn off this session's read limits and auto-handover. Use it when you need to read many large files at once and don't mind spending the tokens; measurement keeps running. @@ -92,7 +92,7 @@ Six steps. Full walkthrough with screenshots: **[docs/quick-start.md](./docs/qui **Extras** - **Multi-subscription orchestration** — quota-aware routing across Copilot / GLM / DeepSeek (any provider participates), peak-window yield, billing-aware scoring, cross-family review enforcement. -- **Manual overrides** — `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **Manual overrides** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. - **Visibility** — live four-line banner in every system prompt, TUI sidebar panel, tmux pane mirroring, per-session artifact workspace, and an audit log of every routing decision. Full options table, architecture, and internals: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). diff --git a/README.pt.md b/README.pt.md new file mode 100644 index 0000000..3571518 --- /dev/null +++ b/README.pt.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | **Português** | [Русский](./README.ru.md) + +> **Também usa zcode?** Confira o [zcode-switchman](https://github.com/mrzturn/zcode-switchman) — um projeto open source irmão, do mesmo autor, que leva a mesma orquestração aos usuários do zcode. + +> O contexto tem medidor. As tarefas se despacham sozinhas. + +![opencode-switchman — o nível d'água do contexto comanda o switchman e traça a rota](docs/assets/hero.svg) + +> Demo interativa: [opencode-switchman em ação](https://mrzturn.github.io/opencode-switchman/) + +Um plugin de orquestração para o [OpenCode](https://opencode.ai). Ele faz duas coisas, e faz bem: + +**1. Controle do nível do contexto.** O contexto da sua sessão é medido a cada turno. As leituras rodam contra um orçamento por turno, então o modelo não consegue engolir o repo inteiro em silêncio; as marcas soft / hard / force disparam primeiro um conselho, depois o wrap-up, e então um handover automático com backup e compactação; cada subagente despachado carrega seu próprio hard cap. O contexto para de acumular — uma sessão pode rodar o dia inteiro sem que os tokens sejam devorados pela própria história. + +**2. Despacho automatizado de decisões.** Seu modelo primário vira um dispatcher: ele perfila cada tarefa e a delega a shells subagente em seis faixas cognitivas (economy / mechanical / main / hard / vision / review). O plugin impõe gates determinísticos, pontuação ponderada por modelo e isolamento de falhas com autorreparo, e registra cada decisão de roteamento. + +E por cima disso: + +- **Vários modelos ou assinaturas? Este plugin foi feito para você.** GitHub Copilot, GLM Coding Plan, DeepSeek — ou qualquer provider do opencode — são orquestrados como um único pool: ordenação ciente de cotas, evitação de janelas de pico, review entre famílias forçada. +- **Só um modelo? Ainda vale a pena.** O controle de contexto e o despacho inteligente, sozinhos, mantêm um único modelo utilizável indefinidamente — por mais longa que seja a sessão, o contexto nunca incha. + +## Instalação + +Um comando — cobre a primeira instalação e as atualizações seguintes. Reinicie o opencode depois. + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +ou + +```bash +npx -y opencode-switchman@latest +``` + +ou + +```bash +bunx opencode-switchman@latest +``` + +Qualquer um dos caminhos reescreve a entrada `plugin` na sua configuração do opencode para a versão exata mais recente e remove caches velhos. Instalação npm manual, build a partir do código-fonte e a nota sobre o "porquê de versões exatas": [Detalhes de instalação](./docs/reference.md#installation). + +Prefere não mexer? Deixe sua IA fazer a instalação — cole este prompt na IA que você usa: + +<details open> +<summary><strong>Prompt de instalação assistida por IA</strong></summary> + +```text +Instale e configure o plugin opencode-switchman para o meu opencode, seguindo rigorosamente as instruções oficiais dele. + +Fontes oficiais (autoritativas, não adivinhe de memória): +- Repo GitHub: https://github.com/mrzturn/opencode-switchman +- Pacote npm: https://www.npmjs.com/package/opencode-switchman +Leia a seção "Instalação" do README do repo e siga-a exatamente. + +Passos: +1. Instale a versão mais recente publicada no npm: execute `npx -y opencode-switchman@latest` (ou `bunx opencode-switchman@latest`) — isso reescreve a entrada `plugin` na minha configuração do opencode para a versão exata mais recente (também funciona no `opencode.json` de projeto, se for o que eu uso). +2. Complete a configuração funcional: todas as configurações do plugin vivem no arquivo autônomo `opencode-switchman.jsonc` no diretório de configuração do opencode, gerado automaticamente com padrões e comentários inline no primeiro início; confira-o contra os meus providers (ex. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) e ajuste se necessário. +3. Verifique a corretude para que o opencode carregue, inicie e execute o plugin: execute `/switchman-doctor` dentro do opencode para um relatório de diagnóstico local sem credenciais e corrija todos os erros reportados; depois reinicie o opencode e confirme que o plugin foi mesmo carregado — o log deve conter `[opencode-switchman] injected N model shells (agents)` e o system prompt do meu modelo primário deve trazer o bloco de banner ao vivo `[ROUTES]/[WATERMARK]/[LIMITS]`. + +Não declare sucesso antes dos três passos passarem; relate o que mudou e mostre as evidências de verificação. +``` + +</details> + +**Pré-requisitos**: [opencode](https://opencode.ai), CLI/TUI recomendada (diálogos, sidebar e banners são mais completos lá; o app desktop compartilha a mesma configuração e estado). Qualquer provider funciona; Copilot / GLM / DeepSeek ganham adicionalmente o roteamento ciente de cotas. As credenciais são lidas apenas para leitura da própria autenticação do opencode — o plugin nunca armazena segredos. + +## Início rápido + +Seis passos. Guia completo com capturas de tela: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). + +1. **Conecte os providers** — `/connect` na TUI: OAuth do Copilot, API key do DeepSeek; o GLM Coding Plan vai no `opencode.json` como provider personalizado `zhipuai-coding-plan`. +2. **Escolha os modelos que entram na orquestração** — `/models` e depois `ctrl+f` para favoritar (app desktop: interruptores em "Gerenciar modelos"). +3. **`/switchman-setup`** *(obrigatório uma vez)* — o assistente guiado cobre a matriz inteira numa passada só: multisseleção de pelo menos um modelo para cada um dos seis pools de tarefas (economy / mechanical / main / hard / vision / review) e, em seguida, a ordenação dos modelos escolhidos do mais forte ao mais fraco. Sem TUI? O `/switchman-setup-chat` roda o mesmo fluxo guiado no chat. Até a configuração terminar, o despacho de tarefas fica bloqueado — pools não configurados não caem mais para "todos os modelos". A configuração salva recarrega a quente; um reinício só é preciso para registrar providers totalmente novos. +4. **Ajuste fino** *(opcional)* — o **`/modelRank`** ajusta manualmente o ranking de capacidade e o **`/poolConfig`** cura as listas de candidatos por pool nos diálogos da TUI (variantes `-chat` no chat); entradas manuais sobrescrevem os padrões iniciais em todos os lugares. +5. **Comandos de contexto** + - **`/handover`** — faça você mesmo o backup da sessão e a compactação. Use quando a linha `[WATERMARK:SESSION]` estiver crescendo ou a tarefa chegar a um bom ponto de parada, em vez de esperar o handover automático. + - **`/ctx-pause`** — desative os limites de leitura e o handover automático desta sessão. Use quando precisar ler muitos arquivos grandes de uma vez e não se importar de gastar tokens; a medição continua rodando. + - **`/ctx-resume`** — reative os limites. Use assim que a leitura pesante terminar; reiniciar o opencode tem o mesmo efeito. +6. **Reinicie e verifique** — confira o banner `[ROUTES]`/`[LIMITS]` e o painel `switchman` na sidebar; rode `/switchman-doctor` se algo parecer errado. Depois é só usar o opencode normalmente. + +## O que você ganha + +**Núcleo** + +- **Controle do nível do contexto** — medição da sessão ao vivo (`[WATERMARK:SESSION]`), limiares soft/hard/force, um orçamento de leitura por turno que limita sozinho leituras excessivamente ávidas, um hard cap com resumo-e-término para cada subagente, e um handover automático (fork de backup completo + compactação) no nível force. +- **Despacho automatizado de decisões** — um protocolo dispatcher embutido transforma seu modelo primário num dispatcher; seis faixas cognitivas encaminham o trabalho para o modelo certo com o esforço certo; seis gates determinísticos verificam cada despacho; falhas acionam breakers e isolamento, e o sistema se cura sozinho. + +**Extras** + +- **Orquestração multi-assinatura** — roteamento ciente de cotas entre Copilot / GLM / DeepSeek (qualquer provider participa), cedência em janelas de pico, pontuação ciente de cobrança, imposição de review entre famílias. +- **Overrides manuais** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **Visibilidade** — banner ao vivo de quatro linhas em cada system prompt, painel na sidebar da TUI, espelhamento em painéis tmux, workspace de artefatos por sessão, e um log de auditoria de cada decisão de roteamento. + +Tabela completa de opções, arquitetura e detalhes internos: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). + +## Documentação + +- Início rápido (ilustrado): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- Manual completo (configuração, comandos, arquitetura): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- Especificação técnica (contratos / algoritmos / notas de campo): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- Notas de versão: [CHANGELOG.md](./CHANGELOG.md) + +## Roadmap + +Curto prazo: suporte a cotas para mais providers — mais planos de assinatura e pools pay-as-you-go além de Copilot / GLM / DeepSeek. Se o seu provider ainda não está coberto, [abra uma issue](https://github.com/mrzturn/opencode-switchman/issues): o uso real decide o que vem a seguir. Sugestões e relatórios de bugs são igualmente bem-vindos. + +## Apoie o autor + +Este plugin é open source e gratuito, e continuará assim. Mantê-lo vivo, porém, não é de graça: dar suporte e testar a compatibilidade de adaptadores entre providers significa manter várias assinaturas e depurar uma a uma — cada rodada custa dinheiro de verdade. + +Se o plugin realmente te ajudou e o seu orçamento permite, me pague um café. Obrigado — sinceramente. + +👇 + +<details> +<summary>☕ Clique aqui 【Pague um café ao autor】</summary> + +| Alipay | WeChat Pay | Escaneie com WeChat e deixe um like | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="QR code do Alipay" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="QR code do WeChat Pay" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="QR code WeChat scan-to-like" /> | + +</details> + +## Licença + +[MIT](./LICENSE) diff --git a/README.ru.md b/README.ru.md new file mode 100644 index 0000000..7dd4372 --- /dev/null +++ b/README.ru.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | **Русский** + +> **Пользуетесь ещё и zcode?** Взгляните на [zcode-switchman](https://github.com/mrzturn/zcode-switchman) — родственный open-source проект того же автора, который приносит такую же оркестрацию пользователям zcode. + +> Контекст — на счётчике. Задачи диспетчируются сами. + +![opencode-switchman — уровень воды в контексте ведёт стрелочника и задаёт маршрут](docs/assets/hero.svg) + +> Интерактивная демо-презентация: [opencode-switchman в действии](https://mrzturn.github.io/opencode-switchman/) + +Плагин оркестрации для [OpenCode](https://opencode.ai). Он делает две вещи — и делает их хорошо: + +**1. Контроль уровня воды в контексте.** Контекст вашей сессии замеряется на каждом ходу. Чтение ограничено бюджетом на каждый ход, поэтому модель не сможет незаметно заглотить весь репозиторий; пороги soft / hard / force запускают сначала совет, затем сворачивание работы, а затем автоматическую передачу с резервной копией и сжатием; каждый отправленный субагент несёт собственный жёсткий лимит. Контекст перестаёт расти снежным комом — сессия может работать хоть весь день, и её собственная история не пожирает токены. + +**2. Автоматическая диспетчеризация решений.** Ваша основная модель становится диспетчером: она профилирует каждую задачу и делегирует её субагентским оболочкам по шести когнитивным направлениям (economy / mechanical / main / hard / vision / review). Плагин обеспечивает детерминированные шлюзы, взвешенную оценку моделей и самовосстанавливающуюся изоляцию сбоев, а каждое решение о маршрутизации записывает в журнал. + +Помимо этого: + +- **Несколько моделей или подписок? Этот плагин создан именно для вас.** GitHub Copilot, GLM Coding Plan, DeepSeek — или любой другой провайдер opencode — оркестрируются как единый пул: порядок с учётом квот, обход пиковых окон, принудительное ревью между семействами моделей. +- **Только одна модель? Всё равно того стоит.** Контроль контекста и умная диспетчеризация сами по себе позволяют единственной модели оставаться рабочей сколь угодно долго — как бы долго ни длилась сессия, контекст никогда не раздувается. + +## Установка + +Одна команда — подходит и для первой установки, и для последующих обновлений. После выполнения перезапустите opencode. + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +или + +```bash +npx -y opencode-switchman@latest +``` + +или + +```bash +bunx opencode-switchman@latest +``` + +Любой из путей переписывает запись `plugin` в вашей конфигурации opencode на точную последнюю версию и вычищает устаревшие кэши. Ручная установка через npm, сборка из исходников и заметка «почему точные версии»: [Подробности установки](./docs/reference.md#installation). + +Предпочитаете ничего не делать руками? Доверьте установку своему ИИ — вставьте этот промпт в используемый вами ИИ: + +<details open> +<summary><strong>Промпт для установки с помощью ИИ</strong></summary> + +```text +Установи и настрой плагин opencode-switchman для моего opencode, строго следуя его официальным инструкциям. + +Официальные источники (авторитетные, не полагайся на память): +- GitHub-репозиторий: https://github.com/mrzturn/opencode-switchman +- npm-пакет: https://www.npmjs.com/package/opencode-switchman +Прочитай в README репозитория раздел "Installation" и следуй ему в точности. + +Шаги: +1. Установи последнюю версию, опубликованную на npm: выполни `npx -y opencode-switchman@latest` (или `bunx opencode-switchman@latest`) — он перепишет запись `plugin` в моём конфиге opencode на точную последнюю версию (работает и в проектном `opencode.json`, если пользуюсь именно им). +2. Заверши функциональную настройку: все параметры плагина находятся в отдельном файле `opencode-switchman.jsonc` в каталоге конфигурации opencode; при первом запуске он создаётся автоматически со значениями по умолчанию и инлайн-комментариями — сверь его с моими провайдерами (например, `zhipuai-coding-plan` / `deepseek` / `github-copilot`) и при необходимости поправь. +3. Убедись в корректности, чтобы opencode загружался, запускался и исполнял плагин: выполни `/switchman-doctor` внутри opencode, получи локальный диагностический отчёт без учётных данных и исправь каждую найденную ошибку; затем перезапусти opencode и подтверди, что плагин действительно загрузился — в логе должна появиться строка `[opencode-switchman] injected N model shells (agents)`, а системный промпт моей основной модели должен нести живой блок баннера `[ROUTES]/[WATERMARK]/[LIMITS]`. + +Не объявляй успех, пока не пройдены все три шага; отчитайся, что именно изменил, и покажи подтверждение проверки. +``` + +</details> + +**Требования**: [opencode](https://opencode.ai), рекомендуется CLI/TUI (именно там диалоги, сайдбар и баннеры наиболее информативны; десктопное приложение использует ту же конфигурацию и то же состояние). Подойдёт любой провайдер; Copilot / GLM / DeepSeek дополнительно получают маршрутизацию с учётом квот. Учётные данные читаются только в режиме read-only из собственного auth opencode — плагин никогда не хранит секреты. + +## Быстрый старт + +Шесть шагов. Полное пошаговое руководство со скриншотами: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). + +1. **Подключите провайдеров** — `/connect` в TUI: Copilot OAuth, API-ключ DeepSeek; GLM Coding Plan прописывается в `opencode.json` как кастомный провайдер `zhipuai-coding-plan`. +2. **Выберите модели, которые войдут в оркестрацию** — `/models`, затем `ctrl+f`, чтобы добавить в избранные (в десктопном приложении — переключатели "Manage models"). +3. **`/switchman-setup`** *(требуется один раз)* — мастер настройки проходит всю матрицу за один заход: в мультиселекте отметьте хотя бы одну модель для каждого из шести пулов задач (economy / mechanical / main / hard / vision / review), затем расставьте выбранные модели от самой сильной к слабой. Нет TUI? `/switchman-setup-chat` запускает тот же мастер в чате. Пока настройка не завершена, диспетчеризация задач жёстко заблокирована — для ненастроенных пулов больше нет значения по умолчанию «все модели». Сохранённый конфиг подхватывается на лету; перезапуск нужен только для регистрации совершенно новых провайдеров. +4. **Тонкая настройка** *(опционально)* — **`/modelRank`** вручную корректирует рейтинг способностей моделей, а **`/poolConfig`** редактирует списки кандидатов по каждому пулу в диалогах TUI (в чате — варианты `-chat`); ручные записи везде переопределяют исходные значения по умолчанию. +5. **Команды контекста** + - **`/handover`** — сделайте резервную копию сессии и сожмите её вручную. Используйте, когда строка `[WATERMARK:SESSION]` становится большой или задача достигла удобной точки остановки, вместо того чтобы ждать автоматическую передачу. + - **`/ctx-pause`** — отключите для этой сессии лимиты на чтение и авто-передачу. Используйте, когда нужно разом прочитать много крупных файлов и не жаль потратить токены; замер продолжается. + - **`/ctx-resume`** — включите лимиты обратно. Сделайте это, как только массовое чтение закончилось; перезапуск opencode даёт тот же эффект. +6. **Перезапустите и проверьте** — посмотрите баннер `[ROUTES]`/`[LIMITS]` и панель `switchman` в сайдбаре; если что-то выглядит подозрительно, запустите `/switchman-doctor`. Дальше просто пользуйтесь opencode как обычно. + +## Что вы получаете + +**Основное** + +- **Контроль уровня воды в контексте** — замер сессии в реальном времени (`[WATERMARK:SESSION]`), пороги soft/hard/force, бюджет чтения на ход, автоматически ограничивающий излишне жадное чтение, жёсткий лимит с резюмированием и завершением для каждого субагента и автоматическая передача (полная резервная копия + сжатие) на принудительном уровне. +- **Автоматическая диспетчеризация решений** — встроенный протокол диспетчера превращает вашу основную модель в диспетчера; шесть когнитивных направлений маршрутизируют работу нужной модели с нужным уровнем усилий; шесть детерминированных шлюзов проверяют каждую отправку; сбои взводят предохранители и изоляцию, и система восстанавливается сама. + +**Дополнительно** + +- **Оркестрация нескольких подписок** — маршрутизация с учётом квот между Copilot / GLM / DeepSeek (участвует любой провайдер), уступание пиковых окон, оценка с учётом биллинга, принудительное ревью между семействами моделей. +- **Ручное управление** — `/switchman-setup`, `/poolConfig`, `/modelRank`, `/expert`, `/handover`, `/ctx-pause`, `/ctx-resume`, `/switchman-doctor`, `/switchman-update`. +- **Наглядность** — живой баннер из четырёх строк в каждом системном промпте, панель в сайдбаре TUI, зеркалирование в панели tmux, рабочее пространство артефактов для каждой сессии и журнал аудита каждого решения о маршрутизации. + +Полная таблица опций, архитектура и внутреннее устройство: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). + +## Документация + +- Быстрый старт (с иллюстрациями): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- Полное руководство (конфигурация, команды, архитектура): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- Техническая спецификация (контракты / алгоритмы / заметки с полевых испытаний): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- Примечания к релизам: [CHANGELOG.md](./CHANGELOG.md) + +## Дорожная карта + +В ближайших планах: поддержка квот для большего числа провайдеров — больше подписочных планов и пулов с оплатой по факту сверх Copilot / GLM / DeepSeek. Если ваш провайдер пока не охвачен, [создайте issue](https://github.com/mrzturn/opencode-switchman/issues): что строить дальше, решает реальное использование. Предложения и сообщения об ошибках приветствуются в равной мере. + +## Поддержите автора + +Этот плагин open source и бесплатен в использовании — и таким он останется. Но его поддержание само по себе не бесплатно: сопровождение и тестирование совместимости адаптеров с провайдерами требуют держать несколько подписок и отлаживать их по очереди — каждый такой обход стоит реальных денег. + +Если плагин действительно вам помог и бюджет позволяет — купите мне чашку кофе. Спасибо, искренне. + +👇 + +<details> +<summary>☕ Нажмите здесь 【Купить автору кофе】</summary> + +| Alipay | WeChat Pay | Отсканируйте через WeChat, чтобы поставить ему лайк | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="Alipay QR code" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="WeChat Pay QR code" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="WeChat scan-to-like QR code" /> | + +</details> + +## Лицензия + +[MIT](./LICENSE) diff --git a/README.zh-TW.md b/README.zh-TW.md new file mode 100644 index 0000000..f5b65fc --- /dev/null +++ b/README.zh-TW.md @@ -0,0 +1,130 @@ +# opencode-switchman + +[English](./README.md) | [简体中文](./README.zh.md) | **繁體中文** | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) + +> **也在用 zcode?** 看看 [zcode-switchman](https://github.com/mrzturn/zcode-switchman)——同作者的開源姊妹專案,為 zcode 使用者帶來同樣的編排能力。 + +> 上下文有水位,任務自己派。 + +![opencode-switchman —— 上下文水位驅動轉轍員自動扳道](docs/assets/hero.svg) + +> 互動式展示:[opencode-switchman 宣傳頁](https://mrzturn.github.io/opencode-switchman/index.zh.html) + +一套 [OpenCode](https://opencode.ai) 編排外掛,核心就兩件事: + +**1. 上下文水位控制。** 外掛每輪實測你的工作階段上下文:讀取有每輪預算閘門,模型沒辦法悶頭把整個儲存庫吞進上下文;軟/硬/強制三檔水位依次觸發提醒、收尾、自動備份壓縮交接;派出去的每個子代理各有一條硬頂。上下文不再滾雪球——工作階段跑一整天,token 也不會被自己的歷史累積一口口吃掉。 + +**2. 自動化決策調度。** 主模型轉型調度員:為任務描繪輪廓,按六個認知檔位(economy / mechanical / main / hard / vision / review)派給子代理空殼執行;外掛進行確定性攔截、加權評分、失敗自癒隔離,每一條路由決策都可追溯。 + +在此之上: + +- **有多個模型或多個訂閱?這個外掛就是為你準備的。** GitHub Copilot、智譜 GLM Coding Plan、DeepSeek——或任意 opencode 供應商——都會被編排成一個池子統一調度:配額感知排序、避開高峰時段、強制跨家族審查。 +- **只有一個模型?照樣好用。** 光是上下文控制與智慧派發,就夠你把這一個模型長久用下去——工作階段再久,上下文也不會失控膨脹。 + +## 安裝 + +一個指令,首次安裝與後續更新一把罩。裝完重新啟動 opencode。 + +```bash +curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash +``` + +或 + +```bash +npx -y opencode-switchman@latest +``` + +或 + +```bash +bunx opencode-switchman@latest +``` + +兩種方式都會把 opencode 設定裡的 `plugin` 項目改寫為最新的精確版本,並清除過期的外掛快取。手動 npm 安裝、原始碼建置,以及「為什麼必須使用精確版本號」的說明:[安裝細節](./docs/reference.zh.md#安裝)。 + +怕麻煩?讓 AI 幫你裝——把下面這段話貼給你正在用的 AI: + +<details open> +<summary><strong>AI 代安裝提示詞</strong></summary> + +```text +請嚴格按照官方說明為我的 opencode 安裝並設定 opencode-switchman 外掛。 + +官方來源(以此為準,不要憑記憶猜測): +- GitHub 儲存庫:https://github.com/mrzturn/opencode-switchman +- npm 套件:https://www.npmjs.com/package/opencode-switchman +請先閱讀儲存庫 README 的「安裝」章節,然後嚴格照做。 + +步驟: +1. 安裝 npm 上釋出的最新版本:執行 `npx -y opencode-switchman@latest`(或 `bunx opencode-switchman@latest`),它會把我的 opencode 設定裡的 `plugin` 項目改寫為精確的最新版本(若我用的是專案層級的 `opencode.json`,它同樣適用)。 +2. 完成功能設定:外掛全部設定都在我 opencode 設定目錄下獨立的 `opencode-switchman.jsonc` 檔案中,首次啟動時自動產生並附有註解;請對照我的 provider(如 `zhipuai-coding-plan` / `deepseek` / `github-copilot`)檢查並視需要調整。 +3. 驗證設定正確、確保 opencode 能正常載入、啟動並執行該外掛:在 opencode 內執行 `/switchman-doctor` 產出本機、不含憑證的診斷報告,並修復所有回報的錯誤;然後重新啟動 opencode 確認外掛確實已載入——日誌應出現 `[opencode-switchman] injected N model shells (agents)`,且主模型的系統提示中應帶有即時的 `[ROUTES]/[WATERMARK]/[LIMITS]` 橫幅區塊。 + +三個步驟全部通過才算完成;請回報你做的修改並提出驗證證據。 +``` + +</details> + +**前置需求**:[opencode](https://opencode.ai),建議使用 CLI/TUI(彈出視窗、側邊欄與橫幅在 TUI 中最完整;桌面版共用同一份設定與狀態)。任意供應商皆可使用;Copilot / GLM / DeepSeek 另享配額感知路由。憑證以唯讀方式取自 opencode 自身的驗證層,外掛不儲存任何金鑰。 + +## 快速上手 + +六個步驟完成設定。完整圖文版:**[docs/quick-start.zh.md](./docs/quick-start.zh.md)** / [English](./docs/quick-start.md)。 + +1. **連接 provider** —— 在 TUI 執行 `/connect`:Copilot 走 OAuth、DeepSeek 貼上 API key;GLM Coding Plan 則在 `opencode.json` 加入 `zhipuai-coding-plan` 自訂 provider。 +2. **挑選參與編排的模型** —— `/models` 後按 `ctrl+f` 加入最愛(桌面版:「管理模型」開關)。 +3. **`/switchman-setup`** *(首次必做)* —— 引導式精靈一次完成整個矩陣:為六個任務池(economy / mechanical / main / hard / vision / review)各多選至少一個模型,再將入選模型按能力由強到弱排出名次。沒有 TUI?`/switchman-setup-chat` 可在對話中走同樣的引導流程。設定完成前任務派發會被強制攔截——未設定的池不再預設「全部模型參與」。設定儲存後立即熱載入;只有選到 opencode 尚未註冊的全新 provider 時才需要重新啟動。 +4. **微調** *(選做)* —— **`/modelRank`** 手動調整能力排名,**`/poolConfig`** 為各任務池自訂候選清單(TUI 彈出視窗,`-chat` 後綴走對話);手動項目在所有決策環節都會覆蓋初始預設。 +5. **上下文指令** + - **`/handover`** —— 手動備份並壓縮目前的工作階段。`[WATERMARK:SESSION]` 行的數字偏高、或任務告一段落時使用,不必等自動交接。 + - **`/ctx-pause`** —— 暫時關閉本工作階段的讀取限制與自動交接。需要一次讀取大量大檔案、不在意多花 token 時使用;測量照常運作。 + - **`/ctx-resume`** —— 重新開啟限制。大檔案讀完就恢復;重新啟動 opencode 效果相同。 +6. **重新啟動、驗證** —— 確認 `[ROUTES]`/`[LIMITS]` 橫幅與側邊欄的 `switchman` 面板,有異常就執行 `/switchman-doctor`。之後照常使用 opencode 即可。 + +## 核心功能 + +**核心** + +- **上下文水位控制** —— 工作階段上下文每輪實測(`[WATERMARK:SESSION]`),軟/硬/強制三檔水位;每輪讀取預算閘門自動約束過度讀取;每個子代理一條硬頂(觸頂時交回總結並終止);強制水位自動交接(完整分叉備份+壓縮),任務不中斷。 +- **自動化決策調度** —— 內建調度員規程讓主模型學會派工;六個認知檔位把任務交給合適的模型與思考檔位;六道確定性閘門逐一檢驗每次派發;失敗自動熔斷隔離、自癒恢復。 + +**附加** + +- **多訂閱編排** —— Copilot / GLM / DeepSeek 跨池配額感知路由(任意供應商皆可參與)、避開高峰時段、計費加權、強制跨家族審查。 +- **手動覆蓋** —— `/switchman-setup`、`/poolConfig`、`/modelRank`、`/expert`、`/handover`、`/ctx-pause`、`/ctx-resume`、`/switchman-doctor`、`/switchman-update`。 +- **看得見** —— 每輪系統提示注入即時四行橫幅、TUI 側邊欄狀態面板、tmux 窗格鏡像、按工作階段歸檔的產物工作區、路由決策稽核日誌。 + +完整設定項目表、架構與內部機制:[docs/reference.zh.md](./docs/reference.zh.md)(English: [docs/reference.md](./docs/reference.md))。 + +## 文件 + +- 快速上手(圖文):[中文](./docs/quick-start.zh.md) · [English](./docs/quick-start.md) +- 完整手冊(設定、指令、架構):[中文](./docs/reference.zh.md) · [English](./docs/reference.md) +- 技術方案(契約/演算法/實測紀錄):[docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- 發行記錄:[CHANGELOG.md](./CHANGELOG.md) + +## 路線圖 + +近期規劃是支援更多供應商的配額——在 Copilot / GLM / DeepSeek 之外,涵蓋更多訂閱制與按量計費池。你的供應商還沒被支援?歡迎[提出 issue](https://github.com/mrzturn/opencode-switchman/issues),我會依實際使用情況安排開發。功能建議與 bug 回報同樣歡迎。 + +## 用愛發電 + +本專案開源、免費,也會一直免費下去。但維護它並不免費:要支援並測試各家供應商對本外掛的相容性,需要開通多個訂閱、一一實地除錯,每一輪都是真金白銀的消耗。 + +如果這個外掛真的幫到了你,手頭也寬裕,不妨請作者喝杯咖啡。在此由衷感謝。 + +👇 + +<details> +<summary>☕ 點擊此處【請作者喝杯咖啡】</summary> + +| 支付寶 | 微信支付 | 用微信掃碼替他按個讚 | +|:---:|:---:|:---:| +| <img src="docs/pay/alipay.png" width="150" alt="支付寶收款 QR Code" /> | <img src="docs/pay/wechat_pay.jpg" width="150" alt="微信收款 QR Code" /> | <img src="docs/pay/wechat_pay_2.jpg" width="150" alt="微信掃碼按讚 QR Code" /> | + +</details> + +## License + +[MIT](./LICENSE) diff --git a/README.zh.md b/README.zh.md index 6557147..5a31382 100644 --- a/README.zh.md +++ b/README.zh.md @@ -1,6 +1,6 @@ # opencode-switchman -[English](./README.md) | **中文** +[English](./README.md) | **简体中文** | [繁體中文](./README.zh-TW.md) | [日本語](./README.ja.md) | [한국어](./README.ko.md) | [Español](./README.es.md) | [Français](./README.fr.md) | [Deutsch](./README.de.md) | [Italiano](./README.it.md) | [Português](./README.pt.md) | [Русский](./README.ru.md) > **也在用 zcode?** 看看 [zcode-switchman](https://github.com/mrzturn/zcode-switchman)——同作者的开源兄弟项目,为 zcode 玩家带来同样的编排能力。 @@ -74,8 +74,8 @@ bunx opencode-switchman@latest 1. **连接 provider** —— TUI 里运行 `/connect`:Copilot 走 OAuth、DeepSeek 粘 API key;GLM Coding Plan 在 `opencode.json` 里加 `zhipuai-coding-plan` 自定义 provider。 2. **挑选参与编排的模型** —— `/models` 后按 `ctrl+f` 收藏(桌面端:「管理模型」开关)。 -3. **`/modelRank`** *(推荐)* —— 优先在 TUI 弹窗里手动调整能力排名,人工条目在所有决策面覆盖初始默认。 -4. **`/poolConfig`** *(推荐)* —— 优先在 TUI 弹窗里为六个任务池手工定制候选清单,覆盖初始默认。 +3. **`/switchman-setup`** *(首次必做)* —— 引导式向导一次跑通整个矩阵:为六个任务池(economy / mechanical / main / hard / vision / review)各多选至少一个模型,再把入选模型按能力强到弱排出名次。没有 TUI?`/switchman-setup-chat` 在对话里走同样的引导流程。配置完成前任务派发会被硬性拦截——未配置的池不再默认「全部模型参与」。配置保存即热加载;只有选到 opencode 尚未注册的全新 provider 时才需要重启。 +4. **微调** *(可选)* —— **`/modelRank`** 手工调整能力排名,**`/poolConfig`** 为各任务池定制候选清单(TUI 弹窗,`-chat` 后缀走对话);人工条目在所有决策面覆盖初始默认。 5. **三个上下文命令** - **`/handover`** —— 手动备份并压缩当前会话。`[WATERMARK:SESSION]` 行的数字偏大、或任务告一段落时用,不必等自动交接。 - **`/ctx-pause`** —— 临时关掉本会话的读取限制和自动交接。需要一次性读大量大文件、不在乎多花 token 时用;测量不受影响。 @@ -92,7 +92,7 @@ bunx opencode-switchman@latest **辅助** - **多订阅编排** —— Copilot / GLM / DeepSeek 跨池配额感知路由(任意供应商均可参与)、高峰避让、计费加权、跨家族评审强制。 -- **手动覆盖** —— `/poolConfig`、`/modelRank`、`/expert`、`/handover`、`/ctx-pause`、`/ctx-resume`、`/switchman-doctor`、`/switchman-update`。 +- **手动覆盖** —— `/switchman-setup`、`/poolConfig`、`/modelRank`、`/expert`、`/handover`、`/ctx-pause`、`/ctx-resume`、`/switchman-doctor`、`/switchman-update`。 - **看得见** —— 每轮系统提示注入实时四行横幅、TUI 侧栏状态面板、tmux 窗格镜像、按会话归档的工件工作区、路由决策审计日志。 完整配置项表、架构与内部机制:[docs/reference.zh.md](./docs/reference.zh.md)(English: [docs/reference.md](./docs/reference.md))。 diff --git a/docs/quick-start.md b/docs/quick-start.md index f73cffa..e509357 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -1,4 +1,4 @@ -# Quick Start — from zero to a routed matrix in five steps +# Quick Start — from zero to a routed matrix in six steps **English** | [Chinese](./quick-start.zh.md) @@ -6,13 +6,14 @@ This walkthrough is for users who have just installed the plugin (or are about t > **Where to configure**: use the **CLI/TUI first** — dialogs, the sidebar panel, and live banners are richest there. The **desktop app** is an optional alternative afterwards; both share the same config and state, and every manual override below works in either surface. -The five steps: +The six steps: 1. [Connect providers](#step-1--connect-providers) — give opencode credentials so models exist 2. [Pick the models that join orchestration](#step-2--pick-the-models-that-join-orchestration-favorites--visible-set) — favorites in the TUI, toggles in the app -3. [Rank models yourself (optional)](#step-3--optional-rank-models-yourself-modelrank-and-modelrank-chat) — `/modelRank` / `/modelRank-chat` -4. [Curate task pools (optional)](#step-4--optional-curate-task-pools-poolconfig-and-poolconfig-chat) — `/poolConfig` / `/poolConfig-chat` -5. [Restart, verify, and watch it route](#step-5--restart-verify-and-watch-it-route) — banners, sidebar, `/switchman-doctor` +3. [Guided setup (required)](#step-3--required-guided-setup-switchman-setup-and-switchman-setup-chat) — `/switchman-setup` / `/switchman-setup-chat` +4. [Adjust the ranking (optional)](#step-4--optional-adjust-the-ranking-modelrank-and-modelrank-chat) — `/modelRank` / `/modelRank-chat` +5. [Curate task pools (optional)](#step-5--optional-curate-task-pools-poolconfig-and-poolconfig-chat) — `/poolConfig` / `/poolConfig-chat` +6. [Restart, verify, and watch it route](#step-6--restart-verify-and-watch-it-route) — banners, sidebar, `/switchman-doctor` --- @@ -72,9 +73,30 @@ Not every model a provider offers needs to join the matrix. You decide the **act > - Favorites also carry a routing hint: within the same capability tier, favorited models are preferred in lane chains. > - Surface changes (favorite added/removed, toggle flipped) trigger an immediate recomputation and probe refresh — no restart needed for this step. -## Step 3 — (Optional) Rank models yourself: /modelRank and /modelRank-chat +## Step 3 — (Required) Guided setup: /switchman-setup and /switchman-setup-chat -By default, model capability comes from an automatic cascade (live third-party index → bundled snapshot → curated table). If you disagree — your workload, your ranking. +Unconfigured task pools no longer fall back to "all models". Until setup completes — every one of the six task pools (`economy` / `mechanical` / `main` / `hard` / `vision` / `review`) has at least one selected model **and** the capability ranking has at least one entry — **task dispatch is hard-blocked**. The setup wizard gets you there in one guided pass. + +**TUI**: run `/switchman-setup`. + +1. **Intro** — shows the current state (pools configured n/6, ranking ok/missing); Start jumps straight to the first unfinished step, so the wizard is resumable at any time. +2. **Six pool dialogs** (economy → mechanical → main → hard → vision → review) — multi-select the models for each pool: Enter toggles a `[x]`/`[ ]` mark in memory, a capability tier is shown per row, select-all / clear-all shortcuts and back navigation are built in; the per-pool confirm persists immediately (at least one model per pool), so every save hot-reloads the running plugin and the wizard stays resumable pool-by-pool. +3. **Ranking** — pick your ranked models one by one, strongest first (at least one); the candidates are exactly the union of the models you selected across the pools. Finish persists the ranking. +4. **Done** — a summary of every pool plus the ranking order. Setup takes effect immediately (hot-reload); the screen also names any selected providers that still need a restart (only brand-new providers opencode hasn't registered yet). + +**Conversational** (TUI or desktop app): run `/switchman-setup-chat` — the same guided flow in chat: the agent shows the current pool/rank state, asks pool by pool which models join (multi-select questions), asks for the strongest-first ranking, persists every answer through the bundled CLI, and verifies all six pools plus the ranking are set before closing. + +While setup is incomplete, main sessions carry a `[SETUP]` advisory telling the model to point you to the wizard, and each task dispatch is denied with the same guidance. This rides on the first-run language ask: until that is answered, the language gate is the single voice blocking task calls. The gate opens the moment the last config file is written — mtime hot-reload, no restart. + +> **Scope & conditions** +> - Gate scope: main sessions only — dispatched shell subagents and internal sessions are never blocked. There is no waiver flag: the only way through is completing setup (or hand-editing the files below). +> - Files: the wizard writes the same `~/.config/opencode/opencode-switchman/pool-config.json` + `capability-rank.json` as Steps 4–5 — safe to hand-edit, hot-reloaded on save (the `[LIMITS]` banner reports `task-pool selection: M pools` / `manual capability rank: N models`). +> - Unsure what to pick? Sensible defaults: economy = cheap/fast models, mechanical = mid-tier workhorse, main = strongest generalist, hard = strongest reasoner, vision = image-capable models, review = a model family different from the main pool's head (cross-family review is preferred). +> - CLI alternative: `node <pkg>/dist/switchman-config.js pool list|set …` + `rank list|set …` (same files, same hot-reload). + +## Step 4 — (Optional) Adjust the ranking: /modelRank and /modelRank-chat + +Step 3 already persisted a base ranking from your wizard picks; this step is for adjusting it later. By default, model capability comes from an automatic cascade (live third-party index → bundled snapshot → curated table). If you disagree — your workload, your ranking. **TUI**: run `/modelRank` — a dialog listing every model by effective capability, manual entries interleaved with base-score models; move a model up/down to anchor it a manual score between its new neighbors (one-spot nudges), or pin it to top / remove it from the ranking. @@ -93,9 +115,9 @@ By default, model capability comes from an automatic cascade (live third-party i > - Persisted to `~/.config/opencode/opencode-switchman/capability-rank.json` (order = strongest first); the file is hot-reloaded on change (mtime), instant effect, sidebar refreshes immediately. The `[LIMITS]` banner reports it as `manual capability rank: N models`. > - CLI alternative: `node <pkg>/dist/switchman-config.js rank list|set|add|remove|clear`. -## Step 4 — (Optional) Curate task pools: /poolConfig and /poolConfig-chat +## Step 5 — (Optional) Curate task pools: /poolConfig and /poolConfig-chat -Dispatches land in one of six task pools — `economy` / `mechanical` / `main` / `hard` / `vision` / `review`. By default each pool considers every activated model, sorted by capability. Curation makes each pool deliberately different (lightweights only for economy, heavy thinkers only for hard). +Dispatches land in one of six task pools — `economy` / `mechanical` / `main` / `hard` / `vision` / `review`. Step 3 already configured them; this step is for later re-curation — replacing candidates after a provider change, or making each pool deliberately different (lightweights only for economy, heavy thinkers only for hard). **TUI**: run `/poolConfig` — pick a pool, then toggle models in/out of it. @@ -114,7 +136,7 @@ Dispatches land in one of six task pools — `economy` / `mechanical` / `main` / > - Persisted to `~/.config/opencode/opencode-switchman/pool-config.json` (key = pool name, value = model array); hot-reloaded on change, instant effect. The `[LIMITS]` banner reports it as `task-pool selection: M pools`. > - CLI alternative: `node <pkg>/dist/switchman-config.js pool list|add|remove|set|clear` (pool name = economy/mechanical/main/hard/vision/review). -## Step 5 — Restart, verify, and watch it route +## Step 6 — Restart, verify, and watch it route 1. **Restart opencode** (required after Step 1 config edits; harmless otherwise). 2. **Check the banner** — every system prompt of your primary model now carries the live `[ROUTES]` / `[WATERMARK]` / `[LIMITS]` block. `[ROUTES]` shows the six lane chains; `[LIMITS]` reports your manual overrides (`manual capability rank: N models, task-pool selection: M pools`). @@ -136,6 +158,8 @@ That's it — from here just use opencode normally. Your primary model is now a | `/connect` | TUI & app | Provider credentials | Models of credentialed providers join the selectable surface (restart after `opencode.json` edits) | opencode auth layer (plugin reads it read-only) | | `ctrl+f` in the model picker (`/models`) | TUI | Favorites = CLI/TUI activation surface; same-tier preferred | Immediately (recompute + probe refresh) | opencode state (`model.json`), synced with the app | | Model-management toggles | Desktop app | Visible set = app activation surface; synced with TUI favorites | Immediately (recompute + probe refresh) | opencode state (`opencode.global.dat`), synced with the TUI | +| `/switchman-setup` | TUI | Guided one-pass setup: all 6 task pools + capability ranking (required — dispatch blocked until complete) | Immediately (hot reload) | `~/.config/opencode/opencode-switchman/pool-config.json` + `capability-rank.json` | +| `/switchman-setup-chat` | TUI & app | Same as `/switchman-setup`, conversational | Immediately (hot reload) | Same files as `/switchman-setup` | | `/modelRank` | TUI | Manual capability ranking, overrides base scores | Immediately (hot reload) | `~/.config/opencode/opencode-switchman/capability-rank.json` | | `/modelRank-chat` | TUI & app | Same as `/modelRank`, conversational | Immediately (hot reload) | Same file as `/modelRank` | | `/poolConfig` | TUI | Per-pool candidate lists, replace pool defaults | Immediately (hot reload) | `~/.config/opencode/opencode-switchman/pool-config.json` | diff --git a/docs/quick-start.zh.md b/docs/quick-start.zh.md index 3a2af4e..aa01eb7 100644 --- a/docs/quick-start.zh.md +++ b/docs/quick-start.zh.md @@ -1,4 +1,4 @@ -# 快速上手 — 五步从零到矩阵路由 +# 快速上手 — 六步从零到矩阵路由 **[English](./quick-start.md)** | 中文 @@ -6,13 +6,14 @@ > **在哪里配置**:**先用 CLI/TUI**——弹窗、侧边栏面板与实时横幅等操作面在 TUI 里最完整。之后可选换用**桌面 app**;两端共享同一份配置与状态,下述所有手动覆盖在任一端都能操作。 -五个步骤: +六个步骤: 1. [连接 provider](#step-1)——给 opencode 凭证,让模型可用 2. [挑选参与编排的模型](#step-2)——TUI 收藏、app 开关 -3. [自己排能力名次(可选)](#step-3)——`/modelRank` / `/modelRank-chat` -4. [定制任务池(可选)](#step-4)——`/poolConfig` / `/poolConfig-chat` -5. [重启、验证、观察路由](#step-5)——横幅、侧栏、`/switchman-doctor` +3. [引导式配置(必做)](#step-3)——`/switchman-setup` / `/switchman-setup-chat` +4. [调整能力排名(可选)](#step-4)——`/modelRank` / `/modelRank-chat` +5. [定制任务池(可选)](#step-5)——`/poolConfig` / `/poolConfig-chat` +6. [重启、验证、观察路由](#step-6)——横幅、侧栏、`/switchman-doctor` --- @@ -72,9 +73,30 @@ > - 收藏还带路由语义:同一能力档内,收藏的模型在链中优先。 > - 启用面变化(收藏增删、开关切换)会立即触发重算与探针刷新——这一步无需重启。 -## <a id="step-3"></a>Step 3 —(可选)自己排能力名次:/modelRank 与 /modelRank-chat +## <a id="step-3"></a>Step 3 —(必做)引导式配置:/switchman-setup 与 /switchman-setup-chat -默认模型能力来自自动级联(实时第三方指数 → 内置快照 → 策展表)。不同意?你的工作负载你说了算。 +未配置的任务池不再回落到「全部模型参与」。在配置完成之前——六个任务池(`economy` / `mechanical` / `main` / `hard` / `vision` / `review`)**每池至少选了一个模型**,且能力排名**至少有一条**——**任务派发会被硬性拦截**。配置向导一次引导帮你跑完全程。 + +**TUI**:运行 `/switchman-setup`。 + +1. **首页**——显示当前状态(已配置池数 n/6、排名缺失与否);「开始」直接跳到第一个未完成的步骤,向导随时可续。 +2. **六个任务池弹窗**(economy → mechanical → main → hard → vision → review)——逐池多选模型:Enter 在内存中切换 `[x]`/`[ ]` 标记,每行展示能力档,内置全选 / 全部取消与返回上一池;每池「确认」即刻落盘(每池至少一个模型),每次保存都热加载运行中的插件,向导逐池可续。 +3. **排名**——按能力强到弱逐个点选排名模型(至少一个);候选恰好是你在各池选入模型的并集。「完成」落盘排名。 +4. **完成页**——各池汇总与排名次序。配置即刻生效(热加载);页面同时点名仍需重启的 provider(仅限 opencode 尚未注册的全新 provider)。 + +**会话式**(TUI 与桌面 app):运行 `/switchman-setup-chat`——对话里走同样的引导流程:agent 展示当前池/排名状态,逐池询问哪些模型入选(多选提问),再询问能力强到弱的排名,通过内置 CLI 逐条落盘,最后校验六池加排名全部就绪才收尾。 + +配置未完成期间,主会话每轮携带 `[SETUP]` 提示、引导模型指引用户打开向导,每次任务派发也会以同样指引被拒绝。该门槛叠加在首跑语言询问之上:语言未配置前,语言闸是拦截任务调用的唯一声音。最后一个配置文件写入的瞬间门槛即开——mtime 热加载,无需重启。 + +> **生效范围与条件** +> - 门槛范围:仅主会话——被派发的壳子代理与内部会话永不被拦。没有豁免开关:唯一通路就是完成配置(或直接手改下列文件)。 +> - 文件:向导写入的与 Step 4–5 相同的 `~/.config/opencode/opencode-switchman/pool-config.json` + `capability-rank.json`——可安全手改,保存即热加载(横幅 `[LIMITS]` 行标注 `task-pool selection: M pools` / `manual capability rank: N models`)。 +> - 不知道怎么选?合理默认:economy = 便宜快速的模型,mechanical = 中坚主力,main = 最强通才,hard = 最强推理,vision = 支持图像的模型,review = 与 main 池链首不同家族的模型(跨家族评审优先)。 +> - CLI 直操作:`node <包目录>/dist/switchman-config.js pool list|set …` + `rank list|set …`(同文件、同热加载)。 + +## <a id="step-4"></a>Step 4 —(可选)调整能力排名:/modelRank 与 /modelRank-chat + +Step 3 已根据向导选择落盘了基础排名;这一步用于之后的调整。默认模型能力来自自动级联(实时第三方指数 → 内置快照 → 策展表)。不同意?你的工作负载你说了算。 **TUI**:运行 `/modelRank`——弹窗按有效能力列出所有模型,手动条目与基础分模型交错;上移/下移会给模型锚定一个介于新上下邻居之间的手动分(一次挪一格),另有置顶/移出排名。 @@ -93,9 +115,9 @@ > - 落盘于 `~/.config/opencode/opencode-switchman/capability-rank.json`(数组顺序 = 能力降序);文件改动 mtime 热加载、即时生效,侧栏同步刷新。横幅 `[LIMITS]` 行标注 `manual capability rank: N models`。 > - CLI 直操作:`node <包目录>/dist/switchman-config.js rank list|set|add|remove|clear`。 -## <a id="step-4"></a>Step 4 —(可选)定制任务池:/poolConfig 与 /poolConfig-chat +## <a id="step-5"></a>Step 5 —(可选)定制任务池:/poolConfig 与 /poolConfig-chat -派发会落入六个任务池之一——`economy` / `mechanical` / `main` / `hard` / `vision` / `review`。默认每池考虑全部启用模型并按能力排序;定制能让各池**体现差异化**(economy 只配轻量模型、hard 只配重思考模型)。 +派发会落入六个任务池之一——`economy` / `mechanical` / `main` / `hard` / `vision` / `review`。Step 3 已完成配置;这一步用于之后的重新定制——provider 变化后替换候选,或让各池**体现差异化**(economy 只配轻量模型、hard 只配重思考模型)。 **TUI**:运行 `/poolConfig`——先选任务池,再逐个勾选/取消模型。 @@ -114,7 +136,7 @@ > - 落盘于 `~/.config/opencode/opencode-switchman/pool-config.json`(键 = 池名,值 = 模型数组);改动热加载、即时生效。横幅 `[LIMITS]` 行标注 `task-pool selection: M pools`。 > - CLI 直操作:`node <包目录>/dist/switchman-config.js pool list|add|remove|set|clear`(池名 = economy/mechanical/main/hard/vision/review)。 -## <a id="step-5"></a>Step 5 — 重启、验证、观察路由 +## <a id="step-6"></a>Step 6 — 重启、验证、观察路由 1. **重启 opencode**(Step 1 改过配置文件后必须;其余情况重启也无害)。 2. **看横幅**——主模型每轮系统提示现在携带实时 `[ROUTES]` / `[WATERMARK]` / `[LIMITS]` 块。`[ROUTES]` 展示六档链;`[LIMITS]` 报告你的手动覆盖(`manual capability rank: N models, task-pool selection: M pools`)。 @@ -136,6 +158,8 @@ | `/connect` | TUI & app | provider 凭证 | 有凭证 provider 的模型进入可选面(改 `opencode.json` 后需重启) | opencode auth 层(插件只读) | | 模型选择器内 `ctrl+f`(`/models`) | TUI | 收藏 = CLI/TUI 启用面;同档内优先 | 即时(重算 + 探针刷新) | opencode 状态(`model.json`),与 app 双向同步 | | 「管理模型」开关 | 桌面 app | 可见集 = app 启用面;与 TUI 收藏同步 | 即时(重算 + 探针刷新) | opencode 状态(`opencode.global.dat`),与 TUI 双向同步 | +| `/switchman-setup` | TUI | 引导式一次配齐:6 个任务池 + 能力排名(必做——完成前派发被拦截) | 即时(热加载) | `~/.config/opencode/opencode-switchman/pool-config.json` + `capability-rank.json` | +| `/switchman-setup-chat` | TUI & app | 同 `/switchman-setup`,会话式 | 即时(热加载) | 与 `/switchman-setup` 同文件 | | `/modelRank` | TUI | 手动能力排名,压过基础分 | 即时(热加载) | `~/.config/opencode/opencode-switchman/capability-rank.json` | | `/modelRank-chat` | TUI & app | 同 `/modelRank`,会话式 | 即时(热加载) | 与 `/modelRank` 同文件 | | `/poolConfig` | TUI | 各任务池候选清单,替换池默认 | 即时(热加载) | `~/.config/opencode/opencode-switchman/pool-config.json` | diff --git a/docs/reference.md b/docs/reference.md index 8f13a85..ab3047f 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -175,7 +175,14 @@ Since TUI plugins have no directory auto-discovery, add the same package spec to ## Manual overrides -Two manual commands let your configuration beat system defaults. All state is persisted to editable files with mtime hot-reload and instant effect — edits trigger an immediate banner/sidebar refresh via a directory watcher. The conversational (AI-driven) variants are the same names with a `-chat` suffix. Introduced in v0.2.5. +Manual commands let your configuration beat system defaults. All state is persisted to editable files with mtime hot-reload and instant effect — edits trigger an immediate banner/sidebar refresh via a directory watcher. The conversational (AI-driven) variants are the same names with a `-chat` suffix. /poolConfig and /modelRank arrived in v0.2.5; /switchman-setup in v1.2.0. + +### /switchman-setup — guided first-run setup (manual wizard; conversational: /switchman-setup-chat) + +- **TUI (/switchman-setup)**: a resumable one-pass wizard — an intro with the live completion state (Start jumps to the first unfinished step), one multi-select dialog per task pool in lane order (Enter toggles `[x]`/`[ ]`, capability tier per row, select-all/clear-all/back, the per-pool confirm persists immediately with a minimum of one model), then a sequential strongest-first ranking pick over exactly the union of the selected models (minimum one), then a done screen with the per-pool summary, the ranking order, and any providers still flagged restartRequired. +- **Non-TUI / in-session (/switchman-setup-chat)**: the same flow conversationally — the agent shows the current pool/rank state, asks multi-select questions pool by pool, asks for the strongest-first ranking, persists via the bundled CLI, and verifies completion before closing. +- **Semantics — the setup hard gate**: unconfigured task pools no longer default to "all models". Until all six pools have ≥1 selected model and the ranking has ≥1 entry, task dispatch is denied in main sessions with guidance toward the wizard; main sessions also carry a `[SETUP]` directive each turn while incomplete. Shells/internal sessions are exempt and there is no waiver flag. The gate rides on the language gate: before the project language preference is configured, the language ask stays the single blocking voice. Config is mtime hot-reloaded — the gate opens the moment the last file is saved, no restart (a restart only registers brand-new providers). +- **Config files**: the same `pool-config.json` + `capability-rank.json` as /poolConfig and /modelRank below. ### /poolConfig — per-lane model assignment (manual dialog; conversational: /poolConfig-chat) @@ -203,7 +210,7 @@ Two manual commands let your configuration beat system defaults. All state is pe - Behavior: dispatches the requirement to the strongest available expert — the head of the **review** chain (cross-family expert seat, read-only shell); when the review pool has no available candidate, it falls back to the head of the **hard** chain on its read-only (`-ro`) shell and declares `DOWNGRADED`. - The expert's conclusions are relayed in full, ending with one line naming the shell and lane used (e.g. `expert: <shell> (review)`). -Both commands can also be driven directly via the bundled CLI: `node <pkg>/dist/switchman-config.js pool list|add|remove|set|clear` (pool name = economy/mechanical/main/hard/vision/review) / `rank list|set|add|remove|clear` (numbers refer to the `list` output). The `[LIMITS]` banner line reports active overrides ("manual rank: N models / task-pool assignment: M pools"). +All of these can also be driven directly via the bundled CLI: `node <pkg>/dist/switchman-config.js pool list|add|remove|set|clear` (pool name = economy/mechanical/main/hard/vision/review) / `rank list|set|add|remove|clear` (numbers refer to the `list` output). The `[LIMITS]` banner line reports active overrides ("manual rank: N models / task-pool assignment: M pools"). ## Core ideas @@ -230,7 +237,7 @@ opencode-switchman splits orchestration into three layers: | Lane | Typical roles | Uses | |---|---|---| -| economy | clerk / scouter scanning | cheapest lightweight model, low→medium→high effort | +| economy | clerk / scouter scanning | cheapest lightweight model, medium→high→low→minimal effort (first supported wins) | | mechanical | tester / ops regression & scripts | lightweight model, medium→high→xhigh→max effort | | main | programmer / uiux / data-analyst | workhorse model, medium→high→xhigh→max effort | | hard | planner, core architecture | strongest model, high→xhigh→max effort | diff --git a/docs/reference.zh.md b/docs/reference.zh.md index d99b7d5..c55ed84 100644 --- a/docs/reference.zh.md +++ b/docs/reference.zh.md @@ -175,7 +175,14 @@ TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** ## 手动覆盖层 -两个手动配置命令让你用配置压过系统默认决策,全部状态落盘、可手改、保存即热加载(mtime 感知,即时生效,侧栏同步刷新)。会话式(AI 交互换算 CLI)版本为同名的 `-chat` 后缀命令。v0.2.5 新增。 +手动配置命令让你用配置压过系统默认决策,全部状态落盘、可手改、保存即热加载(mtime 感知,即时生效,侧栏同步刷新)。会话式(AI 交互换算 CLI)版本为同名的 `-chat` 后缀命令。/poolConfig 与 /modelRank 于 v0.2.5 引入;/switchman-setup 于 v1.2.0 引入。 + +### /switchman-setup —— 引导式首次配置(手动向导;会话式用 /switchman-setup-chat) + +- **TUI(/switchman-setup)**:可续跑的一站式向导——首页展示实时完成状态(「开始」直达第一个未完成步骤),按车道序逐池弹出多选框(Enter 切换 `[x]`/`[ ]`,每行标注能力档,含全选/全部取消/返回,每池确认即刻落盘、每池至少一个模型),随后在入选模型并集上按能力强到弱逐个点选排名(至少一个),完成页汇总各池选配、排名次序与仍需重启的 provider。 +- **非 TUI / 会话内(/switchman-setup-chat)**:同流程会话式——agent 展示当前池/排名状态,逐池多选提问,询问能力强到弱的排名,经内置 CLI 落盘,校验六池加排名齐备后收尾。 +- **语义——配置硬门槛**:未配置的任务池不再默认「全部模型参与」。六池各有 ≥1 模型且排名 ≥1 条之前,主会话的任务派发被拒并附向导指引;未完成期间主会话每轮携带 `[SETUP]` 指令。壳/内部会话豁免,且无豁免开关。门槛叠加于语言闸:项目语言偏好未配置前,语言询问保持唯一拦截声音。配置 mtime 热加载——最后一个文件保存的瞬间门槛即开,无需重启(重启只为注册全新 provider)。 +- **配置文件**:与下方 /poolConfig、/modelRank 相同的 `pool-config.json` + `capability-rank.json`。 ### /poolConfig —— 任务池选配(手动弹窗;会话式用 /poolConfig-chat) @@ -203,7 +210,7 @@ TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** - 行为:把需求派发给当前最强的可用专家——优先 **review** 链头(跨家族专家席位,只读壳);review 池无可用候选时降级到 **hard** 链头的只读(`-ro`)壳,并声明 `DOWNGRADED`。 - 专家结论完整转述,末尾注明所用壳与车道(如 `expert: <shell> (review)`)。 -两命令亦可用随包 CLI 直操作:`node <包目录>/dist/switchman-config.js pool list|add|remove|set|clear`(池名=economy/mechanical/main/hard/vision/review)/ `rank list|set|add|remove|clear`(编号引用 `list` 输出)。横幅 `[LIMITS]` 行会标注当前生效的手动覆盖(「manual capability rank: N models / task-pool selection: M pools」)。 +上述命令亦可用随包 CLI 直操作:`node <包目录>/dist/switchman-config.js pool list|add|remove|set|clear`(池名=economy/mechanical/main/hard/vision/review)/ `rank list|set|add|remove|clear`(编号引用 `list` 输出)。横幅 `[LIMITS]` 行会标注当前生效的手动覆盖(「manual capability rank: N models / task-pool selection: M pools」)。 ## 核心思想 @@ -230,7 +237,7 @@ opencode-switchman 把编排拆成三层,各司其职: | 档位 | 典型角色 | 用什么 | |---|---|---| -| economy | clerk / scouter 扫描清点 | 最便宜的轻量模型,low→medium→high 档 | +| economy | clerk / scouter 扫描清点 | 最便宜的轻量模型,medium→high→low→minimal 档(先支持哪个用哪个) | | mechanical | tester / ops 回归与脚本 | 轻量模型,medium→high→xhigh→max 档 | | main | programmer / uiux / data-analyst | 主力模型,medium→high→xhigh→max 档 | | hard | planner 架构核心 | 最强模型,high→xhigh→max 档 | diff --git a/package.json b/package.json index 19297a7..4f9be25 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-switchman", - "version": "1.1.1", + "version": "1.2.0", "description": "OpenCode orchestration plugin: six-lane shell matrix dispatch (hard ROUTE_META validation / breaker self-healing / probes / three-pool quota awareness / cost-aware tiebreaker)", "license": "MIT", "repository": { diff --git a/src/assets/agents-md.ts b/src/assets/agents-md.ts index 6b08f47..a1fcbf4 100644 --- a/src/assets/agents-md.ts +++ b/src/assets/agents-md.ts @@ -13,6 +13,8 @@ // opencode's default system prompt and nothing re-surfaced the list, so it was written once and never updated; pairs with the // plugin-injected [TODO] per-turn status line (index.ts sessionTodoLine)] // [2026-09-05]-[v1 read budget: §5 rewritten from one-time nudge semantics to always-on per-call budget; placeholders preserved] +// [2026-09-18]-[v1.1 anti-fragmentation: §5 budget sentence gains the one-shot headroom grant (reads up to the remaining +// per-turn headroom land in one bounded read) and the continuation-completion rule — matches src/context-watch.ts] // [2026-09-14]-[shell handoff relay §2 item 5 + §6 declaration widening: D1's soft tiers end with the inline HANDOFF marker the // dispatcher must treat as the authoritative remaining-work state; §6's declaration duty moves from a major-action list to // every substantive action, matching the per-turn [ROUTE] line (src/route-line.ts)] @@ -72,7 +74,7 @@ Task artifacts (plans, implementation progress, process-control notes, design do - Logic changes must be verified once; changes >20 lines, multiple call sites, or long output → hand to tester; >300 lines or core/security/data logic → reviewer re-review (review chain, cross-family preferred — same-family self-review only as a last-resort DOWNGRADED seat). ## 5. Self-read Budget and Broad-Search Clarify (always on, every turn) -Each self-read is costed against a per-call injection budget (default ~1500 tokens; the live cap rides the \`[WATERMARK:SESSION]\` banner line). Reads over the cap are auto-bounded or rejected with exact bounded-retry params (\`read <file> limit=N offset=M\`); once the per-turn self-read cap is spent, delegate the turn's remaining reads to an economy shell. Watermarks are lifecycle advice only: past {{SOFT}} prefer delegating new scans; past {{HARD}} wrap up (verification/delivery bash stays open; state-changing git is delivery — run it yourself, never delegate it); at {{FORCE}} compact immediately. Unbounded history dumps (e.g. \`git log -p\` without \`-n\`) are rejected at any context size — scope them or delegate. +Each self-read is costed against a per-call injection budget (default ~1500 tokens; the live cap rides the \`[WATERMARK:SESSION]\` banner line). Reads up to the remaining per-turn headroom (~2× the per-call budget) are granted one-shot — request the exact range you need in a single bounded read instead of fragmenting; reads over the headroom are auto-bounded or rejected with exact bounded-retry params (\`read <file> limit=N offset=M\`), and a follow-up read resuming where the granted window ended completes the original range in one shot. Once the per-turn self-read cap is spent, delegate the turn's remaining reads to an economy shell. Watermarks are lifecycle advice only: past {{SOFT}} prefer delegating new scans; past {{HARD}} wrap up (verification/delivery bash stays open; state-changing git is delivery — run it yourself, never delegate it); at {{FORCE}} compact immediately. Unbounded history dumps (e.g. \`git log -p\` without \`-n\`) are rejected at any context size — scope them or delegate. Broad-search clarify: the session's first whole-project search (glob \`**\` without a path scope, pathless grep, or recursive rg/grep -r/find/fd at the project root) is denied once by the plugin with an ask-first error — relay that marker question to the user verbatim (more precise file/directory guidance?). With narrower guidance, redo the search scoped to it (never silently widen back to whole-project while that scope holds); without guidance or on a decline, retry the same call (it passes once the ask completed). Retrying the search without asking is a violation. Disable via jsonc \`search.clarify:false\`. ## 6. Major-Action Reporting and the Expert Panel diff --git a/src/banner.ts b/src/banner.ts index 5907a7c..152e518 100644 --- a/src/banner.ts +++ b/src/banner.ts @@ -28,8 +28,11 @@ export interface BannerInput { doctorSummary?: string | null /** [2026-08-29]-[dynamic matrix: [LIMITS] line appends mode/watch/configStatus, restartRequired, models.dev downgrade marks; absent = legacy as-is] */ matrixInfo?: { mode: string; configStatus: string; watch: boolean; restartRequired?: string[]; invalidConfigured?: string[]; degradedModels?: number; retiredModels?: number } | null - /** [2026-09-03]-[user manual override annotations (effective entries in capability-rank.json/pool-config.json; 0 = unconfigured, not shown)] */ - overrides?: { rankModels: number; poolLanes: number } | null + /** [2026-09-03]-[user manual override annotations (effective entries in capability-rank.json/pool-config.json; 0 = unconfigured, not shown)] + * [2026-09-19]-[setup: live setup completion (all 6 task pools + capability rank); while incomplete the [LIMITS] + * line carries a setup-required segment (dispatch is denied until /switchman-setup completes); null/absent or + * complete → nothing shown] */ + overrides?: { rankModels: number; poolLanes: number; setup?: { configuredLanes: number; missingRank: boolean; complete: boolean } | null } | null } function routeLine(lanes: Record<string, LaneResult> | null): string { @@ -125,11 +128,30 @@ export interface ProviderStatusRow { usedPct: number | null /** weakened tail supplement (reset/refresh time, warning) */ tail?: string + /** [2026-09-19]-[P4 render-time i18n: key+params is the future quota-brief render source (t(locale, key, params) + * against the quota.* catalog in src/locales/en.ts; label/text/tail keep emitting the same English as now + * (debug/legacy until the TUI migration renders via key). No import of src/i18n.ts here on purpose — + * banner stays decoupled from the locale catalogs; key is a plain string like StatusLogEntry.key] */ + key?: string + /** render params; names match the catalog template placeholders exactly ({bar8},{pct},{usedSuffix},{usage},…) */ + params?: Record<string, string | number> + /** [2026-09-19]-[quota i18n labels/tails: labelKey renders the row label via quota.row5h/rowWeek/rowMcp/rowCredits/ + * rowBalance (no params; rowRefresh stays as the main key since the refresh text is raw data); tailKey renders + * the tail via quota.resetLater/resetTime/resetDate/resetDateTime/balanceWarn with exact catalog params + * ({hhmm}/{mmdd}/{thr}); legacy label/tail strings unchanged] */ + labelKey?: string + labelParams?: Record<string, string | number> + tailKey?: string + tailParams?: Record<string, string | number> } export interface ProviderStatusEntry { pool: "glm" | "copilot" | "deepseek" label: string + /** [2026-09-19]-[quota i18n pool labels: key renders the block label via quota.poolGlm/poolCopilot/poolDeepSeek + * (params empty); legacy label string unchanged] */ + key?: string + params?: Record<string, string | number> rows: ProviderStatusRow[] /** observe only (routing=false, not part of dispatch ranking) */ observeOnly: boolean @@ -163,54 +185,80 @@ function resetParts(reset: number | null | undefined): { md: string; hm: string // ---- sidebar rows output ([WATERMARK] banner glmBrief/copilotBrief/dsBrief compact single-line format unchanged)---- -const NO_DATA_ROW: ProviderStatusRow[] = [{ label: "", text: "querying/no data", usedPct: null }] +const NO_DATA_ROW: ProviderStatusRow[] = [{ label: "", text: "querying/no data", usedPct: null, key: "quota.queryingNoData" }] function glmRows(data: GlmQuota | null): ProviderStatusRow[] { if (!data || data.status !== "ok") return NO_DATA_ROW const rows: ProviderStatusRow[] = [] + // [2026-09-19]-[P4 render-time i18n: bar rows carry quota.barPct + exact {bar8},{pct} params (t() reproduces text + // verbatim in English); label ("5h"/"week"/"MCP") and tail ("→…") keep English legacy — one key slot holds the + // primary body, label/tail catalog keys (quota.row*, quota.reset*) are consumed by the TUI phase] + // [2026-09-19]-[quota i18n labels/tails: push now also fills labelKey (quota.row5h/rowWeek/rowMcp) and tailKey+ + // tailParams (quota.resetLater with no params, quota.resetTime {hhmm}, quota.resetDate {mmdd}, + // quota.resetDateTime {mmdd,hhmm}); legacy label/tail strings byte-identical] + const ROW_LABEL_KEY: Record<string, string> = { "5h": "quota.row5h", week: "quota.rowWeek", MCP: "quota.rowMcp" } const push = (label: string, pct: number, reset: number | null | undefined, mode: "hm" | "mdhm" | "md") => { const parts = resetParts(reset) const tail = !parts ? "→later" : mode === "hm" ? `→${parts.hm}` : mode === "md" ? `→${parts.md}` : `→${parts.md} ${parts.hm}` - rows.push({ label, text: `${bar8(pct)} ${pct}%`, usedPct: pct, tail }) + const tailKey = !parts ? "quota.resetLater" : mode === "hm" ? "quota.resetTime" : mode === "md" ? "quota.resetDate" : "quota.resetDateTime" + const tailParams: Record<string, string | number> | undefined = !parts ? undefined + : mode === "hm" ? { hhmm: parts.hm } + : mode === "md" ? { mmdd: parts.md } + : { mmdd: parts.md, hhmm: parts.hm } + const bar = bar8(pct) + rows.push({ label, text: `${bar} ${pct}%`, usedPct: pct, tail, key: "quota.barPct", params: { bar8: bar, pct }, labelKey: ROW_LABEL_KEY[label], ...(tailParams ? { tailKey, tailParams } : { tailKey }) }) } // 5h window always resets within 5 hours → HH:mm only; weekly window spans days → MM-DD HH:mm; MCP monthly → MM-DD if (typeof data.five_hour?.used_pct === "number") push("5h", data.five_hour.used_pct, data.five_hour.reset_at, "hm") if (typeof data.weekly?.used_pct === "number") push("week", data.weekly.used_pct, data.weekly.reset_at, "mdhm") const mcp = data.mcp_monthly if (mcp && typeof mcp.used_pct === "number") push("MCP", mcp.used_pct, mcp.reset_at, "md") - if (rows.length === 0) return [{ label: "", text: "no quota data", usedPct: null }] + if (rows.length === 0) return [{ label: "", text: "no quota data", usedPct: null, key: "quota.noData" }] return rows } function copilotRows(data: CopilotQuota | null): ProviderStatusRow[] { if (!data || data.status !== "ok") return NO_DATA_ROW - const refresh: ProviderStatusRow = { label: "refresh", text: data.reset_date ?? "?", usedPct: null } - if (data.gateway_exhausted) return [{ label: "credits", text: "monthly pool exhausted", usedPct: 100 }, refresh] + // [2026-09-19]-[P4 render-time i18n: the refresh row's text is raw data (a date, no catalog key), so it carries the + // label key quota.rowRefresh (no params); the date itself stays data in the legacy text field, never translated] + // [2026-09-19]-[quota i18n labels: credits rows gain labelKey quota.rowCredits (no params); the refresh row keeps + // quota.rowRefresh as its main key with no labelKey slot; legacy label/text byte-identical] + const refresh: ProviderStatusRow = { label: "refresh", text: data.reset_date ?? "?", usedPct: null, key: "quota.rowRefresh" } + if (data.gateway_exhausted) return [{ label: "credits", text: "monthly pool exhausted", usedPct: 100, key: "quota.monthlyExhausted", labelKey: "quota.rowCredits" }, refresh] const p = data.premium - if (!p) return [{ label: "", text: "no quota data", usedPct: null }] + if (!p) return [{ label: "", text: "no quota data", usedPct: null, key: "quota.noData" }] if (p.unlimited) { const used = typeof p.used === "number" ? `, used ${p.used}` : "" - return [{ label: "credits", text: `unlimited${used}`, usedPct: null }, refresh] + return [{ label: "credits", text: `unlimited${used}`, usedPct: null, key: "quota.unlimited", params: { usedSuffix: used }, labelKey: "quota.rowCredits" }, refresh] } const pct = p.percent_remaining const usedPct = typeof pct === "number" ? Math.max(0, Math.min(100, 100 - pct)) : null const quotaTxt = typeof p.used === "number" && typeof p.entitlement === "number" ? ` ${p.used}/${p.entitlement}` : "" if (typeof pct === "number" && pct <= 0 && p.overage_permitted) { - return [{ label: "credits", text: `exhausted·overage billing${quotaTxt}`, usedPct: 100 }, refresh] + return [{ label: "credits", text: `exhausted·overage billing${quotaTxt}`, usedPct: 100, key: "quota.exhaustedOverage", params: { usage: quotaTxt }, labelKey: "quota.rowCredits" }, refresh] } const pctTxt = typeof pct === "number" ? (Number.isInteger(pct) ? pct : pct.toFixed(1)) : "?" - return [{ label: "credits", text: `${bar8(usedPct)} ${pctTxt}% left${quotaTxt}`, usedPct }, refresh] + const bar = bar8(usedPct) + return [{ label: "credits", text: `${bar} ${pctTxt}% left${quotaTxt}`, usedPct, key: "quota.barPctLeft", params: { bar8: bar, pctTxt, usage: quotaTxt }, labelKey: "quota.rowCredits" }, refresh] } function dsRows(data: DeepseekQuota | null, lowWarnCny?: number): ProviderStatusRow[] { if (!data || data.status !== "ok") return NO_DATA_ROW - if (data.exhausted) return [{ label: "balance", text: "exhausted", usedPct: 100 }] + if (data.exhausted) return [{ label: "balance", text: "exhausted", usedPct: 100, key: "quota.exhausted", labelKey: "quota.rowBalance" }] const cny = dsBalanceCny(data) - if (cny === null) return [{ label: "balance", text: "unknown (pay-as-you-go)", usedPct: null }] + if (cny === null) return [{ label: "balance", text: "unknown (pay-as-you-go)", usedPct: null, key: "quota.unknownPayg", labelKey: "quota.rowBalance" }] const thr = typeof lowWarnCny === "number" && lowWarnCny >= 0 ? lowWarnCny : 10 // pay-as-you-go has no "total" concept: use 3× the warning threshold as the "ample balance" anchor for a relative gradient, coloring only, not a precise metric + // [2026-09-19]-[P4 render-time i18n: balance row carries quota.barBalance + exact {bar8},{balance} params; the low- + // balance tail keeps English legacy (quota.balanceWarn + {thr} is consumed by the TUI phase — one key slot holds + // the primary body)] + // [2026-09-19]-[quota i18n labels/tails: balance rows gain labelKey quota.rowBalance (no params); the low-balance + // warn tail gains tailKey quota.balanceWarn + tailParams {thr}; legacy label/text/tail byte-identical] const usedPct = Math.max(0, Math.min(100, 100 - (cny / (thr * 3)) * 100)) - return [{ label: "balance", text: `${bar8(usedPct)} ¥${cny.toFixed(2)}`, usedPct, tail: cny < thr ? ` (<¥${thr} warn)` : undefined }] + const bar = bar8(usedPct) + const balance = cny.toFixed(2) + const warn = cny < thr + return [{ label: "balance", text: `${bar} ¥${balance}`, usedPct, tail: warn ? ` (<¥${thr} warn)` : undefined, key: "quota.barBalance", params: { bar8: bar, balance }, labelKey: "quota.rowBalance", ...(warn ? { tailKey: "quota.balanceWarn", tailParams: { thr } } : {}) }] } export interface ProviderStatusInput { @@ -223,6 +271,9 @@ export interface ProviderStatusInput { export function providerStatusEntries(input: ProviderStatusInput): ProviderStatusEntry[] { const out: ProviderStatusEntry[] = [] + // [2026-09-19]-[quota i18n pool labels: block entries carry key quota.poolGlm/poolCopilot/poolDeepSeek (params empty); + // legacy label strings byte-identical; model-facing banner lines untouched] + const POOL_KEY: Record<"glm" | "copilot" | "deepseek", string> = { glm: "quota.poolGlm", copilot: "quota.poolCopilot", deepseek: "quota.poolDeepSeek" } for (const pool of ["glm", "copilot", "deepseek"] as const) { const policy = input.providerPolicy?.[pool] if (policy?.observe === false) continue // observe:false → skip this block @@ -241,6 +292,8 @@ export function providerStatusEntries(input: ProviderStatusInput): ProviderStatu out.push({ pool, label: POOL_LABEL[pool], + key: POOL_KEY[pool], + params: {}, rows, observeOnly: policy ? policy.routing === false : false, peakActive: input.peakOf ? Boolean(input.peakOf(POOL_PROVIDER_ID[pool])) : false, @@ -305,8 +358,16 @@ function limitLine(down: Set<string> | string[] | Map<string, string>, unknownCo const parts: string[] = [] if (overrides.rankModels > 0) parts.push(`manual capability rank: ${overrides.rankModels} models`) if (overrides.poolLanes > 0) parts.push(`task-pool selection: ${overrides.poolLanes} pools`) + // [2026-09-18]-[rank universe = pool selection: surface the scoping so users see /modelRank only ranks pool-selected models + const universe = (overrides as { universeModels?: number }).universeModels + if (universe !== undefined && universe > 0) parts.push(`rankable universe: ${universe} models`) line += ` | ${parts.join(", ")} active (/modelRank /poolConfig to adjust)` } + // [2026-09-19]-[setup hard gate: appended after the overrides block so the actionable remedy reads last — dispatch is + // hard-blocked until /switchman-setup completes; silent once complete or when the input is absent]- + if (overrides?.setup && !overrides.setup.complete) { + line += ` | setup required: pools ${overrides.setup.configuredLanes}/${LANE_ORDER.length}${overrides.setup.missingRank ? ", rank missing" : ""} (/switchman-setup)` + } return line } diff --git a/src/breaker.ts b/src/breaker.ts index 86e4c84..44a07b7 100644 --- a/src/breaker.ts +++ b/src/breaker.ts @@ -13,10 +13,13 @@ const TAIL_BYTES = 262144 // NOTE: the Chinese hints below match inbound error text emitted by external systems (providers/opencode core), // not copy produced by this plugin; they are kept as-is on purpose during localization. const NOT_FOUND_HINTS = ["not found", "not_found", "未找到", "无法找到"] -export const REAL_FAIL_TTL_MS = 1_800_000 -// [2026-08-29]-[failure classification: transient 429 gets a short TTL vs the long TTL for real failures -- avoids rate-limit false positives lasting 30 minutes] +// [2026-09-19]-[real-fail isolation window 30m -> 5m: probe-ok-but-real-call-failed states are usually transient vendor +// blips and 30 minutes of head-of-chain lockout starved lanes far too long]-[isolation now lifts after 5 minutes; +// note RATE_LIMIT_TTL_MS stays 10m (longer than the default now) — 429 self-heal has its own explicit TTL path] +export const REAL_FAIL_TTL_MS = 300_000 +// [2026-08-29]-[failure classification: transient 429 gets a dedicated short-TTL path vs the default TTL for real failures -- avoids rate-limit false positives polluting the default isolation] export const RATE_LIMIT_TTL_MS = 600_000 -// [2026-09-01]-[endpoint-class permanent config-layer errors: retrying after 30 minutes is pointless, isolate with a 6h long TTL] +// [2026-09-01]-[endpoint-class permanent config-layer errors: retrying soon is pointless, isolate with a 6h long TTL] export const ENDPOINT_TTL_MS = 21_600_000 const realFailedCombos = new Map<string, number>() @@ -34,7 +37,8 @@ export function recordIsolation(agent: string, comboKey: string, category: strin const reason = `real-call isolation(${mins}m·${category}): ${reasonRaw.split(/\s+/).join(" ")}`.slice(0, 200) ensureStateDir() appendFileSync(paths().failures, `${JSON.stringify({ agent, key: comboKey, shell: agent, combo: comboKey, reason, ts: now, kind: "isolated" })}\n`) - appendStatusLog(`${agent} real-call isolated for ${mins}m (${category}): ${reasonRaw.slice(0, 60)}`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.breaker.realCallIsolated", { agent, mins, category, reason: reasonRaw.slice(0, 60) }) } catch { /* fail-open */ } } @@ -45,7 +49,7 @@ export function recordInjection(agent: string, reasonRaw: string): void { const reason = `shell not injected into opencode (no isolation): ${reasonRaw.split(/\s+/).join(" ")}`.slice(0, 200) ensureStateDir() appendFileSync(paths().failures, `${JSON.stringify({ agent, key: agent, shell: null, combo: null, reason, ts: now, kind: "injection" })}\n`) - appendStatusLog(`shell not injected into opencode (no isolation): ${agent} ${reasonRaw.slice(0, 60)}`) + appendStatusLog("notice.breaker.shellNotInjected", { agent, reason: reasonRaw.slice(0, 60) }) } catch { /* fail-open */ } } @@ -197,7 +201,7 @@ export function recordFailure( } return { key, tripped: false } } catch (exc) { - appendStatusLog(`breaker fail-open: ${exc}`) + appendStatusLog("notice.breaker.failOpen", { exc: String(exc) }) return { key: agent, tripped: false } } } diff --git a/src/capability.ts b/src/capability.ts index e2d95d1..248c6da 100644 --- a/src/capability.ts +++ b/src/capability.ts @@ -243,7 +243,8 @@ export function loadBundledCapability(): CapabilityIndex | null { if (bundledCache !== undefined) return bundledCache const v = bundledDefaultJson as unknown as CapabilityIndex bundledCache = validIndex(v) ? { ...v, bundled: true } : null - if (bundledCache === null) appendStatusLog("bundled capability rank snapshot corrupted (skipping, falling back to the curated table)") + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + if (bundledCache === null) appendStatusLog("notice.capability.snapshotCorrupted") return bundledCache } @@ -296,7 +297,7 @@ export async function refreshCapability(opts: CapabilityOptions): Promise<void> used = "artificial-analysis" version = deriveVersion("aa", r.etag, parsed.versionHint) } catch (exc) { - appendStatusLog(`capability index primary source AA failed (${exc})${wantOr ? " -> switching to backup source OpenRouter" : " -> keeping last-good/bundled default ranks"}`) + appendStatusLog("notice.capability.primarySourceFailed", { exc: String(exc), nextStep: wantOr ? " -> switching to backup source OpenRouter" : " -> keeping last-good/bundled default ranks" }) } } if (!parsed && wantOr) { @@ -308,12 +309,12 @@ export async function refreshCapability(opts: CapabilityOptions): Promise<void> used = "openrouter" version = deriveVersion("or", r.etag, parsed.versionHint) } catch (exc) { - appendStatusLog(`capability index backup source OpenRouter failed (${exc}) -> keeping last-good/bundled default ranks`) + appendStatusLog("notice.capability.backupSourceFailed", { exc: String(exc) }) } } if (!parsed || !used || Object.keys(parsed.models).length === 0) { // [2026-08-31]-[log empty parses: a silent return makes upstream believe the refresh succeeded (hit in smoke testing)] - appendStatusLog(`capability index parsed empty (${used ?? "no source"}) -> keeping last-good/bundled default ranks`) + appendStatusLog("notice.capability.parsedEmpty", { source: used ?? "no source" }) return } const scores = Object.values(parsed.models).map((e) => e.score) @@ -330,10 +331,10 @@ export async function refreshCapability(opts: CapabilityOptions): Promise<void> } mem = { dir: paths().dir, idx } writeJsonAtomic(paths().capability, idx) - appendStatusLog(`capability index refreshed: ${used} ${scores.length} models (version=${version})`) + appendStatusLog("notice.capability.refreshed", { source: used, modelCount: scores.length, version: String(version) }) if (opts.lmarenaCheck) crossCheckLmarena(idx).catch(() => {}) } catch (exc) { - appendStatusLog(`capability index refresh fail-open (keeping last-good/bundled default ranks): ${exc}`) + appendStatusLog("notice.capability.refreshFailOpen", { exc: String(exc) }) } } @@ -369,10 +370,10 @@ export async function crossCheckLmarena(idx: CapabilityIndex): Promise<void> { } const rate = pairs > 0 ? (agree / pairs) * 100 : 0 if (rate < 70) { - appendStatusLog(`capability LMArena cross-check: tier-order vs ELO-order agreement only ${rate.toFixed(0)}% (${both.length} overlapping models) -- data source may be anomalous, manual review advised`) + appendStatusLog("notice.capability.lmarenaDisagreement", { rate: rate.toFixed(0), overlapCount: both.length }) } } catch (exc) { - appendStatusLog(`capability LMArena cross-check fail-open (skipped): ${exc}`) + appendStatusLog("notice.capability.lmarenaFailOpen", { exc: String(exc) }) } } @@ -482,3 +483,13 @@ export function manualRankResult(modelId: string): DynamicBaseResult | null { matchedAs: entryKey, } } + +/** [2026-09-18]-[pool lane manual ordering: normalized modelId → manual rank index (0 = strongest). Prefix-matched like + * manualRankResult so hand-edited family entries cover their variants; null = unranked (sorts after ranked members). + * Feeds the pool-lane absolute ordering key in scoring.rankCandidates] */ +export function manualRankIndexOf(modelId: string): number | null { + const norm = normalizeModelKey(modelId) + if (!norm) return null + const hit = manualRankMatch(norm) + return hit ? hit.index : null +} diff --git a/src/catalog.ts b/src/catalog.ts index 0f481ea..e81a2fd 100644 --- a/src/catalog.ts +++ b/src/catalog.ts @@ -150,7 +150,8 @@ export function loadCatalog(now = Date.now()): Promise<CatalogResult> { }, (exc) => { if (cache?.index) return { index: cache.index, status: "stale" as const, etag: cache.etag ?? null } - appendStatusLog(`models.dev catalog unavailable and no cache (fail-open degradation): ${exc}`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.catalog.unavailableNoCache", { exc: String(exc) }) return { index: {}, status: "none" as const, etag: null } }, ) diff --git a/src/commands-md.ts b/src/commands-md.ts index 7039ccb..dbefba1 100644 --- a/src/commands-md.ts +++ b/src/commands-md.ts @@ -43,26 +43,65 @@ export function modelRankCommandMd(cliPath: string): string { const run = (args: string): string => `!\`node ${cli} ${args} 2>/dev/null || bun ${cli} ${args}\`` return [ "---", - "description: interactively configure the model capability ranking (manual ranking takes precedence over base capability scores; the higher, the stronger)", + "description: interactively configure the model capability ranking (manual ranking takes precedence over base capability scores; the higher, the stronger; scoped to the task-pool selection)", "---", "", run("rank list"), "", - "The first section above is the manual capability ranking (#1 strongest; hit models take their capability score/lane from it), the second is a reference ordering of the currently available models. Please:", + "The above listing ranks ONLY the models selected into task pools via /poolConfig (one merged ordering, #1 strongest; models not in any task pool are never listed, so unused models need no ranking; hit models take their capability score/lane from it). If it prints the no-task-pool guidance instead, walk the user through /poolConfig (or the pool set command) first — the flow is always poolConfig → modelRank. Please:", "1. Ask the user to state the adjustment intent (e.g. \"move glm-5.3 to the very front\", \"swap kimi-k3 and glm-5.2\", \"remove deepseek-v4-pro\", \"clear the ranking\").", - "2. Translate that into the corresponding commands (numbers reference the global indices across both sections):", + "2. Translate that into the corresponding commands (numbers reference the current listing's indices):", ` - Full reorder (in the given order): ${run("rank set <number-or-modelId...>")}`, ` - Append to the end of the ranking (weakest end): ${run("rank add <number-or-modelId...>")}`, ` - Remove from the ranking: ${run("rank remove <number-or-modelId...>")}`, ` - Clear (all fall back to base capability scores): ${run("rank clear")}`, "3. After executing, run `rank list` once more to verify, and report the new ranking and when it takes effect (immediate) in one sentence.", - "Note: `#number` is only valid against the most recent list output; if the ranking may have changed between two operations, re-run list before converting numbers.", + "Note: `#number` is only valid against the most recent list output; if the ranking or task-pool selection may have changed between two operations, re-run list before converting numbers.", "", `Config file: ${paths().capabilityRank} (safe to hand-edit; models array order = capability descending, hot-reloaded on save).`, "", ].join("\n") } +// [2026-09-19]-[/switchman-setup-chat: chat fallback for the TUI /switchman-setup wizard (which lives in src/tui.tsx). +// The setup hard gate (src/setup-gate.ts, wired in src/index.ts) denies task dispatch until all 6 task pools have +// >=1 selected model AND the capability ranking has >=1 entry — this template guides the user through exactly that +// in conversation: show state → ask multi-select per lane (question tool) → pool set per lane → rank the union +// strongest-first → verify. Real CLI syntax per src/config-cli.ts (pool list/set, rank list/set); config hot-reloads, +// a restart is only needed for brand-new providers]- +export function switchmanSetupCommandMd(cliPath: string): string { + const cli = q(cliPath) + const run = (args: string): string => `!\`node ${cli} ${args} 2>/dev/null || bun ${cli} ${args}\`` + return [ + "---", + "description: guided switchman setup — pick at least one model for each of the 6 task pools (economy/mechanical/main/hard/vision/review) and rank the union strongest-first; task dispatch is blocked until setup completes (chat fallback when the TUI /switchman-setup is unavailable)", + "---", + "", + "The user invoked the switchman setup wizard in chat form. Task dispatch is hard-blocked until EVERY one of the six task pools has at least one selected model AND the capability ranking has at least one entry — unconfigured pools no longer default to \"all models\". Walk through all steps below; relay every question, option list and answer in the user's conversation language.", + "", + "Current state (task-pool selection overview and capability ranking):", + "", + run("pool list"), + "", + run("rank list"), + "", + "Step 1 — select models for EACH of the six pools, one at a time: economy, mechanical, main, hard, vision, review. For each pool: run `pool list <task-pool>` to show its numbered candidate list, then use the question tool to ask the user which of those models should join the pool (multi-select; AT LEAST ONE per pool — required, not optional; one model may join several pools), and persist the answer with:", + "", + run("pool set <task-pool> <number-or-modelId...>"), + "", + "Repeat the ask→set loop until all six pools report a selection. `#number` is only valid against the most recent list output; re-run `pool list <task-pool>` first if the candidate set may have changed. When the user is unsure, suggest sensible defaults: economy = cheap/fast models, mechanical = mid-tier workhorse, main = strongest generalist, hard = strongest reasoner, vision = image-capable models, review = a model family different from the main pool's head (cross-family review is preferred).", + "", + "Step 2 — capability ranking. After all six pools are saved, run `rank list` again: it now shows exactly the union of the selected models (the rankable universe), sorted by effective capability. Ask the user to order them strongest-first (at least 1 model must be ranked; models left out of the ranking simply use their base capability score), then persist with:", + "", + run("rank set <number-or-modelId...>"), + "", + "Step 3 — verify and close. Run `pool list` and `rank list` once more: all six pools must report a manual selection and the ranking must be non-empty. Then tell the user (in their conversation language): the setup takes effect immediately (config hot-reloads on save, no restart needed); a restart is only required if brand-new providers/models were selected that opencode has not registered yet.", + "", + `Config files: ${paths().poolConfig} + ${paths().capabilityRank} (safe to hand-edit, hot-reloaded on save).`, + "", + ].join("\n") +} + // [2026-09-05]-[/switchman-lang: show/reconfigure the project language preference — reads the settings file fresh via a // `!` block; re-ask goes through the same marker-question flow (plugin captures and overwrites, the model never edits // the file); reset = delete the file (next session asks again); AGENTS.md marker applies only while the file is absent] diff --git a/src/config-cli.ts b/src/config-cli.ts index dbe15b0..ef8b062 100644 --- a/src/config-cli.ts +++ b/src/config-cli.ts @@ -4,16 +4,27 @@ // [2026-09-03]-[Added with the task-pool selection/manual ranking features; [2026-09-03 semantics fix]-[pool = task-pool lane (not a provider pool); // select the models joining each lane, the same model may join multiple lanes]; exit codes 0=success 1=failure] import { baseScoreDynamic, normalizeModelKey } from "./capability" -import { loadSupersetShells, loadManifest, paths } from "./state" +import { loadSupersetShells, loadManifest, paths, readUiLocale } from "./state" import { - loadCapabilityRank, loadPoolConfig, poolAllowlist, + loadCapabilityRank, loadPoolConfig, poolAllowlist, poolUniverse, writeCapabilityRank, clearCapabilityRank, writePoolConfig, resetPoolConfig, type RankScoreOverride, } from "./user-overrides" import { LANE_ORDER, type Lane } from "./types" import { TIER_RANK } from "./model-ranks" +import { resolveDisplayLocale, t, type LocaleTag } from "./i18n" -interface ModelRow { key: string; modelId: string; tier: string; source: string; raw: number | null; manualIdx?: number } +// [2026-09-19]-[render-time CLI i18n: the CLI has no project context, so the display locale is resolved ONCE per +// process (global ui.lang snapshot → terminal env → "en"; see src/i18n.ts) and every user-visible console/error +// string with a `cli.config.*` key renders via t(locale, key, params); flags, subcommand names, model/tier text and +// path placeholders stay verbatim; exit codes and control flow unchanged] +let cachedLocale: LocaleTag | null = null +function cliLocale(): LocaleTag { + if (!cachedLocale) cachedLocale = resolveDisplayLocale({ uiLang: readUiLocale(), env: process.env }) + return cachedLocale +} + +interface ModelRow { key: string; modelId: string; tier: string; source: string; raw: number | null; manualIdx?: number; poolMember?: boolean } // [2026-09-10]-[manual-first tie-break: on exact (tier, raw) ties manual entries sort above base entries, ordered by // their models-array slot — lets anchored moves win ties without touching base-vs-base ordering] @@ -61,73 +72,87 @@ export function allModelRows(): ModelRow[] { return rows } -function fmtRow(n: number, row: ModelRow, selected: boolean): string { - const mark = selected ? "[x]" : "[ ]" +function fmtRow(n: number, row: ModelRow, selected: boolean, locale: LocaleTag): string { + const checkMark = selected ? "[x]" : "[ ]" const manualTag = row.source === "manual" ? "·manual rank" : "" - return ` #${String(n).padStart(2, "0")} ${mark} ${row.modelId} (${row.tier}-tier${manualTag})` + return t(locale, "cli.config.poolRow", { + rankPadded: String(n).padStart(2, "0"), checkMark, modelId: row.modelId, tier: row.tier, manualTag, + }) } -function laneOrThrow(lane?: string): Lane { +function laneOrThrow(lane: string | undefined, locale: LocaleTag): Lane { const key = String(lane ?? "").trim().toLowerCase() as Lane if (!(LANE_ORDER as string[]).includes(key)) { - throw new Error(`unknown task pool: ${lane ?? "(missing)"} (six task pools: ${LANE_ORDER.join("/")})`) + throw new Error(t(locale, "cli.config.unknownPool", { lane: lane ?? "(missing)", laneList: LANE_ORDER.join("/") })) } return key } function printPoolList(filterLane?: string): void { + const locale = cliLocale() const rows = allModelRows() const allow = loadPoolConfig() - const head = `Task-pool selection (config file ${paths().poolConfig}; selection = the models joining that task pool; the same model may join multiple pools; unconfigured pools use the system default decision)` + const head = t(locale, "cli.config.poolHeader", { poolConfigPath: paths().poolConfig }) if (filterLane) { - const lane = laneOrThrow(filterLane) + const lane = laneOrThrow(filterLane, locale) const sel = allow[lane] console.log(head) - console.log(`== ${lane} == (${sel ? `manually selected ${sel.size}/${rows.length} participating models` : "unconfigured: system default (all available models participate)"})`) - rows.forEach((row, i) => console.log(fmtRow(i + 1, row, sel ? sel.has(row.key) : true))) + console.log(t(locale, "cli.config.poolSection", { + lane, + selection: sel + ? `manually selected ${sel.size}/${rows.length} participating models` + : "unconfigured: system default (all available models participate)", + })) + rows.forEach((row, i) => console.log(fmtRow(i + 1, row, sel ? sel.has(row.key) : true, locale))) return } console.log(head) for (const lane of LANE_ORDER) { const sel = allow[lane] - console.log(`== ${lane} ==${sel ? ` manually selected ${sel.size} models: ${[...sel].join(", ")}` : " system default (all available models participate)"}`) + console.log(t(locale, "cli.config.poolSectionBrief", { + lane, + detail: sel + ? ` manually selected ${sel.size} models: ${[...sel].join(", ")}` + : " system default (all available models participate)", + })) } - console.log(`(view a single pool's full list with numbers: pool list <${LANE_ORDER.join("|")}>)`) + console.log(t(locale, "cli.config.poolListHint", { laneList: LANE_ORDER.join("|") })) } -function resolveRefs(refs: string[], rows: ModelRow[]): string[] { +function resolveRefs(refs: string[], rows: ModelRow[], locale: LocaleTag): string[] { // Dot-folding fallback: hand-typed args often give "glm-5-3-flash" ↔ manifest key "glm-5.3-flash" (normalizeModelKey keeps dots) const alt = new Map(rows.map((r) => [r.key.replace(/\./g, "-"), r.key])) const out: string[] = [] for (const r of refs) { if (/^\d+$/.test(r)) { const hit = rows[Number(r) - 1] - if (!hit) throw new Error(`index out of range #${r} (list has ${rows.length} items)`) + if (!hit) throw new Error(t(locale, "cli.config.indexOutOfRange", { index: r, rowCount: rows.length })) out.push(hit.key) continue } const key = normalizeModelKey(r) - if (!key) throw new Error(`invalid model name: ${r}`) + if (!key) throw new Error(t(locale, "cli.config.invalidModel", { model: r })) out.push(alt.get(key.replace(/\./g, "-")) ?? key) } return out } function cmdPool(args: string[]): number { + const locale = cliLocale() const [sub, lane, ...rest] = args if (!sub || sub === "list") { printPoolList(lane) return 0 } - const key = laneOrThrow(lane) + const key = laneOrThrow(lane, locale) const rows = allModelRows() - if (rows.length === 0) throw new Error("no available model manifest (check provider connections and the superset manifest)") + if (rows.length === 0) throw new Error(t(locale, "cli.config.noManifest")) // add/remove semantics operate on the "currently effective selection set": unconfigured lane = system default full set (the first operation materializes it into an explicit list, consistent with TUI checkboxes) const explicit = poolAllowlist(key) const current = [...(explicit ?? rows.map((r) => r.key))] if (sub === "add" || sub === "remove" || sub === "set") { - if (rest.length === 0) throw new Error(`pool ${sub} requires an index or model name`) - const refs = resolveRefs(rest, rows) + if (rest.length === 0) throw new Error(t(locale, "cli.config.poolRequiresArg", { sub })) + const refs = resolveRefs(rest, rows, locale) let next: string[] if (sub === "add") next = [...current, ...refs.filter((k) => !current.includes(k))] else if (sub === "remove") next = current.filter((k) => !refs.includes(k)) @@ -135,54 +160,89 @@ function cmdPool(args: string[]): number { const file = writePoolConfig(key, next) const n = file?.pools[key]?.length console.log(n === undefined - ? `${key} task-pool selection cleared (back to the system default candidate set, effective immediately, sidebar refreshes in sync)` - : `Updated ${key} task-pool selection (${n} models participating, effective immediately, sidebar refreshes in sync)`) + ? t(locale, "cli.config.poolSelectionCleared", { lane: key }) + : t(locale, "cli.config.poolUpdated", { lane: key, modelCount: n })) printPoolList(key) return 0 } if (sub === "clear") { resetPoolConfig(key) - console.log(`Cleared the ${key} task-pool selection config (that pool returns to the system default candidate set, effective immediately, sidebar refreshes in sync)`) + console.log(t(locale, "cli.config.poolConfigCleared", { lane: key })) return 0 } - throw new Error(`unknown subcommand pool ${sub} (list/add/remove/set/clear)`) + throw new Error(t(locale, "cli.config.unknownPoolSub", { sub })) } /** [2026-09-10]-[merged interleaved view: manual entries no longer float as a block on top — every model (manual + base) * is sorted by effective capability (tier, raw; manual wins exact ties), so /modelRank moves and rank CLI indices act - * on one global ordering. Manual keys missing from the model universe keep a row (dead-key tolerance)] */ + * on one global ordering. Manual keys missing from the model universe keep a row (dead-key tolerance)] + * [2026-09-18]-[rank universe = pool selection: with at least one task pool configured the view shows EXACTLY the + * pool-selected universe — dead manual keys (rank entries absent from every pool) are no longer listed; the next + * rank write prunes them from capability-rank.json instead (see writeCapabilityRank). With NO pool configured the + * view degenerates to the manual entries alone (cleanup-only) while the CLI/TUI guide the user to /poolConfig first] */ export function rankViewRows(): ModelRow[] { const rank = loadCapabilityRank() - const rows = allModelRows() - const seen = new Set(rows.map((r) => r.key)) - for (const k of rank?.models ?? []) { - if (seen.has(k)) continue - seen.add(k) - rows.push(toRow(k)) + const universe = poolUniverse() + let rows: ModelRow[] + if (universe.size === 0) { + // cleanup-only degeneration: the manual entries alone (base rows filtered out entirely) + const seen = new Set<string>() + rows = [] + for (const k of rank?.models ?? []) { + if (seen.has(k)) continue + seen.add(k) + rows.push(toRow(k)) + } + } else { + rows = allModelRows() + .filter((r) => universe.has(r.key)) + .map((r) => ({ ...r, poolMember: true })) } rows.sort(capabilityCompare) return rows } function cmdRank(args: string[]): number { + const locale = cliLocale() const [sub, ...rest] = args const rank = loadCapabilityRank() + const universe = poolUniverse() if (!sub || sub === "list") { + if (universe.size === 0) { + console.log(t(locale, "cli.config.rankDisabledUntilPools", { capabilityRankPath: paths().capabilityRank })) + console.log(t(locale, "cli.config.rankHowTo")) + const legacy = rank?.models ?? [] + if (legacy.length > 0) { + console.log(t(locale, "cli.config.legacyHeader")) + legacy.forEach((k, i) => console.log(t(locale, "cli.config.legacyRow", { + rankPadded: String(i + 1).padStart(2, "0"), modelKey: k, + }))) + } + return 0 + } const view = rankViewRows() const manualCount = rank?.models.length ?? 0 - console.log(`Model capability ranking (config file ${paths().capabilityRank}; one merged ordering — manual entries interleave with base-score models by effective score; higher up = stronger)`) - console.log(`== Merged ordering (${manualCount} manual${manualCount > 0 ? "" : "; none = all use the base capability score"}; CLI set/add order entries by the legacy ladder, TUI moves anchor scores between neighbors) ==`) + console.log(t(locale, "cli.config.rankHeader", { capabilityRankPath: paths().capabilityRank, universeCount: universe.size })) + console.log(t(locale, "cli.config.mergedHeader", { + manualCount, manualSuffix: manualCount > 0 ? "" : "; none = all use the base capability score", + })) view.forEach((row, i) => { const manualTag = row.source === "manual" - ? `·manual${row.raw !== null ? ` ${row.raw}` : ""}` + ? t(locale, "cli.config.manualTag", { score: row.raw !== null ? ` ${row.raw}` : "" }) : "" - console.log(` #${String(i + 1).padStart(2, "0")} ${row.modelId} (${row.tier}-tier${manualTag})`) + const poolTag = row.poolMember === false ? ` ${t(locale, "cli.config.notInPoolTag")}` : "" + console.log(t(locale, "cli.config.rankRow", { + rankPadded: String(i + 1).padStart(2, "0"), modelId: row.modelId, tier: row.tier, manualTag, poolTag, + })) }) return 0 } if (sub === "add" || sub === "remove" || sub === "set") { - if (rest.length === 0) throw new Error(`rank ${sub} requires an index or model name`) - const refs = resolveRefs(rest, rankViewRows()) + if (sub !== "remove" && universe.size === 0) { + throw new Error(t(locale, "cli.config.rankNoPools")) + } + if (rest.length === 0) throw new Error(t(locale, "cli.config.rankRequiresArg", { sub })) + const refs = resolveRefs(rest, rankViewRows(), locale) const current = [...(rank?.models ?? [])] // [2026-09-10]-[CLI writes must preserve anchored scores: add keeps every existing entry's score, remove/set drop // only the keys leaving the list (ladder fallback covers the rest)] @@ -206,37 +266,38 @@ function cmdRank(args: string[]): number { nextScores = keepScores(refs) } const file = writeCapabilityRank(next, nextScores) - console.log(`Updated the manual capability ranking (${file.models.length} models, effective immediately, sidebar refreshes in sync)`) + console.log(t(locale, "cli.config.rankUpdated", { modelCount: file.models.length })) return cmdRank(["list"]) } if (sub === "clear") { clearCapabilityRank() - console.log("Cleared the manual capability ranking (everything falls back to the base capability score, effective immediately, sidebar refreshes in sync)") + console.log(t(locale, "cli.config.rankCleared")) return 0 } - throw new Error(`unknown subcommand rank ${sub} (list/set/add/remove/clear)`) + throw new Error(t(locale, "cli.config.unknownRankSub", { sub })) } /** CLI entry (callable directly by tests); argv excludes node/self */ export function runCli(argv: string[]): number { + const locale = cliLocale() const [group, ...args] = argv try { if (group === "pool") return cmdPool(args) if (group === "rank") return cmdRank(args) - console.log("Usage: switchman-config <pool|rank> ...") - console.log(` pool list [task-pool] Pool selection overview (economy/mechanical/main/hard/vision/review; with a pool name = full list with indices)`) - console.log(" pool add <task-pool> <index|model...> Check models joining that task pool") - console.log(" pool remove <task-pool> <index|model...> Uncheck participation") - console.log(" pool set <task-pool> <index|model...> Fully replace that pool's participation list (the same model may join multiple pools)") - console.log(" pool clear <task-pool> Clear that pool's config (back to the system default candidate set)") - console.log(" rank list View the manual capability ranking and the reference ordering of available models") - console.log(" rank set <index|model...> Fully reorder (in the given order, #1 is strongest)") - console.log(" rank add <index|model...> Append to the end of the ranking") - console.log(" rank remove <index|model...> Remove from the ranking") - console.log(" rank clear Clear the ranking (fall back to the base capability score)") + console.log(t(locale, "cli.config.usage")) + console.log(t(locale, "cli.config.usagePoolList")) + console.log(t(locale, "cli.config.usagePoolAdd")) + console.log(t(locale, "cli.config.usagePoolRemove")) + console.log(t(locale, "cli.config.usagePoolSet")) + console.log(t(locale, "cli.config.usagePoolClear")) + console.log(t(locale, "cli.config.usageRankList")) + console.log(t(locale, "cli.config.usageRankSet")) + console.log(t(locale, "cli.config.usageRankAdd")) + console.log(t(locale, "cli.config.usageRankRemove")) + console.log(t(locale, "cli.config.usageRankClear")) return group ? 1 : 0 } catch (exc) { - console.error(`switchman-config: ${exc instanceof Error ? exc.message : exc}`) + console.error(t(locale, "cli.config.errorPrefix", { message: exc instanceof Error ? exc.message : String(exc) })) return 1 } } diff --git a/src/config.ts b/src/config.ts index 642ab2d..800ca59 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,6 +5,7 @@ import { canonicalKeyOf, defaultProviderConfig, genericProviderDefaults, PROVIDE import type { PeakRange, ProviderKey, ProviderUserConfig } from "./provider-config" import type { CapabilityTierThresholds, Lane, Pool, RoutePolicy, SwitchmanOptions } from "./types" import { DEFAULT_LANG_CANDIDATES } from "./types" +import { normalizeUiLocale } from "./lang-config" import { DEFAULT_READ_BUDGET_TOKENS, MAX_READ_BUDGET_TOKENS, MAX_SUBAGENT_CAP_TOKENS, MIN_READ_BUDGET_TOKENS, MIN_SUBAGENT_CAP_TOKENS } from "./context-watch" export interface ConfigDiagnostic { code: string; level: "error" | "warn" | "info"; path?: string; hint?: string } @@ -39,6 +40,8 @@ export interface UserConfig { workspace: { enabled: boolean; dirname: string } // [2026-09-05]-[project language preference: conversation/comments/docs language — first-run ask + per-turn [LANG] iron-rule line] lang: { enabled: boolean; ask: boolean; candidates: string[] } + // [2026-09-19]-[global UI language: raw locale tag for render-time localization of user-visible UI strings ("" = not set, falls through to terminal env)] + ui: { lang: string } // [2026-09-17]-[broad-search clarify: whole-project searches ask the user for narrower guidance once per session] search: { clarify: boolean } // [2026-09-06]-[tmux pane mirroring: live subagent attach panes in the home tmux window's right column] @@ -54,7 +57,7 @@ export const DEFAULT_CONTEXT_TOKENS = { soft: 50_000, hard: 90_000, force: 130_0 export const DEFAULT_DELEGATION_FLOOR = 3_000 /** Factory defaults for behavior sections (fillMissing baseline; only bad-typed values fall back and report SWM037) */ -export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "capability" | "matrix" | "banner" | "rules" | "context" | "builtinAgents" | "injection" | "dispatch" | "relay" | "workspace" | "lang" | "search" | "tmux" | "lanes"> { +export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "capability" | "matrix" | "banner" | "rules" | "context" | "builtinAgents" | "injection" | "dispatch" | "relay" | "workspace" | "lang" | "ui" | "search" | "tmux" | "lanes"> { return { quota: { glmFiveHourReservePct: 90, deepseekLowBalanceWarnCny: 10 }, cost: { enabled: true }, @@ -70,6 +73,8 @@ export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "ca relay: { image: true }, workspace: { enabled: true, dirname: ".switchman" }, lang: { enabled: true, ask: true, candidates: [...DEFAULT_LANG_CANDIDATES] }, + // [2026-09-19]-[global UI language default: "" = not set (locale chain falls through to terminal env)] + ui: { lang: "" }, search: { clarify: true }, tmux: { enabled: true, rightPct: 60, maxPanes: 3, mini: false }, lanes: {}, @@ -208,6 +213,10 @@ export function validateUserConfig(value: unknown): { config: UserConfig; diagno if (typeof filled.lang.enabled !== "boolean") bad("lang.enabled", () => { filled.lang.enabled = defaults.lang.enabled }) if (typeof filled.lang.ask !== "boolean") bad("lang.ask", () => { filled.lang.ask = defaults.lang.ask }) if (!Array.isArray(filled.lang.candidates) || filled.lang.candidates.length === 0 || !filled.lang.candidates.every((c: unknown) => typeof c === "string" && c.trim() === c && !!c.trim() && c.length <= 48)) bad("lang.candidates", () => { filled.lang.candidates = structuredClone(defaults.lang.candidates) }) + // [2026-09-19]-[global UI language: ui.lang must be a string; "" = not set (no diagnostic); a non-empty value that + // does not normalize via normalizeUiLocale resets to "" with SWM063 (next free code after SWM062)] + if (!plain(filled.ui) || typeof (filled.ui as any).lang !== "string") { ds.push({ code: "SWM063", level: "error", path: "ui.lang" }); filled.ui = { lang: "" } } + else if ((filled.ui as any).lang !== "" && normalizeUiLocale((filled.ui as any).lang) === null) { ds.push({ code: "SWM063", level: "error", path: "ui.lang" }); (filled.ui as any).lang = "" } // [2026-09-17]-[broad-search clarify switch] if (typeof filled.search.clarify !== "boolean") bad("search.clarify", () => { filled.search.clarify = defaults.search.clarify }) // [2026-09-06]-[tmux pane mirroring: enabled/mini booleans; rightPct integer 10..90; maxPanes integer 1..4] diff --git a/src/context-watch.ts b/src/context-watch.ts index 099b911..2844910 100644 --- a/src/context-watch.ts +++ b/src/context-watch.ts @@ -3,6 +3,13 @@ // deliberate probe-retry loops. Reads are now judged from turn 1 by estimated injection size (context is sunk cost; // only the marginal injection compounds), watermarks keep lifecycle duties only (soft=advice, hard=wrap-up deny, // force=auto-handover). v2 (dynamic R*) is parked in docs/Pending-Confirmation-and-Implementation/.] +// [2026-09-18]-[v1.1 anti-fragmentation: deny→partial-read→continuation cycles proved the fixed per-call R* fragments +// reads the model demonstrably needs (it re-reads the rest anyway, plus one wasted deny round trip per fragment). +// Three additions: a tolerance band (R* + deny-retry overhead ≈ 400 tok passes outright), need-aware grant sizing +// (reads up to the remaining turn headroom, max 2×R*, land one-shot), and continuation merge (a follow-up read +// resuming at the granted window's end completes the original want in one bounded shot, even past the spent turn +// budget — delegating a ≤band fragment costs more than the fragment). Per-turn self-read injection stays bounded +// (≈2×R* + band + one bounded completion); the parked dynamic-R* v2 is unaffected and remains a separate idea.] // [2026-09-04]-[English localization: translate runtime messages and comments; no logic change] // Pure-function layer: token estimation, watermark tiering, read-gate decisions; state (Maps) is held by index.ts, no IO here. import type { ContextOptions } from "./types" @@ -150,6 +157,10 @@ export function isArchaeologyBash(command: string): boolean { export const DEFAULT_READ_BUDGET_TOKENS = 1500 export const MIN_READ_BUDGET_TOKENS = 200 export const MAX_READ_BUDGET_TOKENS = 20_000 +/** [2026-09-18]-[v1.1 read budget: fixed cost of one deny→retry round trip (deny error text + re-issued call + model + * re-reasoning ≈ 400 tok). Reads estimated within R* + this band are allowed outright: denying a barely-over-budget + * read costs more than the overshoot it saves, and the model reads the rest anyway in fragments] */ +export const DENY_RETRY_OVERHEAD_TOKENS = 400 /** Used when a file sample yields no usable line structure (empty/one-line files) */ const FALLBACK_TOKENS_PER_LINE = 7.5 @@ -274,19 +285,27 @@ export interface ReadEstimate { /** estimated tokens the requested range would inject */ totalTokens: number tokensPerLine: number - /** bounded-retry line count that fits the budget (clamped 50..500) */ + /** bounded-retry line count that fits the grant ceiling (clamped 50..500) */ suggestedLimit: number hasLimit: boolean requestedLimit?: number offset?: number + /** [2026-09-18]-[v1.1 need-aware sizing: effective per-call grant ceiling in tokens the suggestion was sized from — + * the remaining turn headroom at the call site (max R* fresh-turn, up to 2×R*), so a demonstrated-range read + * lands one-shot instead of deny → partial read → continuation fragments] */ + grantTokens: number + /** [2026-09-18]-[v1.1 continuation merge: 1-based inclusive end line of the effective requested range (the demonstrated want)] */ + requestedEndLine: number } /** Estimate the injection cost of a read call from a 64KB head sample: bytes/line → tokens/line (clamped 3..20 to - * absorb minified/verbose outliers), then tokens/line × effective lines (honoring limit/offset). Pure. */ + * absorb minified/verbose outliers), then tokens/line × effective lines (honoring limit/offset). Pure. The optional + * grantTokens ceiling sizes suggestedLimit (defaults to readBudget — callers riding the turn headroom pass it). */ export function estimateReadRange( sample: FileSample, args: { limit?: unknown; offset?: unknown } | undefined, readBudget: number, + grantTokens?: number, ): ReadEstimate { const sampleLines = sample.newlines + 1 const coversFile = sample.sampleBytes >= sample.bytes @@ -297,16 +316,57 @@ export function estimateReadRange( const offset = typeof args?.offset === "number" && args.offset > 0 ? Math.floor(args.offset) : 1 const effectiveLines = limit !== undefined ? Math.max(1, Math.min(limit, Math.max(1, totalLines - offset + 1))) : totalLines + const grant = grantTokens ?? readBudget return { totalTokens: Math.ceil(tokensPerLine * effectiveLines), tokensPerLine, - suggestedLimit: Math.min(500, Math.max(50, Math.floor(readBudget / tokensPerLine))), + suggestedLimit: Math.min(500, Math.max(50, Math.floor(grant / tokensPerLine))), hasLimit: limit !== undefined, requestedLimit: limit, offset, + grantTokens: grant, + requestedEndLine: offset + effectiveLines - 1, } } +// [2026-09-18]-[v1.1 continuation merge: the last window granted by a cap/deny-budget is remembered per session; a +// follow-up read of the same file resuming at/near the granted window's end is the SAME logical read continuing — +// its bounded remainder (≤ R* + overhead band) completes in one shot instead of re-fragmenting] +/** Per-session memory of the last granted-but-not-completed read window (held by index.ts; pure matching lives here) */ +export interface ReadContinuation { + filePath: string + /** 1-based inclusive end line of the window granted last time (cap rewrite or deny-budget retry params) */ + grantedEndLine: number + /** 1-based inclusive end line of the originally requested range (the demonstrated want) */ + wantEndLine: number +} + +/** Offset slack when matching a follow-up read to the granted window's end (models resume exactly at, or a few + * lines before/after, the boundary for context) */ +export const CONTINUATION_OFFSET_SLACK = 10 + +export interface ReadContinuationMatch { + offset: number + /** lines of the original want not yet granted past this offset */ + wantRemainderLines: number + wantRemainderTokens: number +} + +/** Match a follow-up read against the last grant: same file + offset resuming within slack of the granted window's + * end; null when not a continuation (different file, offset elsewhere, or want already exhausted) */ +export function matchContinuation( + prev: ReadContinuation | undefined, + args: { filePath?: unknown; offset?: unknown } | undefined, + tokensPerLine: number, +): ReadContinuationMatch | null { + if (!prev || typeof args?.filePath !== "string" || args.filePath !== prev.filePath) return null + const offset = typeof args.offset === "number" && args.offset > 0 ? Math.floor(args.offset) : 1 + if (offset < prev.grantedEndLine - CONTINUATION_OFFSET_SLACK || offset > prev.grantedEndLine + CONTINUATION_OFFSET_SLACK) return null + const wantRemainderLines = prev.wantEndLine - offset + 1 + if (wantRemainderLines <= 0) return null + return { offset, wantRemainderLines, wantRemainderTokens: Math.ceil(tokensPerLine * wantRemainderLines) } +} + export interface BudgetGateInput { tool: string level: WatermarkLevel @@ -315,6 +375,9 @@ export interface BudgetGateInput { bashCommand?: string /** read-range estimate (read tool only; glob/grep/list and unsampleable paths pass null → fail-open) */ est?: ReadEstimate | null + /** [2026-09-18]-[v1.1 continuation merge: recognized continuation of the last granted window (matchContinuation hit); + * null/undefined = not a continuation */ + cont?: ReadContinuationMatch | null } export type BudgetGateAction = @@ -332,12 +395,17 @@ export type BudgetGateAction = * context bomb at 10k or 90k * - other bash passes at ok/soft (charged post-hoc in tool.execute.after) and is denied at hard/force (wrap-up mode) * - read-class is denied at hard/force (wrap-up mode); once the per-turn cap (2×R*) is spent, denied until the next - * user turn - * - read with an estimate over R*: auto-bounded ("cap") when no explicit limit was set; denied with exact - * bounded-retry params ("deny-budget") when the caller's own limit still overshoots + * user turn — EXCEPT a recognized continuation whose remaining want fits the per-call band (R* + deny-retry + * overhead): it completes the demonstrated need in one bounded shot, because delegating a ≤band fragment costs + * more than the fragment itself (the only read path allowed past the turn wall; hard/force wrap-up still wins) + * - read with an estimate within R* + the deny-retry overhead band passes outright (the deny round trip costs ≈ the + * overshoot it saves); up to the grant ceiling (turn headroom, est.grantTokens) it passes one-shot (need-aware — + * a demonstrated range lands in one request instead of deny → partial → continuation fragments); above that it is + * auto-bounded ("cap") when no explicit limit was set, or denied with exact bounded-retry params ("deny-budget") + * when the caller's own limit still overshoots * - everything else (un-estimable read-class included) is fail-open "allow" — post-hoc charging still applies */ export function budgetGateDecision(input: BudgetGateInput): BudgetGateAction { - const { tool, level, readBudget, turnUsed, bashCommand, est } = input + const { tool, level, readBudget, turnUsed, bashCommand, est, cont } = input if (tool === "bash") { if (bashCommand !== undefined && isVerificationBash(bashCommand)) return "allow" if (bashCommand !== undefined && isArchaeologyBash(bashCommand)) return "deny-archaeology" @@ -345,8 +413,10 @@ export function budgetGateDecision(input: BudgetGateInput): BudgetGateAction { } if (!READ_CLASS_TOOLS.has(tool)) return "allow" if (level === "hard" || level === "force") return "deny-hard" + if (tool === "read" && cont && cont.wantRemainderTokens <= readBudget + DENY_RETRY_OVERHEAD_TOKENS) return "allow" if (turnUsed >= turnBudgetOf(readBudget)) return "deny-turn" if (tool !== "read" || !est) return "allow" - if (est.totalTokens <= readBudget) return "allow" + if (est.totalTokens <= readBudget + DENY_RETRY_OVERHEAD_TOKENS) return "allow" + if (est.totalTokens <= est.grantTokens) return "allow" return est.hasLimit ? "deny-budget" : "cap" } diff --git a/src/copilot-thinking.ts b/src/copilot-thinking.ts index e5f40a6..434d857 100644 --- a/src/copilot-thinking.ts +++ b/src/copilot-thinking.ts @@ -68,9 +68,10 @@ export async function refreshThinkingShapesIfStale(ghToken: string | undefined, const cache: ThinkingCache = { fetched_at: Date.now(), shapes } writeJsonAtomic(paths().copilotThinking, cache) mem = { dir: paths().dir, cache } - appendStatusLog(`Copilot thinking-parameter shape cache refreshed: ${Object.keys(shapes).length} models`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.copilot.shapeCacheRefreshed", { modelCount: Object.keys(shapes).length }) } catch (exc) { - appendStatusLog(`Copilot thinking-parameter shape refresh fail-open: ${exc}`) + appendStatusLog("notice.copilot.shapeRefreshFailOpen", { exc: String(exc) }) } } diff --git a/src/cost.ts b/src/cost.ts index 8462d0f..0449f6e 100644 --- a/src/cost.ts +++ b/src/cost.ts @@ -41,7 +41,8 @@ export async function refreshCosts(): Promise<void> { cached = { scores, fetched_at: Date.now() / 1000 } writeJsonAtomic(paths().costs, cached) } catch (exc) { - appendStatusLog(`cost snapshot refresh failed (keeping stale data): ${exc}`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.cost.refreshFailed", { exc: String(exc) }) } } diff --git a/src/dispatch-mode.ts b/src/dispatch-mode.ts index 67a9c0f..4cbb1f3 100644 --- a/src/dispatch-mode.ts +++ b/src/dispatch-mode.ts @@ -6,6 +6,7 @@ import { existsSync, readFileSync } from "node:fs" import { join } from "node:path" import { appendStatusLog } from "./state" +import type { MsgKey } from "./i18n" import { LANG_SETTINGS_FILE } from "./lang-config" export type DispatchMode = "fleet" | "off" @@ -44,11 +45,13 @@ const brokenWarned = new Set<string>() const invalidNoted = new Set<string>() /** Read the project dispatch mode (sync, cheap, fail-open, never throws). Logs the broken-settings warning and the - * present-but-invalid note once per process per path via the injected log callback (defaults to appendStatusLog). */ + * present-but-invalid note once per process per path via the injected log callback (defaults to appendStatusLog). + * [2026-09-19]-[P3c status-log i18n: the log callback carries structured (key, params); English only, no behavior change] + * [2026-09-19]-[i18n cleanup: tighten the log callback key to MsgKey (both sites use catalog keys)] */ export function loadDispatchMode( projectDir: string, workspaceDirname: string, - log: (text: string) => void = appendStatusLog, + log: (key: MsgKey, params?: Record<string, string | number>) => void = appendStatusLog, ): DispatchMode { const abs = join(projectDir, workspaceDirname, LANG_SETTINGS_FILE) try { @@ -57,13 +60,13 @@ export function loadDispatchMode( if (parsed.broken) { if (!brokenWarned.has(abs)) { brokenWarned.add(abs) - log(`[opencode-switchman] ${workspaceDirname}/${LANG_SETTINGS_FILE} is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)`) + log("notice.lang.settingsInvalidJson", { workspaceDirname, langSettingsFile: LANG_SETTINGS_FILE }) } return "fleet" } if (parsed.invalidValue && !invalidNoted.has(abs)) { invalidNoted.add(abs) - log(`[opencode-switchman] ${workspaceDirname}/${LANG_SETTINGS_FILE} "dispatch" present but not exactly "off" (got: ${parsed.rawValue}) — ignored, fleet behavior`) + log("notice.lang.dispatchNotOff", { workspaceDirname, langSettingsFile: LANG_SETTINGS_FILE, rawValue: parsed.rawValue ?? "" }) } return parsed.mode } catch { diff --git a/src/doctor-cli.ts b/src/doctor-cli.ts index d667acd..9a04de4 100644 --- a/src/doctor-cli.ts +++ b/src/doctor-cli.ts @@ -1,11 +1,17 @@ // [2026-09-04]-[English localization: translate CLI messages and comments; no logic change] +// [2026-09-19]-[render-time CLI i18n: the CLI has no project context, so the display locale is resolved ONCE per +// process (global ui.lang snapshot → terminal env → "en"; see src/i18n.ts) and the usage line plus the doctor +// report render via t(locale, key, params); SWM codes, env-var names and exit codes stay verbatim] import { loadUserConfig } from "./config" import { formatDoctorReport, runDoctor } from "./doctor" +import { resolveDisplayLocale, t } from "./i18n" +import { readUiLocale } from "./state" +const locale = resolveDisplayLocale({ uiLang: readUiLocale(), env: process.env }) if (process.argv.slice(2).some((arg) => arg === "--help" || arg === "-h")) { - console.log("Usage: switchman-doctor checks the opencode-switchman config; the OPENCODE_CONFIG_DIR env var selects the config directory; exit codes 0=no issues, 1=warnings, 2=errors") + console.log(t(locale, "cli.doctor.usage")) } else { const config = loadUserConfig() -const result = runDoctor({ configPath: config.path, diagnostics: config.diagnostics, env: process.env }) -console.log(formatDoctorReport(result)) +const result = runDoctor({ configPath: config.path, diagnostics: config.diagnostics, env: process.env }, locale) +console.log(formatDoctorReport(result, locale)) process.exitCode = result.diagnostics.some((d) => d.level === "error") ? 2 : result.diagnostics.some((d) => d.level === "warn") ? 1 : 0 } diff --git a/src/doctor.ts b/src/doctor.ts index d71aaf0..d87d199 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -1,10 +1,16 @@ // [2026-09-04]-[English localization: translate CLI messages and comments; no logic change] +// [2026-09-19]-[render-time CLI i18n: report prose with a `cli.doctor.*` key renders via t(locale, key, params) +// (SWM codes, paths and level tokens stay verbatim; {pathPart}/{hintPart} are flattened variant params per +// i18n-keys.md); the locale is an optional second arg (omitted → English) so the plugin's background doctor call +// in src/index.ts and existing direct callers keep byte-identical output; only switchman-doctor passes the CLI +// display locale — no logic or exit-code changes] import { existsSync, statSync, readFileSync, accessSync, constants } from "node:fs" import { dirname, isAbsolute, join } from "node:path" import { parseJsonc, resolveOpencodeConfigDir, validateUserConfig } from "./config" import { canonicalKeyOf, PROVIDER_KEYS } from "./provider-config" import { loadManifest, paths } from "./state" import { baseScoreDynamic } from "./capability" +import { t } from "./i18n" import type { ConfigDiagnostic } from "./config" export interface DoctorInput { @@ -22,7 +28,7 @@ function suggestion(actual: string, expected: readonly string[]): string | undef } return expected.find((x) => norm(actual).includes(norm(x)) || norm(x).includes(norm(actual)) || distance(norm(actual), norm(x)) <= 2) } -export function runDoctor(input: DoctorInput): DoctorResult { +export function runDoctor(input: DoctorInput, locale?: unknown): DoctorResult { const out = [...(input.diagnostics ?? [])] let value: unknown = null try { const p = parseJsonc(input.configText ?? readFileSync(input.configPath, "utf8")); if ("error" in p) out.push({ code: "SWM001", level: "error", path: input.configPath }); else value = p.value } catch { out.push({ code: "SWM001", level: "error", path: input.configPath }) } @@ -53,9 +59,9 @@ export function runDoctor(input: DoctorInput): DoctorResult { try { const shells = loadManifest().shells const unknown = shells.filter((s) => baseScoreDynamic(s.modelId).source === "global") - if (unknown.length > 0) out.push({ code: "SWM060", level: "info", path: "shells", hint: `${unknown.length} models not matched by the known system (unknown group, ranked to the bottom by coefficient)` }) + if (unknown.length > 0) out.push({ code: "SWM060", level: "info", path: "shells", hint: t(locale, "cli.doctor.unknownModelsHint", { unknownCount: unknown.length }) }) const approx = shells.filter((s) => ["prefix", "family"].includes(baseScoreDynamic(s.modelId).source)) - if (approx.length > 0) out.push({ code: "SWM062", level: "info", path: "shells", hint: `${approx.length} models classified approximately by prefix/family` }) + if (approx.length > 0) out.push({ code: "SWM062", level: "info", path: "shells", hint: t(locale, "cli.doctor.approxModelsHint", { approxCount: approx.length }) }) } catch { /* fail-open */ } } try { statSync(dirname(input.configPath)); accessSync(dirname(input.configPath), constants.W_OK) } catch { out.push({ code: "SWM051", level: "error", path: dirname(input.configPath) }) } @@ -69,7 +75,7 @@ export function runDoctor(input: DoctorInput): DoctorResult { if (input.legacy?.quotaEnabled && Object.keys(input.legacy.quotaEnabled).length) out.push({ code: "SWM042", level: "warn", path: "legacy.quota" }) if (input.legacy?.billingWindow) out.push({ code: "SWM043", level: "warn", path: "legacy.billingWindow" }) // [2026-09-01]-[Unified config surface: tuple explicit behavior sections prompt migration to opencode-switchman.jsonc (gen-1 compatible, explicit values still win)] - for (const section of input.legacy?.sections ?? []) out.push({ code: "SWM044", level: "warn", path: `legacy.${section}`, hint: "opencode-switchman.jsonc" }) + for (const section of input.legacy?.sections ?? []) out.push({ code: "SWM044", level: "warn", path: `legacy.${section}`, hint: t(locale, "cli.doctor.configFileHint") }) if (value !== null) { const providers = (value as any)?.providers if (providers && typeof providers === "object" && PROVIDER_KEYS.some((key) => (providers as any)[key]?.enabled === true && (providers as any)[key]?.observe === false)) out.push({ code: "SWM040", level: "warn", path: "providers" }) @@ -83,8 +89,11 @@ export function runDoctor(input: DoctorInput): DoctorResult { arr.findIndex((x) => x.code === d.code && x.path === d.path && x.level === d.level && (x.hint ?? "") === (d.hint ?? "")) === i) return { diagnostics: deduped.sort((a, b) => ({ error: 0, warn: 1, info: 2 }[a.level] - { error: 0, warn: 1, info: 2 }[b.level] || a.code.localeCompare(b.code))) } } -export function formatDoctorReport(result: DoctorResult): string { - if (!result.diagnostics.length) return "opencode-switchman doctor: no issues found" +export function formatDoctorReport(result: DoctorResult, locale?: unknown): string { + if (!result.diagnostics.length) return t(locale, "cli.doctor.noIssues") const rank = { error: 0, warn: 1, info: 2 } - return [...result.diagnostics].sort((a, b) => rank[a.level] - rank[b.level] || a.code.localeCompare(b.code)).map((d) => `${d.level.toUpperCase()} ${d.code}${d.path ? ` ${d.path}` : ""}${d.hint ? ` (hint: ${d.hint})` : ""}`).join("\n") + return [...result.diagnostics].sort((a, b) => rank[a.level] - rank[b.level] || a.code.localeCompare(b.code)).map((d) => t(locale, "cli.doctor.findingLine", { + level: d.level.toUpperCase(), code: d.code, + pathPart: d.path ? ` ${d.path}` : "", hintPart: d.hint ? ` (hint: ${d.hint})` : "", + })).join("\n") } diff --git a/src/gates.ts b/src/gates.ts index 7b0d8cd..1ac49aa 100644 --- a/src/gates.ts +++ b/src/gates.ts @@ -3,6 +3,8 @@ // Pure functions: all state injected via GateSnapshot; deny = return a reason (index.ts layer turns it into a thrown Error to block). import { META_LEGAL } from "./types" import type { GateSnapshot, Meta, ShellRegEntry } from "./types" +import type { MsgKey } from "./i18n" +import { t } from "./i18n" import { metaErrorHint, parseRouteMeta } from "./meta" import { computeLane, firstCandidate, laneOfShell } from "./lane" import { baseScoreDynamic, normalizeModelKey } from "./capability" @@ -12,7 +14,16 @@ import { isFallbackCandidate, isPrimaryCandidate } from "./lane-policy" // zero-retry silent redirection); non-redirectable classes (same-name conflict / chain exhausted with no candidate / gate-6 meta) stay null] // [2026-09-04]-[English localization: deny copy is now English — the earlier "deny copy frozen verbatim (locked by // legacy fixtures)" constraint is lifted as of 2026-09-04; test fixtures updated in sync] -export interface GateResult { deny: string | null; note: string | null; redirect: string | null } +// [2026-09-19]-[P3c status-log i18n: gate observe notes are structured GateNote {key, params} (index.ts emits +// notes[] via appendStatusLog(key, params); keys/params mirror src/locales/en.ts placeholders). The legacy English +// `note` string stays byte-identical for copy-pinning consumers: it is still built from the original literals +// side-by-side with each GateNote (not via t("en", ...) — gates.ts must stay importable while the i18n module graph +// is still being assembled by the parallel lane; switching the legacy render to t is a one-line follow-up). +// Deny/redirect stay prose; English only; no dispatch-decision change] +// [2026-09-19]-[i18n cleanup: observe-note legacy strings now render via t("en", key, params) (single source with +// the notes[] keys); deny literals stay prose. Byte-identical output — copy-pinning tests in dispatch-gates/routing prove it] +export interface GateNote { key: MsgKey; params?: Record<string, string | number> } +export interface GateResult { deny: string | null; note: string | null; notes: GateNote[] | null; redirect: string | null } function matrixStatus(shell: ShellRegEntry, mcombos: GateSnapshot["matrix"]): [string, string] { if (!shell.matrixKey) return ["unprobed", ""] @@ -60,7 +71,7 @@ function synthesizeMeta(agent: string, lanes: Record<string, string[]>): Meta { } } -const ROUTE_META_SYNTH_NOTE = "[opencode-switchman] ROUTE_META missing/malformed — synthesized from lane; declare it to enable review cross-family / source=user semantics" +const ROUTE_META_SYNTH_KEY = "notice.dispatch.routeMetaSynthNote" as MsgKey export function checkShell( agent: string, @@ -77,7 +88,8 @@ export function checkShell( // required field on a parseable line) keeps the gate-6 deny below — a producer error the delegator must fix]- if (metaErr === "missing" || metaErr === "malformed") { meta = synthesizeMeta(agent, snap.lanes) - metaSynthNote = ROUTE_META_SYNTH_NOTE + // [2026-09-19]-[i18n cleanup: legacy note renders from the catalog (byte-identical to the removed literal)] + metaSynthNote = t("en", ROUTE_META_SYNTH_KEY) } const lane = laneForCheck(agent, meta, snap.lanes) const base = snap.lanes[lane] ?? [] @@ -132,7 +144,7 @@ export function checkShell( if (act && act.enabled) { if (act.conflicts && act.conflicts.has(agent)) { // Non-redirectable class: same-name conflict requires user action - return { deny: `${agent} conflicts with a user-defined agent of the same name, not dispatchable (rename or delete the custom agent)${hint()}`, note: null, redirect: null } + return { deny: `${agent} conflicts with a user-defined agent of the same name, not dispatchable (rename or delete the custom agent)${hint()}`, note: null, notes: null, redirect: null } } if (act.activeShells && !act.activeShells.has(agent)) { const restart = act.restartRequired.length > 0 @@ -142,7 +154,7 @@ export function checkShell( return { // [2026-08-29]-[re-review P2 wording fix: "realtime" → "takes effect on the next request" (activation-face changes reach the dispatch gate on the next tool delegation)] deny: `${agent} not activated (model not in the current activation matrix: set it visible in model management / add it to favorites / switch the main session to this model to activate; takes effect on the next request${restart})${hint()}`, - note: null, + note: null, notes: null, redirect: cand, } } @@ -151,16 +163,21 @@ export function checkShell( if (status !== "enabled") { const [mstat, mreason] = snap.matrix !== null ? matrixStatus(shell, snap.matrix) : ["unknown", ""] if (status === "disabled" && snap.matrix !== null && mstat !== "down") { - return { - deny: null, - note: `[opencode-switchman] ${agent} registry=disabled but matrix status=${mstat || "missing"} (not down): fail-open, auto-corrected after the next probe refresh`, - redirect: null, + { + const registryNote: GateNote = { key: "notice.dispatch.registryDisabledNote", params: { agent, matrixStatus: mstat || "missing" } } + return { + deny: null, + // [2026-09-19]-[i18n cleanup: legacy note renders from the catalog (byte-identical)] + note: t("en", registryNote.key, registryNote.params), + notes: [registryNote], + redirect: null, + } } } const cand = candidateOf() return { deny: `${agent} not dispatchable (registry status=${status}${snap.matrix !== null && mstat === "down" ? `, matrix ${mstat}: ${mreason}` : ""})${hint()}`, - note: null, + note: null, notes: null, redirect: cand, } } @@ -169,28 +186,32 @@ export function checkShell( if (snap.matrix !== null) { const [mstat, mreason] = matrixStatus(shell, snap.matrix) if (mstat === "down") { - return { deny: `${agent} unavailable (matrix down, ${mreason})${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} unavailable (matrix down, ${mreason})${hint()}`, note: null, notes: null, redirect: candidateOf() } } if (mstat === "unknown" || mstat === "missing" || mstat === "unprobed") { - return { deny: null, note: `[opencode-switchman] ${agent} matrix status=${mstat} (not down): not blocked, probe refreshes next round`, redirect: null } + { + const matrixNote: GateNote = { key: "notice.dispatch.matrixStatusNote", params: { agent, matrixStatus: mstat } } + // [2026-09-19]-[i18n cleanup: legacy note renders from the catalog (byte-identical)] + return { deny: null, note: t("en", matrixNote.key, matrixNote.params), notes: [matrixNote], redirect: null } + } } } // Gate 2.5: model retired (consecutive 404s remove it from candidates permanently; cleared on restart; only the dynamic matrix injects retiredModels) // [2026-08-29]-[failure classification: vendor-agnostic; deny on provider/modelId hit, no pool hardcoding] if (snap.retiredModels?.has(`${shell.provider}/${shell.modelId}`)) { - return { deny: `${agent} unavailable (model retired: consecutive 404s, redirect to another candidate)${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} unavailable (model retired: consecutive 404s, redirect to another candidate)${hint()}`, note: null, notes: null, redirect: candidateOf() } } - // Gate 3: in-process isolation for probe-ok but real-call failures (not persisted; recovers after 30 minutes or on restart) + // Gate 3: in-process isolation for probe-ok but real-call failures (not persisted; recovers after 5 minutes or on restart) if (shell.comboKey && snap.realFailedCombos?.has(shell.comboKey)) { - return { deny: `${agent} temporarily unavailable (probe ok but actual delegation failed; auto-unlocks after 30 minutes or restart opencode)${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} temporarily unavailable (probe ok but actual delegation failed; auto-unlocks after 5 minutes or restart opencode)${hint()}`, note: null, notes: null, redirect: candidateOf() } } // Gate 4 breaker: down_agents hit by shell name or comboKey (600s window × 2 failures) const down = snap.routing?.down_agents if (down && ((agent in down) || (shell.comboKey && shell.comboKey in down))) { - return { deny: `${agent} temporarily unavailable (breaker tripped after consecutive failures; auto-recovers in about 10 minutes)${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} temporarily unavailable (breaker tripped after consecutive failures; auto-recovers in about 10 minutes)${hint()}`, note: null, notes: null, redirect: candidateOf() } } // Gate 5 pool exhaustion (only blocks when calls are certain to fail; unknown/high watermark does not block) @@ -199,7 +220,7 @@ export function checkShell( const why = pool === "glm" ? "GLM plan exhausted" : pool === "copilot" ? "Copilot credits exhausted" : "DeepSeek balance exhausted" - return { deny: `${agent} temporarily unavailable (${why})${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} temporarily unavailable (${why})${hint()}`, note: null, notes: null, redirect: candidateOf() } } // Gate 5.5 task-pool selection (manual pool-config.json): lane → participating-model list; a non-empty list overrides @@ -207,7 +228,7 @@ export function checkShell( { const allow = snap.poolConfig?.[lane] if (allow && allow.size > 0 && !allow.has(normalizeModelKey(shell.modelId))) { - return { deny: `${agent} not in the ${lane} task-pool selection list (use /poolConfig to adjust participating models per task pool, or redirect to another candidate)${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} not in the ${lane} task-pool selection list (use /poolConfig to adjust participating models per task pool, or redirect to another candidate)${hint()}`, note: null, notes: null, redirect: candidateOf() } } } @@ -225,7 +246,7 @@ export function checkShell( } return { deny: `${agent} dispatched to a shell name, invalid ROUTE_META: ${metaErrorHint(metaErr)}${fallback}`, - note: null, + note: null, notes: null, // a present-but-wrong META must be corrected by the delegator (rewriting it plugin-side would mask the error); stays null here redirect: null, } @@ -237,7 +258,7 @@ export function checkShell( // self-review seat (DOWNGRADED) instead of an unconditional deny that dead-ends the review lane ("review: none // available"). The exemption note is attached at the final return so the structural rw/ro + vision gates and the // fallback-chain checks below still apply to an exempted dispatch; a deny always supersedes the note.] - const REVIEW_SELF_REVIEW_NOTE = "[opencode-switchman] DOWNGRADED: no cross-family reviewer available — same-family self-review allowed; declare DOWNGRADED in the review conclusion" + const REVIEW_SELF_REVIEW_KEY = "notice.dispatch.reviewSelfNote" as MsgKey let reviewSelfReviewNote: string | null = null // Lazily computed once, only when the review-lane chain is actually needed (same try/catch pattern as the fallback block below) let reviewChain: import("./types").LaneResult | null = null @@ -265,22 +286,30 @@ export function checkShell( // same-family shell to the chain tail (scoring famClass), so cross-family is still served first. const hasCrossFamily = reviewChainOf()?.chain.some((c) => String(c.family ?? "") !== String(pf).toLowerCase()) ?? false if (hasCrossFamily) { - return { deny: `${agent} same family as producer (${pf}); re-review requires a cross-family perspective${hint("review")}`, note: null, redirect: candidateOf("review") } + return { deny: `${agent} same family as producer (${pf}); re-review requires a cross-family perspective${hint("review")}`, note: null, notes: null, redirect: candidateOf("review") } } - reviewSelfReviewNote = REVIEW_SELF_REVIEW_NOTE + reviewSelfReviewNote = t("en", REVIEW_SELF_REVIEW_KEY) } } if (meta!.capability === "rw" && String(shell.capability) === "ro") { - return { deny: `${agent} is a read-only shell (ro) and cannot take rw write tasks${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} is a read-only shell (ro) and cannot take rw write tasks${hint()}`, note: null, notes: null, redirect: candidateOf() } } if ((meta!.modality === "image" || meta!.modality === "vision") && !shell.vision) { - return { deny: `${agent} is not a vision shell and cannot take modality=${meta!.modality} tasks${hint("vision")}`, note: null, redirect: candidateOf("vision") } + return { deny: `${agent} is not a vision shell and cannot take modality=${meta!.modality} tasks${hint("vision")}`, note: null, notes: null, redirect: candidateOf("vision") } } if (lane === "vision" && meta!.modality === "text") { - return { deny: `${agent} lane=vision requires declaring an image/vision modality${hint("vision")}`, note: null, redirect: candidateOf("vision") } + return { deny: `${agent} lane=vision requires declaring an image/vision modality${hint("vision")}`, note: null, notes: null, redirect: candidateOf("vision") } } const capability = baseScoreDynamic(shell.modelId) - if (!isPrimaryCandidate(lane as import("./types").Lane, capability) && !isFallbackCandidate(lane as import("./types").Lane, capability)) { + // [2026-09-18]-[pool-config membership = qualification: a model explicitly selected into this lane's task pool is + // exempt from the capability level floor and the cross-level fallback top-2 checks — explicit user config wins over + // score judgment; the allow note records the override for the decision log] + const poolMember = snap.poolConfig?.[lane]?.has(normalizeModelKey(shell.modelId)) === true + // [2026-09-19]-[i18n cleanup: legacy note renders from the catalog (byte-identical to the removed literal)] + const poolOverrideNote = poolMember + ? t("en", "notice.dispatch.poolOverrideNote") + : null + if (!poolMember && !isPrimaryCandidate(lane as import("./types").Lane, capability) && !isFallbackCandidate(lane as import("./types").Lane, capability)) { // [2026-09-05]-[review last-resort seat exemption: a below-fallback shell (e.g. B-tier/L3) holding a last-resort // review seat — on the chain while the chain carries no L5 primary candidate — is allowed with the DOWNGRADED // note instead of denying "capability level too low", keeping the review lane dispatchable when only B-tier @@ -290,22 +319,29 @@ export function checkShell( const onChain = Boolean(rc?.chain.some((c) => c.shell === agent)) const noPrimary = Boolean(rc && !rc.chain.some((c) => isPrimaryCandidate("review" as import("./types").Lane, baseScoreDynamic(snap.registry?.[c.shell]?.modelId ?? "")))) // [2026-09-14]-[D5: the gate-6 synth note rides along when the META was synthesized for this dispatch] - if (onChain && noPrimary) return { deny: null, note: [metaSynthNote, REVIEW_SELF_REVIEW_NOTE].filter(Boolean).join(" ") || null, redirect: null } + if (onChain && noPrimary) { + const both: GateNote[] = [ + ...(metaSynthNote ? [{ key: ROUTE_META_SYNTH_KEY } as GateNote] : []), + { key: REVIEW_SELF_REVIEW_KEY }, + ] + // [2026-09-19]-[i18n cleanup: legacy note renders from the catalog (byte-identical)] + return { deny: null, note: [metaSynthNote, t("en", REVIEW_SELF_REVIEW_KEY)].filter(Boolean).join(" ") || null, notes: both, redirect: null } + } } - return { deny: `${agent} capability level too low to take ${lane} tasks${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} capability level too low to take ${lane} tasks${hint()}`, note: null, notes: null, redirect: candidateOf() } } - if (isFallbackCandidate(lane as import("./types").Lane, capability) && meta!.source !== "user") { + if (!poolMember && isFallbackCandidate(lane as import("./types").Lane, capability) && meta!.source !== "user") { let current try { current = computeLane(lane as import("./types").Lane, snap.lanes[lane] ?? base, buildParams() as any) } catch { - return { deny: `${agent} cannot confirm cross-level fallback eligibility for ${lane}; dispatch denied to avoid an unintended downgrade${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} cannot confirm cross-level fallback eligibility for ${lane}; dispatch denied to avoid an unintended downgrade${hint()}`, note: null, notes: null, redirect: candidateOf() } } if (!current.chain.some((candidate) => candidate.shell === agent)) { - return { deny: `${agent} not among the top-2 cross-level fallback candidates for ${lane}${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} not among the top-2 cross-level fallback candidates for ${lane}${hint()}`, note: null, notes: null, redirect: candidateOf() } } if (current.chain.some((candidate) => isPrimaryCandidate(lane as import("./types").Lane, baseScoreDynamic(snap.registry?.[candidate.shell]?.modelId ?? "")))) { - return { deny: `${agent} is a cross-level fallback candidate for ${lane}; same-level models are still available${hint()}`, note: null, redirect: candidateOf() } + return { deny: `${agent} is a cross-level fallback candidate for ${lane}; same-level models are still available${hint()}`, note: null, notes: null, redirect: candidateOf() } } } // [2026-08-31]-[de-vendorization: removed the hard deny for source=auto mis-picking pay-as-you-go pools — api billing is @@ -315,12 +351,20 @@ export function checkShell( // [2026-09-05]-[review same-family self-review: the last-resort exemption note (no cross-family reviewer on the chain) // is emitted here after every structural gate passed] // [2026-09-14]-[D5: a synthesized META rides as an observe note (a deny always supersedes it); both notes joined when they co-occur] - return { deny: null, note: [metaSynthNote, reviewSelfReviewNote].filter(Boolean).join(" ") || null, redirect: null } + // [2026-09-18]-[pool-config override note rides along on the allow path (deny branches above already carried the exemption)] + { + const allowNotes: GateNote[] = [ + ...(metaSynthNote ? [{ key: ROUTE_META_SYNTH_KEY } as GateNote] : []), + ...(reviewSelfReviewNote ? [{ key: REVIEW_SELF_REVIEW_KEY } as GateNote] : []), + ...(poolOverrideNote ? [{ key: "notice.dispatch.poolOverrideNote" } as GateNote] : []), + ] + return { deny: null, note: [metaSynthNote, reviewSelfReviewNote, poolOverrideNote].filter(Boolean).join(" ") || null, notes: allowNotes.length > 0 ? allowNotes : null, redirect: null } + } } /** Unregistered / non-shell name → fail-open (unknown built-in agents are not governed by routing) */ -export function noteUnknownAgent(agent: string): string { - return `[opencode-switchman] unknown subagent_type='${agent}': allowed (not in the shell list; built-in agents are not governed by routing)` +export function noteUnknownAgent(agent: string): GateNote { + return { key: "notice.dispatch.unknownAgentAllowed", params: { agent } } } /** [2026-09-04]-[built-in subagent block: explore/general competed with shell routing while being fail-open by default, diff --git a/src/i18n.ts b/src/i18n.ts new file mode 100644 index 0000000..d26f8b2 --- /dev/null +++ b/src/i18n.ts @@ -0,0 +1,77 @@ +// [2026-09-19]-[i18n core: render-time localization for all user-visible switchman UI strings (sidebar chrome, +// dialogs, status-log notices, quota labels, CLI copy). Locale chain: current session's project lang +// (lang.conversation: <workspace>/settings.json → AGENTS.md marker) → global ui.lang (state ui-locale.json, +// from the plugin config "ui" section) → terminal env (LC_ALL/LANG) → "en". Model-facing protocol copy +// (agents-md.ts protocol, [ROUTES]/[WATERMARK]/[LIMITS] lines, [LANG] line, lang-gate denials, ask directive +// body) stays English by design — capture anchors must remain byte-stable across locales] +import { detectUiLocale, loadLangConfig, normalizeUiLocale } from "./lang-config" +import { en } from "./locales/en" +import { zhCN } from "./locales/zh-CN" +import { zhTW } from "./locales/zh-TW" +import { ja } from "./locales/ja" +import { ko } from "./locales/ko" +import { es } from "./locales/es" +import { fr } from "./locales/fr" +import { de } from "./locales/de" +import { it } from "./locales/it" +import { pt } from "./locales/pt" +import { ru } from "./locales/ru" + +/** All locale tags shipped (mirrors UI_LOCALE_TAGS in lang-config.ts; keep the two in sync) */ +export const LOCALE_TAGS = ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de", "it", "pt", "ru"] as const +export type LocaleTag = (typeof LOCALE_TAGS)[number] + +/** Canonical message key set — keyof the English catalog (source of truth); other locales are Partial but completeness-tested */ +export type MsgKey = keyof typeof en + +export const CATALOGS: Record<LocaleTag, Partial<Record<MsgKey, string>>> = { + en, "zh-CN": zhCN, "zh-TW": zhTW, ja, ko, es, fr, de, it, pt, ru, +} + +/** Translate `key` into `locale` with `{param}` interpolation. Unknown locale or key falls back to English, then + * to `fallback`, then to the key itself — never throws, so a missing translation can never break rendering. */ +export function t(locale: unknown, key: MsgKey, params?: Record<string, string | number>, fallback?: string): string { + // [2026-09-19]-[typecheck fix: normalizeUiLocale returns string|null but is contractually limited to UI_LOCALE_TAGS, + // which mirrors LOCALE_TAGS exactly (keep the two in sync) — so its non-null results are safe to cast to LocaleTag] + const tag = (normalizeUiLocale(locale) as LocaleTag | null) ?? "en" + const cat = CATALOGS[tag] ?? CATALOGS.en! + const tmpl = cat[key] ?? CATALOGS.en![key] ?? fallback ?? String(key) + if (!params) return tmpl + return tmpl.replace(/\{([a-zA-Z0-9_]+)\}/g, (m: string, p: string) => (params[p] === undefined ? m : String(params[p]))) +} + +export interface DisplayLocaleInputs { + /** Project directory of the session being viewed (sidebar) — null/absent skips the project step (CLI) */ + sessionDir?: string | null + /** Configured workspace dirname (state workspace-meta.json); defaults to ".switchman" */ + workspaceDirname?: string + /** Global UI language override (state ui-locale.json; from plugin config "ui"."lang") */ + uiLang?: string | null + /** Environment for terminal-locale detection (defaults to process.env inside detectUiLocale) */ + env?: Record<string, string | undefined> +} + +/** Resolve the display locale for the sidebar/CLI: project lang → global ui.lang → terminal env → "en". + * Pure — callers own the IO (reading state files / session directory). */ +export function resolveDisplayLocale(inputs: DisplayLocaleInputs): LocaleTag { + if (inputs.sessionDir) { + try { + const loaded = loadLangConfig(inputs.sessionDir, inputs.workspaceDirname?.trim() || ".switchman") + if (loaded) { + const tag = normalizeUiLocale(loaded.cfg.conversation) + // UI_LOCALE_TAGS ≡ LOCALE_TAGS sync contract: normalizeUiLocale only returns tags from that set + if (tag) return tag as LocaleTag + } + } catch { /* fail-open: fall through to the next chain step */ } + } + const ui = normalizeUiLocale(inputs.uiLang) + if (ui) return ui as LocaleTag + return detectUiLocale(inputs.env).locale as LocaleTag +} + +/** Render one persisted status-log entry: legacy text-only entries pass through verbatim; keyed entries translate + * (unknown runtime keys — e.g. after a downgrade — fall back to the stored text, then the key). */ +export function renderNotice(entry: { key?: string; params?: Record<string, string | number>; text?: string }, locale: unknown): string { + if (!entry.key) return entry.text ?? "" + return t(locale, entry.key as MsgKey, entry.params, entry.text ?? entry.key) +} diff --git a/src/index.ts b/src/index.ts index 44bf88c..ccad481 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,6 +19,8 @@ import { appendStatusLog, writeRouteSnapshot, writeQuotaBrief, + writeUiLocale, + writeWorkspaceMeta, loadProviderCache, saveProviderCache, nowIso, providerCacheStale, providerModelsDelta, loadSubagentCapRegistry, saveSubagentCapRegistry, withPathLock, @@ -34,8 +36,9 @@ import { capThresholdsByWindow, subagentCapOf, capByWindow, subagentCapDenyMessage, subagentResumeDenyMessage, ctxControlMarkerOf, pausedWindowWarning, subagentSoftTiersOf, shellSoftTierDecision, + matchContinuation, DENY_RETRY_OVERHEAD_TOKENS, } from "./context-watch" -import type { CtxControlAction, ReadEstimate, FileSample, ContextThresholds } from "./context-watch" +import type { CtxControlAction, ReadEstimate, FileSample, ContextThresholds, ReadContinuation } from "./context-watch" import { backupSession, compactSession, v1HandoverPort, type HandoverResult } from "./handover-core" import { logDecision, BILLING_API_BOOST } from "./scoring" import type { WaterFactor, DecisionRecord } from "./scoring" @@ -47,7 +50,8 @@ import { injectShells, injectShellDefs, selectInjectableDefs } from "./shells" import { buildBanner, shortName, providerStatusEntries } from "./banner" import { refreshSelfUpdate, updateBannerText, ensureUpdateCommands, detectLoadMode, pluginCliPath } from "./selfupdate" import { loadPoolConfig, overrideSummary } from "./user-overrides" -import { poolConfigCommandMd, modelRankCommandMd, expertCommandMd, langCommandMd, ctxPauseCommandMd, ctxResumeCommandMd } from "./commands-md" +import { poolConfigCommandMd, modelRankCommandMd, expertCommandMd, langCommandMd, ctxPauseCommandMd, ctxResumeCommandMd, switchmanSetupCommandMd } from "./commands-md" +import { setupCompletionNow, setupDenyMessage, setupDirective, setupMissingBrief } from "./setup-gate" import { billingOfProvider, loadUserConfig, resolveEffectiveOptions, routingPeakActive, routePolicy, DEFAULT_DELEGATION_FLOOR } from "./config" import { poolForProviderId } from "./provider-config" import { runDoctor } from "./doctor" @@ -61,7 +65,7 @@ import { LANE_ORDER, DEFAULT_LANG_CANDIDATES } from "./types" import type { SwitchmanOptions, Lane, LaneResult, Pool, ShellRegEntry, ModelKey } from "./types" import { WorkspaceTracker, DEFAULT_WORKSPACE_DIRNAME, type EnsuredWorkspace } from "./workspace" import { TmuxPaneManager, serverOriginOf } from "./tmux" -import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion, langGateDecision, LANG_GATE_TOOLS, hasLangMarkerQuestions, detectUiLocale } from "./lang-config" +import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion, langGateDecision, LANG_GATE_TOOLS, hasLangMarkerQuestions, detectUiLocale, normalizeUiLocale } from "./lang-config" import { SEARCH_CLARIFY_TOOLS, SEARCH_CLARIFY_MAX_DENIES, isBroadSearchCall, describeSearchCall, searchClarifyDenyMessage, hasSearchMarkerQuestion } from "./search-clarify" import { renderRouteLine, routeLineEnabled } from "./route-line" import { loadDispatchMode } from "./dispatch-mode" @@ -174,6 +178,10 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-05]-[v1 read budget: per-turn self-read spend (resets each user turn), watermark sample history for // pace estimation, and last-seen user message id for turn-boundary detection (assistant parentID comparison)] const turnReadUsage = new Map<string, { used: number; at: number }>() + // [2026-09-18]-[v1.1 continuation merge: last granted-but-not-completed read window per main session (same logical + // read = same file + follow-up offset resuming near the granted end); a bounded continuation completes the original + // want in one shot. Reset with the turn (turnReadUsage spots) and on session.deleted] + const readContinuation = new Map<string, ReadContinuation>() const wmHistory = new Map<string, number[]>() const lastUserMsg = new Map<string, string>() // [2026-09-11]-[/ctx-pause //ctx-resume: per-session context-control suspension — the commands inject a fixed marker @@ -228,7 +236,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { options: () => options.tmux, serverOrigin: serverOriginOf((input as any).serverUrl, process.env.OPENCODE_PORT) ?? "", dir: pluginDirectory, - log: (m) => appendStatusLog(m), + // [2026-09-19]-[P3c status-log i18n: tmux/dispatch-mode log callbacks carry structured (key, params)] + log: (k, p) => appendStatusLog(k, p), }) void tmuxPanes.init() const pendingTask = new Map<string, Array<{ agent: string; at: number }>>() @@ -254,9 +263,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { function applyCtxControlAction(sid: string, act: CtxControlAction | null): void { if (act === "pause" && !ctxPaused.has(sid)) { ctxPaused.add(sid) - appendStatusLog(`ctx control paused for session ${sid} (/ctx-pause): read gates + self-read budget + auto-handover suspended; measurement continues`) + // [2026-09-19]-[i18n sweep: all appendStatusLog prose in this file migrated to message keys (src/locales/en.ts) + // via the new key+params writer signature; gates.ts/tmux.ts note forwarders stay as-is (their templates live + // in those files)]-[no behavior change, log entries are now structured {key, params}] + appendStatusLog("notice.ctx.paused", { sid }) } else if (act === "resume" && ctxPaused.delete(sid)) { - appendStatusLog(`ctx control resumed for session ${sid} (/ctx-resume): read gates + auto-handover live again`) + appendStatusLog("notice.ctx.resumed", { sid }) } } @@ -459,8 +471,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (!id || isShellOrInternalSession(id)) return workspace.record(info as any) const ensured = workspace.ensure(id) - if (ensured?.created) appendStatusLog(`artifact workspace created: ${ensured.rel}`) - else if (ensured?.renamed) appendStatusLog(`artifact workspace renamed: ${ensured.renamed} → ${ensured.rel}`) + if (ensured?.created) appendStatusLog("notice.workspace.created", { rel: ensured.rel }) + else if (ensured?.renamed) appendStatusLog("notice.workspace.renamed", { oldRel: ensured.renamed, rel: ensured.rel }) } catch { /* fail-open */ } } @@ -534,11 +546,11 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // verified missing → opencode will create a fresh session; the session.created path covers that pane if (res && !(res as any)?.data?.id) return void tmuxPanes.noteChild(sessionID, tid, shellName) - appendStatusLog(`tmux pane mirroring: resume dispatch ses_${tid.slice(-6)} (${shellName}) — task_id reuse, pane opened directly (no session.created will fire)`) + appendStatusLog("notice.dispatch.mirrorResumeReuse", { taskId: tid.slice(-6), shellName }) }) .catch(() => { void tmuxPanes.noteChild(sessionID, tid, shellName) - appendStatusLog(`tmux pane mirroring: resume dispatch ses_${tid.slice(-6)} (${shellName}) — session lookup failed, fail-open pane`) + appendStatusLog("notice.dispatch.mirrorResumeLookupFailed", { taskId: tid.slice(-6), shellName }) }) } catch { /* fail-open */ } } @@ -566,7 +578,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (overrideWatchTimer) clearTimeout(overrideWatchTimer) overrideWatchTimer = setTimeout(() => { overrideWatchTimer = null - try { appendStatusLog("capability rank/task-pool selection changed: banner and sidebar refresh immediately") } catch { /* fail-open */ } + try { appendStatusLog("notice.capability.selectionChanged") } catch { /* fail-open */ } refreshSidebarState() }, 200) if (typeof overrideWatchTimer === "object" && overrideWatchTimer !== null && "unref" in overrideWatchTimer) (overrideWatchTimer as any).unref() @@ -581,7 +593,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const w = watch(dir, { recursive: false }, (_event, filename) => { if (filename && OVERRIDE_WATCH_FILES.has(String(filename))) onOverrideConfigChanged() }) - w.on("error", (exc) => { try { appendStatusLog(`fs.watch(${dir}) override-config watch error (mtime polling fallback): ${exc}`) } catch { /* fail-open */ } }) + w.on("error", (exc) => { try { appendStatusLog("notice.capability.overrideWatchError", { dir, exc: String(exc) }) } catch { /* fail-open */ } }) } catch { /* fail-open: missing directory/startup failure is covered by polling */ } // mtime polling fallback: first run records a baseline without triggering const poll = () => { @@ -603,7 +615,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-08-29]-[re-review P2-5: legacy in-memory marks are always empty yet still guarded, matching the new gate's write point against future non-dynamic write paths]- if (!dynamic) return routing const down = { ...routing.down_agents } - for (const combo of realFailedComboKeys()) down[combo] = "probe ok but real delegation failed (30-min in-memory isolation)" + for (const combo of realFailedComboKeys()) down[combo] = "probe ok but real delegation failed (5-min in-memory isolation)" return { ...routing, down_agents: down } } @@ -639,7 +651,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { try { return readConfigured(stateRoot, mode) } catch (exc) { - appendStatusLog(`config surface read fail-open: ${exc}`) + appendStatusLog("notice.matrix.configSurfaceFailOpen", { exc: String(exc) }) return { configStatus: "empty" as const, models: [] as ModelKey[] } } } @@ -667,12 +679,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const floorModels = freeFloor.length > 0 ? freeFloor : [...new Set(loadManifest().shells.map((s) => `${s.provider}/${s.modelId}`))] - if (freeFloor.length > 0) appendStatusLog(`floor = ${freeFloor.length} OpenCode Zen free models (catalog ${catalog.status})`) - else appendStatusLog(`floor fell back to the static manifest (catalog ${catalog.status}, 0 free models)`) + if (freeFloor.length > 0) appendStatusLog("notice.matrix.floorFreeModels", { floorCount: freeFloor.length, catalogStatus: catalog.status }) + else appendStatusLog("notice.matrix.floorFallback", { catalogStatus: catalog.status }) const realKnownProviders = new Set(providerModels.providers) const invalidFavoriteModels = configured.models.filter((m) => !realKnownProviders.has(m.slice(0, m.indexOf("/")))) if (invalidFavoriteModels.length > 0) { - appendStatusLog(`visible set/favorites contain invalid models with unknown provider (provider not connected; ignored, no shells built): ${invalidFavoriteModels.join(", ")}`) + appendStatusLog("notice.matrix.invalidModelsUnknownProvider", { modelList: invalidFavoriteModels.join(", ") }) } const validConfiguredModels = configured.models.filter((m) => realKnownProviders.has(m.slice(0, m.indexOf("/")))) const supersetModels = [...new Set([...validConfiguredModels, ...providerModels.models, ...floorModels])] @@ -770,18 +782,18 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (PROVIDER_LIST_BACKOFF_MS[i] > 0) await new Promise((r) => setTimeout(r, PROVIDER_LIST_BACKOFF_MS[i])) try { const result = await attemptProviderList(input, PROVIDER_LIST_ATTEMPT_TIMEOUT_MS) - if (i > 0) appendStatusLog(`provider.list attempt ${i + 1} succeeded (previous ${i} not ready)`) + if (i > 0) appendStatusLog("notice.provider.probeAttemptSucceeded", { attempt: i + 1, prevAttempts: i }) return { ...result, fellBack: false } } catch (exc) { lastExc = exc if (i < PROVIDER_LIST_BACKOFF_MS.length - 1) { - appendStatusLog(`provider.list attempt ${i + 1} not ready, backing off: ${exc}`) + appendStatusLog("notice.provider.probeAttemptBackoff", { attempt: i + 1, exc: String(exc) }) } } } // all attempts failed: fall back to the cfg.provider key set (providerIDs only, as restartRequired baseline; model surface covered by config surface/built-in chains) const keys = Object.keys(cfg.provider ?? {}) - appendStatusLog(`provider.list unavailable (fell back to ${keys.length} cfg.provider keys after ${PROVIDER_LIST_BACKOFF_MS.length} attempts): ${lastExc}`) + appendStatusLog("notice.provider.unavailableCfgFallback", { keyCount: keys.length, attemptCount: PROVIDER_LIST_BACKOFF_MS.length, exc: String(lastExc) }) return { models: [], providers: keys, fellBack: true } } @@ -806,7 +818,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { saveProviderCache({ at: nowIso(), models: result.models, providers: result.providers }) const fresh = result.providers.filter((p) => !knownProviders.has(p)) if (fresh.length > 0) { - appendStatusLog(`provider.list background probe: new provider(s) connected (${fresh.join(", ")}) — restart opencode to complete shell registration`) + appendStatusLog("notice.provider.probeNewProvider", { providers: fresh.join(", ") }, true) clearBannerCache() } // [2026-09-06]-[model-drift heal: when the fresh list differs from the one the current superset was built from @@ -824,9 +836,16 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { delta.added.length > 0 ? `added: ${delta.added.join(", ")}` : null, delta.removed.length > 0 ? `removed: ${delta.removed.join(", ")}` : null, ].filter(Boolean).join("; ") - appendStatusLog(`provider.list background probe: model list drifted (${drift}) — superset manifest rebuilt, /modelRank //poolConfig lists updated${delta.added.length > 0 ? "; new shells dispatch after the next opencode restart" : ""}`) + appendStatusLog( + "notice.provider.probeModelDrift", + { + drift, + restartHint: delta.added.length > 0 ? "; new shells dispatch after the next opencode restart" : "", + }, + true, + ) } catch (exc) { - appendStatusLog(`provider.list background probe: superset rebuild failed (kept previous manifest): ${exc}`) + appendStatusLog("notice.provider.probeRebuildFailed", { exc: String(exc) }) } } return @@ -878,7 +897,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { }, 600_000) if (typeof timer === "object" && timer !== null && "unref" in timer) (timer as any).unref() } catch (exc) { - appendStatusLog(`warmup fail-open: ${exc}`) + appendStatusLog("notice.probe.warmupFailOpen", { exc: String(exc) }) } } @@ -892,10 +911,15 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { try { const s = syncBundledSkills() if (s.installed.length + s.updated.length + s.removed.length > 0) { - appendStatusLog(`skills synced: ${s.installed.length} installed, ${s.updated.length} updated, ${s.removed.length} removed (${[...s.installed, ...s.updated, ...s.removed].join(", ")})`) + appendStatusLog("notice.skills.synced", { + installedCount: s.installed.length, + updatedCount: s.updated.length, + removedCount: s.removed.length, + skillNames: [...s.installed, ...s.updated, ...s.removed].join(", "), + }) } } catch (exc) { - appendStatusLog(`skill sync fail-open: ${exc}`) + appendStatusLog("notice.skills.syncFailOpen", { exc: String(exc) }) } } @@ -1085,7 +1109,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { doctorSummary, matrixInfo, update: updateBannerText(), - overrides: overrideSummary(), + overrides: { ...overrideSummary(), setup: setupCompletionNow() }, }) // [WATERMARK] line needs raw quota data → second assembly (the banner pure function takes a snapshot; real quota added here) const lines2 = buildBanner({ @@ -1100,7 +1124,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { dsLowWarnCny: options.quota!.deepseek!.lowBalanceWarnCny, matrixInfo, update: updateBannerText(), - overrides: overrideSummary(), + overrides: { ...overrideSummary(), setup: setupCompletionNow() }, }) // [2026-08-29]-[scoring engine decision log: every banner rebuild (15s cache expiry) appends per-lane score details; fail-open, never blocks] try { @@ -1137,7 +1161,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { bannerCache = { at: Date.now(), lines: lines2 } return lines2 } catch (exc) { - appendStatusLog(`banner fail-open: ${exc}`) + appendStatusLog("notice.banner.failOpen", { exc: String(exc) }) return [] } } @@ -1213,13 +1237,49 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const filePath = typeof output.args?.filePath === "string" ? output.args.filePath : "" if (filePath && BINARY_EXT.test(filePath)) return const sample = await fileSample(filePath) - est = sample ? estimateReadRange(sample, output.args, readBudget) : null + // [2026-09-18]-[v1.1 need-aware sizing: the per-call grant ceiling rides the remaining turn headroom (max R* + // on a spent turn, up to 2×R* fresh) — a demonstrated-range read lands one-shot instead of deny → partial → + // continuation fragments; post-hoc charging keeps the per-turn top intact] + const grantTokens = Math.max(readBudget, Math.max(0, turnBudgetOf(readBudget) - turnUsed)) + est = sample ? estimateReadRange(sample, output.args, readBudget, grantTokens) : null + } + // [2026-09-18]-[v1.1 continuation merge: a follow-up read resuming at/near the last granted window's end is the + // same logical read continuing — its bounded remainder completes in one shot (see budgetGateDecision)] + const cont = input.tool === "read" && est ? matchContinuation(readContinuation.get(sid), output.args, est.tokensPerLine) : null + const action = budgetGateDecision({ tool: input.tool, level, readBudget, turnUsed, bashCommand: cmd, est, cont }) + if (action === "allow") { + // [2026-09-18]-[v1.1: an in-band continuation is bounded to the remaining want (never grows past the ask); + // a smaller explicit ask keeps the un-granted tail pending, otherwise the want is closed] + if (cont && cont.wantRemainderTokens <= readBudget + DENY_RETRY_OVERHEAD_TOKENS) { + const callLimit = typeof output.args?.limit === "number" && output.args.limit > 0 ? Math.floor(output.args.limit) : Number.POSITIVE_INFINITY + const granted = Math.max(1, Math.min(callLimit, cont.wantRemainderLines)) + output.args.limit = granted + const prev = readContinuation.get(sid) + if (prev && granted < cont.wantRemainderLines) readContinuation.set(sid, { ...prev, grantedEndLine: cont.offset + granted - 1 }) + else readContinuation.delete(sid) + appendStatusLog("notice.ctx.readBudgetContinuation", { + fileName: basename(String(output.args.filePath)), + granted, + offset: cont.offset, + turnUsed, + turnBudget: turnBudgetOf(readBudget), + }) + } else if (input.tool === "read") { + readContinuation.delete(sid) // the ask is fully served in one shot — the want is closed + } + return } - const action = budgetGateDecision({ tool: input.tool, level, readBudget, turnUsed, bashCommand: cmd, est }) - if (action === "allow") return if (action === "cap" && est) { output.args.limit = est.suggestedLimit - appendStatusLog(`read budget gate cap (tool read, file ${basename(String(output.args.filePath))}, est ~${est.totalTokens} -> limit ${est.suggestedLimit}, turn ${turnUsed}/${turnBudgetOf(readBudget)})`) + // [2026-09-18]-[v1.1: remember the granted window + the demonstrated want so the model's own continuation completes in one shot] + readContinuation.set(sid, { filePath: String(output.args?.filePath ?? ""), grantedEndLine: (est.offset ?? 1) + est.suggestedLimit - 1, wantEndLine: est.requestedEndLine }) + appendStatusLog("notice.ctx.readBudgetGateCap", { + fileName: basename(String(output.args.filePath)), + totalTokens: est.totalTokens, + suggestedLimit: est.suggestedLimit, + turnUsed, + turnBudget: turnBudgetOf(readBudget), + }) return } const { ctx } = currentContext() @@ -1227,10 +1287,11 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const cand = hint ? ` (e.g. ${hint}, ROUTE_META role=scouter)` : "" const candPlain = hint ? ` (e.g. ${hint})` : "" const pace = watermarkPace(sid) - const denyLog = `read budget gate ${action} (tool ${input.tool}, est ~${est ? est.totalTokens : "-"}, C~${kk(wm.tokens)}, T_est≈${pace ? pace.turnsToHard : "-"}, turn ${turnUsed}/${turnBudgetOf(readBudget)})` let msg: string if (action === "deny-budget" && est) { - msg = `[opencode-switchman] read ${output.args.filePath} would inject ~${est.totalTokens} tok (self-read budget ${readBudget}): retry bounded as \`read ${output.args.filePath} limit=${est.suggestedLimit} offset=${est.offset ?? 1}\` or delegate to an economy shell${cand}` + // [2026-09-18]-[v1.1: record the grant the retry params promise, so the model's bounded retry and its continuation merge] + readContinuation.set(sid, { filePath: String(output.args?.filePath ?? ""), grantedEndLine: (est.offset ?? 1) + est.suggestedLimit - 1, wantEndLine: est.requestedEndLine }) + msg = `[opencode-switchman] read ${output.args.filePath} would inject ~${est.totalTokens} tok (self-read budget ${readBudget}, turn headroom ${Math.max(0, turnBudgetOf(readBudget) - turnUsed)}): retry bounded as \`read ${output.args.filePath} limit=${est.suggestedLimit} offset=${est.offset ?? 1}\` or delegate to an economy shell${cand}` } else if (action === "deny-turn") { msg = `[opencode-switchman] per-turn self-read budget spent (${turnUsed}/${turnBudgetOf(readBudget)}; resets on your next user message): delegate this read to an economy shell${cand}` } else if (action === "deny-archaeology") { @@ -1243,11 +1304,20 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { return } denySkip.add(input.callID) - appendStatusLog(denyLog) + appendStatusLog("notice.ctx.readBudgetGate", { + action, + tool: input.tool, + totalTokens: est ? est.totalTokens : "-", + contRem: cont ? `, cont rem ~${cont.wantRemainderTokens}` : "", + wmTokens: kk(wm.tokens), + turnsToHard: pace ? pace.turnsToHard : "-", + turnUsed, + turnBudget: turnBudgetOf(readBudget), + }) throw new Error(msg) } catch (exc) { if (denySkip.has(input.callID)) throw exc - appendStatusLog(`read budget gate fail-open (allowed): ${exc}`) + appendStatusLog("notice.ctx.readBudgetGateFailOpen", { exc: String(exc) }) } } @@ -1272,11 +1342,11 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { ? `delegate the vision shell ${head} (ROUTE_META {"lane":"vision","role":"observer","modality":"image","capability":"ro","source":"auto"}) with this path in the prompt` : "call an MCP vision tool on this path" denySkip.add(input.callID) - appendStatusLog(`image read guard: model ${key} has no vision input; denied read ${basename(filePath)} (session ${sid})`) + appendStatusLog("notice.image.readGuardDenied", { modelKey: key, fileName: basename(filePath), sid }) throw new Error(`[opencode-switchman] this session's model (${key}) has no vision input — the host would reject the image content of ${filePath}. Instead: ${redirect}, or skip reading this image.`) } catch (exc) { if (denySkip.has(input.callID)) throw exc - appendStatusLog(`image read guard fail-open (allowed): ${exc}`) + appendStatusLog("notice.image.readGuardFailOpen", { exc: String(exc) }) } } @@ -1324,8 +1394,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const errors = doctor.diagnostics.filter((d) => d.level === "error").length const warns = doctor.diagnostics.filter((d) => d.level === "warn").length doctorSummary = errors || warns ? `doctor: ${errors} error / ${warns} warn` : null - if (doctorSummary) appendStatusLog(`doctor found ${errors} error / ${warns} warn; run /switchman-doctor to view`) + if (doctorSummary) appendStatusLog("notice.doctor.summary", { errorCount: errors, warnCount: warns }) try { writeJsonAtomic(paths().doctorSnapshot, { at: new Date().toISOString(), diagnostics: doctor.diagnostics.map((d) => ({ code: d.code, level: d.level, path: d.path })) }) } catch { /* fail-open */ } + // [2026-09-19]-[i18n wiring step 1: persist the normalized global UI locale + workspace dirname to state files + // once per startup for the render-time locale chain (src/i18n.ts resolveDisplayLocale reads them back)]-[fail-open] + try { writeUiLocale(normalizeUiLocale(userConfig.config.ui.lang) ?? null) } catch { /* fail-open */ } + try { writeWorkspaceMeta(userConfig.config.workspace.dirname) } catch { /* fail-open */ } collectCreds(cfg) creds.copilotToken = creds.copilotToken ?? readAuthStore().githubToken // [2026-08-29]-[one-click upgrade command assets: prod registers /switchman-update, local removes leftovers — effective on both legacy/dynamic paths]- @@ -1335,6 +1409,10 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { cfg.command = { "poolConfig-chat": { template: poolConfigCommandMd(pluginCliPath("switchman-config.js")), description: "Configure task-pool participating models conversationally (economy/mechanical/main/hard/vision/review); use /poolConfig for the manual dialog" }, "modelRank-chat": { template: modelRankCommandMd(pluginCliPath("switchman-config.js")), description: "Configure model capability ranks conversationally (manual ranks override base capability scores); use /modelRank for the manual dialog" }, + // [2026-09-19]-[/switchman-setup-chat: chat fallback for the TUI /switchman-setup wizard (src/tui.tsx) — the + // setup hard gate (setup-gate.ts) denies task dispatch until all 6 pools + the rank are configured, so the + // guided flow must be reachable from non-TUI clients too]- + "switchman-setup-chat": { template: switchmanSetupCommandMd(pluginCliPath("switchman-config.js")), description: "Guided switchman setup: configure all 6 task pools and the capability ranking (chat fallback when the TUI /switchman-setup is unavailable)" }, // [2026-09-05]-[/expert: expert consultation — review-pool head preferred, hard-pool head's ro face as fallback; // selection is read live from the [ROUTES] banner at execution time (no stale CLI snapshot), dispatch goes // through the standard six gates + auto-redirect] @@ -1359,7 +1437,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // legacy: static shells.json path (behavior byte-identical with v1.2) const { registry } = currentContext() const n = injectShells(cfg, registry) - appendStatusLog(`injected ${n} model shells (agents, legacy static matrix)`) + appendStatusLog("notice.injection.legacyStaticMatrix", { shellCount: n }) // [2026-08-29]-[config hook triggers the self-update check]-[async check; failure never blocks startup] refreshSelfUpdate().then((state) => { if (state?.outdated) clearBannerCache() }).catch(() => {}) return @@ -1378,14 +1456,14 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (providerCache && !providerCacheStale(providerCache)) { providerModels = { models: providerCache.models, providers: providerCache.providers, fellBack: false } usedProviderCache = true - appendStatusLog(`provider.list using cross-restart cache (${providerCache.providers.length} providers, cached at ${providerCache.at}); verifying additions in background`) + appendStatusLog("notice.provider.cacheUsed", { providerCount: providerCache.providers.length, cachedAt: providerCache.at }) } else if (providerCache) { // [2026-09-06]-[stale cache no longer trusted blindly: provider model lists grow over time (new flagship models), and // the old "cache first, heal next restart" flow locked brand-new models out of the injected surface until a second // restart. A cache past TTL (or with an unparseable timestamp) now triggers a live probe (full backoff budget) before // the superset build; on probe failure the stale cache is still used (fail-open) and the background watchdog keeps // retrying]-[new provider models surface in the same restart] - appendStatusLog(`provider.list cache stale (cached at ${providerCache.at}), probing live before the superset build`) + appendStatusLog("notice.provider.cacheStale", { cachedAt: providerCache.at }) const live = await collectProviderModels(input, cfg) if (!live.fellBack) { providerModels = live @@ -1435,17 +1513,29 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { refreshSidebarState() probeP.then(refreshSidebarState).catch(() => {}) // [2026-08-31]-[switched to persisted status-log rendered by the tui.tsx sidebar, no longer flooding stderr over the input box]-[high-frequency recompute notices] - appendStatusLog(`activation matrix recomputed (gen=${state.generation}, active shells ${state.activeShells.length}, probes ${source}×${targets.length})`) + appendStatusLog("notice.matrix.recomputed", { + generation: state.generation, + activeShellCount: state.activeShells.length, + source, + targetCount: targets.length, + }) }, }) manager.recompute(face.configured) manager.start() - appendStatusLog(`injected ${injected.size} shells (mode=${runMode}, injection surface=${options.injection!.mode}=${fullSupersetCount}→${face.defs.length} after curation, conflicts ${conflicts.size}; activation gating active)`) + appendStatusLog("notice.injection.shellCount", { + shellCount: injected.size, + runMode, + injectionMode: String(options.injection!.mode), + fullSupersetCount, + faceCount: face.defs.length, + conflictCount: conflicts.size, + }) // [2026-08-29]-[config hook triggers the self-update check]-[async check; failure never blocks startup] refreshSelfUpdate().then((state) => { if (state?.outdated) clearBannerCache() }).catch(() => {}) } catch (exc) { configFailed = true - appendStatusLog(`config hook fail-open: ${exc}`) + appendStatusLog("notice.injection.configHookFailOpen", { exc: String(exc) }) } }, @@ -1498,19 +1588,33 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-07]-[moved BELOW the shell/internal early-return: main-session-only injection (shell subagents and // title/compaction sessions must not receive the [LANG] line or the ask directive); for main sessions it is // still the first injected part of the turn]- + // [2026-09-19]-[loadLangConfig hoisted out of the lang.enabled branch: the [SETUP] directive below reuses the + // same read (one disk read per turn, cheap) and keys on language-config existence exactly like the tool-level + // lang gate / setup gate, so prompt copy and enforcement can never disagree]- + const langLoaded = loadLangConfig(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) if (options.lang!.enabled) { - const loaded = loadLangConfig(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) - if (loaded) output.system.push(renderLangLine(loaded.cfg, loaded.source)) + if (langLoaded) output.system.push(renderLangLine(langLoaded.cfg, langLoaded.source)) else if (options.lang!.ask !== false && input.sessionID && !langAsked.has(input.sessionID) && !langGateWaived.has(input.sessionID)) { langAsked.add(input.sessionID) // [2026-09-14]-[D4 locale-following ask: question texts follow the detected UI locale (env LC_ALL → LANG, // normalized, fail-open "en"); the `switchman-lang n/3: ` marker prefix stays byte-stable so the plugin-side // capture anchor is locale-independent; the directive body/deny copy stay English (model-facing)] const ui = detectUiLocale() - appendStatusLog(`lang ask locale=${ui.locale} (${ui.via === "default" ? "default" : `env ${ui.via}`})`) + appendStatusLog("notice.lang.askLocale", { locale: ui.locale, source: ui.via === "default" ? "default" : `env ${ui.via}` }) output.system.push(renderAskDirective(options.lang!.candidates ?? DEFAULT_LANG_CANDIDATES, ui.locale)) } } + // [2026-09-19]-[setup hard gate directive: while switchman setup is incomplete (any of the 6 task pools without + // a selected model, or the capability ranking missing) AND the project language config exists, push a [SETUP] + // advisory right after the lang logic (same output.system push mechanism, English body by design — the model + // relays it in the user's conversation language). The transform re-runs per model request, so it renders every + // turn while incomplete — no latch. Silent while the language config is missing: the lang ask must stay the + // single voice until it is answered (the tool-level lang gate blocks task meanwhile); reads are mtime-cached, + // so a /switchman-setup write clears this directive on the next turn]- + if (langLoaded) { + const setup = setupCompletionNow() + if (!setup.complete) output.system.push(setupDirective(setup)) + } // [2026-08-29]-[fail-open visibility: explicit warning when injection crashes — don't dispatch; do it yourself or tell the user]- if (configFailed) { output.system.push("[opencode-switchman] ⚠ plugin injection failed (shells/dispatch gates unavailable) — task delegation forbidden this turn; do it yourself or explain to the user, then proceed yourself") @@ -1570,7 +1674,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } } } catch (exc) { - appendStatusLog(`rules/banner fail-open: ${exc}`) + appendStatusLog("notice.banner.rulesFailOpen", { exc: String(exc) }) } }, @@ -1643,9 +1747,9 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { written += res.written } } - if (written > 0) appendStatusLog(`image relay: model ${key} has no vision input; persisted ${written} image(s) to disk (${relayed} image part(s) relayed across session history, session ${sid})`) + if (written > 0) appendStatusLog("notice.relay.persisted", { modelKey: key, written, relayed, sid }) } catch (exc) { - appendStatusLog(`image relay fail-open (passed through): ${exc}`) + appendStatusLog("notice.relay.failOpen", { exc: String(exc) }) } }, @@ -1660,14 +1764,14 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (capSid && terminatedSessions.has(capSid)) { denySkip.add(input.callID) const cap = effectiveSubagentCap(capSid) ?? subagentCapOf(options.context) ?? 0 - appendStatusLog(`subagent context cap: tool '${input.tool}' denied in terminated session ${capSid}`) + appendStatusLog("notice.ctx.capToolDenied", { tool: input.tool, sid: capSid }) throw new Error(subagentCapDenyMessage(shellWatermark.get(capSid)?.tokens ?? cap, cap)) } if (input.tool === "task") { const tid = (output.args as any)?.task_id if (typeof tid === "string" && tid && terminatedSessions.has(tid)) { denySkip.add(input.callID) - appendStatusLog(`subagent context cap: resume of terminated session ses_${tid.slice(-6)} denied (permanent)`) + appendStatusLog("notice.ctx.capResumeDenied", { taskId: tid.slice(-6) }) throw new Error(subagentResumeDenyMessage(tid)) } } @@ -1693,7 +1797,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { }) if (reason) { denySkip.add(input.callID) - appendStatusLog(`lang gate: tool '${input.tool}' denied in unconfigured project session ${lgSid}`) + appendStatusLog("notice.lang.gateDenied", { tool: input.tool, sid: lgSid }) throw new Error(reason) } } @@ -1717,10 +1821,10 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { searchDenyCount.set(scSid, n) if (n > SEARCH_CLARIFY_MAX_DENIES) { searchScopeAsked.add(scSid) - appendStatusLog(`search clarify gate: fail-open after ${SEARCH_CLARIFY_MAX_DENIES} denies without an ask — gate open for session ${scSid}`) + appendStatusLog("notice.search.clarifyFailOpen", { maxDenies: SEARCH_CLARIFY_MAX_DENIES, sid: scSid }) } else { denySkip.add(input.callID) - appendStatusLog(`search clarify gate: tool '${input.tool}' denied (broad search, ask-first) in session ${scSid} (${n}/${SEARCH_CLARIFY_MAX_DENIES})`) + appendStatusLog("notice.search.clarifyDenied", { tool: input.tool, sid: scSid, denyCount: n, maxDenies: SEARCH_CLARIFY_MAX_DENIES }) throw new Error(searchClarifyDenyMessage(describeSearchCall(input.tool, output.args))) } } @@ -1740,11 +1844,34 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (input.tool === "task") { try { if (loadDispatchMode(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) === "off") { - appendStatusLog(`dispatch off: task call allowed ungoverned (subagent_type='${String(output.args?.subagent_type ?? "")}')`) + appendStatusLog("notice.dispatch.offUngoverned", { subagentType: String(output.args?.subagent_type ?? "") }) return } } catch { /* fail-open */ } } + // [2026-09-19]-[setup hard gate: while switchman setup is incomplete (any of the 6 task pools without a selected + // model, or the capability ranking missing), deny task dispatch — unconfigured no longer defaults to all models. + // Placement is deliberate: AFTER the dispatch:"off" early-return above (a project that opted out of dispatch + // governance is never denied by it), BEFORE the task-governance gates below; only main sessions are gated + // (dispatched shells and internal sessions exempt via isShellOrInternalSession, same as the lang gate), and only + // when the project language config exists — while language is unconfigured the lang gate above already blocks + // task and must stay the single voice. No waiver flag: hard gate by design. Reads are mtime-cached, so a + // /switchman-setup (or CLI) write opens the gate immediately without a restart; fail-open on internal errors]- + try { + const stSid = (input as any).sessionID as string | undefined + if (input.tool === "task" && stSid && !isShellOrInternalSession(stSid) + && loadLangConfig(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME)) { + const setup = setupCompletionNow() + if (!setup.complete) { + denySkip.add(input.callID) + appendStatusLog("notice.setup.gateDenied", { missing: setupMissingBrief(setup), sid: stSid }, true) + throw new Error(setupDenyMessage(setup)) + } + } + } catch (e) { + if (denySkip.has(input.callID)) throw e + // internal error on our side (never one of our own denies) → fail-open, do not break the tool path + } // [2026-09-04]-[read watermark gate: read-class/bash tools other than task are intercepted by tier per the measured session watermark] if (input.tool !== "task") { // [2026-09-05]-[no-vision image read guard runs first: image files are skipped by the read budget gate (BINARY_EXT), @@ -1819,7 +1946,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (autoRedirectOn) { const cand = firstCandidateShell(agent, ctx, gateExtras) if (cand && tryRedirect(cand, output.args?.prompt)) { - appendStatusLog(`auto-redirect ${agent} → ${cand} (uninjected shell; redirected to the chain-head candidate)`) + appendStatusLog("notice.dispatch.redirectUninjected", { agent, candidate: cand }) traceDispatch(input.sessionID, cand, output.args?.prompt, true, gateSnap.lanes) noteResumedChild(input.sessionID, cand, output.args) return @@ -1840,7 +1967,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const lane = BUILTIN_SUBAGENTS[agent] const cand = lane ? laneHeadCandidate(lane, ctx) : null if (cand && tryRedirect(cand, output.args?.prompt)) { - appendStatusLog(`auto-redirect ${agent} → ${cand} (built-in agent blocked)`) + appendStatusLog("notice.dispatch.redirectBuiltinBlocked", { agent, candidate: cand }) traceDispatch(input.sessionID, cand, output.args?.prompt, true, gateSnap.lanes) noteResumedChild(input.sessionID, cand, output.args) return @@ -1849,13 +1976,14 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { denySkip.add(input.callID) throw new Error(builtinDeny) } - appendStatusLog(noteUnknownAgent(agent)) + const unknownNote = noteUnknownAgent(agent) + appendStatusLog(unknownNote.key, unknownNote.params) traceDispatch(input.sessionID, agent, output.args?.prompt, false, gateSnap.lanes) noteResumedChild(input.sessionID, agent, output.args) return } const r = checkShell(agent, shell, output.args?.prompt, gateSnap) - if (r.note) appendStatusLog(r.note) + if (r.notes) for (const n of r.notes) appendStatusLog(n.key, n.params) if (!r.deny) { traceDispatch(input.sessionID, agent, output.args?.prompt, false, gateSnap.lanes) noteResumedChild(input.sessionID, agent, output.args) @@ -1863,7 +1991,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (r.deny) { // [2026-09-04]-[autoRedirect: denied and a hint candidate is already computed → one-hop silent redirect (guard re-check), zero retries] if (tryRedirect(r.redirect, output.args?.prompt)) { - appendStatusLog(`auto-redirect ${agent} → ${r.redirect} (${r.deny.slice(0, 60)})`) + appendStatusLog("notice.dispatch.redirectDenied", { agent, redirect: String(r.redirect), deny: r.deny.slice(0, 60) }) traceDispatch(input.sessionID, r.redirect ?? agent, output.args?.prompt, true, gateSnap.lanes) noteResumedChild(input.sessionID, r.redirect ?? agent, output.args) return @@ -1876,7 +2004,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } } catch (exc) { if (denySkip.has(input.callID)) throw exc // deny rethrown as-is (blocks dispatch) - appendStatusLog(`six gates fail-open (allowed): ${exc}`) + appendStatusLog("notice.dispatch.gatesFailOpen", { exc: String(exc) }) } }, @@ -1900,16 +2028,21 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const saved = saveLangFromQuestion(hookInput.args, (hookOutput as any)?.output, pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) if (saved) { langAsked.delete(hookInput.sessionID) - appendStatusLog(`project language preference saved (${saved.rel}): conversation=${saved.cfg.conversation} comments=${saved.cfg.comments} docs=${saved.cfg.docs}`) + appendStatusLog("notice.lang.prefsSaved", { + rel: saved.rel, + conversation: saved.cfg.conversation, + comments: saved.cfg.comments, + docs: saved.cfg.docs, + }) } else if (hasLangMarkerQuestions(hookInput.args)) { langGateWaived.add(hookInput.sessionID) - appendStatusLog(`lang gate: marker question completed without a saved config — gate waived for session ${hookInput.sessionID}`) + appendStatusLog("notice.lang.gateWaived", { sid: hookInput.sessionID }) } // [2026-09-17]-[broad-search clarify latch: our marker question completed (answered or declined — either // way the user was asked) → broad searches pass for the rest of the session] if (hasSearchMarkerQuestion(hookInput.args)) { searchScopeAsked.add(hookInput.sessionID) - appendStatusLog(`search clarify: scope ask completed — gate open for session ${hookInput.sessionID}`) + appendStatusLog("notice.search.scopeAskDone", { sid: hookInput.sessionID }) } } catch { /* fail-open */ } } @@ -1922,7 +2055,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const len = JSON.stringify((hookOutput as any)?.output ?? "").length const charge = estimateOutputTokens(len) chargeTurnRead(sid, charge) - if (charge >= 100) appendStatusLog(`read budget charge +${charge} (tool ${hookInput.tool}, turn ${turnUsedOf(sid)}/${turnBudgetOf(readBudgetOf(options.context))})`) + if (charge >= 100) appendStatusLog("notice.ctx.readBudgetCharge", { + charge, + tool: hookInput.tool, + turnUsed: turnUsedOf(sid), + turnBudget: turnBudgetOf(readBudgetOf(options.context)), + }) } } catch { /* fail-open */ } try { @@ -1936,7 +2074,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (handoverInflight.has(sid)) return if (Date.now() - (handoverCooldown.get(sid) ?? 0) < HANDOVER_COOLDOWN_MS) return handoverInflight.add(sid) - appendStatusLog(`auto-handover triggered (after ${hookInput.tool}, ~${kk(wm.tokens)} exceeds the force-compaction watermark): full backup + queued compaction of the current session`) + appendStatusLog("notice.handover.autoTriggered", { tool: hookInput.tool, wmTokens: kk(wm.tokens) }) // [2026-09-05]-[backup leg bounded: the SDK disables HTTP timeouts (client.js req.timeout = false), so any unbounded // await here could hang the tool path forever; 45s is generous for the DB-local fork+tag leg (fail-open on timeout)] const result = await Promise.race([ @@ -1947,10 +2085,11 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { }), ]) handoverCooldown.set(sid, Date.now()) - appendStatusLog(`auto-handover backup ${result.ok ? "done" : "failed"}: ${result.message}`) + appendStatusLog("notice.handover.backupResult", { outcome: result.ok ? "done" : "failed", message: result.message }) // compaction leg: NEVER awaited here (see the 2026-09-05 header note) — fired detached if (result.ok) { turnReadUsage.delete(sid) + readContinuation.delete(sid) wmHistory.delete(sid) lastUserMsg.delete(sid) sessionMsgModel.delete(sid) @@ -1962,18 +2101,16 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const compactionModel = key && slash > 0 ? { providerID: key.slice(0, slash), modelID: key.slice(slash + 1) } : undefined void compactSession(v1HandoverPort(pluginClient), sid, pluginDirectory, compactionModel).then((accepted) => { appendStatusLog( - `auto-handover compaction ${accepted ? "accepted" : "failed"}: ${ - accepted - ? "session.summarize returned (compaction ran on the session loop)" - : compactionModel - ? "session.summarize rejected (backup stands)" - : "no session model recorded (chat.params never fired); backup stands" - }`, + accepted + ? "notice.handover.compactionAccepted" + : compactionModel + ? "notice.handover.compactionRejected" + : "notice.handover.compactionNoModel", ) }) } } catch (exc) { - appendStatusLog(`auto-handover fail-open: ${exc}`) + appendStatusLog("notice.handover.failOpen", { exc: String(exc) }) } finally { if (sid) handoverInflight.delete(sid) } @@ -2026,9 +2163,10 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const sid = props?.sessionID const info = props?.info if (typeof sid === "string" && !isShellOrInternalSession(sid)) { - if (info?.role === "user") { - lastUserMsg.set(sid, info.id) - turnReadUsage.delete(sid) + if (info?.role === "user") { + lastUserMsg.set(sid, info.id) + turnReadUsage.delete(sid) + readContinuation.delete(sid) // [2026-09-18]-[v1.1: a pending read want does not survive the user turn] // [2026-09-11]-[opportunistic first-try: if the host ever ships parts on the event's info this fires // before the transform pass; in the real host info carries no parts so this no-ops and the reliable // capture lives in experimental.chat.messages.transform (see applyCtxControlAction)] @@ -2058,6 +2196,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (pid && known !== undefined && pid !== known) { lastUserMsg.set(sid, pid) turnReadUsage.delete(sid) + readContinuation.delete(sid) // [2026-09-18]-[v1.1: a pending read want does not survive the user turn] } } } else if (typeof sid === "string" && isShellAgentSession(sid) && info?.role === "assistant") { @@ -2077,7 +2216,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { terminatedSessions.add(sid) const agentName = dynamic ? manager?.sessionAgentName(sid) : sessionAgent.get(sid) persistTerminatedSession(sid, est, agentName) - appendStatusLog(`subagent context cap: session ${sid}${agentName ? ` (${agentName})` : ""} reached ~${Math.round(est / 1000)}k tokens (cap ${Math.round(cap / 1000)}k) — tools denied, progress summary demanded, session terminated (no task_id resume)`) + appendStatusLog("notice.ctx.capTerminated", { + sid, + agentSuffix: agentName ? ` (${agentName})` : "", + estTokens: Math.round(est / 1000), + capTokens: Math.round(cap / 1000), + }) } } } @@ -2092,6 +2236,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { shellWatermark.delete(sid) // [2026-09-06]-[subagent cap watermark follows the same cleanup; terminatedSessions is intentionally NOT cleaned — termination is permanent] shellSoftTierDelivered.delete(sid) // [2026-09-14]-[subagent soft-tier dedup follows the session out (re-arm on a fresh same-id session is impossible; keeps the map bounded)] turnReadUsage.delete(sid) + readContinuation.delete(sid) // [2026-09-18]-[v1.1: pending read want follows the session out] wmHistory.delete(sid) lastUserMsg.delete(sid) sessionMsgModel.delete(sid) @@ -2147,7 +2292,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-08-29]-[feature 1 dynamic matrix only: legacy keeps the original recordFailure breaker path (tester regression found the missing gate)]- const realFailed = dynamic && Boolean(combo && ctx.matrix?.combos[combo]?.status === "ok") if (realFailed) { - // rate limit uses a short TTL (10-min self-heal); endpoint uses 6h (retrying a permanent config error is pointless); others default to 30 minutes + // rate limit uses a short TTL (10-min self-heal); endpoint uses 6h (retrying a permanent config error is pointless); others default to 5 minutes const ttlMs = category === "rate_limit" ? RATE_LIMIT_TTL_MS : category === "endpoint" ? ENDPOINT_TTL_MS : undefined markRealFailure(combo!, undefined, ttlMs) // [2026-09-01]-[isolation events persisted: previously purely in-memory with zero audit — the banner reported down but no record existed] @@ -2157,7 +2302,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const rec = realFailed ? null : recordFailure(agent, reason, registry) // Copilot gateway quota-class errors → second truth source marks the pool exhausted (trusted until reset_date) // [2026-08-29]-[failure classification: only a real quota marks pool exhaustion, transient 429s never do; quota on non-copilot pools gets no - // pool-level handling — the 10min probe keeps reporting down, the banner degrades naturally, and the 30-min in-memory mark already covers it] + // pool-level handling — the 10min probe keeps reporting down, the banner degrades naturally, and the 5-min in-memory mark already covers it] if (category === "quota") { const shell = registry[agent] if (shell?.pool === "copilot") markCopilotGatewayExhausted(reason) @@ -2167,12 +2312,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const shell = registry[agent] if (shell && noteModelNotFound(`${shell.provider}/${shell.modelId}`)) { clearBannerCache() - appendStatusLog(`model retired (consecutive 404s), removed from candidates: ${shell.provider}/${shell.modelId}`) + appendStatusLog("notice.provider.modelRetired", { provider: shell.provider, modelId: shell.modelId }) } } - if (rec?.tripped) appendStatusLog(`${agent} breaker tripped (600s): ${reason.slice(0, 80)}`) + if (rec?.tripped) appendStatusLog("notice.breaker.agentTripped", { agent, reason: reason.slice(0, 80) }) } catch (exc) { - appendStatusLog(`failure accounting fail-open: ${exc}`) + appendStatusLog("notice.breaker.accountingFailOpen", { exc: String(exc) }) } }, } diff --git a/src/lane-policy.ts b/src/lane-policy.ts index 87dd093..1401c8f 100644 --- a/src/lane-policy.ts +++ b/src/lane-policy.ts @@ -43,12 +43,15 @@ export interface LanePolicyInput { // [2026-08-29]-[scoring-engine reuse: LANE_SPEC ordinals exported for scoring.effortFit to compute lane affinity]- // [2026-09-02]-[thinking-level preference layer: efforts keeps only the thinking-level preference order -// (hard/review default high→xhigh→max, main/mechanical/vision default medium→high→xhigh→max, economy default -// low→medium→high); off no longer enters any lane preference order — off shells are always lane-level fallback -// (when the lane has thinking-level candidates they rank after all thinking levels, see the computeLaneChain -// thinking-level partition), serving only models that support just on/off or scenarios where other levels are unavailable] +// (hard/review default high→xhigh→max, main/mechanical/vision default medium→high→xhigh→max); off no longer enters +// any lane preference order — off shells are always lane-level fallback (when the lane has thinking-level candidates +// they rank after all thinking levels, see the computeLaneChain thinking-level partition), serving only models that +// support just on/off or scenarios where other levels are unavailable]- +// [2026-09-18]-[economy order inverted to medium→high→low→minimal: economy models (cheap flash tier) may also run +// high thinking — the first effort the model supports wins, so a low/medium-less flash (e.g. glm-5.3-flash) takes +// its high face as the economy chain head instead of being pinned to low; cheap tiers stay as fallback, not default] export const LANE_SPEC: Record<Lane, { efforts: string[]; vision: boolean; ro: boolean; minimumLevel: CapabilityLevel | null }> = { - economy: { efforts: ["low", "minimal", "medium", "high"], vision: false, ro: false, minimumLevel: "L1" }, + economy: { efforts: ["medium", "high", "low", "minimal"], vision: false, ro: false, minimumLevel: "L1" }, mechanical: { efforts: ["medium", "high", "xhigh", "max"], vision: false, ro: false, minimumLevel: "L2" }, main: { efforts: ["medium", "high", "xhigh", "max"], vision: false, ro: false, minimumLevel: "L3" }, hard: { efforts: ["high", "xhigh", "max", "medium"], vision: false, ro: false, minimumLevel: "L4" }, diff --git a/src/lane.ts b/src/lane.ts index b041f67..486bb1d 100644 --- a/src/lane.ts +++ b/src/lane.ts @@ -14,7 +14,7 @@ import type { WaterFactor } from "./scoring" import { evaluatePeakSchedules } from "./config" import { defaultProviderConfig } from "./provider-config" import { appendStatusLog } from "./state" -import { normalizeModelKey } from "./capability" +import { normalizeModelKey, manualRankIndexOf } from "./capability" // ---- Billing window (configurable) ---- export interface BillingWindowCfg { @@ -363,6 +363,20 @@ export function computeLane(lane: Lane, base: string[], p: ComputeLaneParams): L matrixStatus: matrixStatusOf(c), latencyMs: c.latency_ms, })) + // [2026-09-18]-[pool lane manual ordering: for a lane with an explicit task-pool selection the manual /modelRank + // order becomes the dispatch priority — shell key → rank index (prefix-matched via manualRankIndexOf) is handed to + // rankCandidates as the ABSOLUTE first comparator key, and poolOrdered lifts the capability level floor (explicit + // membership = the user's qualification verdict; health hard gates are unchanged)] + const poolOrderedLane = Boolean(p.poolConfig?.[lane]?.size) + const manualOrder = new Map<string, number>() + if (poolOrderedLane && registry) { + for (const c of chain) { + const mid = registry[c.shell]?.modelId + if (!mid) continue + const idx = manualRankIndexOf(mid) + if (idx !== null) manualOrder.set(c.shell, idx) + } + } const { ranked, breakdowns } = rankCandidates(rankables, { lane, immediate, @@ -381,6 +395,8 @@ export function computeLane(lane: Lane, base: string[], p: ComputeLaneParams): L billingBoostOf: p.billingBoostOf, peakOf: p.peakOf, preferredModels: p.preferredModels, + poolOrdered: poolOrderedLane, + manualOrder: manualOrder.size > 0 ? manualOrder : null, }) const order = new Map(ranked.map((r, i) => [r.key, i])) // rankCandidates also drops non-pool models and cross-level fallbacks that missed the top-2; custom static chains must not bypass it. @@ -391,7 +407,8 @@ export function computeLane(lane: Lane, base: string[], p: ComputeLaneParams): L if (bd) c.score = bd } } catch (exc) { - appendStatusLog(`scoring failed, fell back to rule-based ordering: ${exc}`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.lane.scoringFallback", { exc: String(exc) }) legacySort(chain, p, glmPeak, immediate) } @@ -475,7 +492,7 @@ export function computeLane(lane: Lane, base: string[], p: ComputeLaneParams): L if (bd) c.score = bd } } catch (exc) { - appendStatusLog(`backfill ranking failed (lane stays empty): ${exc}`) + appendStatusLog("notice.lane.backfillFailed", { exc: String(exc) }) } } diff --git a/src/locales/de.ts b/src/locales/de.ts new file mode 100644 index 0000000..689b942 --- /dev/null +++ b/src/locales/de.ts @@ -0,0 +1,525 @@ +// [2026-09-19]-[German message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const de: Partial<Record<MsgKey, string>> = { + // ---- notices (status log; appendStatusLog) ---- + + // src/breaker.ts:37 + "notice.breaker.realCallIsolated": "{agent}-Echtaufruf für {mins} Min. isoliert ({category}): {reason}", + // src/breaker.ts:48 + "notice.breaker.shellNotInjected": "Shell nicht in opencode injiziert (keine Isolation): {agent} {reason}", + // src/breaker.ts:200 + "notice.breaker.failOpen": "Breaker fail-open: {exc}", + // src/capability.ts:246 + "notice.capability.snapshotCorrupted": "Gebündelter Capability-Rank-Snapshot beschädigt (übersprungen, Rückfall auf die kuratierte Tabelle)", + // src/capability.ts:299 + "notice.capability.primarySourceFailed": "Capability-Index-Primärquelle AA fehlgeschlagen ({exc}){nextStep}", + // src/capability.ts:311 + "notice.capability.backupSourceFailed": "Capability-Index-Backupquelle OpenRouter fehlgeschlagen ({exc}) -> behalte letzte gute/gebündelte Standardränge", + // src/capability.ts:316 + "notice.capability.parsedEmpty": "Capability-Index leer geparst ({source}) -> behalte letzte gute/gebündelte Standardränge", + // src/capability.ts:333 + "notice.capability.refreshed": "Capability-Index aktualisiert: {source} {modelCount} Modelle (version={version})", + // src/capability.ts:336 + "notice.capability.refreshFailOpen": "Capability-Index-Aktualisierung fail-open (behalte letzte gute/gebündelte Standardränge): {exc}", + // src/capability.ts:372 + "notice.capability.lmarenaDisagreement": "Capability-LMArena-Quervergleich: Tier-Reihenfolge vs. ELO-Reihenfolge nur {rate}% Übereinstimmung ({overlapCount} überlappende Modelle) -- Datenquelle möglicherweise anomal, manuelle Prüfung empfohlen", + // src/capability.ts:375 + "notice.capability.lmarenaFailOpen": "Capability-LMArena-Quervergleich fail-open (übersprungen): {exc}", + // src/catalog.ts:153 + "notice.catalog.unavailableNoCache": "models.dev-Katalog nicht verfügbar und kein Cache (fail-open-Degradation): {exc}", + // src/copilot-thinking.ts:71 + "notice.copilot.shapeCacheRefreshed": "Copilot-Thinking-Parameter-Shape-Cache aktualisiert: {modelCount} Modelle", + // src/copilot-thinking.ts:73 + "notice.copilot.shapeRefreshFailOpen": "Copilot-Thinking-Parameter-Shape-Aktualisierung fail-open: {exc}", + // src/cost.ts:44 + "notice.cost.refreshFailed": "Kosten-Snapshot-Aktualisierung fehlgeschlagen (behalte veraltete Daten): {exc}", + // src/dispatch-mode.ts:60 (log callback defaults to appendStatusLog) + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} ist kein gültiges JSON — ignoriert (Lang-Konfiguration fällt auf den AGENTS.md-Marker zurück; \"dispatch\":\"off\" nicht angewendet)", + // src/dispatch-mode.ts:66 (log callback defaults to appendStatusLog) + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} \"dispatch\" vorhanden, aber nicht exakt \"off\" (erhalten: {rawValue}) — ignoriert, Fleet-Verhalten", + // src/index.ts:262 + "notice.ctx.paused": "ctx-Steuerung für Sitzung {sid} pausiert (/ctx-pause): Read-Gates + Self-Read-Budget + Auto-Handover ausgesetzt; Messung läuft weiter", + // src/index.ts:264 + "notice.ctx.resumed": "ctx-Steuerung für Sitzung {sid} fortgesetzt (/ctx-resume): Read-Gates + Auto-Handover wieder aktiv", + // src/index.ts:467 + "notice.workspace.created": "Artefakt-Workspace erstellt: {rel}", + // src/index.ts:468 + "notice.workspace.renamed": "Artefakt-Workspace umbenannt: {oldRel} → {rel}", + // src/index.ts:542 + "notice.dispatch.mirrorResumeReuse": "tmux-Pane-Spiegelung: Resume-Dispatch ses_{taskId} ({shellName}) — task_id wiederverwendet, Pane direkt geöffnet (kein session.created wird ausgelöst)", + // src/index.ts:546 + "notice.dispatch.mirrorResumeLookupFailed": "tmux-Pane-Spiegelung: Resume-Dispatch ses_{taskId} ({shellName}) — Sitzungslookup fehlgeschlagen, fail-open-Pane", + // src/index.ts:574 + "notice.capability.selectionChanged": "Capability-Rang/Task-Pool-Auswahl geändert: Banner und Sidebar werden sofort aktualisiert", + // src/index.ts:589 + "notice.capability.overrideWatchError": "fs.watch({dir}) Override-Konfigurations-Beobachtungsfehler (mtime-Polling-Fallback): {exc}", + // src/index.ts:647 + "notice.matrix.configSurfaceFailOpen": "Konfigurationsoberfläche-Lesen fail-open: {exc}", + // src/index.ts:675 + "notice.matrix.floorFreeModels": "floor = {floorCount} OpenCode-Zen-Free-Modelle (Katalog {catalogStatus})", + // src/index.ts:676 + "notice.matrix.floorFallback": "floor auf das statische Manifest zurückgefallen (Katalog {catalogStatus}, 0 Free-Modelle)", + // src/index.ts:680 + "notice.matrix.invalidModelsUnknownProvider": "Sichtbare Menge/Favoriten enthalten ungültige Modelle mit unbekanntem Provider (Provider nicht verbunden; ignoriert, keine Shells gebaut): {modelList}", + // src/index.ts:778 + "notice.provider.probeAttemptSucceeded": "provider.list-Versuch {attempt} erfolgreich (vorherige {prevAttempts} nicht bereit)", + // src/index.ts:783 + "notice.provider.probeAttemptBackoff": "provider.list-Versuch {attempt} nicht bereit, warte: {exc}", + // src/index.ts:789 + "notice.provider.unavailableCfgFallback": "provider.list nicht verfügbar (Rückfall auf {keyCount} cfg.provider-Schlüssel nach {attemptCount} Versuchen): {exc}", + // src/index.ts:814 (alert) + "notice.provider.probeNewProvider": "provider.list-Hintergrundprobe: neue Provider verbunden ({providers}) — starten Sie opencode neu, um die Shell-Registrierung abzuschließen", + // src/index.ts:832 (alert) + "notice.provider.probeModelDrift": "provider.list-Hintergrundprobe: Modellliste gedriftet ({drift}) — Superset-Manifest neu gebaut, /modelRank-//poolConfig-Listen aktualisiert{restartHint}", + // src/index.ts:834 + "notice.provider.probeRebuildFailed": "provider.list-Hintergrundprobe: Superset-Neubau fehlgeschlagen (vorheriges Manifest behalten): {exc}", + // src/index.ts:886 + "notice.probe.warmupFailOpen": "Warmup fail-open: {exc}", + // src/index.ts:900 + "notice.skills.synced": "Skills synchronisiert: {installedCount} installiert, {updatedCount} aktualisiert, {removedCount} entfernt ({skillNames})", + // src/index.ts:903 + "notice.skills.syncFailOpen": "Skill-Sync fail-open: {exc}", + // src/index.ts:1145 + "notice.banner.failOpen": "Banner fail-open: {exc}", + // src/index.ts:1241 + "notice.ctx.readBudgetContinuation": "Read-Budget-Fortsetzungsabschluss (Datei {fileName}, +{granted} Zeilen ab {offset}, Turn {turnUsed}/{turnBudget})", + // src/index.ts:1251 + "notice.ctx.readBudgetGateCap": "Read-Budget-Gate-Cap (Tool read, Datei {fileName}, gesch. ~{totalTokens} -> Limit {suggestedLimit}, Turn {turnUsed}/{turnBudget})", + // src/index.ts:1277 (template built at src/index.ts:1259 as denyLog) + "notice.ctx.readBudgetGate": "Read-Budget-Gate {action} (Tool {tool}, gesch. ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, Turn {turnUsed}/{turnBudget})", + // src/index.ts:1281 + "notice.ctx.readBudgetGateFailOpen": "Read-Budget-Gate fail-open (erlaubt): {exc}", + // src/index.ts:1306 + "notice.image.readGuardDenied": "Bild-Leseschutz: Modell {modelKey} hat keinen Vision-Input; Lesen von {fileName} verweigert (Sitzung {sid})", + // src/index.ts:1310 + "notice.image.readGuardFailOpen": "Bild-Leseschutz fail-open (erlaubt): {exc}", + // src/index.ts:1358 + "notice.doctor.summary": "Doctor fand {errorCount} Fehler / {warnCount} Warnungen; /switchman-doctor zur Ansicht ausführen", + // src/index.ts:1393 + "notice.injection.legacyStaticMatrix": "{shellCount} Modell-Shells injiziert (Agents, legacy statische Matrix)", + // src/index.ts:1412 + "notice.provider.cacheUsed": "provider.list nutzt Restart-übergreifenden Cache ({providerCount} Provider, gecacht um {cachedAt}); Ergänzungen werden im Hintergrund geprüft", + // src/index.ts:1419 + "notice.provider.cacheStale": "provider.list-Cache veraltet (gecacht um {cachedAt}), Live-Probe vor dem Superset-Bau", + // src/index.ts:1469 + "notice.matrix.recomputed": "Aktivierungsmatrix neu berechnet (gen={generation}, aktive Shells {activeShellCount}, Proben {source}×{targetCount})", + // src/index.ts:1474 + "notice.injection.shellCount": "{shellCount} Shells injiziert (mode={runMode}, Injektionsoberfläche={injectionMode}={fullSupersetCount}→{faceCount} nach Kuratierung, Konflikte {conflictCount}; Aktivierungs-Gating aktiv)", + // src/index.ts:1479 + "notice.injection.configHookFailOpen": "Konfigurations-Hook fail-open: {exc}", + // src/index.ts:1541 + "notice.lang.askLocale": "lang-Abfrage locale={locale} ({source})", + // src/index.ts:1604 + "notice.banner.rulesFailOpen": "Regel/Banner fail-open: {exc}", + // src/index.ts:1677 + "notice.relay.persisted": "Bild-Relay: Modell {modelKey} hat keinen Vision-Input; {written} Bild(er) auf Platte gespeichert ({relayed} Bildteil(e) über den Sitzungsverlauf weitergeleitet, Sitzung {sid})", + // src/index.ts:1679 + "notice.relay.failOpen": "Bild-Relay fail-open (durchgereicht): {exc}", + // src/index.ts:1694 + "notice.ctx.capToolDenied": "Subagent-Kontext-Cap: Tool '{tool}' in beendeter Sitzung {sid} verweigert", + // src/index.ts:1701 + "notice.ctx.capResumeDenied": "Subagent-Kontext-Cap: Resume der beendeten Sitzung ses_{taskId} verweigert (permanent)", + // src/index.ts:1727 + "notice.lang.gateDenied": "Lang-Gate: Tool '{tool}' in unkonfigurierter Projektsitzung {sid} verweigert", + // src/index.ts:1751 + "notice.search.clarifyFailOpen": "Search-Clarify-Gate: fail-open nach {maxDenies} Verweigerungen ohne Nachfrage — Gate offen für Sitzung {sid}", + // src/index.ts:1754 + "notice.search.clarifyDenied": "Search-Clarify-Gate: Tool '{tool}' verweigert (breite Suche, zuerst fragen) in Sitzung {sid} ({denyCount}/{maxDenies})", + // src/index.ts:1774 + "notice.dispatch.offUngoverned": "Dispatch off: Task-Aufruf ungeregelt erlaubt (subagent_type='{subagentType}')", + // src/index.ts:1853 + "notice.dispatch.redirectUninjected": "Auto-Redirect {agent} → {candidate} (nicht injizierte Shell; zum Chain-Head-Kandidaten umgeleitet)", + // src/index.ts:1874 + "notice.dispatch.redirectBuiltinBlocked": "Auto-Redirect {agent} → {candidate} (eingebauter Agent blockiert)", + // src/index.ts:1883 (via src/gates.ts:331 noteUnknownAgent) + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] unbekannter subagent_type='{agent}': erlaubt (nicht in der Shell-Liste; eingebaute Agents werden nicht durch Routing gesteuert)", + // src/index.ts:1889 (r.note via src/gates.ts:156) + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled, aber Matrix-Status={matrixStatus} (nicht down): fail-open, nach der nächsten Probe-Aktualisierung automatisch korrigiert", + // src/index.ts:1889 (r.note via src/gates.ts:175) + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} Matrix-Status={matrixStatus} (nicht down): nicht blockiert, Probe aktualisiert nächste Runde", + // src/index.ts:1889 (r.note via src/gates.ts:63 ROUTE_META_SYNTH_NOTE) + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META fehlt/fehlerhaft — aus lane synthetisiert; deklarieren Sie es, um Review-Cross-Family-/source=user-Semantik zu aktivieren", + // src/index.ts:1889 (r.note via src/gates.ts:240 REVIEW_SELF_REVIEW_NOTE) + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED: kein Cross-Family-Reviewer verfügbar — gleichfamiliäres Self-Review erlaubt; DOWNGRADED im Review-Fazit deklarieren", + // src/index.ts:1889 (r.note via src/gates.ts:288 poolOverrideNote) + "notice.dispatch.poolOverrideNote": "Pool-Konfigurations-Override: explizit in diesen Task-Pool gewählt (Capability-Level-Floor aufgehoben)", + // src/index.ts:1897 + "notice.dispatch.redirectDenied": "Auto-Redirect {agent} → {redirect} ({deny})", + // src/index.ts:1910 + "notice.dispatch.gatesFailOpen": "Sechs Gates fail-open (erlaubt): {exc}", + // src/index.ts:1934 + "notice.lang.prefsSaved": "Projekt-Spracheinstellung gespeichert ({rel}): conversation={conversation} comments={comments} docs={docs}", + // src/index.ts:1937 + "notice.lang.gateWaived": "Lang-Gate: Marker-Frage ohne gespeicherte Konfiguration abgeschlossen — Gate für Sitzung {sid} aufgehoben", + // src/index.ts:1943 + "notice.search.scopeAskDone": "Search-Clarify: Scope-Abfrage abgeschlossen — Gate offen für Sitzung {sid}", + // src/index.ts:1956 + "notice.ctx.readBudgetCharge": "Read-Budget-Belastung +{charge} (Tool {tool}, Turn {turnUsed}/{turnBudget})", + // src/index.ts:1970 + "notice.handover.autoTriggered": "Auto-Handover ausgelöst (nach {tool}, ~{wmTokens} überschreitet die Force-Compaction-Watermark): Vollbackup + eingereihte Kompaktierung der aktuellen Sitzung", + // src/index.ts:1981 + "notice.handover.backupResult": "Auto-Handover-Backup {outcome}: {message}", + // src/index.ts:1996 (variant 1 of 3) + "notice.handover.compactionAccepted": "Auto-Handover-Kompaktierung akzeptiert: session.summarize zurückgekehrt (Kompaktierung lief auf der Session-Loop)", + // src/index.ts:1996 (variant 2 of 3) + "notice.handover.compactionRejected": "Auto-Handover-Kompaktierung fehlgeschlagen: session.summarize abgelehnt (Backup besteht)", + // src/index.ts:1996 (variant 3 of 3) + "notice.handover.compactionNoModel": "Auto-Handover-Kompaktierung fehlgeschlagen: kein Sitzungsmodell erfasst (chat.params nie ausgelöst); Backup besteht", + // src/index.ts:2008 + "notice.handover.failOpen": "Auto-Handover fail-open: {exc}", + // src/index.ts:2114 + "notice.ctx.capTerminated": "Subagent-Kontext-Cap: Sitzung {sid}{agentSuffix} erreichte ~{estTokens}k Tokens (Cap {capTokens}k) — Tools verweigert, Fortschrittszusammenfassung gefordert, Sitzung beendet (kein task_id-Resume)", + // src/index.ts:2205 + "notice.provider.modelRetired": "Modell außer Dienst (aufeinanderfolgende 404s), aus Kandidaten entfernt: {provider}/{modelId}", + // src/index.ts:2208 + "notice.breaker.agentTripped": "{agent}-Breaker ausgelöst (600s): {reason}", + // src/index.ts:2210 + "notice.breaker.accountingFailOpen": "Fehlerabrechnung fail-open: {exc}", + // src/lane.ts:410 + "notice.lane.scoringFallback": "Scoring fehlgeschlagen, Rückfall auf regelbasierte Reihenfolge: {exc}", + // src/lane.ts:494 + "notice.lane.backfillFailed": "Backfill-Ranking fehlgeschlagen (lane bleibt leer): {exc}", + // src/matrix-manager.ts:196 + "notice.matrix.favoritesScanNoChange": "Favoriten/sichtbare Menge gescannt: Aktivierung unverändert (gen={generation}; kein Recompute, kein Re-Probe)", + // src/matrix-manager.ts:204 + "notice.matrix.invalidModels": "Sichtbare Menge/Favoriten enthalten ungültige Modelle (Provider bekannt, aber keine solche modelId, keine Shell erzeugt): {modelList}", + // src/matrix-manager.ts:217 + "notice.matrix.persistFailOpen": "Aktivierungsmatrix-Persistierung fail-open: {exc}", + // src/matrix-manager.ts:222 + "notice.matrix.callbackFailOpen": "Aktivierungsmatrix-Callback fail-open: {exc}", + // src/matrix-manager.ts:250 + "notice.matrix.configReadFailOpen": "Konfigurationsoberfläche-Lesen fail-open (als leer behandelt): {exc}", + // src/matrix-manager.ts:272 + "notice.matrix.watchError": "fs.watch({dir}) fehlerhaft, Rückfall auf mtime-Polling: {exc}", + // src/matrix-manager.ts:277 + "notice.matrix.watchStartFailed": "fs.watch({dir}) Start fehlgeschlagen, Rückfall auf mtime-Polling: {exc}", + // src/matrix-manager.ts:308 + "notice.matrix.recomputeFailOpen": "Recompute fail-open: {exc}", + // src/probe.ts:144 + "notice.probe.failOpen": "Probe fail-open: {exc}", + // src/probe.ts:162 + "notice.probe.incrementalFailOpen": "Inkrementelle Probe fail-open: {exc}", + // src/probe.ts:201 + "notice.probe.copilotPoolExhausted": "Copilot-Monatspool erschöpft (Gateway zweite Source of Truth), vertraut bis reset_date", + // src/probe.ts:207 + "notice.probe.resultsDiscarded": "Proben-Ergebnisse verworfen (Matrix-Generation wechselte {oldGen}->{newGen}; durch Recompute der neuen Generation neu geplant)", + // src/probe.ts:214 + "notice.probe.matrixRefreshed": "Matrix aktualisiert: {comboCount} Kombos {okCount} ok (gesamt {totalCount})", + // src/probe.ts:233 + "notice.probe.schedulingFailOpen": "Probe-Planung fail-open: {exc}", + // src/scoring.ts:399 + "notice.scoring.decisionLogFailOpen": "Entscheidungslog fail-open: {exc}", + // src/selfupdate.ts:122 + "notice.selfupdate.checkFailOpen": "Self-Update-Prüfung fail-open: {exc}", + // src/selfupdate.ts:255 + "notice.selfupdate.upgradeAssetsFailOpen": "Upgrade-Command-Assets fail-open: {exc}", + // src/tmux.ts:149 (via log callback wired to appendStatusLog at src/index.ts:236) + "notice.dispatch.mirrorDisabled": "tmux-Pane-Spiegelung deaktiviert (Init fehlgeschlagen): {message}", + // src/tmux.ts:221 + "notice.dispatch.mirrorOpFailed": "tmux-Pane-Spiegelungs-Op fehlgeschlagen (wird fortgesetzt): {message}", + // src/tmux.ts:230 + "notice.dispatch.mirrorPaneFull": "tmux-Pane-Spiegelung: Spalte voll ({slotCount} Panes), ses_{sessionId} ({agent}) eingereiht", + // src/tmux.ts:280 + "notice.dispatch.mirrorAllClosed": "tmux-Pane-Spiegelung: alle Subagent-Panes geschlossen, Haupt-Pane wiederhergestellt", + // src/tmux.ts:290 + "notice.dispatch.mirrorDisplayed": "tmux-Pane-Spiegelung: ses_{sessionId} ({agent}) in Pane {pane} angezeigt", + // src/tmux.ts:303 + "notice.dispatch.mirrorReconciling": "tmux-Pane-Spiegelung: geschlossene Pane(s) erkannt, Layout wird abgeglichen", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "Einrichtung erforderlich ({missing}) — führen Sie /switchman-setup (oder /switchman-setup-chat) aus; Dispatchen ist bis zur Konfiguration blockiert", + + // ---- sidebar (tui.tsx sidebar chrome) ---- + + // src/tui.tsx:308 + "sidebar.peakTag": " ·Peak", + // src/tui.tsx:309 + "sidebar.staleTag": " ·veraltet", + // src/tui.tsx:310 + "sidebar.observeOnlyTag": " ·observe-only", + // src/tui.tsx:346 + "sidebar.updateAvailable": " → {updateVersion}", + // src/tui.tsx:351 + "sidebar.restartNeeded": " [NEUSTART ERFORDERLICH]", + // src/tui.tsx:358 + "sidebar.noneAvailable": "keine verfügbar", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "Ökonomie", + "sidebar.lane.mechanical": "Mechanik", + "sidebar.lane.main": "Haupt", + "sidebar.lane.hard": "Schwer", + "sidebar.lane.vision": "Vision", + "sidebar.lane.review": "Review", + // src/tui.tsx:368 + "sidebar.noticeLabel": "Hinweis", + + // ---- dialogs (tui.tsx: pool picker / pool models / rank / handover) ---- + + // src/tui.tsx:426 (pool picker title) + "dialog.pool.title": "Task-Pools (Task-Pool wählen; Esc zum Beenden)", + // src/tui.tsx:428 (pool picker lane row) + "dialog.pool.laneRow": "{pinMark}{lane}", + // src/tui.tsx:431 (pool picker option description) + "dialog.pool.manualSelection": "manuelle Auswahl: {selCount}/{totalCount} Modelle nehmen teil", + // src/tui.tsx:432 (pool picker option description) + "dialog.pool.notConfigured": "nicht konfiguriert: Systemstandard (alle verfügbaren Modelle nehmen teil)", + // src/tui.tsx:453 (pool models dialog, toggle persist) + "dialog.pool.toggleWriteFailed": "Schreiben fehlgeschlagen: {message}", + // src/tui.tsx:458 (pool models dialog, toggle toast) + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} den {lane}-Pool (sofort wirksam, Sidebar aktualisiert)", + // src/tui.tsx:469 (pool models dialog, min-selection guard toast) + "dialog.pool.keepOneModel": "Behalten Sie mindestens ein teilnehmendes Modell; nutzen Sie \"Clear config\", um den Systemstandard wiederherzustellen", + // src/tui.tsx:482 (pool models dialog, bulk select-all persist) + "dialog.pool.bulkWriteFailed": "Schreiben fehlgeschlagen: {message}", + // src/tui.tsx:485 (pool models dialog, bulk toast) + "dialog.pool.allSelected": "{lane}-Pool: alle Modelle ausgewählt", + // src/tui.tsx:490 (pool models dialog, clear-config toast) + "dialog.pool.configCleared": "{lane}-Pool-Konfiguration gelöscht (Systemstandard-Kandidatenmenge wiederhergestellt)", + // src/tui.tsx:499 (pool models dialog, uncheck-all toast) + "dialog.pool.allUnchecked": "{lane}-Pool: alle abgewählt — markieren Sie die zu behaltenden Modelle; Beenden ohne Auswahl behält die vorherige Auswahl", + // src/tui.tsx:503 (pool models dialog option) + "dialog.pool.back": "← Zurück zur Pool-Liste", + // src/tui.tsx:504 (pool models dialog option) + "dialog.pool.selectAll": "☑ Alle auswählen", + // src/tui.tsx:505 (pool models dialog option) + "dialog.pool.uncheckAll": "☐ Alle abwählen (dann die wenigen zu behaltenden markieren; Beenden ohne Auswahl behält die alte Liste)", + // src/tui.tsx:506 (pool models dialog option) + "dialog.pool.clearConfig": "✕ Konfiguration löschen (Systemstandard: alle verfügbaren Modelle nehmen teil)", + // src/tui.tsx:508 (pool models dialog model row) + "dialog.pool.modelRow": "{checkMark} {modelId}", + // src/tui.tsx:510 (pool models dialog row description) + "dialog.pool.rowMeta": "{tier}-Tier{manualSuffix}", + // src/tui.tsx:516 (pool models dialog title) + "dialog.pool.selectionTitle": "{lane}-Pool-Auswahl ({selCount}/{rowCount} teilnehmend; Auswahl schaltet um, Duplikate über Pools erlaubt)", + // src/tui.tsx:538 (rank universe-empty dialog option) + "dialog.rank.openPoolSelection": "→ Task-Pool-Auswahl öffnen (wählen Sie die Modelle pro Pool, dann ranken)", + // src/tui.tsx:539 (rank universe-empty dialog option) + "dialog.rank.close": "✕ Schließen", + // src/tui.tsx:543 (rank universe-empty dialog title) + "dialog.rank.universeEmptyTitle": "Modellranking ist deaktiviert, bis Task-Pools konfiguriert sind — nur in Task-Pools gewählte Modelle sind rankbar, so ranken Sie nie Modelle, die Sie nicht dispatchen können", + // src/tui.tsx:561 (rank move at edge toast) + "dialog.rank.alreadyAtEdge": "{modelName} ist bereits am {edge} der zusammengeführten Capability-Liste", + // src/tui.tsx:568 (rank move persist) + "dialog.rank.moveWriteFailed": "Schreiben fehlgeschlagen: {message}", + // src/tui.tsx:573 (rank move/pin toast) + "dialog.rank.pinnedOrMoved": "{verb} {modelName} auf #{position} (manueller Score {tier}/{raw}, zwischen Nachbarn verankert; sofort wirksam, Sidebar aktualisiert)", + // src/tui.tsx:627 (rank picker title) + "dialog.rank.title": "Modell-Capability-Ranking — zusammengeführte Reihenfolge (#1 stärkstes; begrenzt auf die Task-Pool-Auswahl; manuelle Einträge mischen sich mit Basis-Score-Modellen; Strg+hoch/Strg+runter bewegt einen Platz; Enter = Aktionen pro Modell)", + // src/tui.tsx:628 (rank picker placeholder) + "dialog.rank.searchHint": "Suche · Alt+hoch/Alt+runter spiegelt Strg+hoch/Strg+runter (funktioniert auch)", + // src/tui.tsx:630 (rank picker row) + "dialog.rank.row": "#{rankPadded} {modelId}", + // src/tui.tsx:632 (rank picker row description) + "dialog.rank.rowMeta": "{tier}-Tier · {scoreSource}{poolSuffix}", + // src/tui.tsx:662 (rank actions, remove persist) + "dialog.rank.removeWriteFailed": "Schreiben fehlgeschlagen: {message}", + // src/tui.tsx:665 (rank actions, remove toast) + "dialog.rank.removed": "{model} aus dem manuellen Ranking entfernt (fällt auf den Basis-Capability-Score zurück, sofort wirksam, Sidebar aktualisiert)", + // src/tui.tsx:669 (rank actions option) + "dialog.rank.pinTop": "▲ Ganz oben anpinnen (über allen Modellen)", + // src/tui.tsx:670 (rank actions option) + "dialog.rank.moveUp": "↑ Einen nach oben (tauscht mit dem Modell darüber; verankert manuellen Score zwischen Nachbarn)", + // src/tui.tsx:671 (rank actions option) + "dialog.rank.moveDown": "↓ Einen nach unten (tauscht mit dem Modell darunter)", + // src/tui.tsx:673 (rank actions option) + "dialog.rank.remove": "✕ Aus Ranking entfernen (zum Basisscore zurück)", + // src/tui.tsx:675 (rank actions option) + "dialog.rank.back": "← Zurück zur Ranking-Liste", + // src/tui.tsx:680 (rank actions title) + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "switchman-Einrichtung — Task-Pools & Capability-Ranking", + "dialog.setup.intro": "Geführte Einrichtung: Wählen Sie Modelle für jeden der 6 Task-Pools und ranken Sie sie (stärkste zuerst). Esc beendet jederzeit; bestätigte Pools werden sofort gespeichert.", + "dialog.setup.start": "Starten (erster unvollendeter Schritt)", + "dialog.setup.statePools": "Pools konfiguriert: {count}/6", + "dialog.setup.stateRank": "Ranking: {state}", + "dialog.setup.laneTitle": "Task-Pool {index}/6 — {lane} ({count} ausgewählt; Enter schaltet um, mindestens 1)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] Alle auswählen", + "dialog.setup.clearAll": "[ ] Alle abwählen", + "dialog.setup.confirmLane": "{lane} bestätigen ({count} Modelle) und fortfahren", + "dialog.setup.back": "Zurück", + "dialog.setup.keepOne": "Behalten Sie mindestens ein Modell in diesem Pool", + "dialog.setup.rankTitle": "Capability-Ranking — wählen Sie Nr. {n} (stärkste zuerst, {remaining} Modelle übrig)", + "dialog.setup.rankFinish": "Ranking abschließen ({count} gewählt; der Rest behält die Basis-Scores des Systems)", + "dialog.setup.rankMinOne": "Ranken Sie mindestens ein Modell, bevor Sie abschließen", + "dialog.setup.doneTitle": "Einrichtung abgeschlossen — sofort aktiv (Hot-Reload)", + "dialog.setup.donePools": "Pools: {summary}", + "dialog.setup.doneRank": "Ranking: {order}", + "dialog.setup.restartHint": "Starten Sie opencode neu, um neue Anbieter zu registrieren: {providers}", + // src/tui.tsx:734 (handover toast) + "dialog.handover.noSession": "/handover: nicht in einer Sitzung, nichts zu sichern", + // src/tui.tsx:739 (handover toast) + "dialog.handover.inProgress": "/handover: aktuelle Sitzung wird vollständig gesichert und kompaktiert…", + // src/tui.tsx:744 (handover toast) + "dialog.handover.resultStay": "{resultMessage}; noch in der ursprünglichen Sitzung, nicht gewechselt", + // src/tui.tsx:747 (handover toast) + "dialog.handover.result": "/handover {resultMessage}", + + // ---- palette (command palette entries) ---- + + // src/tui.tsx:770 + "palette.handover.title": "Aktuelle Sitzung sichern und kompaktieren", + // src/tui.tsx:771 + "palette.handover.desc": "Vollständiger Fork der aktuellen Sitzung als Backup ([backup]-Titel-Tag) plus Kompaktierung der aktuellen Sitzung; kein Sitzungswechsel (anders als eingebautes /fork)", + // src/tui.tsx:772 (palette category label) + "palette.category.label": "switchman", + // src/tui.tsx:779 + "palette.poolConfig.title": "Task-Pool-Auswahl", + // src/tui.tsx:780 + "palette.poolConfig.desc": "Teilnehmende Modelle pro Task-Pool wählen (economy/mechanical/main/hard/vision/review)", + // src/tui.tsx:788 + "palette.modelRank.title": "Modell-Capability-Ranking", + // src/tui.tsx:789 + "palette.modelRank.desc": "Manuelles Capability-Ranking (hat Vorrang vor Basisscores; weiter oben = stärker)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "Geführte Einrichtung (Pools + Ranking)", + "palette.setup.desc": "Assistent: Modelle pro Task-Pool mehrfach auswählen und ranken — erforderlich, bevor das Dispatchen funktioniert", + + // ---- quota (quota-brief.json rows; banner.ts builders) ---- + + // src/banner.ts:142 (POOL_LABEL) + "quota.poolGlm": "GLM", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolCopilot": "Copilot", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolDeepSeek": "DeepSeek", + // src/banner.ts:166 + "quota.queryingNoData": "Abfrage/keine Daten", + // src/banner.ts:173 + "quota.resetLater": "→später", + // src/banner.ts:173 + "quota.resetTime": "→{hhmm}", + // src/banner.ts:173 + "quota.resetDate": "→{mmdd}", + // src/banner.ts:173 + "quota.resetDateTime": "→{mmdd} {hhmm}", + // src/banner.ts:174 + "quota.barPct": "{bar8} {pct}%", + // src/banner.ts:177 (row label) + "quota.row5h": "5h", + // src/banner.ts:178 (row label) + "quota.rowWeek": "Woche", + // src/banner.ts:180 (row label) + "quota.rowMcp": "MCP", + // src/banner.ts:181 + "quota.noData": "keine Kontingentdaten", + // src/banner.ts:187 (row label) + "quota.rowRefresh": "Aktualisierung", + // src/banner.ts:188 (row label) + "quota.rowCredits": "Guthaben", + // src/banner.ts:188 + "quota.monthlyExhausted": "Monatspool erschöpft", + // src/banner.ts:193 + "quota.unlimited": "unbegrenzt{usedSuffix}", + // src/banner.ts:199 + "quota.exhaustedOverage": "erschöpft·Overage-Abrechnung{usage}", + // src/banner.ts:202 + "quota.barPctLeft": "{bar8} {pctTxt}% übrig{usage}", + // src/banner.ts:207 (row label) + "quota.rowBalance": "Saldo", + // src/banner.ts:207 + "quota.exhausted": "erschöpft", + // src/banner.ts:209 + "quota.unknownPayg": "unbekannt (Pay-as-you-go)", + // src/banner.ts:213 + "quota.barBalance": "{bar8} ¥{balance}", + // src/banner.ts:213 + "quota.balanceWarn": "(<¥{thr} Warnung)", + + // ---- cli (switchman-config / switchman-doctor) ---- + + // src/config-cli.ts:67 (fmtRow, printed at :87) + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-Tier{manualTag})", + // src/config-cli.ts:73 (thrown, surfaced via console.error at :267) + "cli.config.unknownPool": "unbekannter Task-Pool: {lane} (sechs Task-Pools: {laneList})", + // src/config-cli.ts:81 (head, printed at :85/:90) + "cli.config.poolHeader": "Task-Pool-Auswahl (Konfigurationsdatei {poolConfigPath}; Auswahl = die Modelle, die diesem Task-Pool beitreten; dasselbe Modell kann mehreren Pools beitreten; unkonfigurierte Pools nutzen die Systemstandard-Entscheidung)", + // src/config-cli.ts:86 + "cli.config.poolSection": "== {lane} == ({selection})", + // src/config-cli.ts:93 + "cli.config.poolSectionBrief": "== {lane} =={detail}", + // src/config-cli.ts:95 + "cli.config.poolListHint": "(vollständige Liste eines einzelnen Pools mit Nummern anzeigen: pool list <{laneList}>)", + // src/config-cli.ts:105 (thrown, surfaced via console.error at :267) + "cli.config.indexOutOfRange": "Index außerhalb des Bereichs #{index} (Liste hat {rowCount} Einträge)", + // src/config-cli.ts:110 (thrown, surfaced via console.error at :267) + "cli.config.invalidModel": "ungültiger Modellname: {model}", + // src/config-cli.ts:124 (thrown, surfaced via console.error at :267) + "cli.config.noManifest": "kein verfügbares Modellmanifest (Provider-Verbindungen und Superset-Manifest prüfen)", + // src/config-cli.ts:129 (thrown, surfaced via console.error at :267) + "cli.config.poolRequiresArg": "pool {sub} erfordert einen Index oder Modellnamen", + // src/config-cli.ts:138 + "cli.config.poolSelectionCleared": "{lane}-Task-Pool-Auswahl gelöscht (zurück zur Systemstandard-Kandidatenmenge, sofort wirksam, Sidebar aktualisiert synchron)", + // src/config-cli.ts:139 + "cli.config.poolUpdated": "{lane}-Task-Pool-Auswahl aktualisiert ({modelCount} teilnehmende Modelle, sofort wirksam, Sidebar aktualisiert synchron)", + // src/config-cli.ts:145 + "cli.config.poolConfigCleared": "{lane}-Task-Pool-Auswahlkonfiguration gelöscht (dieser Pool kehrt zur Systemstandard-Kandidatenmenge zurück, sofort wirksam, Sidebar aktualisiert synchron)", + // src/config-cli.ts:148 (thrown, surfaced via console.error at :267) + "cli.config.unknownPoolSub": "unbekannter Unterbefehl pool {sub} (list/add/remove/set/clear)", + // src/config-cli.ts:186 + "cli.config.rankDisabledUntilPools": "Manuelles Capability-Ranking (Konfigurationsdatei {capabilityRankPath}) ist deaktiviert, bis Task-Pools konfiguriert sind: nur in Task-Pools gewählte Modelle sind rankbar.", + // src/config-cli.ts:187 + "cli.config.rankHowTo": "Führen Sie hier zuerst /poolConfig (TUI-Dialog) oder pool set <task-pool> <index|model...> aus, dann ranken Sie nur die Modelle, die Sie tatsächlich nutzen.", + // src/config-cli.ts:190 + "cli.config.legacyHeader": "== Legacy manuelle Einträge (nur Bereinigung; rank remove/clear funktionieren weiter, oder wählen Sie die Modelle in einen Task-Pool, um sie zu ranken) ==", + // src/config-cli.ts:191 + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + // src/config-cli.ts:197 + "cli.config.rankHeader": "Modell-Capability-Ranking (Konfigurationsdatei {capabilityRankPath}; begrenzt auf die {universeCount} via /poolConfig in Task-Pools gewählten Modelle — eine zusammengeführte Reihenfolge, manuelle Einträge mischen sich per effektivem Score mit Basis-Score-Modellen; weiter oben = stärker)", + // src/config-cli.ts:198 + "cli.config.mergedHeader": "== Zusammengeführte Reihenfolge ({manualCount} manuell{manualSuffix}; CLI set/add ordnet Einträge per Legacy-Leiter, TUI-Moves verankern Scores zwischen Nachbarn) ==", + // src/config-cli.ts:201 + "cli.config.manualTag": "·manuell{score}", + // src/config-cli.ts:203 + "cli.config.notInPoolTag": "·in keinem Task-Pool", + // src/config-cli.ts:204 + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-Tier{manualTag}{poolTag})", + // src/config-cli.ts:210 (thrown, surfaced via console.error at :267) + "cli.config.rankNoPools": "noch keine Task-Pool-Auswahl — Ranking folgt der Pool-Auswahl; zuerst /poolConfig (oder pool set) ausführen", + // src/config-cli.ts:212 (thrown, surfaced via console.error at :267) + "cli.config.rankRequiresArg": "rank {sub} erfordert einen Index oder Modellnamen", + // src/config-cli.ts:237 + "cli.config.rankUpdated": "Manuelles Capability-Ranking aktualisiert ({modelCount} Modelle, sofort wirksam, Sidebar aktualisiert synchron)", + // src/config-cli.ts:242 + "cli.config.rankCleared": "Manuelles Capability-Ranking gelöscht (alles fällt auf den Basis-Capability-Score zurück, sofort wirksam, Sidebar aktualisiert synchron)", + // src/config-cli.ts:245 (thrown, surfaced via console.error at :267) + "cli.config.unknownRankSub": "unbekannter Unterbefehl rank {sub} (list/set/add/remove/clear)", + // src/config-cli.ts:254 + "cli.config.usage": "Verwendung: switchman-config <pool|rank> ...", + // src/config-cli.ts:255 + "cli.config.usagePoolList": " pool list [task-pool] Pool-Auswahlübersicht (economy/mechanical/main/hard/vision/review; mit Pool-Namen = vollständige Liste mit Indizes)", + // src/config-cli.ts:256 + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> Modelle für diesen Task-Pool markieren", + // src/config-cli.ts:257 + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> Teilnahme entmarkieren", + // src/config-cli.ts:258 + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> Teilnahmeliste dieses Pools vollständig ersetzen (dasselbe Modell kann mehreren Pools beitreten)", + // src/config-cli.ts:259 + "cli.config.usagePoolClear": " pool clear <task-pool> Konfiguration dieses Pools löschen (zurück zur Systemstandard-Kandidatenmenge)", + // src/config-cli.ts:260 + "cli.config.usageRankList": " rank list Manuelles Capability-Ranking anzeigen (begrenzt auf die Task-Pool-Auswahl; verweist auf /poolConfig, wenn kein Pool konfiguriert ist)", + // src/config-cli.ts:261 + "cli.config.usageRankSet": " rank set <index|model...> Vollständig neu ordnen (in der angegebenen Reihenfolge, #1 ist stärkstes; nur Pool-gewählte Modelle)", + // src/config-cli.ts:262 + "cli.config.usageRankAdd": " rank add <index|model...> Ans Ende des Rankings anhängen (nur Pool-gewählte Modelle)", + // src/config-cli.ts:263 + "cli.config.usageRankRemove": " rank remove <index|model...> Aus dem Ranking entfernen", + // src/config-cli.ts:264 + "cli.config.usageRankClear": " rank clear Ranking löschen (zum Basis-Capability-Score zurück)", + // src/config-cli.ts:267 + "cli.config.errorPrefix": "switchman-config: {message}", + // src/doctor-cli.ts:5 + "cli.doctor.usage": "Verwendung: switchman-doctor prüft die opencode-switchman-Konfiguration; die Umgebungsvariable OPENCODE_CONFIG_DIR wählt das Konfigurationsverzeichnis; Exit-Codes 0=keine Probleme, 1=Warnungen, 2=Fehler", + // src/doctor.ts:56 (SWM060 hint) + "cli.doctor.unknownModelsHint": "{unknownCount} Modelle vom bekannten System nicht zugeordnet (unbekannte Gruppe, per Koeffizient nach unten gerankt)", + // src/doctor.ts:58 (SWM062 hint) + "cli.doctor.approxModelsHint": "{approxCount} Modelle approximativ per Präfix/Familie klassifiziert", + // src/doctor.ts:72 (SWM044 hint) + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + // src/doctor.ts:87 + "cli.doctor.noIssues": "opencode-switchman doctor: keine Probleme gefunden", + // src/doctor.ts:89 + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/locales/en.ts b/src/locales/en.ts new file mode 100644 index 0000000..60b72bc --- /dev/null +++ b/src/locales/en.ts @@ -0,0 +1,532 @@ +// [2026-09-19]-[English message catalog: single source of truth for the MsgKey set (src/i18n.ts keyof typeof en); +// values verbatim from the i18n inventory, dynamic parts as {camelCase} placeholders] +// Conventions for downstream locales/rewrite agents: +// - One entry per UNIQUE inventory template; sites marked `dup` in the inventory share the earlier line's key. +// - `{a|b}` fixed-variant groups from the inventory are flattened into ONE camelCase param whose runtime value is the +// chosen variant text (see i18n-keys.md "variant flattening" notes), e.g. `{done|failed}` -> `{outcome}`. +// - Comments above each entry cite the inventory site (file:line, plus the inventory's parenthetical qualifier). +export const en = { + // ---- notices (status log; appendStatusLog) ---- + + // src/breaker.ts:37 + "notice.breaker.realCallIsolated": "{agent} real-call isolated for {mins}m ({category}): {reason}", + // src/breaker.ts:48 + "notice.breaker.shellNotInjected": "shell not injected into opencode (no isolation): {agent} {reason}", + // src/breaker.ts:200 + "notice.breaker.failOpen": "breaker fail-open: {exc}", + // src/capability.ts:246 + "notice.capability.snapshotCorrupted": "bundled capability rank snapshot corrupted (skipping, falling back to the curated table)", + // src/capability.ts:299 + "notice.capability.primarySourceFailed": "capability index primary source AA failed ({exc}){nextStep}", + // src/capability.ts:311 + "notice.capability.backupSourceFailed": "capability index backup source OpenRouter failed ({exc}) -> keeping last-good/bundled default ranks", + // src/capability.ts:316 + "notice.capability.parsedEmpty": "capability index parsed empty ({source}) -> keeping last-good/bundled default ranks", + // src/capability.ts:333 + "notice.capability.refreshed": "capability index refreshed: {source} {modelCount} models (version={version})", + // src/capability.ts:336 + "notice.capability.refreshFailOpen": "capability index refresh fail-open (keeping last-good/bundled default ranks): {exc}", + // src/capability.ts:372 + "notice.capability.lmarenaDisagreement": "capability LMArena cross-check: tier-order vs ELO-order agreement only {rate}% ({overlapCount} overlapping models) -- data source may be anomalous, manual review advised", + // src/capability.ts:375 + "notice.capability.lmarenaFailOpen": "capability LMArena cross-check fail-open (skipped): {exc}", + // src/catalog.ts:153 + "notice.catalog.unavailableNoCache": "models.dev catalog unavailable and no cache (fail-open degradation): {exc}", + // src/copilot-thinking.ts:71 + "notice.copilot.shapeCacheRefreshed": "Copilot thinking-parameter shape cache refreshed: {modelCount} models", + // src/copilot-thinking.ts:73 + "notice.copilot.shapeRefreshFailOpen": "Copilot thinking-parameter shape refresh fail-open: {exc}", + // src/cost.ts:44 + "notice.cost.refreshFailed": "cost snapshot refresh failed (keeping stale data): {exc}", + // src/dispatch-mode.ts:60 (log callback defaults to appendStatusLog) + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; \"dispatch\":\"off\" not applied)", + // src/dispatch-mode.ts:66 (log callback defaults to appendStatusLog) + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} \"dispatch\" present but not exactly \"off\" (got: {rawValue}) — ignored, fleet behavior", + // src/index.ts:262 + "notice.ctx.paused": "ctx control paused for session {sid} (/ctx-pause): read gates + self-read budget + auto-handover suspended; measurement continues", + // src/index.ts:264 + "notice.ctx.resumed": "ctx control resumed for session {sid} (/ctx-resume): read gates + auto-handover live again", + // src/index.ts:467 + "notice.workspace.created": "artifact workspace created: {rel}", + // src/index.ts:468 + "notice.workspace.renamed": "artifact workspace renamed: {oldRel} → {rel}", + // src/index.ts:542 + "notice.dispatch.mirrorResumeReuse": "tmux pane mirroring: resume dispatch ses_{taskId} ({shellName}) — task_id reuse, pane opened directly (no session.created will fire)", + // src/index.ts:546 + "notice.dispatch.mirrorResumeLookupFailed": "tmux pane mirroring: resume dispatch ses_{taskId} ({shellName}) — session lookup failed, fail-open pane", + // src/index.ts:574 + "notice.capability.selectionChanged": "capability rank/task-pool selection changed: banner and sidebar refresh immediately", + // src/index.ts:589 + "notice.capability.overrideWatchError": "fs.watch({dir}) override-config watch error (mtime polling fallback): {exc}", + // src/index.ts:647 + "notice.matrix.configSurfaceFailOpen": "config surface read fail-open: {exc}", + // src/index.ts:675 + "notice.matrix.floorFreeModels": "floor = {floorCount} OpenCode Zen free models (catalog {catalogStatus})", + // src/index.ts:676 + "notice.matrix.floorFallback": "floor fell back to the static manifest (catalog {catalogStatus}, 0 free models)", + // src/index.ts:680 + "notice.matrix.invalidModelsUnknownProvider": "visible set/favorites contain invalid models with unknown provider (provider not connected; ignored, no shells built): {modelList}", + // src/index.ts:778 + "notice.provider.probeAttemptSucceeded": "provider.list attempt {attempt} succeeded (previous {prevAttempts} not ready)", + // src/index.ts:783 + "notice.provider.probeAttemptBackoff": "provider.list attempt {attempt} not ready, backing off: {exc}", + // src/index.ts:789 + "notice.provider.unavailableCfgFallback": "provider.list unavailable (fell back to {keyCount} cfg.provider keys after {attemptCount} attempts): {exc}", + // src/index.ts:814 (alert) + "notice.provider.probeNewProvider": "provider.list background probe: new provider(s) connected ({providers}) — restart opencode to complete shell registration", + // src/index.ts:832 (alert) + "notice.provider.probeModelDrift": "provider.list background probe: model list drifted ({drift}) — superset manifest rebuilt, /modelRank //poolConfig lists updated{restartHint}", + // src/index.ts:834 + "notice.provider.probeRebuildFailed": "provider.list background probe: superset rebuild failed (kept previous manifest): {exc}", + // src/index.ts:886 + "notice.probe.warmupFailOpen": "warmup fail-open: {exc}", + // src/index.ts:900 + "notice.skills.synced": "skills synced: {installedCount} installed, {updatedCount} updated, {removedCount} removed ({skillNames})", + // src/index.ts:903 + "notice.skills.syncFailOpen": "skill sync fail-open: {exc}", + // src/index.ts:1145 + "notice.banner.failOpen": "banner fail-open: {exc}", + // src/index.ts:1241 + "notice.ctx.readBudgetContinuation": "read budget continuation completion (file {fileName}, +{granted} lines from {offset}, turn {turnUsed}/{turnBudget})", + // src/index.ts:1251 + "notice.ctx.readBudgetGateCap": "read budget gate cap (tool read, file {fileName}, est ~{totalTokens} -> limit {suggestedLimit}, turn {turnUsed}/{turnBudget})", + // src/index.ts:1277 (template built at src/index.ts:1259 as denyLog) + "notice.ctx.readBudgetGate": "read budget gate {action} (tool {tool}, est ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, turn {turnUsed}/{turnBudget})", + // src/index.ts:1281 + "notice.ctx.readBudgetGateFailOpen": "read budget gate fail-open (allowed): {exc}", + // src/index.ts:1306 + "notice.image.readGuardDenied": "image read guard: model {modelKey} has no vision input; denied read {fileName} (session {sid})", + // src/index.ts:1310 + "notice.image.readGuardFailOpen": "image read guard fail-open (allowed): {exc}", + // src/index.ts:1358 + "notice.doctor.summary": "doctor found {errorCount} error / {warnCount} warn; run /switchman-doctor to view", + // src/index.ts:1393 + "notice.injection.legacyStaticMatrix": "injected {shellCount} model shells (agents, legacy static matrix)", + // src/index.ts:1412 + "notice.provider.cacheUsed": "provider.list using cross-restart cache ({providerCount} providers, cached at {cachedAt}); verifying additions in background", + // src/index.ts:1419 + "notice.provider.cacheStale": "provider.list cache stale (cached at {cachedAt}), probing live before the superset build", + // src/index.ts:1469 + "notice.matrix.recomputed": "activation matrix recomputed (gen={generation}, active shells {activeShellCount}, probes {source}×{targetCount})", + // src/index.ts:1474 + "notice.injection.shellCount": "injected {shellCount} shells (mode={runMode}, injection surface={injectionMode}={fullSupersetCount}→{faceCount} after curation, conflicts {conflictCount}; activation gating active)", + // src/index.ts:1479 + "notice.injection.configHookFailOpen": "config hook fail-open: {exc}", + // src/index.ts:1541 + "notice.lang.askLocale": "lang ask locale={locale} ({source})", + // src/index.ts:1604 + "notice.banner.rulesFailOpen": "rules/banner fail-open: {exc}", + // src/index.ts:1677 + "notice.relay.persisted": "image relay: model {modelKey} has no vision input; persisted {written} image(s) to disk ({relayed} image part(s) relayed across session history, session {sid})", + // src/index.ts:1679 + "notice.relay.failOpen": "image relay fail-open (passed through): {exc}", + // src/index.ts:1694 + "notice.ctx.capToolDenied": "subagent context cap: tool '{tool}' denied in terminated session {sid}", + // src/index.ts:1701 + "notice.ctx.capResumeDenied": "subagent context cap: resume of terminated session ses_{taskId} denied (permanent)", + // src/index.ts:1727 + "notice.lang.gateDenied": "lang gate: tool '{tool}' denied in unconfigured project session {sid}", + // src/index.ts:1751 + "notice.search.clarifyFailOpen": "search clarify gate: fail-open after {maxDenies} denies without an ask — gate open for session {sid}", + // src/index.ts:1754 + "notice.search.clarifyDenied": "search clarify gate: tool '{tool}' denied (broad search, ask-first) in session {sid} ({denyCount}/{maxDenies})", + // src/index.ts:1774 + "notice.dispatch.offUngoverned": "dispatch off: task call allowed ungoverned (subagent_type='{subagentType}')", + // src/index.ts:1853 + "notice.dispatch.redirectUninjected": "auto-redirect {agent} → {candidate} (uninjected shell; redirected to the chain-head candidate)", + // src/index.ts:1874 + "notice.dispatch.redirectBuiltinBlocked": "auto-redirect {agent} → {candidate} (built-in agent blocked)", + // src/index.ts:1883 (via src/gates.ts:331 noteUnknownAgent) + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] unknown subagent_type='{agent}': allowed (not in the shell list; built-in agents are not governed by routing)", + // src/index.ts:1889 (r.note via src/gates.ts:156) + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled but matrix status={matrixStatus} (not down): fail-open, auto-corrected after the next probe refresh", + // src/index.ts:1889 (r.note via src/gates.ts:175) + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} matrix status={matrixStatus} (not down): not blocked, probe refreshes next round", + // src/index.ts:1889 (r.note via src/gates.ts:63 ROUTE_META_SYNTH_NOTE) + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META missing/malformed — synthesized from lane; declare it to enable review cross-family / source=user semantics", + // src/index.ts:1889 (r.note via src/gates.ts:240 REVIEW_SELF_REVIEW_NOTE) + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED: no cross-family reviewer available — same-family self-review allowed; declare DOWNGRADED in the review conclusion", + // src/index.ts:1889 (r.note via src/gates.ts:288 poolOverrideNote) + "notice.dispatch.poolOverrideNote": "pool-config override: explicitly selected into this task pool (capability level floor waived)", + // src/index.ts:1897 + "notice.dispatch.redirectDenied": "auto-redirect {agent} → {redirect} ({deny})", + // src/index.ts:1910 + "notice.dispatch.gatesFailOpen": "six gates fail-open (allowed): {exc}", + // src/index.ts:1934 + "notice.lang.prefsSaved": "project language preference saved ({rel}): conversation={conversation} comments={comments} docs={docs}", + // src/index.ts:1937 + "notice.lang.gateWaived": "lang gate: marker question completed without a saved config — gate waived for session {sid}", + // src/index.ts:1943 + "notice.search.scopeAskDone": "search clarify: scope ask completed — gate open for session {sid}", + // src/index.ts:1956 + "notice.ctx.readBudgetCharge": "read budget charge +{charge} (tool {tool}, turn {turnUsed}/{turnBudget})", + // src/index.ts:1970 + "notice.handover.autoTriggered": "auto-handover triggered (after {tool}, ~{wmTokens} exceeds the force-compaction watermark): full backup + queued compaction of the current session", + // src/index.ts:1981 + "notice.handover.backupResult": "auto-handover backup {outcome}: {message}", + // src/index.ts:1996 (variant 1 of 3) + "notice.handover.compactionAccepted": "auto-handover compaction accepted: session.summarize returned (compaction ran on the session loop)", + // src/index.ts:1996 (variant 2 of 3) + "notice.handover.compactionRejected": "auto-handover compaction failed: session.summarize rejected (backup stands)", + // src/index.ts:1996 (variant 3 of 3) + "notice.handover.compactionNoModel": "auto-handover compaction failed: no session model recorded (chat.params never fired); backup stands", + // src/index.ts:2008 + "notice.handover.failOpen": "auto-handover fail-open: {exc}", + // src/index.ts:2114 + "notice.ctx.capTerminated": "subagent context cap: session {sid}{agentSuffix} reached ~{estTokens}k tokens (cap {capTokens}k) — tools denied, progress summary demanded, session terminated (no task_id resume)", + // src/index.ts:2205 + "notice.provider.modelRetired": "model retired (consecutive 404s), removed from candidates: {provider}/{modelId}", + // src/index.ts:2208 + "notice.breaker.agentTripped": "{agent} breaker tripped (600s): {reason}", + // src/index.ts:2210 + "notice.breaker.accountingFailOpen": "failure accounting fail-open: {exc}", + // src/lane.ts:410 + "notice.lane.scoringFallback": "scoring failed, fell back to rule-based ordering: {exc}", + // src/lane.ts:494 + "notice.lane.backfillFailed": "backfill ranking failed (lane stays empty): {exc}", + // src/matrix-manager.ts:196 + "notice.matrix.favoritesScanNoChange": "favorites/visible set scanned: activation unchanged (gen={generation}; no recompute, no re-probe)", + // src/matrix-manager.ts:204 + "notice.matrix.invalidModels": "visible set/favorites contain invalid models (provider known but no such modelId, no shell generated): {modelList}", + // src/matrix-manager.ts:217 + "notice.matrix.persistFailOpen": "activation matrix persist fail-open: {exc}", + // src/matrix-manager.ts:222 + "notice.matrix.callbackFailOpen": "activation matrix callback fail-open: {exc}", + // src/matrix-manager.ts:250 + "notice.matrix.configReadFailOpen": "config surface read fail-open (treated as empty): {exc}", + // src/matrix-manager.ts:272 + "notice.matrix.watchError": "fs.watch({dir}) errored, falling back to mtime polling: {exc}", + // src/matrix-manager.ts:277 + "notice.matrix.watchStartFailed": "fs.watch({dir}) failed to start, falling back to mtime polling: {exc}", + // src/matrix-manager.ts:308 + "notice.matrix.recomputeFailOpen": "recompute fail-open: {exc}", + // src/probe.ts:144 + "notice.probe.failOpen": "probe fail-open: {exc}", + // src/probe.ts:162 + "notice.probe.incrementalFailOpen": "incremental probe fail-open: {exc}", + // src/probe.ts:201 + "notice.probe.copilotPoolExhausted": "Copilot monthly pool exhausted (gateway second source of truth), trusted until reset_date", + // src/probe.ts:207 + "notice.probe.resultsDiscarded": "probe results discarded (matrix generation changed {oldGen}->{newGen}; rescheduled by the new generation recompute)", + // src/probe.ts:214 + "notice.probe.matrixRefreshed": "matrix refreshed: {comboCount} combos {okCount} ok (total {totalCount})", + // src/probe.ts:233 + "notice.probe.schedulingFailOpen": "probe scheduling fail-open: {exc}", + // src/scoring.ts:399 + "notice.scoring.decisionLogFailOpen": "decision log fail-open: {exc}", + // src/selfupdate.ts:122 + "notice.selfupdate.checkFailOpen": "self-update check fail-open: {exc}", + // src/selfupdate.ts:255 + "notice.selfupdate.upgradeAssetsFailOpen": "upgrade command assets fail-open: {exc}", + // src/tmux.ts:149 (via log callback wired to appendStatusLog at src/index.ts:236) + "notice.dispatch.mirrorDisabled": "tmux pane mirroring disabled (init failed): {message}", + // src/tmux.ts:221 + "notice.dispatch.mirrorOpFailed": "tmux pane mirroring op failed (continuing): {message}", + // src/tmux.ts:230 + "notice.dispatch.mirrorPaneFull": "tmux pane mirroring: column full ({slotCount} panes), queued ses_{sessionId} ({agent})", + // src/tmux.ts:280 + "notice.dispatch.mirrorAllClosed": "tmux pane mirroring: all subagent panes closed, main pane restored", + // src/tmux.ts:290 + "notice.dispatch.mirrorDisplayed": "tmux pane mirroring: ses_{sessionId} ({agent}) displayed in pane {pane}", + // src/tmux.ts:303 + "notice.dispatch.mirrorReconciling": "tmux pane mirroring: detected closed pane(s), reconciling layout", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "Setup required ({missing}) — run /switchman-setup (or /switchman-setup-chat); dispatch blocked until configured", + + // ---- sidebar (tui.tsx sidebar chrome) ---- + // [2026-09-19]-[sidebar.restartHintPattern (the old RESTART_HINT_RE regex) deliberately NOT a message key: the + // structured alert flag on status-log entries replaces regex highlighting; keys are translatable prose only] + + // src/tui.tsx:308 + "sidebar.peakTag": " ·peak", + // src/tui.tsx:309 + "sidebar.staleTag": " ·stale", + // src/tui.tsx:310 + "sidebar.observeOnlyTag": " ·observe-only", + // src/tui.tsx:346 + "sidebar.updateAvailable": " → {updateVersion}", + // src/tui.tsx:351 + "sidebar.restartNeeded": " [RESTART NEEDED]", + // src/tui.tsx:358 + "sidebar.noneAvailable": "none available", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + // [2026-09-19]-[sidebar lane names localized for display only: t() falls back to the raw lane identifier for + // unknown/custom lanes, so runtime LANE_ORDER, pool-config.json keys and the protocol are untouched] + "sidebar.lane.economy": "economy", + "sidebar.lane.mechanical": "mechanical", + "sidebar.lane.main": "main", + "sidebar.lane.hard": "hard", + "sidebar.lane.vision": "vision", + "sidebar.lane.review": "review", + // src/tui.tsx:368 + "sidebar.noticeLabel": "notice", + + // ---- dialogs (tui.tsx: pool picker / pool models / rank / handover) ---- + + // src/tui.tsx:426 (pool picker title) + "dialog.pool.title": "Task pools (pick a task pool; Esc to exit)", + // src/tui.tsx:428 (pool picker lane row) + "dialog.pool.laneRow": "{pinMark}{lane}", + // src/tui.tsx:431 (pool picker option description) + "dialog.pool.manualSelection": "manual selection: {selCount}/{totalCount} models participating", + // src/tui.tsx:432 (pool picker option description) + "dialog.pool.notConfigured": "not configured: system default (all available models participate)", + // src/tui.tsx:453 (pool models dialog, toggle persist) + "dialog.pool.toggleWriteFailed": "write failed: {message}", + // src/tui.tsx:458 (pool models dialog, toggle toast) + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} the {lane} pool (effective immediately, sidebar refreshes)", + // src/tui.tsx:469 (pool models dialog, min-selection guard toast) + "dialog.pool.keepOneModel": "Keep at least one participating model; use \"Clear config\" to restore the system default", + // src/tui.tsx:482 (pool models dialog, bulk select-all persist) + "dialog.pool.bulkWriteFailed": "write failed: {message}", + // src/tui.tsx:485 (pool models dialog, bulk toast) + "dialog.pool.allSelected": "{lane} pool: all models selected", + // src/tui.tsx:490 (pool models dialog, clear-config toast) + "dialog.pool.configCleared": "{lane} pool config cleared (system default candidate set restored)", + // src/tui.tsx:499 (pool models dialog, uncheck-all toast) + "dialog.pool.allUnchecked": "{lane} pool: all unchecked — check the models to keep; exiting with none checked keeps the previous selection", + // src/tui.tsx:503 (pool models dialog option) + "dialog.pool.back": "← Back to pool list", + // src/tui.tsx:504 (pool models dialog option) + "dialog.pool.selectAll": "☑ Select all", + // src/tui.tsx:505 (pool models dialog option) + "dialog.pool.uncheckAll": "☐ Uncheck all (then check the few to keep; exit with none checked keeps the old list)", + // src/tui.tsx:506 (pool models dialog option) + "dialog.pool.clearConfig": "✕ Clear config (system default: all available models participate)", + // src/tui.tsx:508 (pool models dialog model row) + "dialog.pool.modelRow": "{checkMark} {modelId}", + // src/tui.tsx:510 (pool models dialog row description) + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + // src/tui.tsx:516 (pool models dialog title) + "dialog.pool.selectionTitle": "{lane} pool selection ({selCount}/{rowCount} participating; select toggles, duplicates across pools allowed)", + // src/tui.tsx:538 (rank universe-empty dialog option) + "dialog.rank.openPoolSelection": "→ Open task-pool selection (pick the models each pool may use, then rank them)", + // src/tui.tsx:539 (rank universe-empty dialog option) + "dialog.rank.close": "✕ Close", + // src/tui.tsx:543 (rank universe-empty dialog title) + "dialog.rank.universeEmptyTitle": "Model ranking is disabled until task pools are configured — only models selected into task pools are rankable, so you never rank models you cannot dispatch", + // src/tui.tsx:561 (rank move at edge toast) + "dialog.rank.alreadyAtEdge": "{modelName} is already at the {edge} of the merged capability list", + // src/tui.tsx:568 (rank move persist) + "dialog.rank.moveWriteFailed": "write failed: {message}", + // src/tui.tsx:573 (rank move/pin toast) + "dialog.rank.pinnedOrMoved": "{verb} {modelName} to #{position} (manual score {tier}/{raw}, anchored between its neighbors; effective immediately, sidebar refreshes)", + // src/tui.tsx:627 (rank picker title) + "dialog.rank.title": "Model capability ranking — merged order (#1 strongest; scoped to the task-pool selection; manual entries interleave with base-score models; ctrl+up/ctrl+down move one spot; enter = per-model actions)", + // src/tui.tsx:628 (rank picker placeholder) + "dialog.rank.searchHint": "Search · alt+up/alt+down mirror ctrl+up/ctrl+down (also work)", + // src/tui.tsx:630 (rank picker row) + "dialog.rank.row": "#{rankPadded} {modelId}", + // src/tui.tsx:632 (rank picker row description) + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + // src/tui.tsx:662 (rank actions, remove persist) + "dialog.rank.removeWriteFailed": "write failed: {message}", + // src/tui.tsx:665 (rank actions, remove toast) + "dialog.rank.removed": "Removed {model} from the manual ranking (falls back to the base capability score, effective immediately, sidebar refreshes)", + // src/tui.tsx:669 (rank actions option) + "dialog.rank.pinTop": "▲ Pin to top (above every model)", + // src/tui.tsx:670 (rank actions option) + "dialog.rank.moveUp": "↑ Move up one (swaps with the model above; anchors a manual score between neighbors)", + // src/tui.tsx:671 (rank actions option) + "dialog.rank.moveDown": "↓ Move down one (swaps with the model below)", + // src/tui.tsx:673 (rank actions option) + "dialog.rank.remove": "✕ Remove from ranking (fall back to the base score)", + // src/tui.tsx:675 (rank actions option) + "dialog.rank.back": "← Back to ranking list", + // src/tui.tsx:680 (rank actions title) + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "switchman setup — task pools & capability ranking", + "dialog.setup.intro": "Guided setup: pick models for each of the 6 task pools, then rank them (strongest first). Esc exits anytime; confirmed pools are saved immediately.", + "dialog.setup.start": "Start (first unfinished step)", + "dialog.setup.statePools": "pools configured: {count}/6", + "dialog.setup.stateRank": "ranking: {state}", + "dialog.setup.laneTitle": "Task pool {index}/6 — {lane} ({count} selected; Enter toggles, min 1)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] Select all", + "dialog.setup.clearAll": "[ ] Clear all", + "dialog.setup.confirmLane": "Confirm {lane} ({count} models) and continue", + "dialog.setup.back": "Back", + "dialog.setup.keepOne": "Keep at least one model in this pool", + "dialog.setup.rankTitle": "Capability ranking — pick #{n} (strongest first, {remaining} models left)", + "dialog.setup.rankFinish": "Finish ranking ({count} picked; the rest keep system base scores)", + "dialog.setup.rankMinOne": "Rank at least one model before finishing", + "dialog.setup.doneTitle": "Setup complete — active immediately (hot-reload)", + "dialog.setup.donePools": "Pools: {summary}", + "dialog.setup.doneRank": "Ranking: {order}", + "dialog.setup.restartHint": "Restart opencode to register new provider(s): {providers}", + // src/tui.tsx:734 (handover toast) + "dialog.handover.noSession": "/handover: not in a session, nothing to back up", + // src/tui.tsx:739 (handover toast) + "dialog.handover.inProgress": "/handover: backing up the current session in full and compacting…", + // src/tui.tsx:744 (handover toast) + "dialog.handover.resultStay": "{resultMessage}; still in the original session, not switched", + // src/tui.tsx:747 (handover toast) + "dialog.handover.result": "/handover {resultMessage}", + + // ---- palette (command palette entries) ---- + + // src/tui.tsx:770 + "palette.handover.title": "Back up and compact the current session", + // src/tui.tsx:771 + "palette.handover.desc": "Full fork of the current session as a backup ([backup] title tag) plus compaction of the current session; no session switch (distinct from built-in /fork)", + // src/tui.tsx:772 (palette category label) + "palette.category.label": "switchman", + // src/tui.tsx:779 + "palette.poolConfig.title": "Task pool selection", + // src/tui.tsx:780 + "palette.poolConfig.desc": "Pick the participating models per task pool (economy/mechanical/main/hard/vision/review)", + // src/tui.tsx:788 + "palette.modelRank.title": "Model capability ranking", + // src/tui.tsx:789 + "palette.modelRank.desc": "Manual capability ranking (takes precedence over base scores; earlier = stronger)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "Guided setup (pools + ranking)", + "palette.setup.desc": "Wizard: multi-select models per task pool, then rank them — required before dispatch works", + + // ---- quota (quota-brief.json rows; banner.ts builders) ---- + + // src/banner.ts:142 (POOL_LABEL) + "quota.poolGlm": "GLM", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolCopilot": "Copilot", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolDeepSeek": "DeepSeek", + // src/banner.ts:166 + "quota.queryingNoData": "querying/no data", + // src/banner.ts:173 + "quota.resetLater": "→later", + // src/banner.ts:173 + "quota.resetTime": "→{hhmm}", + // src/banner.ts:173 + "quota.resetDate": "→{mmdd}", + // src/banner.ts:173 + "quota.resetDateTime": "→{mmdd} {hhmm}", + // src/banner.ts:174 + "quota.barPct": "{bar8} {pct}%", + // src/banner.ts:177 (row label) + "quota.row5h": "5h", + // src/banner.ts:178 (row label) + "quota.rowWeek": "week", + // src/banner.ts:180 (row label) + "quota.rowMcp": "MCP", + // src/banner.ts:181 + "quota.noData": "no quota data", + // src/banner.ts:187 (row label) + "quota.rowRefresh": "refresh", + // src/banner.ts:188 (row label) + "quota.rowCredits": "credits", + // src/banner.ts:188 + "quota.monthlyExhausted": "monthly pool exhausted", + // src/banner.ts:193 + "quota.unlimited": "unlimited{usedSuffix}", + // src/banner.ts:199 + "quota.exhaustedOverage": "exhausted·overage billing{usage}", + // src/banner.ts:202 + "quota.barPctLeft": "{bar8} {pctTxt}% left{usage}", + // src/banner.ts:207 (row label) + "quota.rowBalance": "balance", + // src/banner.ts:207 + "quota.exhausted": "exhausted", + // src/banner.ts:209 + "quota.unknownPayg": "unknown (pay-as-you-go)", + // src/banner.ts:213 + "quota.barBalance": "{bar8} ¥{balance}", + // src/banner.ts:213 + "quota.balanceWarn": "(<¥{thr} warn)", + + // ---- cli (switchman-config / switchman-doctor) ---- + + // src/config-cli.ts:67 (fmtRow, printed at :87) + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + // src/config-cli.ts:73 (thrown, surfaced via console.error at :267) + "cli.config.unknownPool": "unknown task pool: {lane} (six task pools: {laneList})", + // src/config-cli.ts:81 (head, printed at :85/:90) + "cli.config.poolHeader": "Task-pool selection (config file {poolConfigPath}; selection = the models joining that task pool; the same model may join multiple pools; unconfigured pools use the system default decision)", + // src/config-cli.ts:86 + "cli.config.poolSection": "== {lane} == ({selection})", + // src/config-cli.ts:93 + "cli.config.poolSectionBrief": "== {lane} =={detail}", + // src/config-cli.ts:95 + "cli.config.poolListHint": "(view a single pool's full list with numbers: pool list <{laneList}>)", + // src/config-cli.ts:105 (thrown, surfaced via console.error at :267) + "cli.config.indexOutOfRange": "index out of range #{index} (list has {rowCount} items)", + // src/config-cli.ts:110 (thrown, surfaced via console.error at :267) + "cli.config.invalidModel": "invalid model name: {model}", + // src/config-cli.ts:124 (thrown, surfaced via console.error at :267) + "cli.config.noManifest": "no available model manifest (check provider connections and the superset manifest)", + // src/config-cli.ts:129 (thrown, surfaced via console.error at :267) + "cli.config.poolRequiresArg": "pool {sub} requires an index or model name", + // src/config-cli.ts:138 + "cli.config.poolSelectionCleared": "{lane} task-pool selection cleared (back to the system default candidate set, effective immediately, sidebar refreshes in sync)", + // src/config-cli.ts:139 + "cli.config.poolUpdated": "Updated {lane} task-pool selection ({modelCount} models participating, effective immediately, sidebar refreshes in sync)", + // src/config-cli.ts:145 + "cli.config.poolConfigCleared": "Cleared the {lane} task-pool selection config (that pool returns to the system default candidate set, effective immediately, sidebar refreshes in sync)", + // src/config-cli.ts:148 (thrown, surfaced via console.error at :267) + "cli.config.unknownPoolSub": "unknown subcommand pool {sub} (list/add/remove/set/clear)", + // src/config-cli.ts:186 + "cli.config.rankDisabledUntilPools": "Manual capability ranking (config file {capabilityRankPath}) is disabled until task pools are configured: only models selected into task pools are rankable.", + // src/config-cli.ts:187 + "cli.config.rankHowTo": "Run /poolConfig (TUI dialog) or pool set <task-pool> <index|model...> here first, then rank only the models you actually use.", + // src/config-cli.ts:190 + "cli.config.legacyHeader": "== Legacy manual entries (cleanup only; rank remove/clear still work, or select the models into a task pool to rank them) ==", + // src/config-cli.ts:191 + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + // src/config-cli.ts:197 + "cli.config.rankHeader": "Model capability ranking (config file {capabilityRankPath}; scoped to the {universeCount} models selected into task pools via /poolConfig — one merged ordering, manual entries interleave with base-score models by effective score; higher up = stronger)", + // src/config-cli.ts:198 + "cli.config.mergedHeader": "== Merged ordering ({manualCount} manual{manualSuffix}; CLI set/add order entries by the legacy ladder, TUI moves anchor scores between neighbors) ==", + // src/config-cli.ts:201 + "cli.config.manualTag": "·manual{score}", + // src/config-cli.ts:203 + "cli.config.notInPoolTag": "·not in any task pool", + // src/config-cli.ts:204 + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + // src/config-cli.ts:210 (thrown, surfaced via console.error at :267) + "cli.config.rankNoPools": "no task-pool selection yet — ranking follows the pool selection; run /poolConfig (or pool set) first", + // src/config-cli.ts:212 (thrown, surfaced via console.error at :267) + "cli.config.rankRequiresArg": "rank {sub} requires an index or model name", + // src/config-cli.ts:237 + "cli.config.rankUpdated": "Updated the manual capability ranking ({modelCount} models, effective immediately, sidebar refreshes in sync)", + // src/config-cli.ts:242 + "cli.config.rankCleared": "Cleared the manual capability ranking (everything falls back to the base capability score, effective immediately, sidebar refreshes in sync)", + // src/config-cli.ts:245 (thrown, surfaced via console.error at :267) + "cli.config.unknownRankSub": "unknown subcommand rank {sub} (list/set/add/remove/clear)", + // src/config-cli.ts:254 + "cli.config.usage": "Usage: switchman-config <pool|rank> ...", + // src/config-cli.ts:255 + "cli.config.usagePoolList": " pool list [task-pool] Pool selection overview (economy/mechanical/main/hard/vision/review; with a pool name = full list with indices)", + // src/config-cli.ts:256 + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> Check models joining that task pool", + // src/config-cli.ts:257 + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> Uncheck participation", + // src/config-cli.ts:258 + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> Fully replace that pool's participation list (the same model may join multiple pools)", + // src/config-cli.ts:259 + "cli.config.usagePoolClear": " pool clear <task-pool> Clear that pool's config (back to the system default candidate set)", + // src/config-cli.ts:260 + "cli.config.usageRankList": " rank list View the manual capability ranking (scoped to the task-pool selection; guides to /poolConfig when no pool is configured)", + // src/config-cli.ts:261 + "cli.config.usageRankSet": " rank set <index|model...> Fully reorder (in the given order, #1 is strongest; only pool-selected models)", + // src/config-cli.ts:262 + "cli.config.usageRankAdd": " rank add <index|model...> Append to the end of the ranking (pool-selected models only)", + // src/config-cli.ts:263 + "cli.config.usageRankRemove": " rank remove <index|model...> Remove from the ranking", + // src/config-cli.ts:264 + "cli.config.usageRankClear": " rank clear Clear the ranking (fall back to the base capability score)", + // src/config-cli.ts:267 + "cli.config.errorPrefix": "switchman-config: {message}", + // src/doctor-cli.ts:5 + "cli.doctor.usage": "Usage: switchman-doctor checks the opencode-switchman config; the OPENCODE_CONFIG_DIR env var selects the config directory; exit codes 0=no issues, 1=warnings, 2=errors", + // src/doctor.ts:56 (SWM060 hint) + "cli.doctor.unknownModelsHint": "{unknownCount} models not matched by the known system (unknown group, ranked to the bottom by coefficient)", + // src/doctor.ts:58 (SWM062 hint) + "cli.doctor.approxModelsHint": "{approxCount} models classified approximately by prefix/family", + // src/doctor.ts:72 (SWM044 hint) + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + // src/doctor.ts:87 + "cli.doctor.noIssues": "opencode-switchman doctor: no issues found", + // src/doctor.ts:89 + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} as const diff --git a/src/locales/es.ts b/src/locales/es.ts new file mode 100644 index 0000000..31ecae3 --- /dev/null +++ b/src/locales/es.ts @@ -0,0 +1,273 @@ +// [2026-09-19]-[Spanish message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const es: Partial<Record<MsgKey, string>> = { + "notice.breaker.realCallIsolated": "{agent} llamada real aislada durante {mins} min ({category}): {reason}", + "notice.breaker.shellNotInjected": "shell no inyectado en opencode (sin aislamiento): {agent} {reason}", + "notice.breaker.failOpen": "breaker fail-open: {exc}", + "notice.capability.snapshotCorrupted": "instantánea incluida del ranking de capacidad corrupta (omitida, se usa la tabla curada)", + "notice.capability.primarySourceFailed": "falló la fuente primaria AA del índice de capacidad ({exc}){nextStep}", + "notice.capability.backupSourceFailed": "falló la fuente de respaldo OpenRouter del índice de capacidad ({exc}) -> se conservan los últimos ranks válidos/incluidos", + "notice.capability.parsedEmpty": "índice de capacidad vacío tras el análisis ({source}) -> se conservan los últimos ranks válidos/incluidos", + "notice.capability.refreshed": "índice de capacidad actualizado: {source} {modelCount} modelos (version={version})", + "notice.capability.refreshFailOpen": "actualización del índice de capacidad fail-open (se conservan los últimos ranks válidos/incluidos): {exc}", + "notice.capability.lmarenaDisagreement": "verificación cruzada de capacidad con LMArena: coincidencia tier-order vs ELO-order solo del {rate}% ({overlapCount} modelos coincidentes) -- la fuente de datos puede ser anómala, se recomienda revisión manual", + "notice.capability.lmarenaFailOpen": "verificación cruzada de capacidad con LMArena fail-open (omitida): {exc}", + "notice.catalog.unavailableNoCache": "catálogo models.dev no disponible y sin caché (degradación fail-open): {exc}", + "notice.copilot.shapeCacheRefreshed": "caché de forma del parámetro thinking de Copilot actualizada: {modelCount} modelos", + "notice.copilot.shapeRefreshFailOpen": "actualización de forma del parámetro thinking de Copilot fail-open: {exc}", + "notice.cost.refreshFailed": "falló la actualización de la instantánea de costos (se conservan datos obsoletos): {exc}", + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} no es JSON válido — ignorado (la config de idioma usa el marcador AGENTS.md; \"dispatch\":\"off\" no aplicado)", + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} \"dispatch\" presente pero no exactamente \"off\" (recibido: {rawValue}) — ignorado, comportamiento fleet", + "notice.ctx.paused": "control ctx pausado para la sesión {sid} (/ctx-pause): read gates + self-read budget + auto-handover suspendidos; la medición continúa", + "notice.ctx.resumed": "control ctx reanudado para la sesión {sid} (/ctx-resume): read gates + auto-handover activos de nuevo", + "notice.workspace.created": "workspace de artefactos creado: {rel}", + "notice.workspace.renamed": "workspace de artefactos renombrado: {oldRel} → {rel}", + "notice.dispatch.mirrorResumeReuse": "tmux pane mirroring: resume dispatch ses_{taskId} ({shellName}) — task_id reutilizado, pane abierto directamente (no se emitirá session.created)", + "notice.dispatch.mirrorResumeLookupFailed": "tmux pane mirroring: resume dispatch ses_{taskId} ({shellName}) — falló la búsqueda de sesión, pane fail-open", + "notice.capability.selectionChanged": "selección de ranking de capacidad/task pool cambiada: el banner y la sidebar se actualizan de inmediato", + "notice.capability.overrideWatchError": "error de fs.watch({dir}) en override-config (respaldo a sondeo mtime): {exc}", + "notice.matrix.configSurfaceFailOpen": "lectura de config surface fail-open: {exc}", + "notice.matrix.floorFreeModels": "floor = {floorCount} modelos gratuitos OpenCode Zen (catálogo {catalogStatus})", + "notice.matrix.floorFallback": "floor recurrió al manifiesto estático (catálogo {catalogStatus}, 0 modelos gratuitos)", + "notice.matrix.invalidModelsUnknownProvider": "el conjunto visible/favoritos contiene modelos inválidos con proveedor desconocido (proveedor no conectado; ignorados, sin shells creados): {modelList}", + "notice.provider.probeAttemptSucceeded": "provider.list intento {attempt} correcto (anteriores {prevAttempts} no listos)", + "notice.provider.probeAttemptBackoff": "provider.list intento {attempt} no listo, reintentando con espera: {exc}", + "notice.provider.unavailableCfgFallback": "provider.list no disponible (recurrió a {keyCount} claves cfg.provider tras {attemptCount} intentos): {exc}", + "notice.provider.probeNewProvider": "sondeo en segundo plano de provider.list: nuevo(s) proveedor(es) conectado(s) ({providers}) — reinicie opencode para completar el registro de shells", + "notice.provider.probeModelDrift": "sondeo en segundo plano de provider.list: la lista de modelos cambió ({drift}) — manifiesto superset reconstruido, listas /modelRank //poolConfig actualizadas{restartHint}", + "notice.provider.probeRebuildFailed": "sondeo en segundo plano de provider.list: falló la reconstrucción del superset (se conserva el manifiesto anterior): {exc}", + "notice.probe.warmupFailOpen": "warmup fail-open: {exc}", + "notice.skills.synced": "skills sincronizados: {installedCount} instalados, {updatedCount} actualizados, {removedCount} eliminados ({skillNames})", + "notice.skills.syncFailOpen": "sincronización de skills fail-open: {exc}", + "notice.banner.failOpen": "banner fail-open: {exc}", + "notice.ctx.readBudgetContinuation": "continuación de read budget completada (archivo {fileName}, +{granted} líneas desde {offset}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateCap": "límite de read budget gate (tool read, archivo {fileName}, est ~{totalTokens} -> límite {suggestedLimit}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGate": "read budget gate {action} (tool {tool}, est ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateFailOpen": "read budget gate fail-open (permitido): {exc}", + "notice.image.readGuardDenied": "image read guard: el modelo {modelKey} no tiene entrada de visión; lectura denegada {fileName} (sesión {sid})", + "notice.image.readGuardFailOpen": "image read guard fail-open (permitido): {exc}", + "notice.doctor.summary": "doctor encontró {errorCount} errores / {warnCount} avisos; ejecute /switchman-doctor para verlos", + "notice.injection.legacyStaticMatrix": "{shellCount} model shells inyectados (agents, legacy static matrix)", + "notice.provider.cacheUsed": "provider.list usando caché entre reinicios ({providerCount} proveedores, en caché a las {cachedAt}); verificando añadidos en segundo plano", + "notice.provider.cacheStale": "caché de provider.list obsoleta (en caché a las {cachedAt}), sondeando en vivo antes de la compilación del superset", + "notice.matrix.recomputed": "matriz de activación recalculada (gen={generation}, shells activos {activeShellCount}, probes {source}×{targetCount})", + "notice.injection.shellCount": "{shellCount} shells inyectados (mode={runMode}, injection surface={injectionMode}={fullSupersetCount}→{faceCount} tras curación, conflictos {conflictCount}; activation gating activo)", + "notice.injection.configHookFailOpen": "config hook fail-open: {exc}", + "notice.lang.askLocale": "pregunta de idioma locale={locale} ({source})", + "notice.banner.rulesFailOpen": "rules/banner fail-open: {exc}", + "notice.relay.persisted": "image relay: el modelo {modelKey} no tiene entrada de visión; {written} imagen(es) guardada(s) en disco ({relayed} parte(s) de imagen retransmitida(s) en el historial de sesión, sesión {sid})", + "notice.relay.failOpen": "image relay fail-open (pasado directamente): {exc}", + "notice.ctx.capToolDenied": "límite de contexto de subagente: tool '{tool}' denegada en la sesión terminada {sid}", + "notice.ctx.capResumeDenied": "límite de contexto de subagente: resume de la sesión terminada ses_{taskId} denegado (permanente)", + "notice.lang.gateDenied": "lang gate: tool '{tool}' denegada en sesión de proyecto sin configurar {sid}", + "notice.search.clarifyFailOpen": "search clarify gate: fail-open tras {maxDenies} denegaciones sin pregunta — gate abierto para la sesión {sid}", + "notice.search.clarifyDenied": "search clarify gate: tool '{tool}' denegada (búsqueda amplia, preguntar primero) en la sesión {sid} ({denyCount}/{maxDenies})", + "notice.dispatch.offUngoverned": "dispatch off: llamada task permitida sin gobierno (subagent_type='{subagentType}')", + "notice.dispatch.redirectUninjected": "auto-redirect {agent} → {candidate} (shell no inyectado; redirigido al candidato chain-head)", + "notice.dispatch.redirectBuiltinBlocked": "auto-redirect {agent} → {candidate} (agente integrado bloqueado)", + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] subagent_type='{agent}' desconocido: permitido (no está en la lista de shells; los agentes integrados no están gobernados por el enrutamiento)", + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled pero matrix status={matrixStatus} (not down): fail-open, se autocorrige tras la próxima actualización del probe", + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} matrix status={matrixStatus} (not down): no bloqueado, el probe se actualiza en la próxima ronda", + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META ausente/malformado — sintetizado desde lane; declárelo para habilitar la semántica review cross-family / source=user", + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED: no hay revisor cross-family disponible — se permite auto-revisión same-family; declare DOWNGRADED en la conclusión de la revisión", + "notice.dispatch.poolOverrideNote": "pool-config override: seleccionado explícitamente en este task pool (nivel mínimo de capacidad exento)", + "notice.dispatch.redirectDenied": "auto-redirect {agent} → {redirect} ({deny})", + "notice.dispatch.gatesFailOpen": "six gates fail-open (permitido): {exc}", + "notice.lang.prefsSaved": "preferencia de idioma del proyecto guardada ({rel}): conversation={conversation} comments={comments} docs={docs}", + "notice.lang.gateWaived": "lang gate: pregunta de marcador completada sin config guardada — gate exento para la sesión {sid}", + "notice.search.scopeAskDone": "search clarify: pregunta de alcance completada — gate abierto para la sesión {sid}", + "notice.ctx.readBudgetCharge": "cargo de read budget +{charge} (tool {tool}, turno {turnUsed}/{turnBudget})", + "notice.handover.autoTriggered": "auto-handover activado (tras {tool}, ~{wmTokens} supera el watermark de compactación forzosa): copia completa + compactación en cola de la sesión actual", + "notice.handover.backupResult": "copia de auto-handover {outcome}: {message}", + "notice.handover.compactionAccepted": "compactación de auto-handover aceptada: session.summarize devuelto (la compactación se ejecutó en el bucle de sesión)", + "notice.handover.compactionRejected": "compactación de auto-handover fallida: session.summarize rechazado (la copia se mantiene)", + "notice.handover.compactionNoModel": "compactación de auto-handover fallida: no hay modelo de sesión registrado (chat.params nunca se ejecutó); la copia se mantiene", + "notice.handover.failOpen": "auto-handover fail-open: {exc}", + "notice.ctx.capTerminated": "límite de contexto de subagente: sesión {sid}{agentSuffix} alcanzó ~{estTokens}k tokens (límite {capTokens}k) — tools denegados, resumen de progreso exigido, sesión terminada (sin resume por task_id)", + "notice.provider.modelRetired": "modelo retirado (404s consecutivos), eliminado de candidatos: {provider}/{modelId}", + "notice.breaker.agentTripped": "breaker de {agent} activado (600s): {reason}", + "notice.breaker.accountingFailOpen": "contabilidad de fallos fail-open: {exc}", + "notice.lane.scoringFallback": "falló el scoring, se recurrió al orden basado en reglas: {exc}", + "notice.lane.backfillFailed": "falló el ranking de relleno (lane queda vacío): {exc}", + "notice.matrix.favoritesScanNoChange": "favoritos/conjunto visible escaneado: activación sin cambios (gen={generation}; sin recálculo, sin nuevo probe)", + "notice.matrix.invalidModels": "el conjunto visible/favoritos contiene modelos inválidos (proveedor conocido pero sin tal modelId, sin shell generado): {modelList}", + "notice.matrix.persistFailOpen": "persistencia de la matriz de activación fail-open: {exc}", + "notice.matrix.callbackFailOpen": "callback de la matriz de activación fail-open: {exc}", + "notice.matrix.configReadFailOpen": "lectura de config surface fail-open (tratada como vacía): {exc}", + "notice.matrix.watchError": "fs.watch({dir}) falló, recurriendo al sondeo mtime: {exc}", + "notice.matrix.watchStartFailed": "fs.watch({dir}) no pudo iniciarse, recurriendo al sondeo mtime: {exc}", + "notice.matrix.recomputeFailOpen": "recálculo fail-open: {exc}", + "notice.probe.failOpen": "probe fail-open: {exc}", + "notice.probe.incrementalFailOpen": "probe incremental fail-open: {exc}", + "notice.probe.copilotPoolExhausted": "pool mensual de Copilot agotado (gateway segunda fuente de verdad), válido hasta reset_date", + "notice.probe.resultsDiscarded": "resultados del probe descartados (generación de matriz cambió {oldGen}->{newGen}; reprogramado por el recálculo de la nueva generación)", + "notice.probe.matrixRefreshed": "matriz actualizada: {comboCount} combos {okCount} ok (total {totalCount})", + "notice.probe.schedulingFailOpen": "programación del probe fail-open: {exc}", + "notice.scoring.decisionLogFailOpen": "registro de decisiones fail-open: {exc}", + "notice.selfupdate.checkFailOpen": "comprobación de auto-actualización fail-open: {exc}", + "notice.selfupdate.upgradeAssetsFailOpen": "assets del comando upgrade fail-open: {exc}", + "notice.dispatch.mirrorDisabled": "tmux pane mirroring deshabilitado (falló la inicialización): {message}", + "notice.dispatch.mirrorOpFailed": "operación de tmux pane mirroring fallida (continúa): {message}", + "notice.dispatch.mirrorPaneFull": "tmux pane mirroring: columna llena ({slotCount} panes), ses_{sessionId} ({agent}) en cola", + "notice.dispatch.mirrorAllClosed": "tmux pane mirroring: todos los panes de subagentes cerrados, pane principal restaurado", + "notice.dispatch.mirrorDisplayed": "tmux pane mirroring: ses_{sessionId} ({agent}) mostrado en el pane {pane}", + "notice.dispatch.mirrorReconciling": "tmux pane mirroring: pane(s) cerrado(s) detectado(s), reconciliando el diseño", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "Configuración requerida ({missing}) — ejecute /switchman-setup (o /switchman-setup-chat); el dispatch está bloqueado hasta configurar", + "sidebar.peakTag": " ·pico", + "sidebar.staleTag": " ·obsoleto", + "sidebar.observeOnlyTag": " ·solo-observar", + "sidebar.updateAvailable": " → {updateVersion}", + "sidebar.restartNeeded": " [REINICIO NECESARIO]", + "sidebar.noneAvailable": "ninguno disponible", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "economía", + "sidebar.lane.mechanical": "mecánica", + "sidebar.lane.main": "principal", + "sidebar.lane.hard": "difícil", + "sidebar.lane.vision": "visión", + "sidebar.lane.review": "revisión", + "sidebar.noticeLabel": "aviso", + "dialog.pool.title": "Task pools (elija un task pool; Esc para salir)", + "dialog.pool.laneRow": "{pinMark}{lane}", + "dialog.pool.manualSelection": "selección manual: {selCount}/{totalCount} modelos participantes", + "dialog.pool.notConfigured": "sin configurar: valor del sistema (todos los modelos disponibles participan)", + "dialog.pool.toggleWriteFailed": "falló la escritura: {message}", + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} el pool {lane} (efectivo de inmediato, la sidebar se actualiza)", + "dialog.pool.keepOneModel": "Conserve al menos un modelo participante; use «Borrar config» para restaurar el valor del sistema", + "dialog.pool.bulkWriteFailed": "falló la escritura: {message}", + "dialog.pool.allSelected": "pool {lane}: todos los modelos seleccionados", + "dialog.pool.configCleared": "config del pool {lane} borrada (conjunto candidato del sistema restaurado)", + "dialog.pool.allUnchecked": "pool {lane}: todo desmarcado — marque los modelos a conservar; salir sin marcar ninguno conserva la selección anterior", + "dialog.pool.back": "← Volver a la lista de pools", + "dialog.pool.selectAll": "☑ Seleccionar todo", + "dialog.pool.uncheckAll": "☐ Desmarcar todo (luego marque los pocos a conservar; salir sin marcar ninguno conserva la lista anterior)", + "dialog.pool.clearConfig": "✕ Borrar config (valor del sistema: todos los modelos disponibles participan)", + "dialog.pool.modelRow": "{checkMark} {modelId}", + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + "dialog.pool.selectionTitle": "selección del pool {lane} ({selCount}/{rowCount} participantes; seleccionar alterna, duplicados entre pools permitidos)", + "dialog.rank.openPoolSelection": "→ Abrir selección de task pool (elija los modelos que cada pool puede usar, luego ordénelos)", + "dialog.rank.close": "✕ Cerrar", + "dialog.rank.universeEmptyTitle": "El ranking de modelos está deshabilitado hasta configurar los task pools — solo los modelos seleccionados en task pools son ordenables, así nunca ordena modelos que no puede despachar", + "dialog.rank.alreadyAtEdge": "{modelName} ya está en el {edge} de la lista combinada de capacidad", + "dialog.rank.moveWriteFailed": "falló la escritura: {message}", + "dialog.rank.pinnedOrMoved": "{verb} {modelName} al n.º {position} (puntuación manual {tier}/{raw}, anclada entre sus vecinos; efectivo de inmediato, la sidebar se actualiza)", + "dialog.rank.title": "Ranking de capacidad de modelos — orden combinado (n.º 1 el más fuerte; limitado a la selección de task pool; entradas manuales intercaladas con modelos de puntuación base; ctrl+up/ctrl+down mueve un puesto; enter = acciones por modelo)", + "dialog.rank.searchHint": "Buscar · alt+up/alt+down replican ctrl+up/ctrl+down (también funcionan)", + "dialog.rank.row": "#{rankPadded} {modelId}", + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + "dialog.rank.removeWriteFailed": "falló la escritura: {message}", + "dialog.rank.removed": "{model} eliminado del ranking manual (vuelve a la puntuación base de capacidad, efectivo de inmediato, la sidebar se actualiza)", + "dialog.rank.pinTop": "▲ Fijar arriba (encima de todos los modelos)", + "dialog.rank.moveUp": "↑ Subir uno (intercambia con el modelo superior; ancla una puntuación manual entre vecinos)", + "dialog.rank.moveDown": "↓ Bajar uno (intercambia con el modelo inferior)", + "dialog.rank.remove": "✕ Quitar del ranking (volver a la puntuación base)", + "dialog.rank.back": "← Volver a la lista de ranking", + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "configuración de switchman — task pools y ranking de capacidad", + "dialog.setup.intro": "Configuración guiada: elija modelos para cada uno de los 6 task pools y luego ordénelos (el más fuerte primero). Esc sale en cualquier momento; los pools confirmados se guardan de inmediato.", + "dialog.setup.start": "Comenzar (primer paso sin terminar)", + "dialog.setup.statePools": "pools configurados: {count}/6", + "dialog.setup.stateRank": "ranking: {state}", + "dialog.setup.laneTitle": "Task pool {index}/6 — {lane} ({count} seleccionados; Enter alterna, mínimo 1)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] Seleccionar todo", + "dialog.setup.clearAll": "[ ] Desmarcar todo", + "dialog.setup.confirmLane": "Confirmar {lane} ({count} modelos) y continuar", + "dialog.setup.back": "Atrás", + "dialog.setup.keepOne": "Conserve al menos un modelo en este pool", + "dialog.setup.rankTitle": "Ranking de capacidad — elija el n.º {n} (el más fuerte primero, quedan {remaining} modelos)", + "dialog.setup.rankFinish": "Terminar el ranking ({count} elegidos; el resto conserva las puntuaciones base del sistema)", + "dialog.setup.rankMinOne": "Ordene al menos un modelo antes de terminar", + "dialog.setup.doneTitle": "Configuración completa — activa de inmediato (hot-reload)", + "dialog.setup.donePools": "Pools: {summary}", + "dialog.setup.doneRank": "Ranking: {order}", + "dialog.setup.restartHint": "Reinicie opencode para registrar nuevo(s) proveedor(es): {providers}", + "dialog.handover.noSession": "/handover: no está en una sesión, nada que respaldar", + "dialog.handover.inProgress": "/handover: respaldando la sesión actual por completo y compactando…", + "dialog.handover.resultStay": "{resultMessage}; aún en la sesión original, sin cambio", + "dialog.handover.result": "/handover {resultMessage}", + "palette.handover.title": "Respaldar y compactar la sesión actual", + "palette.handover.desc": "Fork completo de la sesión actual como respaldo (etiqueta de título [backup]) más compactación de la sesión actual; sin cambio de sesión (distinto del /fork integrado)", + "palette.category.label": "switchman", + "palette.poolConfig.title": "Selección de task pool", + "palette.poolConfig.desc": "Elija los modelos participantes por task pool (economy/mechanical/main/hard/vision/review)", + "palette.modelRank.title": "Ranking de capacidad de modelos", + "palette.modelRank.desc": "Ranking manual de capacidad (prevalece sobre las puntuaciones base; antes = más fuerte)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "Configuración guiada (pools + ranking)", + "palette.setup.desc": "Asistente: seleccione varios modelos por task pool y luego ordénelos — necesario antes de que el dispatch funcione", + "quota.poolGlm": "GLM", + "quota.poolCopilot": "Copilot", + "quota.poolDeepSeek": "DeepSeek", + "quota.queryingNoData": "consultando/sin datos", + "quota.resetLater": "→luego", + "quota.resetTime": "→{hhmm}", + "quota.resetDate": "→{mmdd}", + "quota.resetDateTime": "→{mmdd} {hhmm}", + "quota.barPct": "{bar8} {pct}%", + "quota.row5h": "5h", + "quota.rowWeek": "semana", + "quota.rowMcp": "MCP", + "quota.noData": "sin datos de cuota", + "quota.rowRefresh": "actualizar", + "quota.rowCredits": "créditos", + "quota.monthlyExhausted": "pool mensual agotado", + "quota.unlimited": "ilimitado{usedSuffix}", + "quota.exhaustedOverage": "agotado·facturación por excedente{usage}", + "quota.barPctLeft": "{bar8} {pctTxt}% restante{usage}", + "quota.rowBalance": "saldo", + "quota.exhausted": "agotado", + "quota.unknownPayg": "desconocido (pago por uso)", + "quota.barBalance": "{bar8} ¥{balance}", + "quota.balanceWarn": "(<¥{thr} aviso)", + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + "cli.config.unknownPool": "task pool desconocido: {lane} (seis task pools: {laneList})", + "cli.config.poolHeader": "Selección de task pool (archivo config {poolConfigPath}; selección = los modelos que se unen a ese task pool; el mismo modelo puede unirse a varios pools; los pools sin configurar usan la decisión del sistema)", + "cli.config.poolSection": "== {lane} == ({selection})", + "cli.config.poolSectionBrief": "== {lane} =={detail}", + "cli.config.poolListHint": "(ver la lista completa de un solo pool con números: pool list <{laneList}>)", + "cli.config.indexOutOfRange": "índice fuera de rango n.º {index} (la lista tiene {rowCount} elementos)", + "cli.config.invalidModel": "nombre de modelo inválido: {model}", + "cli.config.noManifest": "no hay manifiesto de modelos disponibles (revise las conexiones de proveedores y el manifiesto superset)", + "cli.config.poolRequiresArg": "pool {sub} requiere un índice o nombre de modelo", + "cli.config.poolSelectionCleared": "selección del task pool {lane} borrada (de vuelta al conjunto candidato del sistema, efectivo de inmediato, la sidebar se actualiza en sincronía)", + "cli.config.poolUpdated": "Selección del task pool {lane} actualizada ({modelCount} modelos participantes, efectivo de inmediato, la sidebar se actualiza en sincronía)", + "cli.config.poolConfigCleared": "Config del task pool {lane} borrada (ese pool vuelve al conjunto candidato del sistema, efectivo de inmediato, la sidebar se actualiza en sincronía)", + "cli.config.unknownPoolSub": "subcomando pool desconocido {sub} (list/add/remove/set/clear)", + "cli.config.rankDisabledUntilPools": "El ranking manual de capacidad (archivo config {capabilityRankPath}) está deshabilitado hasta configurar los task pools: solo los modelos seleccionados en task pools son ordenables.", + "cli.config.rankHowTo": "Ejecute /poolConfig (diálogo TUI) o pool set <task-pool> <index|model...> aquí primero, luego ordene solo los modelos que realmente usa.", + "cli.config.legacyHeader": "== Entradas manuales legacy (solo limpieza; rank remove/clear aún funcionan, o seleccione los modelos en un task pool para ordenarlos) ==", + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + "cli.config.rankHeader": "Ranking de capacidad de modelos (archivo config {capabilityRankPath}; limitado a los {universeCount} modelos seleccionados en task pools vía /poolConfig — un solo orden combinado, entradas manuales intercaladas con modelos de puntuación base por puntuación efectiva; más arriba = más fuerte)", + "cli.config.mergedHeader": "== Orden combinado ({manualCount} manual{manualSuffix}; CLI set/add ordena entradas por la escala legacy, movimientos TUI anclan puntuaciones entre vecinos) ==", + "cli.config.manualTag": "·manual{score}", + "cli.config.notInPoolTag": "·en ningún task pool", + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + "cli.config.rankNoPools": "aún sin selección de task pool — el ranking sigue la selección de pools; ejecute /poolConfig (o pool set) primero", + "cli.config.rankRequiresArg": "rank {sub} requiere un índice o nombre de modelo", + "cli.config.rankUpdated": "Ranking manual de capacidad actualizado ({modelCount} modelos, efectivo de inmediato, la sidebar se actualiza en sincronía)", + "cli.config.rankCleared": "Ranking manual de capacidad borrado (todo vuelve a la puntuación base de capacidad, efectivo de inmediato, la sidebar se actualiza en sincronía)", + "cli.config.unknownRankSub": "subcomando rank desconocido {sub} (list/set/add/remove/clear)", + "cli.config.usage": "Uso: switchman-config <pool|rank> ...", + "cli.config.usagePoolList": " pool list [task-pool] Resumen de selección de pools (economy/mechanical/main/hard/vision/review; con nombre de pool = lista completa con índices)", + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> Marcar modelos que se unen a ese task pool", + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> Desmarcar participación", + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> Reemplazar por completo la lista de participación de ese pool (el mismo modelo puede unirse a varios pools)", + "cli.config.usagePoolClear": " pool clear <task-pool> Borrar la config de ese pool (de vuelta al conjunto candidato del sistema)", + "cli.config.usageRankList": " rank list Ver el ranking manual de capacidad (limitado a la selección de task pool; guía a /poolConfig si ningún pool está configurado)", + "cli.config.usageRankSet": " rank set <index|model...> Reordenar por completo (en el orden dado, n.º 1 el más fuerte; solo modelos seleccionados en pools)", + "cli.config.usageRankAdd": " rank add <index|model...> Añadir al final del ranking (solo modelos seleccionados en pools)", + "cli.config.usageRankRemove": " rank remove <index|model...> Quitar del ranking", + "cli.config.usageRankClear": " rank clear Borrar el ranking (volver a la puntuación base de capacidad)", + "cli.config.errorPrefix": "switchman-config: {message}", + "cli.doctor.usage": "Uso: switchman-doctor revisa la config de opencode-switchman; la variable OPENCODE_CONFIG_DIR selecciona el directorio de config; códigos de salida 0=sin problemas, 1=avisos, 2=errores", + "cli.doctor.unknownModelsHint": "{unknownCount} modelos no reconocidos por el sistema conocido (grupo desconocido, ordenados al fondo por coeficiente)", + "cli.doctor.approxModelsHint": "{approxCount} modelos clasificados aproximadamente por prefijo/familia", + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + "cli.doctor.noIssues": "opencode-switchman doctor: sin problemas", + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} \ No newline at end of file diff --git a/src/locales/fr.ts b/src/locales/fr.ts new file mode 100644 index 0000000..0460ba9 --- /dev/null +++ b/src/locales/fr.ts @@ -0,0 +1,273 @@ +// [2026-09-19]-[French message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const fr: Partial<Record<MsgKey, string>> = { + "notice.breaker.realCallIsolated": "{agent} appel réel isolé pendant {mins} min ({category}) : {reason}", + "notice.breaker.shellNotInjected": "shell non injecté dans opencode (aucune isolation) : {agent} {reason}", + "notice.breaker.failOpen": "breaker fail-open : {exc}", + "notice.capability.snapshotCorrupted": "snapshot du classement de capacité intégré corrompu (ignoré, repli sur la table de référence)", + "notice.capability.primarySourceFailed": "échec de la source principale AA de l’index de capacité ({exc}){nextStep}", + "notice.capability.backupSourceFailed": "échec de la source de secours OpenRouter de l’index de capacité ({exc}) -> conservation des derniers rangs valides/intégrés", + "notice.capability.parsedEmpty": "index de capacité analysé vide ({source}) -> conservation des derniers rangs valides/intégrés", + "notice.capability.refreshed": "index de capacité actualisé : {source} {modelCount} modèles (version={version})", + "notice.capability.refreshFailOpen": "actualisation de l’index de capacité fail-open (conservation des derniers rangs valides/intégrés) : {exc}", + "notice.capability.lmarenaDisagreement": "contre-vérification LMArena de la capacité : accord ordre de tiers vs ordre ELO de seulement {rate} % ({overlapCount} modèles communs) -- source de données possiblement anormale, vérification manuelle conseillée", + "notice.capability.lmarenaFailOpen": "contre-vérification LMArena de la capacité fail-open (ignorée) : {exc}", + "notice.catalog.unavailableNoCache": "catalogue models.dev indisponible et aucun cache (dégradation fail-open) : {exc}", + "notice.copilot.shapeCacheRefreshed": "cache de forme du paramètre thinking Copilot actualisé : {modelCount} modèles", + "notice.copilot.shapeRefreshFailOpen": "actualisation du cache de forme du paramètre thinking Copilot fail-open : {exc}", + "notice.cost.refreshFailed": "échec d’actualisation du snapshot de coûts (données périmées conservées) : {exc}", + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} n’est pas un JSON valide — ignoré (la config de langue se replie sur le marqueur AGENTS.md ; « dispatch »:« off » non appliqué)", + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} « dispatch » présent mais pas exactement « off » (reçu : {rawValue}) — ignoré, comportement de flotte", + "notice.ctx.paused": "contrôle ctx en pause pour la session {sid} (/ctx-pause) : read gates + budget d’auto-lecture + auto-handover suspendus ; la mesure continue", + "notice.ctx.resumed": "contrôle ctx repris pour la session {sid} (/ctx-resume) : read gates + auto-handover de nouveau actifs", + "notice.workspace.created": "workspace d’artefacts créé : {rel}", + "notice.workspace.renamed": "workspace d’artefacts renommé : {oldRel} → {rel}", + "notice.dispatch.mirrorResumeReuse": "miroir de panneaux tmux : reprise ses_{taskId} ({shellName}) — réutilisation du task_id, panneau ouvert directement (aucun session.created ne sera émis)", + "notice.dispatch.mirrorResumeLookupFailed": "miroir de panneaux tmux : reprise ses_{taskId} ({shellName}) — recherche de session échouée, panneau fail-open", + "notice.capability.selectionChanged": "sélection de classement de capacité / task pool modifiée : la bannière et la barre latérale s’actualisent immédiatement", + "notice.capability.overrideWatchError": "erreur de surveillance fs.watch({dir}) de la config d’override (repli sur sondage mtime) : {exc}", + "notice.matrix.configSurfaceFailOpen": "lecture de la surface de config fail-open : {exc}", + "notice.matrix.floorFreeModels": "plancher = {floorCount} modèles gratuits OpenCode Zen (catalogue {catalogStatus})", + "notice.matrix.floorFallback": "plancher replié sur le manifeste statique (catalogue {catalogStatus}, 0 modèle gratuit)", + "notice.matrix.invalidModelsUnknownProvider": "l’ensemble visible / les favoris contiennent des modèles invalides à fournisseur inconnu (fournisseur non connecté ; ignorés, aucun shell construit) : {modelList}", + "notice.provider.probeAttemptSucceeded": "tentative provider.list {attempt} réussie ({prevAttempts} précédentes non prêtes)", + "notice.provider.probeAttemptBackoff": "tentative provider.list {attempt} non prête, nouvelle tentative différée : {exc}", + "notice.provider.unavailableCfgFallback": "provider.list indisponible (repli sur {keyCount} clés cfg.provider après {attemptCount} tentatives) : {exc}", + "notice.provider.probeNewProvider": "sonde d’arrière-plan provider.list : nouveau(x) fournisseur(s) connecté(s) ({providers}) — redémarrez opencode pour terminer l’enregistrement des shells", + "notice.provider.probeModelDrift": "sonde d’arrière-plan provider.list : liste de modèles modifiée ({drift}) — manifeste superset reconstruit, listes /modelRank //poolConfig mises à jour{restartHint}", + "notice.provider.probeRebuildFailed": "sonde d’arrière-plan provider.list : reconstruction du superset échouée (manifeste précédent conservé) : {exc}", + "notice.probe.warmupFailOpen": "préchauffage fail-open : {exc}", + "notice.skills.synced": "skills synchronisés : {installedCount} installés, {updatedCount} mis à jour, {removedCount} supprimés ({skillNames})", + "notice.skills.syncFailOpen": "synchronisation des skills fail-open : {exc}", + "notice.banner.failOpen": "bannière fail-open : {exc}", + "notice.ctx.readBudgetContinuation": "achèvement de continuation du budget de lecture (fichier {fileName}, +{granted} lignes depuis {offset}, tour {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateCap": "plafond du garde de budget de lecture (outil read, fichier {fileName}, est. ~{totalTokens} -> limite {suggestedLimit}, tour {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGate": "garde du budget de lecture {action} (outil {tool}, est. ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, tour {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateFailOpen": "garde du budget de lecture fail-open (autorisé) : {exc}", + "notice.image.readGuardDenied": "garde de lecture d’image : le modèle {modelKey} n’a pas d’entrée vision ; lecture {fileName} refusée (session {sid})", + "notice.image.readGuardFailOpen": "garde de lecture d’image fail-open (autorisée) : {exc}", + "notice.doctor.summary": "doctor a trouvé {errorCount} erreur(s) / {warnCount} avertissement(s) ; exécutez /switchman-doctor pour voir", + "notice.injection.legacyStaticMatrix": "{shellCount} shells de modèles injectés (agents, matrice statique héritée)", + "notice.provider.cacheUsed": "provider.list utilise le cache inter-redémarrages ({providerCount} fournisseurs, mis en cache à {cachedAt}) ; vérification des ajouts en arrière-plan", + "notice.provider.cacheStale": "cache provider.list périmé (mis en cache à {cachedAt}), sondage en direct avant la construction du superset", + "notice.matrix.recomputed": "matrice d’activation recalculée (gen={generation}, shells actifs {activeShellCount}, sondes {source}×{targetCount})", + "notice.injection.shellCount": "{shellCount} shells injectés (mode={runMode}, surface d’injection={injectionMode}={fullSupersetCount}→{faceCount} après curation, conflits {conflictCount} ; gating d’activation actif)", + "notice.injection.configHookFailOpen": "hook de config fail-open : {exc}", + "notice.lang.askLocale": "question de langue locale={locale} ({source})", + "notice.banner.rulesFailOpen": "règles/bannière fail-open : {exc}", + "notice.relay.persisted": "relais d’image : le modèle {modelKey} n’a pas d’entrée vision ; {written} image(s) enregistrée(s) sur disque ({relayed} partie(s) d’image relayée(s) dans l’historique de session, session {sid})", + "notice.relay.failOpen": "relais d’image fail-open (transmis tel quel) : {exc}", + "notice.ctx.capToolDenied": "plafond de contexte du subagent : outil « {tool} » refusé dans la session terminée {sid}", + "notice.ctx.capResumeDenied": "plafond de contexte du subagent : reprise de la session terminée ses_{taskId} refusée (définitive)", + "notice.lang.gateDenied": "garde de langue : outil « {tool} » refusé dans la session de projet non configurée {sid}", + "notice.search.clarifyFailOpen": "garde de clarification de recherche : fail-open après {maxDenies} refus sans question — garde ouverte pour la session {sid}", + "notice.search.clarifyDenied": "garde de clarification de recherche : outil « {tool} » refusé (recherche large, question d’abord) dans la session {sid} ({denyCount}/{maxDenies})", + "notice.dispatch.offUngoverned": "dispatch off : appel de tâche autorisé sans gouvernance (subagent_type='{subagentType}')", + "notice.dispatch.redirectUninjected": "redirection auto {agent} → {candidate} (shell non injecté ; redirigé vers le candidat en tête de chaîne)", + "notice.dispatch.redirectBuiltinBlocked": "redirection auto {agent} → {candidate} (agent intégré bloqué)", + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] subagent_type inconnu='{agent}' : autorisé (hors liste des shells ; les agents intégrés ne sont pas gouvernés par le routage)", + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled mais statut matrice={matrixStatus} (pas down) : fail-open, auto-corrigé après le prochain rafraîchissement des sondes", + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} statut matrice={matrixStatus} (pas down) : non bloqué, la sonde s’actualise au prochain tour", + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META manquant/malformé — synthétisé depuis la lane ; déclarez-le pour activer la sémantique review cross-family / source=user", + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED : aucun reviewer cross-family disponible — auto-review même famille autorisée ; déclarez DOWNGRADED dans la conclusion de review", + "notice.dispatch.poolOverrideNote": "override de pool-config : explicitement sélectionné dans ce task pool (plancher de niveau de capacité levé)", + "notice.dispatch.redirectDenied": "redirection auto {agent} → {redirect} ({deny})", + "notice.dispatch.gatesFailOpen": "six gardes fail-open (autorisées) : {exc}", + "notice.lang.prefsSaved": "préférence de langue du projet enregistrée ({rel}) : conversation={conversation} comments={comments} docs={docs}", + "notice.lang.gateWaived": "garde de langue : question du marqueur terminée sans config enregistrée — garde levée pour la session {sid}", + "notice.search.scopeAskDone": "clarification de recherche : question de périmètre terminée — garde ouverte pour la session {sid}", + "notice.ctx.readBudgetCharge": "imputation du budget de lecture +{charge} (outil {tool}, tour {turnUsed}/{turnBudget})", + "notice.handover.autoTriggered": "auto-handover déclenché (après {tool}, ~{wmTokens} dépasse le watermark de compaction forcée) : sauvegarde complète + compaction en file de la session actuelle", + "notice.handover.backupResult": "sauvegarde auto-handover {outcome} : {message}", + "notice.handover.compactionAccepted": "compaction auto-handover acceptée : session.summarize revenu (la compaction a tourné sur la boucle de session)", + "notice.handover.compactionRejected": "compaction auto-handover échouée : session.summarize rejeté (la sauvegarde subsiste)", + "notice.handover.compactionNoModel": "compaction auto-handover échouée : aucun modèle de session enregistré (chat.params jamais déclenché) ; la sauvegarde subsiste", + "notice.handover.failOpen": "auto-handover fail-open : {exc}", + "notice.ctx.capTerminated": "plafond de contexte du subagent : la session {sid}{agentSuffix} a atteint ~{estTokens}k tokens (plafond {capTokens}k) — outils refusés, résumé de progression exigé, session terminée (aucune reprise task_id)", + "notice.provider.modelRetired": "modèle retiré (404 consécutives), supprimé des candidats : {provider}/{modelId}", + "notice.breaker.agentTripped": "breaker {agent} déclenché (600s) : {reason}", + "notice.breaker.accountingFailOpen": "comptabilisation des échecs fail-open : {exc}", + "notice.lane.scoringFallback": "scoring échoué, repli sur l’ordre basé sur les règles : {exc}", + "notice.lane.backfillFailed": "remplissage du classement échoué (la lane reste vide) : {exc}", + "notice.matrix.favoritesScanNoChange": "favoris / ensemble visible analysés : activation inchangée (gen={generation} ; aucun recalcul, aucune nouvelle sonde)", + "notice.matrix.invalidModels": "l’ensemble visible / les favoris contiennent des modèles invalides (fournisseur connu mais modelId inexistant, aucun shell généré) : {modelList}", + "notice.matrix.persistFailOpen": "persistance de la matrice d’activation fail-open : {exc}", + "notice.matrix.callbackFailOpen": "callback de la matrice d’activation fail-open : {exc}", + "notice.matrix.configReadFailOpen": "lecture de la surface de config fail-open (traitée comme vide) : {exc}", + "notice.matrix.watchError": "fs.watch({dir}) en erreur, repli sur le sondage mtime : {exc}", + "notice.matrix.watchStartFailed": "fs.watch({dir}) n’a pas pu démarrer, repli sur le sondage mtime : {exc}", + "notice.matrix.recomputeFailOpen": "recalcul fail-open : {exc}", + "notice.probe.failOpen": "sonde fail-open : {exc}", + "notice.probe.incrementalFailOpen": "sonde incrémentale fail-open : {exc}", + "notice.probe.copilotPoolExhausted": "pool mensuel Copilot épuisé (gateway seconde source de vérité), considéré fiable jusqu’à reset_date", + "notice.probe.resultsDiscarded": "résultats de sonde écartés (génération de matrice passée de {oldGen}->{newGen} ; replanifiés par le recalcul de la nouvelle génération)", + "notice.probe.matrixRefreshed": "matrice actualisée : {comboCount} combos dont {okCount} ok (total {totalCount})", + "notice.probe.schedulingFailOpen": "planification des sondes fail-open : {exc}", + "notice.scoring.decisionLogFailOpen": "journal de décisions fail-open : {exc}", + "notice.selfupdate.checkFailOpen": "vérification d’auto-update fail-open : {exc}", + "notice.selfupdate.upgradeAssetsFailOpen": "assets de la commande upgrade fail-open : {exc}", + "notice.dispatch.mirrorDisabled": "miroir de panneaux tmux désactivé (init échouée) : {message}", + "notice.dispatch.mirrorOpFailed": "opération de miroir de panneaux tmux échouée (poursuite) : {message}", + "notice.dispatch.mirrorPaneFull": "miroir de panneaux tmux : colonne pleine ({slotCount} panneaux), ses_{sessionId} ({agent}) en file", + "notice.dispatch.mirrorAllClosed": "miroir de panneaux tmux : tous les panneaux de subagents fermés, panneau principal restauré", + "notice.dispatch.mirrorDisplayed": "miroir de panneaux tmux : ses_{sessionId} ({agent}) affiché dans le panneau {pane}", + "notice.dispatch.mirrorReconciling": "miroir de panneaux tmux : panneau(x) fermé(s) détecté(s), réconciliation de la mise en page", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "Configuration requise ({missing}) — lancez /switchman-setup (ou /switchman-setup-chat) ; la distribution est bloquée tant que ce n’est pas configuré", + "sidebar.peakTag": " ·pic", + "sidebar.staleTag": " ·périmé", + "sidebar.observeOnlyTag": " ·lecture-seule", + "sidebar.updateAvailable": " → {updateVersion}", + "sidebar.restartNeeded": " [REDÉMARRAGE REQUIS]", + "sidebar.noneAvailable": "aucun disponible", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "économie", + "sidebar.lane.mechanical": "mécanique", + "sidebar.lane.main": "principal", + "sidebar.lane.hard": "difficile", + "sidebar.lane.vision": "vision", + "sidebar.lane.review": "révision", + "sidebar.noticeLabel": "avis", + "dialog.pool.title": "Task pools (choisissez un task pool ; Échap pour quitter)", + "dialog.pool.laneRow": "{pinMark}{lane}", + "dialog.pool.manualSelection": "sélection manuelle : {selCount}/{totalCount} modèles participants", + "dialog.pool.notConfigured": "non configuré : défaut système (tous les modèles disponibles participent)", + "dialog.pool.toggleWriteFailed": "écriture échouée : {message}", + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} le pool {lane} (effectif immédiat, la barre latérale s’actualise)", + "dialog.pool.keepOneModel": "Conservez au moins un modèle participant ; utilisez « Clear config » pour restaurer le défaut système", + "dialog.pool.bulkWriteFailed": "écriture échouée : {message}", + "dialog.pool.allSelected": "pool {lane} : tous les modèles sélectionnés", + "dialog.pool.configCleared": "config du pool {lane} effacée (jeu de candidats par défaut restauré)", + "dialog.pool.allUnchecked": "pool {lane} : tout décoché — cochez les modèles à conserver ; quitter sans rien cocher conserve la sélection précédente", + "dialog.pool.back": "← Retour à la liste des pools", + "dialog.pool.selectAll": "☑ Tout sélectionner", + "dialog.pool.uncheckAll": "☐ Tout décocher (puis cochez les quelques-uns à conserver ; quitter sans rien cocher conserve l’ancienne liste)", + "dialog.pool.clearConfig": "✕ Effacer la config (défaut système : tous les modèles disponibles participent)", + "dialog.pool.modelRow": "{checkMark} {modelId}", + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + "dialog.pool.selectionTitle": "sélection du pool {lane} ({selCount}/{rowCount} participants ; la sélection bascule, les doublons entre pools sont autorisés)", + "dialog.rank.openPoolSelection": "→ Ouvrir la sélection des task pools (choisissez les modèles que chaque pool peut utiliser, puis classez-les)", + "dialog.rank.close": "✕ Fermer", + "dialog.rank.universeEmptyTitle": "Le classement des modèles est désactivé tant que les task pools ne sont pas configurés — seuls les modèles sélectionnés dans des task pools sont classables, vous ne classez ainsi jamais des modèles non distribuables", + "dialog.rank.alreadyAtEdge": "{modelName} est déjà au {edge} de la liste de capacité fusionnée", + "dialog.rank.moveWriteFailed": "écriture échouée : {message}", + "dialog.rank.pinnedOrMoved": "{verb} {modelName} en #{position} (score manuel {tier}/{raw}, ancré entre ses voisins ; effectif immédiat, la barre latérale s’actualise)", + "dialog.rank.title": "Classement de capacité des modèles — ordre fusionné (#1 le plus fort ; limité à la sélection des task pools ; les entrées manuelles s’entremêlent aux modèles à score de base ; ctrl+haut/ctrl+bas déplace d’un cran ; entrée = actions par modèle)", + "dialog.rank.searchHint": "Rechercher · alt+haut/alt+bas reflètent ctrl+haut/ctrl+bas (fonctionnent aussi)", + "dialog.rank.row": "#{rankPadded} {modelId}", + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + "dialog.rank.removeWriteFailed": "écriture échouée : {message}", + "dialog.rank.removed": "{model} retiré du classement manuel (repli sur le score de capacité de base, effectif immédiat, la barre latérale s’actualise)", + "dialog.rank.pinTop": "▲ Épingler en haut (au-dessus de tous les modèles)", + "dialog.rank.moveUp": "↑ Monter d’un cran (échange avec le modèle au-dessus ; ancre un score manuel entre voisins)", + "dialog.rank.moveDown": "↓ Descendre d’un cran (échange avec le modèle en dessous)", + "dialog.rank.remove": "✕ Retirer du classement (repli sur le score de base)", + "dialog.rank.back": "← Retour à la liste de classement", + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "configuration de switchman — task pools et classement de capacité", + "dialog.setup.intro": "Configuration guidée : choisissez les modèles pour chacun des 6 task pools, puis classez-les (le plus fort en premier). Échap quitte à tout moment ; les pools confirmés sont enregistrés immédiatement.", + "dialog.setup.start": "Commencer (première étape inachevée)", + "dialog.setup.statePools": "pools configurés : {count}/6", + "dialog.setup.stateRank": "classement : {state}", + "dialog.setup.laneTitle": "Task pool {index}/6 — {lane} ({count} sélectionnés ; entrée bascule, minimum 1)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] Tout sélectionner", + "dialog.setup.clearAll": "[ ] Tout décocher", + "dialog.setup.confirmLane": "Confirmer {lane} ({count} modèles) et continuer", + "dialog.setup.back": "Retour", + "dialog.setup.keepOne": "Gardez au moins un modèle dans ce pool", + "dialog.setup.rankTitle": "Classement de capacité — choisissez le n° {n} (le plus fort en premier, {remaining} modèles restants)", + "dialog.setup.rankFinish": "Terminer le classement ({count} choisis ; les autres conservent les scores de base du système)", + "dialog.setup.rankMinOne": "Classez au moins un modèle avant de terminer", + "dialog.setup.doneTitle": "Configuration terminée — active immédiatement (rechargement à chaud)", + "dialog.setup.donePools": "Pools : {summary}", + "dialog.setup.doneRank": "Classement : {order}", + "dialog.setup.restartHint": "Redémarrez opencode pour enregistrer le(s) nouveau(x) fournisseur(s) : {providers}", + "dialog.handover.noSession": "/handover : hors session, rien à sauvegarder", + "dialog.handover.inProgress": "/handover : sauvegarde complète de la session actuelle et compaction…", + "dialog.handover.resultStay": "{resultMessage} ; toujours dans la session d’origine, sans bascule", + "dialog.handover.result": "/handover {resultMessage}", + "palette.handover.title": "Sauvegarder et compacter la session actuelle", + "palette.handover.desc": "Fork complet de la session actuelle en sauvegarde (tag de titre [backup]) plus compaction de la session actuelle ; sans bascule de session (distinct du /fork intégré)", + "palette.category.label": "switchman", + "palette.poolConfig.title": "Sélection des task pools", + "palette.poolConfig.desc": "Choisissez les modèles participants par task pool (economy/mechanical/main/hard/vision/review)", + "palette.modelRank.title": "Classement de capacité des modèles", + "palette.modelRank.desc": "Classement de capacité manuel (prioritaire sur les scores de base ; plus haut = plus fort)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "Configuration guidée (pools + classement)", + "palette.setup.desc": "Assistant : sélection multiple de modèles par task pool, puis classement — requis avant que la distribution fonctionne", + "quota.poolGlm": "GLM", + "quota.poolCopilot": "Copilot", + "quota.poolDeepSeek": "DeepSeek", + "quota.queryingNoData": "interrogation/aucune donnée", + "quota.resetLater": "→plus tard", + "quota.resetTime": "→{hhmm}", + "quota.resetDate": "→{mmdd}", + "quota.resetDateTime": "→{mmdd} {hhmm}", + "quota.barPct": "{bar8} {pct} %", + "quota.row5h": "5h", + "quota.rowWeek": "semaine", + "quota.rowMcp": "MCP", + "quota.noData": "aucune donnée de quota", + "quota.rowRefresh": "actualiser", + "quota.rowCredits": "crédits", + "quota.monthlyExhausted": "pool mensuel épuisé", + "quota.unlimited": "illimité{usedSuffix}", + "quota.exhaustedOverage": "épuisé·facturation au dépassement{usage}", + "quota.barPctLeft": "{bar8} {pctTxt} % restants{usage}", + "quota.rowBalance": "solde", + "quota.exhausted": "épuisé", + "quota.unknownPayg": "inconnu (paiement à l’usage)", + "quota.barBalance": "{bar8} ¥{balance}", + "quota.balanceWarn": "(<¥{thr} alerte)", + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + "cli.config.unknownPool": "task pool inconnu : {lane} (six task pools : {laneList})", + "cli.config.poolHeader": "Sélection des task pools (fichier de config {poolConfigPath} ; sélection = les modèles rejoignant ce task pool ; un même modèle peut rejoindre plusieurs pools ; les pools non configurés utilisent la décision système par défaut)", + "cli.config.poolSection": "== {lane} == ({selection})", + "cli.config.poolSectionBrief": "== {lane} =={detail}", + "cli.config.poolListHint": "(voir la liste complète numérotée d’un seul pool : pool list <{laneList}>)", + "cli.config.indexOutOfRange": "index hors limites #{index} (la liste contient {rowCount} éléments)", + "cli.config.invalidModel": "nom de modèle invalide : {model}", + "cli.config.noManifest": "aucun manifeste de modèles disponibles (vérifiez les connexions des fournisseurs et le manifeste superset)", + "cli.config.poolRequiresArg": "pool {sub} requiert un index ou un nom de modèle", + "cli.config.poolSelectionCleared": "sélection du task pool {lane} effacée (retour au jeu de candidats par défaut, effectif immédiat, barre latérale actualisée en sync)", + "cli.config.poolUpdated": "Sélection du task pool {lane} mise à jour ({modelCount} modèles participants, effectif immédiat, barre latérale actualisée en sync)", + "cli.config.poolConfigCleared": "Config de sélection du task pool {lane} effacée (ce pool revient au jeu de candidats par défaut, effectif immédiat, barre latérale actualisée en sync)", + "cli.config.unknownPoolSub": "sous-commande inconnue pool {sub} (list/add/remove/set/clear)", + "cli.config.rankDisabledUntilPools": "Le classement de capacité manuel (fichier de config {capabilityRankPath}) est désactivé tant que les task pools ne sont pas configurés : seuls les modèles sélectionnés dans des task pools sont classables.", + "cli.config.rankHowTo": "Exécutez d’abord /poolConfig (dialogue TUI) ou pool set <task-pool> <index|model...> ici, puis classez uniquement les modèles que vous utilisez réellement.", + "cli.config.legacyHeader": "== Entrées manuelles héritées (nettoyage uniquement ; rank remove/clear fonctionnent toujours, ou sélectionnez les modèles dans un task pool pour les classer) ==", + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + "cli.config.rankHeader": "Classement de capacité des modèles (fichier de config {capabilityRankPath} ; limité aux {universeCount} modèles sélectionnés dans des task pools via /poolConfig — un seul ordre fusionné, les entrées manuelles s’entremêlent aux modèles à score de base selon le score effectif ; plus haut = plus fort)", + "cli.config.mergedHeader": "== Ordre fusionné ({manualCount} manuels{manualSuffix} ; set/add en CLI ordonnent les entrées selon l’échelle héritée, les déplacements TUI ancrent les scores entre voisins) ==", + "cli.config.manualTag": "·manuel{score}", + "cli.config.notInPoolTag": "·hors de tout task pool", + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + "cli.config.rankNoPools": "aucune sélection de task pool pour l’instant — le classement suit la sélection des pools ; exécutez d’abord /poolConfig (ou pool set)", + "cli.config.rankRequiresArg": "rank {sub} requiert un index ou un nom de modèle", + "cli.config.rankUpdated": "Classement de capacité manuel mis à jour ({modelCount} modèles, effectif immédiat, barre latérale actualisée en sync)", + "cli.config.rankCleared": "Classement de capacité manuel effacé (tout revient au score de capacité de base, effectif immédiat, barre latérale actualisée en sync)", + "cli.config.unknownRankSub": "sous-commande inconnue rank {sub} (list/set/add/remove/clear)", + "cli.config.usage": "Usage : switchman-config <pool|rank> ...", + "cli.config.usagePoolList": " pool list [task-pool] Aperçu de la sélection des pools (economy/mechanical/main/hard/vision/review ; avec un nom de pool = liste complète avec indices)", + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> Cocher les modèles rejoignant ce task pool", + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> Décocher la participation", + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> Remplacer entièrement la liste de participation de ce pool (un même modèle peut rejoindre plusieurs pools)", + "cli.config.usagePoolClear": " pool clear <task-pool> Effacer la config de ce pool (retour au jeu de candidats par défaut)", + "cli.config.usageRankList": " rank list Voir le classement de capacité manuel (limité à la sélection des task pools ; guide vers /poolConfig si aucun pool n’est configuré)", + "cli.config.usageRankSet": " rank set <index|model...> Réordonner entièrement (dans l’ordre donné, #1 est le plus fort ; modèles sélectionnés en pool uniquement)", + "cli.config.usageRankAdd": " rank add <index|model...> Ajouter à la fin du classement (modèles sélectionnés en pool uniquement)", + "cli.config.usageRankRemove": " rank remove <index|model...> Retirer du classement", + "cli.config.usageRankClear": " rank clear Effacer le classement (repli sur le score de capacité de base)", + "cli.config.errorPrefix": "switchman-config: {message}", + "cli.doctor.usage": "Usage : switchman-doctor vérifie la config opencode-switchman ; la variable d’env OPENCODE_CONFIG_DIR sélectionne le répertoire de config ; codes de sortie 0=aucun problème, 1=avertissements, 2=erreurs", + "cli.doctor.unknownModelsHint": "{unknownCount} modèles non reconnus par le système connu (groupe inconnu, classés en bas par coefficient)", + "cli.doctor.approxModelsHint": "{approxCount} modèles classés approximativement par préfixe/famille", + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + "cli.doctor.noIssues": "opencode-switchman doctor : aucun problème trouvé", + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/locales/it.ts b/src/locales/it.ts new file mode 100644 index 0000000..00e0611 --- /dev/null +++ b/src/locales/it.ts @@ -0,0 +1,273 @@ +// [2026-09-19]-[Italian message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const it: Partial<Record<MsgKey, string>> = { + "notice.breaker.realCallIsolated": "real-call di {agent} isolata per {mins} min ({category}): {reason}", + "notice.breaker.shellNotInjected": "shell non iniettata in opencode (nessun isolamento): {agent} {reason}", + "notice.breaker.failOpen": "breaker fail-open: {exc}", + "notice.capability.snapshotCorrupted": "snapshot dei rank di capability danneggiato (ignorato, ripiego sulla tabella curata)", + "notice.capability.primarySourceFailed": "origine primaria indice capability AA non riuscita ({exc}){nextStep}", + "notice.capability.backupSourceFailed": "origine di riserva indice capability OpenRouter non riuscita ({exc}) -> mantengo gli ultimi rank validi/predefiniti", + "notice.capability.parsedEmpty": "indice capability analizzato vuoto ({source}) -> mantengo gli ultimi rank validi/predefiniti", + "notice.capability.refreshed": "indice capability aggiornato: {source} {modelCount} modelli (versione={version})", + "notice.capability.refreshFailOpen": "aggiornamento indice capability fail-open (mantengo gli ultimi rank validi/predefiniti): {exc}", + "notice.capability.lmarenaDisagreement": "controllo incrociato capability LMArena: concordanza ordine tier vs ordine ELO solo {rate}% ({overlapCount} modelli sovrapposti) -- origine dati forse anomala, revisione manuale consigliata", + "notice.capability.lmarenaFailOpen": "controllo incrociato capability LMArena fail-open (ignorato): {exc}", + "notice.catalog.unavailableNoCache": "catalogo models.dev non disponibile e nessuna cache (degrado fail-open): {exc}", + "notice.copilot.shapeCacheRefreshed": "cache forme parametro thinking Copilot aggiornata: {modelCount} modelli", + "notice.copilot.shapeRefreshFailOpen": "aggiornamento forme parametro thinking Copilot fail-open: {exc}", + "notice.cost.refreshFailed": "aggiornamento snapshot costi non riuscito (mantengo i dati precedenti): {exc}", + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} non è JSON valido — ignorato (la config lingua ripiega sul marcatore AGENTS.md; \"dispatch\":\"off\" non applicato)", + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} contiene \"dispatch\" ma non esattamente \"off\" (ricevuto: {rawValue}) — ignorato, comportamento fleet", + "notice.ctx.paused": "controllo ctx sospeso per la sessione {sid} (/ctx-pause): read gate + budget auto-lettura + auto-handover sospesi; la misurazione continua", + "notice.ctx.resumed": "controllo ctx ripreso per la sessione {sid} (/ctx-resume): read gate + auto-handover di nuovo attivi", + "notice.workspace.created": "workspace artefatti creato: {rel}", + "notice.workspace.renamed": "workspace artefatti rinominato: {oldRel} → {rel}", + "notice.dispatch.mirrorResumeReuse": "mirroring pannello tmux: dispatch resume ses_{taskId} ({shellName}) — task_id riusato, pannello aperto direttamente (nessun session.created verrà emesso)", + "notice.dispatch.mirrorResumeLookupFailed": "mirroring pannello tmux: dispatch resume ses_{taskId} ({shellName}) — ricerca sessione non riuscita, pannello fail-open", + "notice.capability.selectionChanged": "selezione rank/pool attività modificata: banner e sidebar aggiornati subito", + "notice.capability.overrideWatchError": "errore watch fs.watch({dir}) sulla config override (ripiego su polling mtime): {exc}", + "notice.matrix.configSurfaceFailOpen": "lettura superficie config fail-open: {exc}", + "notice.matrix.floorFreeModels": "floor = {floorCount} modelli gratuiti OpenCode Zen (catalogo {catalogStatus})", + "notice.matrix.floorFallback": "floor ripiegato sul manifest statico (catalogo {catalogStatus}, 0 modelli gratuiti)", + "notice.matrix.invalidModelsUnknownProvider": "l'insieme visibile/preferiti contiene modelli non validi con provider sconosciuto (provider non connesso; ignorati, nessuna shell creata): {modelList}", + "notice.provider.probeAttemptSucceeded": "tentativo provider.list {attempt} riuscito (precedenti {prevAttempts} non pronti)", + "notice.provider.probeAttemptBackoff": "tentativo provider.list {attempt} non pronto, attendo: {exc}", + "notice.provider.unavailableCfgFallback": "provider.list non disponibile (ripiego su {keyCount} chiavi cfg.provider dopo {attemptCount} tentativi): {exc}", + "notice.provider.probeNewProvider": "sonda background provider.list: nuovi provider connessi ({providers}) — riavvii opencode per completare la registrazione delle shell", + "notice.provider.probeModelDrift": "sonda background provider.list: elenco modelli variato ({drift}) — manifest superset ricostruito, elenchi /modelRank //poolConfig aggiornati{restartHint}", + "notice.provider.probeRebuildFailed": "sonda background provider.list: ricostruzione superset non riuscita (mantenuto il manifest precedente): {exc}", + "notice.probe.warmupFailOpen": "warmup fail-open: {exc}", + "notice.skills.synced": "skill sincronizzate: {installedCount} installate, {updatedCount} aggiornate, {removedCount} rimosse ({skillNames})", + "notice.skills.syncFailOpen": "sincronizzazione skill fail-open: {exc}", + "notice.banner.failOpen": "banner fail-open: {exc}", + "notice.ctx.readBudgetContinuation": "continuazione budget lettura (file {fileName}, +{granted} righe da {offset}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateCap": "limite gate budget lettura (lettura tool, file {fileName}, stima ~{totalTokens} -> limite {suggestedLimit}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGate": "gate budget lettura {action} (tool {tool}, stima ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateFailOpen": "gate budget lettura fail-open (consentito): {exc}", + "notice.image.readGuardDenied": "guardia lettura immagini: il modello {modelKey} non supporta input vision; lettura negata {fileName} (sessione {sid})", + "notice.image.readGuardFailOpen": "guardia lettura immagini fail-open (consentita): {exc}", + "notice.doctor.summary": "doctor: {errorCount} errori / {warnCount} avvisi; esegua /switchman-doctor per i dettagli", + "notice.injection.legacyStaticMatrix": "iniettate {shellCount} shell modello (agenti, matrice statica legacy)", + "notice.provider.cacheUsed": "provider.list usa la cache tra riavvii ({providerCount} provider, cache del {cachedAt}); verifica aggiunte in background", + "notice.provider.cacheStale": "cache provider.list obsoleta (cache del {cachedAt}), sonda live prima della build superset", + "notice.matrix.recomputed": "matrice di attivazione ricalcolata (gen={generation}, shell attive {activeShellCount}, sonde {source}×{targetCount})", + "notice.injection.shellCount": "iniettate {shellCount} shell (modalità={runMode}, superficie iniezione={injectionMode}={fullSupersetCount}→{faceCount} dopo curatela, conflitti {conflictCount}; gating attivazione attivo)", + "notice.injection.configHookFailOpen": "hook config fail-open: {exc}", + "notice.lang.askLocale": "lang ask locale={locale} ({source})", + "notice.banner.rulesFailOpen": "regole/banner fail-open: {exc}", + "notice.relay.persisted": "relay immagini: il modello {modelKey} non supporta input vision; {written} immagine/i salvata/e su disco ({relayed} parte/i immagine inoltrata/e nella cronologia sessione, sessione {sid})", + "notice.relay.failOpen": "relay immagini fail-open (inoltrato): {exc}", + "notice.ctx.capToolDenied": "limite contesto subagent: tool '{tool}' negato nella sessione terminata {sid}", + "notice.ctx.capResumeDenied": "limite contesto subagent: resume della sessione terminata ses_{taskId} negato (permanente)", + "notice.lang.gateDenied": "gate lingua: tool '{tool}' negato nella sessione progetto non configurata {sid}", + "notice.search.clarifyFailOpen": "gate chiarimento ricerca: fail-open dopo {maxDenies} dinieghi senza ask — gate aperto per la sessione {sid}", + "notice.search.clarifyDenied": "gate chiarimento ricerca: tool '{tool}' negato (ricerca ampia, prima ask) nella sessione {sid} ({denyCount}/{maxDenies})", + "notice.dispatch.offUngoverned": "dispatch off: chiamata task consentita non governata (subagent_type='{subagentType}')", + "notice.dispatch.redirectUninjected": "reindirizzamento automatico {agent} → {candidate} (shell non iniettata; reindirizzato al candidato head catena)", + "notice.dispatch.redirectBuiltinBlocked": "reindirizzamento automatico {agent} → {candidate} (agente built-in bloccato)", + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] subagent_type='{agent}' sconosciuto: consentito (non nell'elenco shell; gli agenti built-in non sono governati dal routing)", + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled ma stato matrice={matrixStatus} (non down): fail-open, correzione automatica al prossimo refresh sonde", + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} stato matrice={matrixStatus} (non down): non bloccato, la sonda aggiorna al prossimo round", + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META mancante/malformato — sintetizzato dalla lane; lo dichiari per abilitare la semantica review cross-family / source=user", + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DECLASSATO: nessun revisore cross-family disponibile — self-review stessa family consentita; lo dichiari nella conclusione review", + "notice.dispatch.poolOverrideNote": "override pool-config: selezionato esplicitamente in questo task pool (soglia livello capability esentata)", + "notice.dispatch.redirectDenied": "reindirizzamento automatico {agent} → {redirect} ({deny})", + "notice.dispatch.gatesFailOpen": "sei gate fail-open (consentito): {exc}", + "notice.lang.prefsSaved": "preferenza lingua progetto salvata ({rel}): conversazione={conversation} commenti={comments} docs={docs}", + "notice.lang.gateWaived": "gate lingua: domanda marcatore completata senza config salvata — gate esentato per la sessione {sid}", + "notice.search.scopeAskDone": "chiarimento ricerca: ask ambito completato — gate aperto per la sessione {sid}", + "notice.ctx.readBudgetCharge": "addebito budget lettura +{charge} (tool {tool}, turno {turnUsed}/{turnBudget})", + "notice.handover.autoTriggered": "auto-handover attivato (dopo {tool}, ~{wmTokens} supera il watermark di compattazione forzata): backup completo + compattazione accodata della sessione corrente", + "notice.handover.backupResult": "backup auto-handover {outcome}: {message}", + "notice.handover.compactionAccepted": "compattazione auto-handover accettata: session.summarize restituito (compattazione eseguita sul loop sessione)", + "notice.handover.compactionRejected": "compattazione auto-handover non riuscita: session.summarize rifiutato (resta il backup)", + "notice.handover.compactionNoModel": "compattazione auto-handover non riuscita: nessun modello sessione registrato (chat.params mai attivato); resta il backup", + "notice.handover.failOpen": "auto-handover fail-open: {exc}", + "notice.ctx.capTerminated": "limite contesto subagent: sessione {sid}{agentSuffix} a ~{estTokens}k token (limite {capTokens}k) — tool negati, riepilogo avanzamento richiesto, sessione terminata (nessun resume task_id)", + "notice.provider.modelRetired": "modello ritirato (404 consecutivi), rimosso dai candidati: {provider}/{modelId}", + "notice.breaker.agentTripped": "breaker {agent} scattato (600s): {reason}", + "notice.breaker.accountingFailOpen": "contabilizzazione errori fail-open: {exc}", + "notice.lane.scoringFallback": "punteggio non riuscito, ripiego su ordinamento a regole: {exc}", + "notice.lane.backfillFailed": "backfill ranking non riuscito (la lane resta vuota): {exc}", + "notice.matrix.favoritesScanNoChange": "preferiti/insieme visibile scansionati: attivazione invariata (gen={generation}; nessun ricalcolo, nessuna nuova sonda)", + "notice.matrix.invalidModels": "l'insieme visibile/preferiti contiene modelli non validi (provider noto ma modelId inesistente, nessuna shell generata): {modelList}", + "notice.matrix.persistFailOpen": "persistenza matrice attivazione fail-open: {exc}", + "notice.matrix.callbackFailOpen": "callback matrice attivazione fail-open: {exc}", + "notice.matrix.configReadFailOpen": "lettura superficie config fail-open (trattata come vuota): {exc}", + "notice.matrix.watchError": "fs.watch({dir}) errore, ripiego su polling mtime: {exc}", + "notice.matrix.watchStartFailed": "fs.watch({dir}) avvio non riuscito, ripiego su polling mtime: {exc}", + "notice.matrix.recomputeFailOpen": "ricalcolo fail-open: {exc}", + "notice.probe.failOpen": "sonda fail-open: {exc}", + "notice.probe.incrementalFailOpen": "sonda incrementale fail-open: {exc}", + "notice.probe.copilotPoolExhausted": "pool mensile Copilot esaurito (gateway seconda fonte di verità), attendibile fino a reset_date", + "notice.probe.resultsDiscarded": "risultati sonda scartati (generazione matrice cambiata {oldGen}->{newGen}; riprogrammati dal ricalcolo nuova generazione)", + "notice.probe.matrixRefreshed": "matrice aggiornata: {comboCount} combo {okCount} ok (totale {totalCount})", + "notice.probe.schedulingFailOpen": "schedulazione sonde fail-open: {exc}", + "notice.scoring.decisionLogFailOpen": "decision log fail-open: {exc}", + "notice.selfupdate.checkFailOpen": "verifica self-update fail-open: {exc}", + "notice.selfupdate.upgradeAssetsFailOpen": "asset comando upgrade fail-open: {exc}", + "notice.dispatch.mirrorDisabled": "mirroring pannello tmux disabilitato (init non riuscita): {message}", + "notice.dispatch.mirrorOpFailed": "op mirroring pannello tmux non riuscita (continuo): {message}", + "notice.dispatch.mirrorPaneFull": "mirroring pannello tmux: colonna piena ({slotCount} pannelli), ses_{sessionId} ({agent}) in coda", + "notice.dispatch.mirrorAllClosed": "mirroring pannello tmux: tutti i pannelli subagent chiusi, pannello main ripristinato", + "notice.dispatch.mirrorDisplayed": "mirroring pannello tmux: ses_{sessionId} ({agent}) mostrato nel pannello {pane}", + "notice.dispatch.mirrorReconciling": "mirroring pannello tmux: rilevati pannelli chiusi, riconcilio il layout", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "Configurazione richiesta ({missing}) — esegua /switchman-setup (o /switchman-setup-chat); il dispatch è bloccato finché non è configurato", + "sidebar.peakTag": " ·picco", + "sidebar.staleTag": " ·obsoleto", + "sidebar.observeOnlyTag": " ·sola-osservazione", + "sidebar.updateAvailable": " → {updateVersion}", + "sidebar.restartNeeded": " [RIAVVIO NECESSARIO]", + "sidebar.noneAvailable": "nessuno disponibile", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "economia", + "sidebar.lane.mechanical": "meccanica", + "sidebar.lane.main": "principale", + "sidebar.lane.hard": "difficile", + "sidebar.lane.vision": "visione", + "sidebar.lane.review": "revisione", + "sidebar.noticeLabel": "avviso", + "dialog.pool.title": "Task pool (scelga un task pool; Esc per uscire)", + "dialog.pool.laneRow": "{pinMark}{lane}", + "dialog.pool.manualSelection": "selezione manuale: {selCount}/{totalCount} modelli partecipanti", + "dialog.pool.notConfigured": "non configurato: default sistema (partecipano tutti i modelli disponibili)", + "dialog.pool.toggleWriteFailed": "scrittura non riuscita: {message}", + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} il pool {lane} (effettivo subito, sidebar aggiornata)", + "dialog.pool.keepOneModel": "Mantenga almeno un modello partecipante; usi «Cancella config» per ripristinare il default sistema", + "dialog.pool.bulkWriteFailed": "scrittura non riuscita: {message}", + "dialog.pool.allSelected": "pool {lane}: tutti i modelli selezionati", + "dialog.pool.configCleared": "config pool {lane} cancellata (ripristinato l'insieme candidati default sistema)", + "dialog.pool.allUnchecked": "pool {lane}: tutto deselezionato — selezioni i modelli da tenere; uscendo senza spunte resta la selezione precedente", + "dialog.pool.back": "← Torna all'elenco pool", + "dialog.pool.selectAll": "☑ Seleziona tutto", + "dialog.pool.uncheckAll": "☐ Deseleziona tutto (poi selezioni i pochi da tenere; uscendo senza spunte resta l'elenco precedente)", + "dialog.pool.clearConfig": "✕ Cancella config (default sistema: partecipano tutti i modelli disponibili)", + "dialog.pool.modelRow": "{checkMark} {modelId}", + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + "dialog.pool.selectionTitle": "selezione pool {lane} ({selCount}/{rowCount} partecipanti; la selezione attiva/disattiva, duplicati tra pool consentiti)", + "dialog.rank.openPoolSelection": "→ Apra la selezione task-pool (scelga i modelli usabili per pool, poi li ordini)", + "dialog.rank.close": "✕ Chiudi", + "dialog.rank.universeEmptyTitle": "Il ranking modelli è disabilitato finché i task pool non sono configurati — solo i modelli selezionati nei task pool sono ordinabili, così non ordina mai modelli non dispacciabili", + "dialog.rank.alreadyAtEdge": "{modelName} è già al {edge} dell'elenco capability unito", + "dialog.rank.moveWriteFailed": "scrittura non riuscita: {message}", + "dialog.rank.pinnedOrMoved": "{verb} {modelName} a #{position} (punteggio manuale {tier}/{raw}, ancorato tra i vicini; effettivo subito, sidebar aggiornata)", + "dialog.rank.title": "Ranking capability modelli — ordine unito (#1 più forte; limitato alla selezione task-pool; voci manuali intercalate ai modelli base; ctrl+su/ctrl+giù sposta di una posizione; invio = azioni per modello)", + "dialog.rank.searchHint": "Cerca · alt+su/alt+giù come ctrl+su/ctrl+giù (funzionano)", + "dialog.rank.row": "#{rankPadded} {modelId}", + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + "dialog.rank.removeWriteFailed": "scrittura non riuscita: {message}", + "dialog.rank.removed": "{model} rimosso dal ranking manuale (ripiega sul punteggio base capability, effettivo subito, sidebar aggiornata)", + "dialog.rank.pinTop": "▲ Fissa in cima (sopra ogni modello)", + "dialog.rank.moveUp": "↑ Sposta su di una posizione (scambia col modello sopra; ancora un punteggio manuale tra vicini)", + "dialog.rank.moveDown": "↓ Sposta giù di una posizione (scambia col modello sotto)", + "dialog.rank.remove": "✕ Rimuovi dal ranking (torna al punteggio base)", + "dialog.rank.back": "← Torna all'elenco ranking", + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "configurazione di switchman — task pool e ranking capability", + "dialog.setup.intro": "Configurazione guidata: scelga i modelli per ciascuno dei 6 task pool, poi li ordini (il più forte prima). Esc esce in qualsiasi momento; i pool confermati vengono salvati subito.", + "dialog.setup.start": "Inizia (primo passo non completato)", + "dialog.setup.statePools": "pool configurati: {count}/6", + "dialog.setup.stateRank": "ranking: {state}", + "dialog.setup.laneTitle": "Task pool {index}/6 — {lane} ({count} selezionati; invio attiva/disattiva, minimo 1)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] Seleziona tutto", + "dialog.setup.clearAll": "[ ] Deseleziona tutto", + "dialog.setup.confirmLane": "Conferma {lane} ({count} modelli) e continua", + "dialog.setup.back": "Indietro", + "dialog.setup.keepOne": "Mantenga almeno un modello in questo pool", + "dialog.setup.rankTitle": "Ranking capability — scelga il n. {n} (il più forte prima, {remaining} modelli rimasti)", + "dialog.setup.rankFinish": "Termina il ranking ({count} scelti; gli altri mantengono i punteggi base di sistema)", + "dialog.setup.rankMinOne": "Ordini almeno un modello prima di terminare", + "dialog.setup.doneTitle": "Configurazione completata — attiva subito (hot-reload)", + "dialog.setup.donePools": "Pool: {summary}", + "dialog.setup.doneRank": "Ranking: {order}", + "dialog.setup.restartHint": "Riavvii opencode per registrare il/i nuovo/i provider: {providers}", + "dialog.handover.noSession": "/handover: non in sessione, nulla da salvare", + "dialog.handover.inProgress": "/handover: backup completo della sessione corrente e compattazione in corso…", + "dialog.handover.resultStay": "{resultMessage}; ancora nella sessione originale, non commutata", + "dialog.handover.result": "/handover {resultMessage}", + "palette.handover.title": "Backup e compattazione della sessione corrente", + "palette.handover.desc": "Fork completo della sessione corrente come backup (tag titolo [backup]) più compattazione della sessione corrente; nessuna commutazione sessione (diverso da /fork built-in)", + "palette.category.label": "switchman", + "palette.poolConfig.title": "Selezione task pool", + "palette.poolConfig.desc": "Scelga i modelli partecipanti per task pool (economy/mechanical/main/hard/vision/review)", + "palette.modelRank.title": "Ranking capability modelli", + "palette.modelRank.desc": "Ranking capability manuale (precede i punteggi base; prima = più forte)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "Configurazione guidata (pool + ranking)", + "palette.setup.desc": "Procedura guidata: selezione multipla dei modelli per task pool, poi ranking — necessario prima che il dispatch funzioni", + "quota.poolGlm": "GLM", + "quota.poolCopilot": "Copilot", + "quota.poolDeepSeek": "DeepSeek", + "quota.queryingNoData": "interrogo/nessun dato", + "quota.resetLater": "→dopo", + "quota.resetTime": "→{hhmm}", + "quota.resetDate": "→{mmdd}", + "quota.resetDateTime": "→{mmdd} {hhmm}", + "quota.barPct": "{bar8} {pct}%", + "quota.row5h": "5h", + "quota.rowWeek": "settimana", + "quota.rowMcp": "MCP", + "quota.noData": "nessun dato quota", + "quota.rowRefresh": "aggiornamento", + "quota.rowCredits": "crediti", + "quota.monthlyExhausted": "pool mensile esaurito", + "quota.unlimited": "illimitato{usedSuffix}", + "quota.exhaustedOverage": "esaurito·fatturazione extra{usage}", + "quota.barPctLeft": "{bar8} {pctTxt}% restanti{usage}", + "quota.rowBalance": "saldo", + "quota.exhausted": "esaurito", + "quota.unknownPayg": "sconosciuto (pay-as-you-go)", + "quota.barBalance": "{bar8} ¥{balance}", + "quota.balanceWarn": "(<¥{thr} avviso)", + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + "cli.config.unknownPool": "task pool sconosciuto: {lane} (sei task pool: {laneList})", + "cli.config.poolHeader": "Selezione task-pool (file config {poolConfigPath}; selezione = i modelli che joinano quel task pool; lo stesso modello può joinare più pool; i pool non configurati usano la decisione default sistema)", + "cli.config.poolSection": "== {lane} == ({selection})", + "cli.config.poolSectionBrief": "== {lane} =={detail}", + "cli.config.poolListHint": "(veda l'elenco completo numerato di un singolo pool con: pool list <{laneList}>)", + "cli.config.indexOutOfRange": "indice fuori intervallo #{index} (l'elenco ha {rowCount} voci)", + "cli.config.invalidModel": "nome modello non valido: {model}", + "cli.config.noManifest": "nessun manifest modelli disponibili (verifichi le connessioni provider e il manifest superset)", + "cli.config.poolRequiresArg": "pool {sub} richiede un indice o un nome modello", + "cli.config.poolSelectionCleared": "selezione task-pool {lane} cancellata (torna ai candidati default sistema, effettiva subito, sidebar sincronizzata)", + "cli.config.poolUpdated": "Selezione task-pool {lane} aggiornata ({modelCount} modelli partecipanti, effettiva subito, sidebar sincronizzata)", + "cli.config.poolConfigCleared": "Config selezione task-pool {lane} cancellata (quel pool torna ai candidati default sistema, effettiva subito, sidebar sincronizzata)", + "cli.config.unknownPoolSub": "sottocomando pool sconosciuto {sub} (list/add/remove/set/clear)", + "cli.config.rankDisabledUntilPools": "Il ranking capability manuale (file config {capabilityRankPath}) è disabilitato finché i task pool non sono configurati: solo i modelli selezionati nei task pool sono ordinabili.", + "cli.config.rankHowTo": "Esegua prima /poolConfig (dialogo TUI) o pool set <task-pool> <index|model...> qui, poi ordini solo i modelli usati.", + "cli.config.legacyHeader": "== Voci manuali legacy (solo pulizia; rank remove/clear funzionano, o selezioni i modelli in un task pool per ordinarli) ==", + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + "cli.config.rankHeader": "Ranking capability modelli (file config {capabilityRankPath}; limitato ai {universeCount} modelli selezionati nei task pool via /poolConfig — un unico ordinamento unito, voci manuali intercalate ai modelli base per punteggio effettivo; più in alto = più forte)", + "cli.config.mergedHeader": "== Ordinamento unito ({manualCount} manuali{manualSuffix}; le voci CLI set/add seguono la ladder legacy, gli spostamenti TUI ancorano i punteggi tra vicini) ==", + "cli.config.manualTag": "·manuale{score}", + "cli.config.notInPoolTag": "·non in alcun task pool", + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + "cli.config.rankNoPools": "nessuna selezione task-pool ancora — il ranking segue la selezione pool; esegua prima /poolConfig (o pool set)", + "cli.config.rankRequiresArg": "rank {sub} richiede un indice o un nome modello", + "cli.config.rankUpdated": "Ranking capability manuale aggiornato ({modelCount} modelli, effettivo subito, sidebar sincronizzata)", + "cli.config.rankCleared": "Ranking capability manuale cancellato (tutto torna al punteggio base capability, effettivo subito, sidebar sincronizzata)", + "cli.config.unknownRankSub": "sottocomando rank sconosciuto {sub} (list/set/add/remove/clear)", + "cli.config.usage": "Uso: switchman-config <pool|rank> ...", + "cli.config.usagePoolList": " pool list [task-pool] Panoramica selezione pool (economy/mechanical/main/hard/vision/review; con nome pool = elenco completo con indici)", + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> Aggiunga modelli a quel task pool", + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> Rimuova la partecipazione", + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> Sostituisca la lista partecipazione pool (lo stesso modello può joinare più pool)", + "cli.config.usagePoolClear": " pool clear <task-pool> Cancelli la config pool (torna ai candidati default sistema)", + "cli.config.usageRankList": " rank list Veda il ranking capability manuale (limitato alla selezione task-pool; guida a /poolConfig se nessun pool è configurato)", + "cli.config.usageRankSet": " rank set <index|model...> Riordini completo (nell'ordine dato, #1 più forte; solo modelli selezionati nel pool)", + "cli.config.usageRankAdd": " rank add <index|model...> Accodi in fondo al ranking (solo modelli selezionati nel pool)", + "cli.config.usageRankRemove": " rank remove <index|model...> Rimuova dal ranking", + "cli.config.usageRankClear": " rank clear Cancelli il ranking (torna al punteggio base capability)", + "cli.config.errorPrefix": "switchman-config: {message}", + "cli.doctor.usage": "Uso: switchman-doctor verifica la config opencode-switchman; la var env OPENCODE_CONFIG_DIR seleziona la dir config; codici uscita 0=nessun problema, 1=avvisi, 2=errori", + "cli.doctor.unknownModelsHint": "{unknownCount} modelli non riconosciuti dal sistema noto (gruppo sconosciuto, relegati in fondo per coefficiente)", + "cli.doctor.approxModelsHint": "{approxCount} modelli classificati approssimativamente per prefisso/famiglia", + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + "cli.doctor.noIssues": "opencode-switchman doctor: nessun problema rilevato", + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/locales/ja.ts b/src/locales/ja.ts new file mode 100644 index 0000000..b4c0c49 --- /dev/null +++ b/src/locales/ja.ts @@ -0,0 +1,525 @@ +// [2026-09-19]-[Japanese message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const ja: Partial<Record<MsgKey, string>> = { + // ---- notices (status log; appendStatusLog) ---- + + // src/breaker.ts:37 + "notice.breaker.realCallIsolated": "{agent}のreal-callを{mins}分間分離しました({category}):{reason}", + // src/breaker.ts:48 + "notice.breaker.shellNotInjected": "shellがopencodeに注入されていません(分離なし):{agent} {reason}", + // src/breaker.ts:200 + "notice.breaker.failOpen": "breakerのfail-open:{exc}", + // src/capability.ts:246 + "notice.capability.snapshotCorrupted": "同梱のcapability rankスナップショットが破損しています(スキップし、curated tableにフォールバックします)", + // src/capability.ts:299 + "notice.capability.primarySourceFailed": "capability indexのprimary source AAに失敗しました({exc}){nextStep}", + // src/capability.ts:311 + "notice.capability.backupSourceFailed": "capability indexのbackup source OpenRouterに失敗しました({exc})→ last-good/同梱のdefault rankを維持します", + // src/capability.ts:316 + "notice.capability.parsedEmpty": "capability indexの解析結果が空でした({source})→ last-good/同梱のdefault rankを維持します", + // src/capability.ts:333 + "notice.capability.refreshed": "capability indexを更新しました:{source}、{modelCount} models(version={version})", + // src/capability.ts:336 + "notice.capability.refreshFailOpen": "capability index更新のfail-open(last-good/同梱のdefault rankを維持します):{exc}", + // src/capability.ts:372 + "notice.capability.lmarenaDisagreement": "capabilityのLMArena cross-check:tier-orderとELO-orderの一致率は{rate}%のみ({overlapCount} modelsが重複)——データソースに異常の可能性があります。手動レビューを推奨します", + // src/capability.ts:375 + "notice.capability.lmarenaFailOpen": "capabilityのLMArena cross-checkのfail-open(スキップしました):{exc}", + // src/catalog.ts:153 + "notice.catalog.unavailableNoCache": "models.dev catalogが利用不可でcacheもありません(fail-open degradation):{exc}", + // src/copilot-thinking.ts:71 + "notice.copilot.shapeCacheRefreshed": "Copilot thinking-parameter shape cacheを更新しました:{modelCount} models", + // src/copilot-thinking.ts:73 + "notice.copilot.shapeRefreshFailOpen": "Copilot thinking-parameter shape更新のfail-open:{exc}", + // src/cost.ts:44 + "notice.cost.refreshFailed": "cost snapshotの更新に失敗しました(古いデータを維持します):{exc}", + // src/dispatch-mode.ts:60 (log callback defaults to appendStatusLog) + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile}は有効なJSONではありません——無視しました(lang設定はAGENTS.md markerにフォールバックします;\"dispatch\":\"off\"は適用されません)", + // src/dispatch-mode.ts:66 (log callback defaults to appendStatusLog) + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile}に\"dispatch\"がありますが、正確に\"off\"ではありません(取得値:{rawValue})——無視し、fleet動作を継続します", + // src/index.ts:262 + "notice.ctx.paused": "session {sid}のctx controlを一時停止しました(/ctx-pause):read gate+self-read budget+auto-handoverを停止します。計測は継続します", + // src/index.ts:264 + "notice.ctx.resumed": "session {sid}のctx controlを再開しました(/ctx-resume):read gate+auto-handoverが再び有効です", + // src/index.ts:467 + "notice.workspace.created": "artifact workspaceを作成しました:{rel}", + // src/index.ts:468 + "notice.workspace.renamed": "artifact workspaceの名前を変更しました:{oldRel} → {rel}", + // src/index.ts:542 + "notice.dispatch.mirrorResumeReuse": "tmux pane mirroring:resume dispatch ses_{taskId}({shellName})——task_idを再利用し、paneを直接開きました(session.createdは発火しません)", + // src/index.ts:546 + "notice.dispatch.mirrorResumeLookupFailed": "tmux pane mirroring:resume dispatch ses_{taskId}({shellName})——session lookupに失敗したため、fail-open paneを開きました", + // src/index.ts:574 + "notice.capability.selectionChanged": "capability rank/task-pool selectionが変更されました:bannerとsidebarを即時更新します", + // src/index.ts:589 + "notice.capability.overrideWatchError": "fs.watch({dir})のoverride-config監視エラー(mtime pollingにフォールバックします):{exc}", + // src/index.ts:647 + "notice.matrix.configSurfaceFailOpen": "config surface読み取りのfail-open:{exc}", + // src/index.ts:675 + "notice.matrix.floorFreeModels": "floor={floorCount}のOpenCode Zen free models(catalog {catalogStatus})", + // src/index.ts:676 + "notice.matrix.floorFallback": "floorはstatic manifestにフォールバックしました(catalog {catalogStatus}、0 free models)", + // src/index.ts:680 + "notice.matrix.invalidModelsUnknownProvider": "visible set/favoritesに不明なproviderの無効なmodelが含まれています(provider未接続のため無視し、shellは構築しません):{modelList}", + // src/index.ts:778 + "notice.provider.probeAttemptSucceeded": "provider.listのattempt {attempt}が成功しました(直前の{prevAttempts}回はnot ready)", + // src/index.ts:783 + "notice.provider.probeAttemptBackoff": "provider.listのattempt {attempt}はnot readyのため、backoffします:{exc}", + // src/index.ts:789 + "notice.provider.unavailableCfgFallback": "provider.listが利用不可です({attemptCount}回のattempt後、{keyCount}件のcfg.provider keyにフォールバックしました):{exc}", + // src/index.ts:814 (alert) + "notice.provider.probeNewProvider": "provider.list background probe:新しいproviderが接続されました({providers})——shell登録を完了するにはopencodeを再起動してください", + // src/index.ts:832 (alert) + "notice.provider.probeModelDrift": "provider.list background probe:model listがdriftしました({drift})——superset manifestを再構築し、/modelRank・/poolConfig listを更新しました{restartHint}", + // src/index.ts:834 + "notice.provider.probeRebuildFailed": "provider.list background probe:supersetの再構築に失敗しました(以前のmanifestを維持します):{exc}", + // src/index.ts:886 + "notice.probe.warmupFailOpen": "warmupのfail-open:{exc}", + // src/index.ts:900 + "notice.skills.synced": "skillを同期しました:{installedCount}件インストール、{updatedCount}件更新、{removedCount}件削除({skillNames})", + // src/index.ts:903 + "notice.skills.syncFailOpen": "skill同期のfail-open:{exc}", + // src/index.ts:1145 + "notice.banner.failOpen": "bannerのfail-open:{exc}", + // src/index.ts:1241 + "notice.ctx.readBudgetContinuation": "read budget継続完了(file {fileName}、{offset}から+{granted} lines、turn {turnUsed}/{turnBudget})", + // src/index.ts:1251 + "notice.ctx.readBudgetGateCap": "read budget gate cap(tool read、file {fileName}、推定約{totalTokens}→limit {suggestedLimit}、turn {turnUsed}/{turnBudget})", + // src/index.ts:1277 (template built at src/index.ts:1259 as denyLog) + "notice.ctx.readBudgetGate": "read budget gate {action}(tool {tool}、推定約{totalTokens}{contRem}、C約{wmTokens}、T_est約{turnsToHard}、turn {turnUsed}/{turnBudget})", + // src/index.ts:1281 + "notice.ctx.readBudgetGateFailOpen": "read budget gateのfail-open(許可しました):{exc}", + // src/index.ts:1306 + "notice.image.readGuardDenied": "image read guard:model {modelKey}にはvision inputがありません。{fileName}の読み取りを拒否しました(session {sid})", + // src/index.ts:1310 + "notice.image.readGuardFailOpen": "image read guardのfail-open(許可しました):{exc}", + // src/index.ts:1358 + "notice.doctor.summary": "doctorが{errorCount}件のerror/{warnCount}件のwarnを検出しました。/switchman-doctorで確認してください", + // src/index.ts:1393 + "notice.injection.legacyStaticMatrix": "{shellCount}件のmodel shellを注入しました(agents、legacy static matrix)", + // src/index.ts:1412 + "notice.provider.cacheUsed": "provider.listはcross-restart cacheを使用しています({providerCount} providers、{cachedAt}にcache)。追加分をbackgroundで検証中です", + // src/index.ts:1419 + "notice.provider.cacheStale": "provider.list cacheが古くなっています({cachedAt}にcache)。superset構築前にlive probeを実行します", + // src/index.ts:1469 + "notice.matrix.recomputed": "activation matrixを再計算しました(gen={generation}、active shell {activeShellCount}件、probe {source}×{targetCount})", + // src/index.ts:1474 + "notice.injection.shellCount": "{shellCount}件のshellを注入しました(mode={runMode}、injection surface={injectionMode}=curation後に{fullSupersetCount}→{faceCount}、conflict {conflictCount}件;activation gating有効)", + // src/index.ts:1479 + "notice.injection.configHookFailOpen": "config hookのfail-open:{exc}", + // src/index.ts:1541 + "notice.lang.askLocale": "lang ask locale={locale}({source})", + // src/index.ts:1604 + "notice.banner.rulesFailOpen": "rules/bannerのfail-open:{exc}", + // src/index.ts:1677 + "notice.relay.persisted": "image relay:model {modelKey}にはvision inputがありません。{written}件のimageをdiskに保存しました(session履歴全体で{relayed}件のimage partをrelay、session {sid})", + // src/index.ts:1679 + "notice.relay.failOpen": "image relayのfail-open(passthroughしました):{exc}", + // src/index.ts:1694 + "notice.ctx.capToolDenied": "subagent context cap:終了済みsession {sid}ではtool '{tool}'を拒否しました", + // src/index.ts:1701 + "notice.ctx.capResumeDenied": "subagent context cap:終了済みsession ses_{taskId}のresumeを拒否しました(permanent)", + // src/index.ts:1727 + "notice.lang.gateDenied": "lang gate:未設定projectのsession {sid}ではtool '{tool}'を拒否しました", + // src/index.ts:1751 + "notice.search.clarifyFailOpen": "search clarify gate:askなしで{maxDenies}回拒否後のfail-open——session {sid}のgateを開きました", + // src/index.ts:1754 + "notice.search.clarifyDenied": "search clarify gate:tool '{tool}'を拒否しました(broad searchのためask-first、session {sid}、{denyCount}/{maxDenies})", + // src/index.ts:1774 + "notice.dispatch.offUngoverned": "dispatch off:task callをungovernedで許可しました(subagent_type='{subagentType}')", + // src/index.ts:1853 + "notice.dispatch.redirectUninjected": "auto-redirect {agent} → {candidate}(未注入shellのため、chain-head候補にredirectしました)", + // src/index.ts:1874 + "notice.dispatch.redirectBuiltinBlocked": "auto-redirect {agent} → {candidate}(built-in agentはブロックされています)", + // src/index.ts:1883 (via src/gates.ts:331 noteUnknownAgent) + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] 不明なsubagent_type='{agent}':許可しました(shell listにありません。built-in agentはroutingの管理対象外です)", + // src/index.ts:1889 (r.note via src/gates.ts:156) + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent}はregistry=disabledですがmatrix status={matrixStatus}(downではありません):fail-openです。次回probe更新後に自動修正されます", + // src/index.ts:1889 (r.note via src/gates.ts:175) + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent}のmatrix status={matrixStatus}(downではありません):ブロックしません。次roundのprobeで更新されます", + // src/index.ts:1889 (r.note via src/gates.ts:63 ROUTE_META_SYNTH_NOTE) + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_METAが欠落/不正です——laneから合成しました。review cross-family/source=user semanticsを有効にするには宣言してください", + // src/index.ts:1889 (r.note via src/gates.ts:240 REVIEW_SELF_REVIEW_NOTE) + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED:利用可能なcross-family reviewerがありません——same-family self-reviewを許可します。review結論でDOWNGRADEDを宣言してください", + // src/index.ts:1889 (r.note via src/gates.ts:288 poolOverrideNote) + "notice.dispatch.poolOverrideNote": "pool-config override:このtask poolに明示的に選択されました(capability level floorを免除します)", + // src/index.ts:1897 + "notice.dispatch.redirectDenied": "auto-redirect {agent} → {redirect}({deny})", + // src/index.ts:1910 + "notice.dispatch.gatesFailOpen": "six gatesのfail-open(許可しました):{exc}", + // src/index.ts:1934 + "notice.lang.prefsSaved": "project言語設定を保存しました({rel}):conversation={conversation} comments={comments} docs={docs}", + // src/index.ts:1937 + "notice.lang.gateWaived": "lang gate:marker質問は完了しましたが設定が保存されなかったため、session {sid}のgateを免除しました", + // src/index.ts:1943 + "notice.search.scopeAskDone": "search clarify:scope askが完了しました——session {sid}のgateを開きました", + // src/index.ts:1956 + "notice.ctx.readBudgetCharge": "read budget charge +{charge}(tool {tool}、turn {turnUsed}/{turnBudget})", + // src/index.ts:1970 + "notice.handover.autoTriggered": "auto-handoverをtriggerしました({tool}実行後、約{wmTokens}がforce-compaction watermarkを超過):現在のsessionのfull backup+compactionをqueueしました", + // src/index.ts:1981 + "notice.handover.backupResult": "auto-handover backup {outcome}:{message}", + // src/index.ts:1996 (variant 1 of 3) + "notice.handover.compactionAccepted": "auto-handover compactionを受理しました:session.summarizeが戻りました(session loop上でcompactionを実行しました)", + // src/index.ts:1996 (variant 2 of 3) + "notice.handover.compactionRejected": "auto-handover compactionに失敗しました:session.summarizeが拒否されました(backupは維持されます)", + // src/index.ts:1996 (variant 3 of 3) + "notice.handover.compactionNoModel": "auto-handover compactionに失敗しました:session modelが記録されていません(chat.params未発火)。backupは維持されます", + // src/index.ts:2008 + "notice.handover.failOpen": "auto-handoverのfail-open:{exc}", + // src/index.ts:2114 + "notice.ctx.capTerminated": "subagent context cap:session {sid}{agentSuffix}が約{estTokens}k tokensに到達しました(cap {capTokens}k)——toolを拒否し、進捗サマリーを要求してsessionを終了しました(task_id resume不可)", + // src/index.ts:2205 + "notice.provider.modelRetired": "modelをretireしました(404連続)。候補から除外します:{provider}/{modelId}", + // src/index.ts:2208 + "notice.breaker.agentTripped": "{agent}のbreakerがtrippedしました(600s):{reason}", + // src/index.ts:2210 + "notice.breaker.accountingFailOpen": "failure accountingのfail-open:{exc}", + // src/lane.ts:410 + "notice.lane.scoringFallback": "scoringに失敗し、rule-based orderingにフォールバックしました:{exc}", + // src/lane.ts:494 + "notice.lane.backfillFailed": "backfill rankingに失敗しました(laneはemptyのままです):{exc}", + // src/matrix-manager.ts:196 + "notice.matrix.favoritesScanNoChange": "favorites/visible setをscanしました:activationに変更ありません(gen={generation}。再計算・再probeなし)", + // src/matrix-manager.ts:204 + "notice.matrix.invalidModels": "visible set/favoritesに無効なmodelが含まれています(providerは既知ですがmodelIdが存在しないため、shellは生成しません):{modelList}", + // src/matrix-manager.ts:217 + "notice.matrix.persistFailOpen": "activation matrix保存のfail-open:{exc}", + // src/matrix-manager.ts:222 + "notice.matrix.callbackFailOpen": "activation matrix callbackのfail-open:{exc}", + // src/matrix-manager.ts:250 + "notice.matrix.configReadFailOpen": "config surface読み取りのfail-open(emptyとして扱います):{exc}", + // src/matrix-manager.ts:272 + "notice.matrix.watchError": "fs.watch({dir})でエラーが発生し、mtime pollingにフォールバックします:{exc}", + // src/matrix-manager.ts:277 + "notice.matrix.watchStartFailed": "fs.watch({dir})の開始に失敗し、mtime pollingにフォールバックします:{exc}", + // src/matrix-manager.ts:308 + "notice.matrix.recomputeFailOpen": "recomputeのfail-open:{exc}", + // src/probe.ts:144 + "notice.probe.failOpen": "probeのfail-open:{exc}", + // src/probe.ts:162 + "notice.probe.incrementalFailOpen": "incremental probeのfail-open:{exc}", + // src/probe.ts:201 + "notice.probe.copilotPoolExhausted": "Copilot monthly poolが枯渇しました(gateway second source of truth)。reset_dateまでtrustedです", + // src/probe.ts:207 + "notice.probe.resultsDiscarded": "probe結果を破棄しました(matrix generationが{oldGen}→{newGen}に変更。新generationの再計算で再スケジュールします)", + // src/probe.ts:214 + "notice.probe.matrixRefreshed": "matrixを更新しました:{comboCount} combos中{okCount} ok(合計{totalCount})", + // src/probe.ts:233 + "notice.probe.schedulingFailOpen": "probe schedulingのfail-open:{exc}", + // src/scoring.ts:399 + "notice.scoring.decisionLogFailOpen": "decision logのfail-open:{exc}", + // src/selfupdate.ts:122 + "notice.selfupdate.checkFailOpen": "self-update checkのfail-open:{exc}", + // src/selfupdate.ts:255 + "notice.selfupdate.upgradeAssetsFailOpen": "upgrade command assetsのfail-open:{exc}", + // src/tmux.ts:149 (via log callback wired to appendStatusLog at src/index.ts:236) + "notice.dispatch.mirrorDisabled": "tmux pane mirroringを無効化しました(init失敗):{message}", + // src/tmux.ts:221 + "notice.dispatch.mirrorOpFailed": "tmux pane mirroring opに失敗しました(継続します):{message}", + // src/tmux.ts:230 + "notice.dispatch.mirrorPaneFull": "tmux pane mirroring:columnがfullです({slotCount} panes)。ses_{sessionId}({agent})をqueueしました", + // src/tmux.ts:280 + "notice.dispatch.mirrorAllClosed": "tmux pane mirroring:すべてのsubagent paneを閉じ、main paneを復元しました", + // src/tmux.ts:290 + "notice.dispatch.mirrorDisplayed": "tmux pane mirroring:ses_{sessionId}({agent})をpane {pane}に表示しました", + // src/tmux.ts:303 + "notice.dispatch.mirrorReconciling": "tmux pane mirroring:閉じられたpaneを検出し、layoutを調整中です", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "setupが必要です({missing})——/switchman-setup(または/switchman-setup-chat)を実行してください;設定されるまでdispatchはブロックされます", + + // ---- sidebar (tui.tsx sidebar chrome) ---- + + // src/tui.tsx:308 + "sidebar.peakTag": " ·ピーク", + // src/tui.tsx:309 + "sidebar.staleTag": " ·古い", + // src/tui.tsx:310 + "sidebar.observeOnlyTag": " ·参照のみ", + // src/tui.tsx:346 + "sidebar.updateAvailable": " → {updateVersion}", + // src/tui.tsx:351 + "sidebar.restartNeeded": " [要再起動]", + // src/tui.tsx:358 + "sidebar.noneAvailable": "なし", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "エコノミー", + "sidebar.lane.mechanical": "機械", + "sidebar.lane.main": "メイン", + "sidebar.lane.hard": "ハード", + "sidebar.lane.vision": "ビジョン", + "sidebar.lane.review": "レビュー", + // src/tui.tsx:368 + "sidebar.noticeLabel": "通知", + + // ---- dialogs (tui.tsx: pool picker / pool models / rank / handover) ---- + + // src/tui.tsx:426 (pool picker title) + "dialog.pool.title": "Task pool(task poolを選択;Escで終了)", + // src/tui.tsx:428 (pool picker lane row) + "dialog.pool.laneRow": "{pinMark}{lane}", + // src/tui.tsx:430 (pool picker option description) + "dialog.pool.manualSelection": "manual selection:{selCount}/{totalCount} modelsが参加中", + // src/tui.tsx:432 (pool picker option description) + "dialog.pool.notConfigured": "未設定:system default(利用可能な全modelが参加)", + // src/tui.tsx:453 (pool models dialog, toggle persist) + "dialog.pool.toggleWriteFailed": "書き込みに失敗しました:{message}", + // src/tui.tsx:458 (pool models dialog, toggle toast) + "dialog.pool.modelToggled": "{lane} pool:{modelKey}を{verb}{direction}しました(即時反映、sidebar更新)", + // src/tui.tsx:469 (pool models dialog, min-selection guard toast) + "dialog.pool.keepOneModel": "参加中のmodelを1件以上残してください。system defaultに戻すには「設定をクリア」を使います", + // src/tui.tsx:482 (pool models dialog, bulk select-all persist) + "dialog.pool.bulkWriteFailed": "書き込みに失敗しました:{message}", + // src/tui.tsx:485 (pool models dialog, bulk toast) + "dialog.pool.allSelected": "{lane} pool:全modelを選択しました", + // src/tui.tsx:490 (pool models dialog, clear-config toast) + "dialog.pool.configCleared": "{lane} poolの設定をクリアしました(system default候補セットに戻しました)", + // src/tui.tsx:499 (pool models dialog, uncheck-all toast) + "dialog.pool.allUnchecked": "{lane} pool:すべて外しました——残すmodelをcheckしてください。何もcheckせず終了すると以前の選択を維持します", + // src/tui.tsx:503 (pool models dialog option) + "dialog.pool.back": "← pool listに戻る", + // src/tui.tsx:504 (pool models dialog option) + "dialog.pool.selectAll": "☑ すべて選択", + // src/tui.tsx:505 (pool models dialog option) + "dialog.pool.uncheckAll": "☐ すべて外す(残すmodelだけcheck;何もcheckせず終了すると以前のlistを維持)", + // src/tui.tsx:506 (pool models dialog option) + "dialog.pool.clearConfig": "✕ 設定をクリア(system default:利用可能な全modelが参加)", + // src/tui.tsx:508 (pool models dialog model row) + "dialog.pool.modelRow": "{checkMark} {modelId}", + // src/tui.tsx:510 (pool models dialog row description) + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + // src/tui.tsx:516 (pool models dialog title) + "dialog.pool.selectionTitle": "{lane} pool selection({selCount}/{rowCount}が参加中;選択でtoggle、pool間の重複可)", + // src/tui.tsx:538 (rank universe-empty dialog option) + "dialog.rank.openPoolSelection": "→ task-pool selectionを開く(各poolが使うmodelを選んでからrankします)", + // src/tui.tsx:539 (rank universe-empty dialog option) + "dialog.rank.close": "✕ 閉じる", + // src/tui.tsx:543 (rank universe-empty dialog title) + "dialog.rank.universeEmptyTitle": "task poolを設定するまでmodel rankingは無効です——task poolに選択されたmodelのみrank可能なので、dispatchできないmodelをrankすることはありません", + // src/tui.tsx:561 (rank move at edge toast) + "dialog.rank.alreadyAtEdge": "{modelName}はmerged capability listの{edge}にあります", + // src/tui.tsx:568 (rank move persist) + "dialog.rank.moveWriteFailed": "書き込みに失敗しました:{message}", + // src/tui.tsx:573 (rank move/pin toast) + "dialog.rank.pinnedOrMoved": "{modelName}を{verb}して#{position}に移動しました(manual score {tier}/{raw}、隣接model間にanchor;即時反映、sidebar更新)", + // src/tui.tsx:627 (rank picker title) + "dialog.rank.title": "Model capability ranking——merged order(#1が最強;task-pool selectionにscoped;manual entryはbase-score modelとinterleave;ctrl+up/ctrl+downで1つ移動;enterでper-model操作)", + // src/tui.tsx:628 (rank picker placeholder) + "dialog.rank.searchHint": "Search · alt+up/alt+downはctrl+up/ctrl+downと同等(こちらも使用可)", + // src/tui.tsx:630 (rank picker row) + "dialog.rank.row": "#{rankPadded} {modelId}", + // src/tui.tsx:632 (rank picker row description) + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + // src/tui.tsx:662 (rank actions, remove persist) + "dialog.rank.removeWriteFailed": "書き込みに失敗しました:{message}", + // src/tui.tsx:665 (rank actions, remove toast) + "dialog.rank.removed": "manual rankingから{model}を削除しました(base capability scoreにフォールバックします。即時反映、sidebar更新)", + // src/tui.tsx:669 (rank actions option) + "dialog.rank.pinTop": "▲ 先頭に固定(全modelの上)", + // src/tui.tsx:670 (rank actions option) + "dialog.rank.moveUp": "↑ 1つ上に移動(上のmodelと入替;隣接間にmanual scoreをanchor)", + // src/tui.tsx:671 (rank actions option) + "dialog.rank.moveDown": "↓ 1つ下に移動(下のmodelと入替)", + // src/tui.tsx:673 (rank actions option) + "dialog.rank.remove": "✕ rankingから削除(base scoreにフォールバック)", + // src/tui.tsx:675 (rank actions option) + "dialog.rank.back": "← ranking listに戻る", + // src/tui.tsx:680 (rank actions title) + "dialog.rank.detailTitle": "{model}({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "switchman setup —— task poolとcapability ranking", + "dialog.setup.intro": "ガイド付きsetup:6つのtask poolそれぞれのmodelを選び、rankします(最強を先頭に)。Escでいつでも終了できます。確定したpoolは即時保存されます。", + "dialog.setup.start": "開始(最初の未完了stepから)", + "dialog.setup.statePools": "設定済みpool:{count}/6", + "dialog.setup.stateRank": "ranking:{state}", + "dialog.setup.laneTitle": "task pool {index}/6 —— {lane}({count}件選択中;Enterでtoggle、最低1件)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] すべて選択", + "dialog.setup.clearAll": "[ ] すべて解除", + "dialog.setup.confirmLane": "{lane}を確認({count}models)して次へ", + "dialog.setup.back": "戻る", + "dialog.setup.keepOne": "このpoolにはmodelを1件以上残してください", + "dialog.setup.rankTitle": "capability ranking —— #{n}を選択(最強を先頭に、残り{remaining}models)", + "dialog.setup.rankFinish": "rankingを終了({count}件選択;残りはsystem base scoreを維持)", + "dialog.setup.rankMinOne": "終了前に最低1件はrankしてください", + "dialog.setup.doneTitle": "setup完了 —— 即時有効(hot-reload)", + "dialog.setup.donePools": "pools:{summary}", + "dialog.setup.doneRank": "ranking:{order}", + "dialog.setup.restartHint": "新しいproviderを登録するためopencodeを再起動してください:{providers}", + // src/tui.tsx:734 (handover toast) + "dialog.handover.noSession": "/handover:session外のため、backup対象がありません", + // src/tui.tsx:739 (handover toast) + "dialog.handover.inProgress": "/handover:現在のsessionをfull backup+compact中…", + // src/tui.tsx:744 (handover toast) + "dialog.handover.resultStay": "{resultMessage}。元のsessionに留まっており、切替はしていません", + // src/tui.tsx:747 (handover toast) + "dialog.handover.result": "/handover {resultMessage}", + + // ---- palette (command palette entries) ---- + + // src/tui.tsx:770 + "palette.handover.title": "現在のsessionをbackup+compactする", + // src/tui.tsx:771 + "palette.handover.desc": "現在のsessionのfull forkをbackup([backup] title tag)として作成し、現在のsessionをcompactします。session切替なし(built-in /forkとは異なります)", + // src/tui.tsx:772 (palette category label) + "palette.category.label": "switchman", + // src/tui.tsx:779 + "palette.poolConfig.title": "Task pool selection", + // src/tui.tsx:780 + "palette.poolConfig.desc": "task poolごとに参加modelを選択します(economy/mechanical/main/hard/vision/review)", + // src/tui.tsx:788 + "palette.modelRank.title": "Model capability ranking", + // src/tui.tsx:789 + "palette.modelRank.desc": "Manual capability ranking(base scoreより優先;上位ほど強力)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "ガイド付きsetup(pool+ranking)", + "palette.setup.desc": "wizard:task poolごとにmodelを複数選択し、rankします——dispatchが機能する前に必須", + + // ---- quota (quota-brief.json rows; banner.ts builders) ---- + + // src/banner.ts:142 (POOL_LABEL) + "quota.poolGlm": "GLM", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolCopilot": "Copilot", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolDeepSeek": "DeepSeek", + // src/banner.ts:166 + "quota.queryingNoData": "取得中/データなし", + // src/banner.ts:173 + "quota.resetLater": "→後", + // src/banner.ts:173 + "quota.resetTime": "→{hhmm}", + // src/banner.ts:173 + "quota.resetDate": "→{mmdd}", + // src/banner.ts:173 + "quota.resetDateTime": "→{mmdd} {hhmm}", + // src/banner.ts:174 + "quota.barPct": "{bar8} {pct}%", + // src/banner.ts:177 (row label) + "quota.row5h": "5h", + // src/banner.ts:178 (row label) + "quota.rowWeek": "週", + // src/banner.ts:180 (row label) + "quota.rowMcp": "MCP", + // src/banner.ts:181 + "quota.noData": "quotaデータなし", + // src/banner.ts:187 (row label) + "quota.rowRefresh": "更新", + // src/banner.ts:188 (row label) + "quota.rowCredits": "クレジット", + // src/banner.ts:188 + "quota.monthlyExhausted": "monthly pool枯渇", + // src/banner.ts:193 + "quota.unlimited": "無制限{usedSuffix}", + // src/banner.ts:199 + "quota.exhaustedOverage": "枯渇·overage課金{usage}", + // src/banner.ts:202 + "quota.barPctLeft": "{bar8} 残り{pctTxt}%{usage}", + // src/banner.ts:207 (row label) + "quota.rowBalance": "残高", + // src/banner.ts:207 + "quota.exhausted": "枯渇", + // src/banner.ts:209 + "quota.unknownPayg": "不明(pay-as-you-go)", + // src/banner.ts:213 + "quota.barBalance": "{bar8} ¥{balance}", + // src/banner.ts:213 + "quota.balanceWarn": "(<¥{thr} 警告)", + + // ---- cli (switchman-config / switchman-doctor) ---- + + // src/config-cli.ts:67 (fmtRow, printed at :87) + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + // src/config-cli.ts:73 (thrown, surfaced via console.error at :267) + "cli.config.unknownPool": "不明なtask pool:{lane}(6 task pools:{laneList})", + // src/config-cli.ts:81 (head, printed at :85/:90) + "cli.config.poolHeader": "Task-pool selection(config file {poolConfigPath};selection=そのtask poolに参加するmodel;同一modelは複数poolに参加可;未設定poolはsystem default決定を使用)", + // src/config-cli.ts:86 + "cli.config.poolSection": "== {lane} ==({selection})", + // src/config-cli.ts:93 + "cli.config.poolSectionBrief": "== {lane} =={detail}", + // src/config-cli.ts:95 + "cli.config.poolListHint": "(単一poolの番号付きfull listを表示:pool list <{laneList}>)", + // src/config-cli.ts:105 (thrown, surfaced via console.error at :267) + "cli.config.indexOutOfRange": "indexが範囲外です #{index}(listは{rowCount}件)", + // src/config-cli.ts:110 (thrown, surfaced via console.error at :267) + "cli.config.invalidModel": "無効なmodel名:{model}", + // src/config-cli.ts:124 (thrown, surfaced via console.error at :267) + "cli.config.noManifest": "利用可能なmodel manifestがありません(provider接続とsuperset manifestを確認してください)", + // src/config-cli.ts:129 (thrown, surfaced via console.error at :267) + "cli.config.poolRequiresArg": "pool {sub}にはindexまたはmodel名が必要です", + // src/config-cli.ts:138 + "cli.config.poolSelectionCleared": "{lane} task-pool selectionをクリアしました(system default候補セットに戻ります。即時反映、sidebarも同期更新)", + // src/config-cli.ts:139 + "cli.config.poolUpdated": "{lane} task-pool selectionを更新しました({modelCount} modelsが参加中。即時反映、sidebarも同期更新)", + // src/config-cli.ts:145 + "cli.config.poolConfigCleared": "{lane} task-pool selection設定をクリアしました(そのpoolはsystem default候補セットに戻ります。即時反映、sidebarも同期更新)", + // src/config-cli.ts:148 (thrown, surfaced via console.error at :267) + "cli.config.unknownPoolSub": "不明なsubcommand pool {sub}(list/add/remove/set/clear)", + // src/config-cli.ts:186 + "cli.config.rankDisabledUntilPools": "Manual capability ranking(config file {capabilityRankPath})はtask pool設定まで無効です:task poolに選択されたmodelのみrank可能です。", + // src/config-cli.ts:187 + "cli.config.rankHowTo": "先に/poolConfig(TUI dialog)またはpool set <task-pool> <index|model...>を実行し、実際に使うmodelのみrankしてください。", + // src/config-cli.ts:190 + "cli.config.legacyHeader": "== Legacy manual entry(cleanup専用;rank remove/clearは有効、またはtask poolに選択してrankします)==", + // src/config-cli.ts:191 + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + // src/config-cli.ts:197 + "cli.config.rankHeader": "Model capability ranking(config file {capabilityRankPath};/poolConfigでtask poolに選択された{universeCount} modelsにscoped——1つのmerged ordering、manual entryはeffective score順でbase-score modelとinterleave;上位ほど強力)", + // src/config-cli.ts:198 + "cli.config.mergedHeader": "== Merged ordering({manualCount} manual{manualSuffix};CLI set/addはlegacy ladder順にentry、TUI moveは隣接間にscoreをanchor)==", + // src/config-cli.ts:201 + "cli.config.manualTag": "·manual{score}", + // src/config-cli.ts:203 + "cli.config.notInPoolTag": "·task pool不参加", + // src/config-cli.ts:204 + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + // src/config-cli.ts:210 (thrown, surfaced via console.error at :267) + "cli.config.rankNoPools": "task-pool selectionが未設定です——rankingはpool selectionに従います。先に/poolConfig(またはpool set)を実行してください", + // src/config-cli.ts:212 (thrown, surfaced via console.error at :267) + "cli.config.rankRequiresArg": "rank {sub}にはindexまたはmodel名が必要です", + // src/config-cli.ts:237 + "cli.config.rankUpdated": "manual capability rankingを更新しました({modelCount} models。即時反映、sidebarも同期更新)", + // src/config-cli.ts:242 + "cli.config.rankCleared": "manual capability rankingをクリアしました(すべてbase capability scoreにフォールバックします。即時反映、sidebarも同期更新)", + // src/config-cli.ts:245 (thrown, surfaced via console.error at :267) + "cli.config.unknownRankSub": "不明なsubcommand rank {sub}(list/set/add/remove/clear)", + // src/config-cli.ts:254 + "cli.config.usage": "Usage: switchman-config <pool|rank> ...", + // src/config-cli.ts:255 + "cli.config.usagePoolList": " pool list [task-pool] Pool selection概要(economy/mechanical/main/hard/vision/review;pool名付きで番号付きfull list)", + // src/config-cli.ts:256 + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> そのtask poolに参加するmodelをcheck", + // src/config-cli.ts:257 + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> 参加をuncheck", + // src/config-cli.ts:258 + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> そのpoolの参加listを完全置換(同一modelは複数poolに参加可)", + // src/config-cli.ts:259 + "cli.config.usagePoolClear": " pool clear <task-pool> そのpoolの設定をクリア(system default候補セットに戻す)", + // src/config-cli.ts:260 + "cli.config.usageRankList": " rank list manual capability rankingを表示(task-pool selectionにscoped;pool未設定時は/poolConfigに案内)", + // src/config-cli.ts:261 + "cli.config.usageRankSet": " rank set <index|model...> 完全並替(指定順、#1が最強;pool選択済みmodelのみ)", + // src/config-cli.ts:262 + "cli.config.usageRankAdd": " rank add <index|model...> ranking末尾に追加(pool選択済みmodelのみ)", + // src/config-cli.ts:263 + "cli.config.usageRankRemove": " rank remove <index|model...> rankingから削除", + // src/config-cli.ts:264 + "cli.config.usageRankClear": " rank clear rankingをクリア(base capability scoreにフォールバック)", + // src/config-cli.ts:267 + "cli.config.errorPrefix": "switchman-config: {message}", + // src/doctor-cli.ts:5 + "cli.doctor.usage": "Usage: switchman-doctorはopencode-switchman設定を検査します;OPENCODE_CONFIG_DIR env varでconfig directoryを選択;exit code 0=問題なし、1=警告、2=エラー", + // src/doctor.ts:56 (SWM060 hint) + "cli.doctor.unknownModelsHint": "{unknownCount} modelsが既知systemにマッチしませんでした(unknown group、係数により最下位にrank)", + // src/doctor.ts:58 (SWM062 hint) + "cli.doctor.approxModelsHint": "{approxCount} modelsをprefix/familyで近似分類しました", + // src/doctor.ts:72 (SWM044 hint) + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + // src/doctor.ts:87 + "cli.doctor.noIssues": "opencode-switchman doctor:問題は見つかりませんでした", + // src/doctor.ts:89 + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/locales/ko.ts b/src/locales/ko.ts new file mode 100644 index 0000000..6049de5 --- /dev/null +++ b/src/locales/ko.ts @@ -0,0 +1,279 @@ +// [2026-09-19]-[Korean message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const ko: Partial<Record<MsgKey, string>> = { + // ---- notices (status log; appendStatusLog) ---- + "notice.breaker.realCallIsolated": "{agent} 실제 호출이 {mins}분간 격리됐어요 ({category}): {reason}", + "notice.breaker.shellNotInjected": "shell이 opencode에 주입되지 않아 격리 없이 동작해요: {agent} {reason}", + "notice.breaker.failOpen": "breaker fail-open(허용 후 계속): {exc}", + "notice.capability.snapshotCorrupted": "내장 capability 순위 스냅샷이 손상됐어요 (건너뛰고 선별된 기본 표로 대체해요)", + "notice.capability.primarySourceFailed": "capability 인덱스 기본 소스 AA를 불러오지 못했어요 ({exc}){nextStep}", + "notice.capability.backupSourceFailed": "capability 인덱스 백업 소스 OpenRouter를 불러오지 못했어요 ({exc}) → 마지막 정상/내장 기본 순위를 유지해요", + "notice.capability.parsedEmpty": "capability 인덱스 파싱 결과가 비어 있어요 ({source}) → 마지막 정상/내장 기본 순위를 유지해요", + "notice.capability.refreshed": "capability 인덱스를 새로고침했어요: {source} 모델 {modelCount}개 (version={version})", + "notice.capability.refreshFailOpen": "capability 인덱스 새로고침 fail-open(마지막 정상/내장 기본 순위를 유지해요): {exc}", + "notice.capability.lmarenaDisagreement": "capability LMArena 교차 검증: tier 순서와 ELO 순서의 일치율이 {rate}%에 불과해요 (겹치는 모델 {overlapCount}개) — 데이터 소스에 이상이 있을 수 있으니 직접 확인해 주세요", + "notice.capability.lmarenaFailOpen": "capability LMArena 교차 검증을 건너뛰고 계속해요(fail-open): {exc}", + "notice.catalog.unavailableNoCache": "models.dev 카탈로그를 사용할 수 없고 캐시도 없어요 (fail-open으로 기능 축소): {exc}", + "notice.copilot.shapeCacheRefreshed": "Copilot thinking 파라미터 shape 캐시를 새로고침했어요: 모델 {modelCount}개", + "notice.copilot.shapeRefreshFailOpen": "Copilot thinking 파라미터 shape 새로고침 fail-open(허용 후 계속): {exc}", + "notice.cost.refreshFailed": "비용 스냅샷 새로고침에 실패했어요 (이전 데이터를 유지해요): {exc}", + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} 파일이 올바른 JSON이 아니에요 — 무시해요 (언어 설정은 AGENTS.md 마커로 대체되고, \"dispatch\":\"off\"는 적용되지 않아요)", + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} 파일에 \"dispatch\"가 있지만 정확히 \"off\"가 아니에요 (받은 값: {rawValue}) — 무시하고 fleet 방식으로 동작해요", + "notice.ctx.paused": "세션 {sid}의 ctx 제어를 일시정지했어요 (/ctx-pause): read gate + self-read 예산 + auto-handover가 중단돼요. 측정은 계속돼요", + "notice.ctx.resumed": "세션 {sid}의 ctx 제어를 다시 시작했어요 (/ctx-resume): read gate + auto-handover가 다시 동작해요", + "notice.workspace.created": "아티팩트 workspace를 만들었어요: {rel}", + "notice.workspace.renamed": "아티팩트 workspace 이름을 바꿨어요: {oldRel} → {rel}", + "notice.dispatch.mirrorResumeReuse": "tmux pane 미러링: ses_{taskId} ({shellName}) 이어받기 dispatch예요 — task_id를 재사용해서 pane을 바로 열었어요 (session.created는 발생하지 않아요)", + "notice.dispatch.mirrorResumeLookupFailed": "tmux pane 미러링: ses_{taskId} ({shellName}) 이어받기 dispatch예요 — 세션 조회에 실패해서 fail-open pane으로 열었어요", + "notice.capability.selectionChanged": "capability 순위/task-pool 선택이 바뀌었어요: banner와 sidebar를 바로 새로고침해요", + "notice.capability.overrideWatchError": "fs.watch({dir}) override 설정 감시 오류예요 (mtime 폴링으로 대체해요): {exc}", + "notice.matrix.configSurfaceFailOpen": "config surface 읽기 fail-open(허용 후 계속): {exc}", + "notice.matrix.floorFreeModels": "floor = OpenCode Zen 무료 모델 {floorCount}개 (catalog {catalogStatus})", + "notice.matrix.floorFallback": "floor가 정적 manifest로 대체됐어요 (catalog {catalogStatus}, 무료 모델 0개)", + "notice.matrix.invalidModelsUnknownProvider": "visible set/즐겨찾기에 알 수 없는 provider의 잘못된 모델이 있어요 (provider 미연결; 무시하고 shell을 만들지 않아요): {modelList}", + "notice.provider.probeAttemptSucceeded": "provider.list 시도 {attempt}이 성공했어요 (이전 {prevAttempts}회는 준비되지 않았어요)", + "notice.provider.probeAttemptBackoff": "provider.list 시도 {attempt}이 아직 준비되지 않아서 대기 후 재시도해요: {exc}", + "notice.provider.unavailableCfgFallback": "provider.list를 사용할 수 없어요 ({attemptCount}회 시도 후 cfg.provider 키 {keyCount}개로 대체했어요): {exc}", + "notice.provider.probeNewProvider": "provider.list 백그라운드 probe: 새 provider가 연결됐어요 ({providers}) — opencode를 다시 시작하면 shell 등록이 완료돼요", + "notice.provider.probeModelDrift": "provider.list 백그라운드 probe: 모델 목록이 바뀌었어요 ({drift}) — superset manifest를 다시 만들었고 /modelRank · /poolConfig 목록을 업데이트했어요{restartHint}", + "notice.provider.probeRebuildFailed": "provider.list 백그라운드 probe: superset 다시 만들기에 실패했어요 (이전 manifest를 유지해요): {exc}", + "notice.probe.warmupFailOpen": "warmup fail-open(허용 후 계속): {exc}", + "notice.skills.synced": "skill 동기화가 끝났어요: 설치 {installedCount}개, 업데이트 {updatedCount}개, 삭제 {removedCount}개 ({skillNames})", + "notice.skills.syncFailOpen": "skill 동기화 fail-open(허용 후 계속): {exc}", + "notice.banner.failOpen": "banner fail-open(허용 후 계속): {exc}", + "notice.ctx.readBudgetContinuation": "read 예산 연속 읽기 완료예요 (파일 {fileName}, {offset}부터 +{granted}줄, turn {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateCap": "read 예산 gate 상한이에요 (tool read, 파일 {fileName}, 예상 ~{totalTokens} → 제한 {suggestedLimit}, turn {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGate": "read 예산 gate {action}이에요 (tool {tool}, 예상 ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, turn {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateFailOpen": "read 예산 gate fail-open(허용)이에요: {exc}", + "notice.image.readGuardDenied": "이미지 읽기 guard: 모델 {modelKey}에는 vision 입력이 없어서 {fileName} 읽기를 거부했어요 (세션 {sid})", + "notice.image.readGuardFailOpen": "이미지 읽기 guard fail-open(허용)이에요: {exc}", + "notice.doctor.summary": "doctor가 오류 {errorCount}개 · 경고 {warnCount}개를 찾았어요. /switchman-doctor로 확인해 주세요", + "notice.injection.legacyStaticMatrix": "{shellCount}개의 모델 shell을 주입했어요 (agents, 기존 정적 matrix)", + "notice.provider.cacheUsed": "provider.list가 재시작 간 캐시를 사용해요 (provider {providerCount}개, 캐시 시각 {cachedAt}). 백그라운드에서 추가분을 확인해요", + "notice.provider.cacheStale": "provider.list 캐시가 오래됐어요 (캐시 시각 {cachedAt}). superset을 만들기 전에 실시간으로 probe해요", + "notice.matrix.recomputed": "activation matrix를 다시 계산했어요 (gen={generation}, 활성 shell {activeShellCount}개, probe {source}×{targetCount})", + "notice.injection.shellCount": "{shellCount}개의 shell을 주입했어요 (mode={runMode}, 주입 범위={injectionMode}={fullSupersetCount}→큐레이션 후 {faceCount}, 충돌 {conflictCount}개; activation gating 동작 중)", + "notice.injection.configHookFailOpen": "config hook fail-open(허용 후 계속): {exc}", + "notice.lang.askLocale": "언어 질문 로케일: locale={locale} ({source})", + "notice.banner.rulesFailOpen": "rules/banner fail-open(허용 후 계속): {exc}", + "notice.relay.persisted": "이미지 relay: 모델 {modelKey}에는 vision 입력이 없어서 이미지 {written}개를 디스크에 저장했어요 (세션 기록에 이미지 파트 {relayed}개를 전달했어요, 세션 {sid})", + "notice.relay.failOpen": "이미지 relay fail-open(그대로 통과)이에요: {exc}", + "notice.ctx.capToolDenied": "subagent context cap: 종료된 세션 {sid}에서 tool '{tool}'을 거부했어요", + "notice.ctx.capResumeDenied": "subagent context cap: 종료된 세션 ses_{taskId}의 이어받기를 거부했어요 (영구적)", + "notice.lang.gateDenied": "lang gate: 미설정 프로젝트의 세션 {sid}에서 tool '{tool}'을 거부했어요", + "notice.search.clarifyFailOpen": "search clarify gate: 질문 없이 {maxDenies}회 거부한 뒤 fail-open으로 열었어요 — 세션 {sid}의 gate가 열려 있어요", + "notice.search.clarifyDenied": "search clarify gate: 세션 {sid}에서 tool '{tool}'을 거부했어요 (광범위 검색, 먼저 질문해요) ({denyCount}/{maxDenies})", + "notice.dispatch.offUngoverned": "dispatch off: task 호출을 제어 없이 허용해요 (subagent_type='{subagentType}')", + "notice.dispatch.redirectUninjected": "자동 리디렉션 {agent} → {candidate} (주입되지 않은 shell; chain-head 후보로 리디렉션했어요)", + "notice.dispatch.redirectBuiltinBlocked": "자동 리디렉션 {agent} → {candidate} (내장 agent가 차단됐어요)", + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] 알 수 없는 subagent_type='{agent}'이에요: 허용해요 (shell 목록에 없고, 내장 agent는 라우팅 제어를 받지 않아요)", + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled이지만 matrix 상태가 {matrixStatus}(down 아님)예요: fail-open으로 계속하고 다음 probe 새로고침 때 자동 수정돼요", + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} matrix 상태가 {matrixStatus}(down 아님)예요: 차단하지 않고 다음 라운드 probe 때 새로고침해요", + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META가 없거나 잘못됐어요 — lane에서 합성했어요. review cross-family / source=user 시맨틱을 쓰려면 선언해 주세요", + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED: cross-family reviewer가 없어요 — 같은 family의 self-review를 허용해요. review 결론에 DOWNGRADED를 명시해 주세요", + "notice.dispatch.poolOverrideNote": "pool-config override: 이 task pool에 직접 선택됐어요 (capability level floor를 적용하지 않아요)", + "notice.dispatch.redirectDenied": "자동 리디렉션 {agent} → {redirect} ({deny})", + "notice.dispatch.gatesFailOpen": "6개 gate fail-open(허용)이에요: {exc}", + "notice.lang.prefsSaved": "프로젝트 언어 설정을 저장했어요 ({rel}): conversation={conversation} comments={comments} docs={docs}", + "notice.lang.gateWaived": "lang gate: 저장된 설정 없이 마커 질문을 마쳤어요 — 세션 {sid}의 gate를 면제해요", + "notice.search.scopeAskDone": "search clarify: 범위 질문을 마쳤어요 — 세션 {sid}의 gate가 열려 있어요", + "notice.ctx.readBudgetCharge": "read 예산 +{charge}를 차감했어요 (tool {tool}, turn {turnUsed}/{turnBudget})", + "notice.handover.autoTriggered": "auto-handover가 시작됐어요 ({tool} 이후 ~{wmTokens}가 강제 compaction watermark를 넘었어요): 현재 세션 전체 백업 + compaction 예약", + "notice.handover.backupResult": "auto-handover 백업 {outcome}: {message}", + "notice.handover.compactionAccepted": "auto-handover compaction을 수락했어요: session.summarize가 반환됐어요 (세션 루프에서 compaction이 실행됐어요)", + "notice.handover.compactionRejected": "auto-handover compaction에 실패했어요: session.summarize가 거부됐어요 (백업은 유지돼요)", + "notice.handover.compactionNoModel": "auto-handover compaction에 실패했어요: 기록된 세션 모델이 없어요 (chat.params가 한 번도 실행되지 않았어요). 백업은 유지돼요", + "notice.handover.failOpen": "auto-handover fail-open(허용 후 계속): {exc}", + "notice.ctx.capTerminated": "subagent context cap: 세션 {sid}{agentSuffix}가 약 {estTokens}k 토큰에 도달했어요 (상한 {capTokens}k) — tool을 거부하고 진행 요약을 요구한 뒤 세션을 종료했어요 (task_id 이어받기 불가)", + "notice.provider.modelRetired": "모델이 은퇴 처리됐어요 (404 연속 발생). 후보에서 제외해요: {provider}/{modelId}", + "notice.breaker.agentTripped": "{agent} breaker가 발동됐어요 (600s): {reason}", + "notice.breaker.accountingFailOpen": "실패 집계 fail-open(허용 후 계속): {exc}", + "notice.lane.scoringFallback": "scoring에 실패해서 규칙 기반 순서로 대체했어요: {exc}", + "notice.lane.backfillFailed": "backfill ranking에 실패했어요 (lane이 비어 있어요): {exc}", + "notice.matrix.favoritesScanNoChange": "즐겨찾기/visible set을 스캔했어요: activation 변경 없음 (gen={generation}, 재계산·재probe 없음)", + "notice.matrix.invalidModels": "visible set/즐겨찾기에 잘못된 모델이 있어요 (provider는 알지만 그런 modelId가 없어서 shell을 만들지 않았어요): {modelList}", + "notice.matrix.persistFailOpen": "activation matrix 저장 fail-open(허용 후 계속): {exc}", + "notice.matrix.callbackFailOpen": "activation matrix 콜백 fail-open(허용 후 계속): {exc}", + "notice.matrix.configReadFailOpen": "config surface 읽기 fail-open(비어 있는 것으로 간주): {exc}", + "notice.matrix.watchError": "fs.watch({dir})에 오류가 생겨서 mtime 폴링으로 대체해요: {exc}", + "notice.matrix.watchStartFailed": "fs.watch({dir})를 시작하지 못해서 mtime 폴링으로 대체해요: {exc}", + "notice.matrix.recomputeFailOpen": "recompute fail-open(허용 후 계속): {exc}", + "notice.probe.failOpen": "probe fail-open(허용 후 계속): {exc}", + "notice.probe.incrementalFailOpen": "incremental probe fail-open(허용 후 계속): {exc}", + "notice.probe.copilotPoolExhausted": "Copilot 월간 pool이 소진됐어요 (gateway를 두 번째 true 소스로 해요). reset_date까지 유지해요", + "notice.probe.resultsDiscarded": "probe 결과를 버렸어요 (matrix generation이 {oldGen}→{newGen}으로 바뀌었어요. 새 generation 재계산에서 다시 예약해요)", + "notice.probe.matrixRefreshed": "matrix를 새로고침했어요: {comboCount}개 조합 중 {okCount}개 정상 (전체 {totalCount}개)", + "notice.probe.schedulingFailOpen": "probe 스케줄링 fail-open(허용 후 계속): {exc}", + "notice.scoring.decisionLogFailOpen": "decision 로그 fail-open(허용 후 계속): {exc}", + "notice.selfupdate.checkFailOpen": "self-update 확인 fail-open(허용 후 계속): {exc}", + "notice.selfupdate.upgradeAssetsFailOpen": "upgrade 명령어 asset fail-open(허용 후 계속): {exc}", + "notice.dispatch.mirrorDisabled": "tmux pane 미러링을 껐어요 (초기화 실패): {message}", + "notice.dispatch.mirrorOpFailed": "tmux pane 미러링 동작에 실패했어요 (계속해요): {message}", + "notice.dispatch.mirrorPaneFull": "tmux pane 미러링: 열이 가득 찼어요 (pane {slotCount}개). ses_{sessionId} ({agent})를 대기열에 넣었어요", + "notice.dispatch.mirrorAllClosed": "tmux pane 미러링: 모든 subagent pane을 닫고 main pane을 복원했어요", + "notice.dispatch.mirrorDisplayed": "tmux pane 미러링: ses_{sessionId} ({agent})를 pane {pane}에 표시했어요", + "notice.dispatch.mirrorReconciling": "tmux pane 미러링: 닫힌 pane을 감지해서 레이아웃을 조정해요", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "setup이 필요해요 ({missing}) — /switchman-setup(또는 /switchman-setup-chat)을 실행해 주세요; 설정 전까지는 dispatch가 막혀요", + // ---- sidebar (tui.tsx sidebar chrome) ---- + "sidebar.peakTag": " ·피크", + "sidebar.staleTag": " ·오래됨", + "sidebar.observeOnlyTag": " ·관찰 전용", + "sidebar.updateAvailable": " → {updateVersion}", + "sidebar.restartNeeded": " [재시작 필요]", + "sidebar.noneAvailable": "사용 가능 없음", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "이코노미", + "sidebar.lane.mechanical": "기계", + "sidebar.lane.main": "메인", + "sidebar.lane.hard": "하드", + "sidebar.lane.vision": "비전", + "sidebar.lane.review": "리뷰", + "sidebar.noticeLabel": "알림", + // ---- dialogs (tui.tsx: pool picker / pool models / rank / handover) ---- + "dialog.pool.title": "Task pool (task pool을 고르세요. Esc로 나가기)", + "dialog.pool.laneRow": "{pinMark}{lane}", + "dialog.pool.manualSelection": "직접 선택: {selCount}/{totalCount}개 모델 참여 중", + "dialog.pool.notConfigured": "미설정: 시스템 기본값 (사용 가능한 모든 모델이 참여해요)", + "dialog.pool.toggleWriteFailed": "쓰기에 실패했어요: {message}", + "dialog.pool.modelToggled": "{lane} pool: {modelKey} {verb} {direction} (바로 적용되고 sidebar가 새로고침돼요)", + "dialog.pool.keepOneModel": "참여 모델을 최소 1개는 유지해 주세요. 시스템 기본값으로 되돌리려면 \"Clear config\"를 사용해 주세요", + "dialog.pool.bulkWriteFailed": "쓰기에 실패했어요: {message}", + "dialog.pool.allSelected": "{lane} pool: 모든 모델을 선택했어요", + "dialog.pool.configCleared": "{lane} pool 설정을 지웠어요 (시스템 기본 후보 집합으로 복원됐어요)", + "dialog.pool.allUnchecked": "{lane} pool: 모두 해제됐어요 — 유지할 모델을 체크해 주세요. 하나도 체크하지 않고 나가면 이전 선택이 유지돼요", + "dialog.pool.back": "← pool 목록으로 돌아가기", + "dialog.pool.selectAll": "☑ 모두 선택", + "dialog.pool.uncheckAll": "☐ 모두 해제 (유지할 소수만 체크해 주세요. 하나도 체크하지 않고 나가면 기존 목록이 유지돼요)", + "dialog.pool.clearConfig": "✕ 설정 지우기 (시스템 기본값: 사용 가능한 모든 모델이 참여해요)", + "dialog.pool.modelRow": "{checkMark} {modelId}", + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + "dialog.pool.selectionTitle": "{lane} pool 선택 ({selCount}/{rowCount}개 참여 중. 선택하면 토글되고 pool 간 중복이 가능해요)", + "dialog.rank.openPoolSelection": "→ task-pool 선택 열기 (각 pool이 쓸 모델을 고른 뒤 순위를 매겨요)", + "dialog.rank.close": "✕ 닫기", + "dialog.rank.universeEmptyTitle": "task pool을 설정하기 전까지는 모델 순위 지정이 꺼져 있어요 — task pool에 선택된 모델만 순위를 매길 수 있어서 dispatch할 수 없는 모델에 순위를 매기는 일이 없어요", + "dialog.rank.alreadyAtEdge": "{modelName}은(는) 이미 병합된 capability 목록의 {edge}에 있어요", + "dialog.rank.moveWriteFailed": "쓰기에 실패했어요: {message}", + "dialog.rank.pinnedOrMoved": "{modelName}을(를) #{position}에 {verb}했어요 (직접 점수 {tier}/{raw}, 이웃 사이에 고정돼요. 바로 적용되고 sidebar가 새로고침돼요)", + "dialog.rank.title": "모델 capability 순위 — 병합된 순서 (#1이 가장 강해요. task-pool 선택 범위로 한정되고, 직접 항목이 기본 점수 모델과 섞여요. ctrl+up/ctrl+down으로 한 칸씩 이동하고 enter는 모델별 동작)", + "dialog.rank.searchHint": "검색 · alt+up/alt+down도 ctrl+up/ctrl+down처럼 동작해요", + "dialog.rank.row": "#{rankPadded} {modelId}", + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + "dialog.rank.removeWriteFailed": "쓰기에 실패했어요: {message}", + "dialog.rank.removed": "직접 순위에서 {model}을(를) 제거했어요 (기본 capability 점수로 돌아가고, 바로 적용되며 sidebar가 새로고침돼요)", + "dialog.rank.pinTop": "▲ 맨 위에 고정 (모든 모델보다 위)", + "dialog.rank.moveUp": "↑ 한 칸 위로 (위 모델과 자리를 바꿔요. 이웃 사이에 직접 점수를 고정해요)", + "dialog.rank.moveDown": "↓ 한 칸 아래로 (아래 모델과 자리를 바꿔요)", + "dialog.rank.remove": "✕ 순위에서 제거 (기본 점수로 돌아가요)", + "dialog.rank.back": "← 순위 목록으로 돌아가기", + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "switchman setup — task pool과 capability 순위", + "dialog.setup.intro": "가이드 setup: 6개 task pool마다 모델을 고르고 순위를 매겨요 (가장 강한 것부터). Esc로 언제든 나갈 수 있고, 확정한 pool은 바로 저장돼요.", + "dialog.setup.start": "시작 (처음 완료 안 한 단계부터)", + "dialog.setup.statePools": "설정된 pool: {count}/6", + "dialog.setup.stateRank": "순위: {state}", + "dialog.setup.laneTitle": "task pool {index}/6 — {lane} ({count}개 선택; Enter로 토글, 최소 1개)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] 모두 선택", + "dialog.setup.clearAll": "[ ] 모두 해제", + "dialog.setup.confirmLane": "{lane} 확정 ({count}개 모델)하고 계속하기", + "dialog.setup.back": "뒤로", + "dialog.setup.keepOne": "이 pool에는 모델을 최소 1개는 유지해 주세요", + "dialog.setup.rankTitle": "capability 순위 — #{n} 고르기 (가장 강한 것부터, {remaining}개 모델 남음)", + "dialog.setup.rankFinish": "순위 마치기 ({count}개 선택; 나머지는 시스템 기본 점수를 유지해요)", + "dialog.setup.rankMinOne": "마치기 전에 최소 1개 모델은 순위를 매겨 주세요", + "dialog.setup.doneTitle": "setup 완료 — 바로 적용돼요 (hot-reload)", + "dialog.setup.donePools": "pool: {summary}", + "dialog.setup.doneRank": "순위: {order}", + "dialog.setup.restartHint": "새 provider 등록을 위해 opencode를 재시작해 주세요: {providers}", + "dialog.handover.noSession": "/handover: 세션에 있지 않아서 백업할 내용이 없어요", + "dialog.handover.inProgress": "/handover: 현재 세션을 전체 백업하고 compaction하는 중이에요…", + "dialog.handover.resultStay": "{resultMessage}. 원래 세션에 그대로 있고 전환하지 않았어요", + "dialog.handover.result": "/handover {resultMessage}", + // ---- palette (command palette entries) ---- + "palette.handover.title": "현재 세션을 백업하고 compaction하기", + "palette.handover.desc": "현재 세션을 전체 fork해서 백업([backup] 제목 태그)하고 현재 세션을 compaction해요. 세션 전환은 없어요 (내장 /fork와 달라요)", + "palette.category.label": "switchman", + "palette.poolConfig.title": "Task pool 선택", + "palette.poolConfig.desc": "task pool별로 참여 모델 고르기 (economy/mechanical/main/hard/vision/review)", + "palette.modelRank.title": "모델 capability 순위", + "palette.modelRank.desc": "직접 capability 순위 (기본 점수보다 우선하고, 앞쪽이 더 강해요)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "가이드 setup (pool + 순위)", + "palette.setup.desc": "wizard: task pool별로 모델을 여러 개 선택하고 순위를 매겨요 — dispatch가 동작하려면 필수예요", + // ---- quota (quota-brief.json rows; banner.ts builders) ---- + "quota.poolGlm": "GLM", + "quota.poolCopilot": "Copilot", + "quota.poolDeepSeek": "DeepSeek", + "quota.queryingNoData": "조회 중/데이터 없음", + "quota.resetLater": "→나중에", + "quota.resetTime": "→{hhmm}", + "quota.resetDate": "→{mmdd}", + "quota.resetDateTime": "→{mmdd} {hhmm}", + "quota.barPct": "{bar8} {pct}%", + "quota.row5h": "5h", + "quota.rowWeek": "주", + "quota.rowMcp": "MCP", + "quota.noData": "할당량 데이터 없음", + "quota.rowRefresh": "새로고침", + "quota.rowCredits": "크레딧", + "quota.monthlyExhausted": "월간 pool 소진됨", + "quota.unlimited": "무제한{usedSuffix}", + "quota.exhaustedOverage": "소진됨·초과 과금{usage}", + "quota.barPctLeft": "{bar8} {pctTxt}% 남음{usage}", + "quota.rowBalance": "잔액", + "quota.exhausted": "소진됨", + "quota.unknownPayg": "알 수 없음 (pay-as-you-go)", + "quota.barBalance": "{bar8} ¥{balance}", + "quota.balanceWarn": "(<¥{thr} 경고)", + // ---- cli (switchman-config / switchman-doctor) ---- + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + "cli.config.unknownPool": "알 수 없는 task pool이에요: {lane} (task pool 6개: {laneList})", + "cli.config.poolHeader": "Task-pool 선택 (설정 파일 {poolConfigPath}. selection = 해당 task pool에 참여하는 모델이고, 같은 모델이 여러 pool에 참여할 수 있어요. 미설정 pool은 시스템 기본 결정을 사용해요)", + "cli.config.poolSection": "== {lane} == ({selection})", + "cli.config.poolSectionBrief": "== {lane} =={detail}", + "cli.config.poolListHint": "(번호가 있는 단일 pool 전체 목록 보기: pool list <{laneList}>)", + "cli.config.indexOutOfRange": "인덱스가 범위를 벗어났어요 #{index} (목록에 {rowCount}개 항목이 있어요)", + "cli.config.invalidModel": "잘못된 모델 이름이에요: {model}", + "cli.config.noManifest": "사용 가능한 모델 manifest가 없어요 (provider 연결과 superset manifest를 확인해 주세요)", + "cli.config.poolRequiresArg": "pool {sub}에는 인덱스나 모델 이름이 필요해요", + "cli.config.poolSelectionCleared": "{lane} task-pool 선택을 지웠어요 (시스템 기본 후보 집합으로 돌아가고, 바로 적용되며 sidebar도 함께 새로고침돼요)", + "cli.config.poolUpdated": "{lane} task-pool 선택을 업데이트했어요 ({modelCount}개 모델 참여 중이고, 바로 적용되며 sidebar도 함께 새로고침돼요)", + "cli.config.poolConfigCleared": "{lane} task-pool 선택 설정을 지웠어요 (해당 pool이 시스템 기본 후보 집합으로 돌아가고, 바로 적용되며 sidebar도 함께 새로고침돼요)", + "cli.config.unknownPoolSub": "알 수 없는 하위 명령어예요 pool {sub} (list/add/remove/set/clear)", + "cli.config.rankDisabledUntilPools": "직접 capability 순위 (설정 파일 {capabilityRankPath})는 task pool을 설정하기 전까지 꺼져 있어요. task pool에 선택된 모델만 순위를 매길 수 있어요.", + "cli.config.rankHowTo": "먼저 /poolConfig (TUI 대화상자)나 pool set <task-pool> <index|model...>을 실행한 뒤, 실제로 쓰는 모델에만 순위를 매겨 주세요.", + "cli.config.legacyHeader": "== Legacy 직접 항목 (정리 전용. rank remove/clear는 계속 동작해요. 순위를 매기려면 모델을 task pool에 선택해 주세요) ==", + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + "cli.config.rankHeader": "모델 capability 순위 (설정 파일 {capabilityRankPath}. /poolConfig로 task pool에 선택된 {universeCount}개 모델 범위로 한정돼요 — 하나의 병합된 순서이고, 직접 항목이 유효 점수 기준으로 기본 점수 모델과 섞여요. 위쪽이 더 강해요)", + "cli.config.mergedHeader": "== 병합된 순서 (직접 {manualCount}개{manualSuffix}. CLI set/add는 legacy ladder 순서로 항목을 정렬하고, TUI 이동은 이웃 사이에 점수를 고정해요) ==", + "cli.config.manualTag": "·직접{score}", + "cli.config.notInPoolTag": "·어느 task pool에도 없음", + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + "cli.config.rankNoPools": "task-pool 선택이 아직 없어요 — 순위는 pool 선택을 따라가요. 먼저 /poolConfig (또는 pool set)를 실행해 주세요", + "cli.config.rankRequiresArg": "rank {sub}에는 인덱스나 모델 이름이 필요해요", + "cli.config.rankUpdated": "직접 capability 순위를 업데이트했어요 ({modelCount}개 모델, 바로 적용되며 sidebar도 함께 새로고침돼요)", + "cli.config.rankCleared": "직접 capability 순위를 지웠어요 (모두 기본 capability 점수로 돌아가고, 바로 적용되며 sidebar도 함께 새로고침돼요)", + "cli.config.unknownRankSub": "알 수 없는 하위 명령어예요 rank {sub} (list/set/add/remove/clear)", + "cli.config.usage": "사용법: switchman-config <pool|rank> ...", + "cli.config.usagePoolList": " pool list [task-pool] Pool 선택 개요 (economy/mechanical/main/hard/vision/review. pool 이름 지정 시 = 번호가 있는 전체 목록)", + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> 해당 task pool에 참여할 모델 체크", + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> 참여 해제", + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> 해당 pool의 참여 목록을 완전히 교체 (같은 모델이 여러 pool에 참여할 수 있어요)", + "cli.config.usagePoolClear": " pool clear <task-pool> 해당 pool 설정을 지우기 (시스템 기본 후보 집합으로 돌아가요)", + "cli.config.usageRankList": " rank list 직접 capability 순위 보기 (task-pool 선택 범위로 한정. pool 미설정 시 /poolConfig로 안내해요)", + "cli.config.usageRankSet": " rank set <index|model...> 전체 순서 교체 (지정한 순서대로, #1이 가장 강해요. pool 선택 모델만 가능해요)", + "cli.config.usageRankAdd": " rank add <index|model...> 순위 맨 뒤에 추가 (pool 선택 모델만 가능해요)", + "cli.config.usageRankRemove": " rank remove <index|model...> 순위에서 제거", + "cli.config.usageRankClear": " rank clear 순위 지우기 (기본 capability 점수로 돌아가요)", + "cli.config.errorPrefix": "switchman-config: {message}", + "cli.doctor.usage": "사용법: switchman-doctor는 opencode-switchman 설정을 검사해요. OPENCODE_CONFIG_DIR 환경 변수로 설정 디렉터리를 고르고, 종료 코드는 0=문제 없음, 1=경고, 2=오류예요", + "cli.doctor.unknownModelsHint": "알려진 체계와 일치하지 않는 모델 {unknownCount}개 (unknown 그룹, 계수로 최하위 순위가 매겨져요)", + "cli.doctor.approxModelsHint": "prefix/family 기준으로 대략 분류된 모델 {approxCount}개", + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + "cli.doctor.noIssues": "opencode-switchman doctor: 문제가 없어요", + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} as const diff --git a/src/locales/pt.ts b/src/locales/pt.ts new file mode 100644 index 0000000..751874f --- /dev/null +++ b/src/locales/pt.ts @@ -0,0 +1,273 @@ +// [2026-09-19]-[Portuguese message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const pt: Partial<Record<MsgKey, string>> = { + "notice.breaker.realCallIsolated": "{agent} real-call isolado por {mins}m ({category}): {reason}", + "notice.breaker.shellNotInjected": "shell não injetado no opencode (sem isolation): {agent} {reason}", + "notice.breaker.failOpen": "breaker fail-open: {exc}", + "notice.capability.snapshotCorrupted": "snapshot do ranking de capability empacotado corrompido (ignorando, voltando à tabela curada)", + "notice.capability.primarySourceFailed": "fonte primária AA do índice de capability falhou ({exc}){nextStep}", + "notice.capability.backupSourceFailed": "fonte de backup OpenRouter do índice de capability falhou ({exc}) -> mantendo os últimos ranks válidos/padrão empacotados", + "notice.capability.parsedEmpty": "índice de capability vazio após o parsing ({source}) -> mantendo os últimos ranks válidos/padrão empacotados", + "notice.capability.refreshed": "índice de capability atualizado: {source} {modelCount} modelos (version={version})", + "notice.capability.refreshFailOpen": "atualização do índice de capability fail-open (mantendo os últimos ranks válidos/padrão empacotados): {exc}", + "notice.capability.lmarenaDisagreement": "verificação cruzada LMArena de capability: concordância tier-order vs ELO-order de apenas {rate}% ({overlapCount} modelos em comum) -- fonte de dados pode estar anômala, revisão manual recomendada", + "notice.capability.lmarenaFailOpen": "verificação cruzada LMArena de capability fail-open (ignorada): {exc}", + "notice.catalog.unavailableNoCache": "catálogo models.dev indisponível e sem cache (degradação fail-open): {exc}", + "notice.copilot.shapeCacheRefreshed": "cache de shape do parâmetro thinking do Copilot atualizado: {modelCount} modelos", + "notice.copilot.shapeRefreshFailOpen": "atualização do shape do parâmetro thinking do Copilot fail-open: {exc}", + "notice.cost.refreshFailed": "falha ao atualizar o snapshot de custos (mantendo dados desatualizados): {exc}", + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} não é um JSON válido — ignorado (config de lang volta ao marcador AGENTS.md; \"dispatch\":\"off\" não aplicado)", + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} com \"dispatch\" presente mas não exatamente \"off\" (recebido: {rawValue}) — ignorado, comportamento fleet", + "notice.ctx.paused": "controle ctx pausado para a sessão {sid} (/ctx-pause): read gates + self-read budget + auto-handover suspensos; medição continua", + "notice.ctx.resumed": "controle ctx retomado para a sessão {sid} (/ctx-resume): read gates + auto-handover ativos novamente", + "notice.workspace.created": "workspace de artefatos criado: {rel}", + "notice.workspace.renamed": "workspace de artefatos renomeado: {oldRel} → {rel}", + "notice.dispatch.mirrorResumeReuse": "espelhamento de pane tmux: resume dispatch ses_{taskId} ({shellName}) — task_id reutilizado, pane aberto diretamente (nenhum session.created será disparado)", + "notice.dispatch.mirrorResumeLookupFailed": "espelhamento de pane tmux: resume dispatch ses_{taskId} ({shellName}) — lookup de sessão falhou, pane fail-open", + "notice.capability.selectionChanged": "seleção de rank/task-pool de capability alterada: banner e sidebar atualizados imediatamente", + "notice.capability.overrideWatchError": "erro no watch de override-config fs.watch({dir}) (fallback para polling mtime): {exc}", + "notice.matrix.configSurfaceFailOpen": "leitura da superfície de config fail-open: {exc}", + "notice.matrix.floorFreeModels": "floor = {floorCount} modelos gratuitos OpenCode Zen (catálogo {catalogStatus})", + "notice.matrix.floorFallback": "floor voltou ao manifesto estático (catálogo {catalogStatus}, 0 modelos gratuitos)", + "notice.matrix.invalidModelsUnknownProvider": "conjunto visível/favoritos contém modelos inválidos com provider desconhecido (provider não conectado; ignorados, nenhum shell criado): {modelList}", + "notice.provider.probeAttemptSucceeded": "tentativa {attempt} de provider.list bem-sucedida ({prevAttempts} anteriores não prontas)", + "notice.provider.probeAttemptBackoff": "tentativa {attempt} de provider.list não pronta, recuando: {exc}", + "notice.provider.unavailableCfgFallback": "provider.list indisponível (voltou a {keyCount} chaves cfg.provider após {attemptCount} tentativas): {exc}", + "notice.provider.probeNewProvider": "probe em segundo plano de provider.list: novo(s) provider(s) conectado(s) ({providers}) — reinicie o opencode para concluir o registro dos shells", + "notice.provider.probeModelDrift": "probe em segundo plano de provider.list: lista de modelos mudou ({drift}) — manifesto superset reconstruído, listas /modelRank //poolConfig atualizadas{restartHint}", + "notice.provider.probeRebuildFailed": "probe em segundo plano de provider.list: falha ao reconstruir o superset (manifesto anterior mantido): {exc}", + "notice.probe.warmupFailOpen": "warmup fail-open: {exc}", + "notice.skills.synced": "skills sincronizadas: {installedCount} instaladas, {updatedCount} atualizadas, {removedCount} removidas ({skillNames})", + "notice.skills.syncFailOpen": "sync de skills fail-open: {exc}", + "notice.banner.failOpen": "banner fail-open: {exc}", + "notice.ctx.readBudgetContinuation": "conclusão de continuação do read budget (arquivo {fileName}, +{granted} linhas desde {offset}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateCap": "limite do read budget gate (tool read, arquivo {fileName}, est ~{totalTokens} -> limite {suggestedLimit}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGate": "read budget gate {action} (tool {tool}, est ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, turno {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateFailOpen": "read budget gate fail-open (permitido): {exc}", + "notice.image.readGuardDenied": "guarda de leitura de imagem: modelo {modelKey} sem entrada vision; leitura de {fileName} negada (sessão {sid})", + "notice.image.readGuardFailOpen": "guarda de leitura de imagem fail-open (permitido): {exc}", + "notice.doctor.summary": "doctor encontrou {errorCount} erro(s) / {warnCount} aviso(s); execute /switchman-doctor para ver", + "notice.injection.legacyStaticMatrix": "{shellCount} model shells injetados (agents, matriz estática legacy)", + "notice.provider.cacheUsed": "provider.list usando cache entre reinícios ({providerCount} providers, cache de {cachedAt}); verificando adições em segundo plano", + "notice.provider.cacheStale": "cache de provider.list desatualizado (cache de {cachedAt}), sondando ao vivo antes da construção do superset", + "notice.matrix.recomputed": "matriz de ativação recalculada (gen={generation}, shells ativos {activeShellCount}, probes {source}×{targetCount})", + "notice.injection.shellCount": "{shellCount} shells injetados (mode={runMode}, superfície de injeção={injectionMode}={fullSupersetCount}→{faceCount} após curadoria, conflitos {conflictCount}; activation gating ativo)", + "notice.injection.configHookFailOpen": "config hook fail-open: {exc}", + "notice.lang.askLocale": "lang ask locale={locale} ({source})", + "notice.banner.rulesFailOpen": "rules/banner fail-open: {exc}", + "notice.relay.persisted": "image relay: modelo {modelKey} sem entrada vision; {written} imagem(ns) gravada(s) em disco ({relayed} parte(s) de imagem retransmitida(s) no histórico da sessão, sessão {sid})", + "notice.relay.failOpen": "image relay fail-open (repassado): {exc}", + "notice.ctx.capToolDenied": "limite de contexto do subagent: tool '{tool}' negada na sessão encerrada {sid}", + "notice.ctx.capResumeDenied": "limite de contexto do subagent: resume da sessão encerrada ses_{taskId} negado (permanente)", + "notice.lang.gateDenied": "lang gate: tool '{tool}' negada na sessão de projeto não configurado {sid}", + "notice.search.clarifyFailOpen": "gate de esclarecimento de busca: fail-open após {maxDenies} negações sem ask — gate aberto para a sessão {sid}", + "notice.search.clarifyDenied": "gate de esclarecimento de busca: tool '{tool}' negada (busca ampla, ask-first) na sessão {sid} ({denyCount}/{maxDenies})", + "notice.dispatch.offUngoverned": "dispatch off: chamada task permitida sem governança (subagent_type='{subagentType}')", + "notice.dispatch.redirectUninjected": "auto-redirect {agent} → {candidate} (shell não injetado; redirecionado ao candidato chain-head)", + "notice.dispatch.redirectBuiltinBlocked": "auto-redirect {agent} → {candidate} (agente built-in bloqueado)", + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] subagent_type desconhecido='{agent}': permitido (fora da lista de shells; agentes built-in não são governados pelo roteamento)", + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled mas status da matriz={matrixStatus} (não down): fail-open, autocorreção após o próximo refresh do probe", + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} status da matriz={matrixStatus} (não down): não bloqueado, probe atualiza na próxima rodada", + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META ausente/malformado — sintetizado a partir da lane; declare-o para ativar a semântica de review cross-family / source=user", + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED: nenhum revisor cross-family disponível — self-review da mesma família permitido; declare DOWNGRADED na conclusão do review", + "notice.dispatch.poolOverrideNote": "override de pool-config: selecionado explicitamente para este task pool (piso de nível de capability dispensado)", + "notice.dispatch.redirectDenied": "auto-redirect {agent} → {redirect} ({deny})", + "notice.dispatch.gatesFailOpen": "six gates fail-open (permitido): {exc}", + "notice.lang.prefsSaved": "preferência de idioma do projeto salva ({rel}): conversation={conversation} comments={comments} docs={docs}", + "notice.lang.gateWaived": "lang gate: pergunta de marcador concluída sem config salva — gate dispensado para a sessão {sid}", + "notice.search.scopeAskDone": "esclarecimento de busca: scope ask concluído — gate aberto para a sessão {sid}", + "notice.ctx.readBudgetCharge": "cobrança de read budget +{charge} (tool {tool}, turno {turnUsed}/{turnBudget})", + "notice.handover.autoTriggered": "auto-handover disparado (após {tool}, ~{wmTokens} excede o watermark de force-compaction): backup completo + compactação enfileirada da sessão atual", + "notice.handover.backupResult": "backup de auto-handover {outcome}: {message}", + "notice.handover.compactionAccepted": "compactação de auto-handover aceita: session.summarize retornou (compactação executada no loop da sessão)", + "notice.handover.compactionRejected": "compactação de auto-handover falhou: session.summarize rejeitado (backup mantido)", + "notice.handover.compactionNoModel": "compactação de auto-handover falhou: nenhum modelo de sessão registrado (chat.params nunca disparou); backup mantido", + "notice.handover.failOpen": "auto-handover fail-open: {exc}", + "notice.ctx.capTerminated": "limite de contexto do subagent: sessão {sid}{agentSuffix} atingiu ~{estTokens}k tokens (limite {capTokens}k) — tools negadas, resumo de progresso exigido, sessão encerrada (sem resume de task_id)", + "notice.provider.modelRetired": "modelo aposentado (404s consecutivos), removido dos candidatos: {provider}/{modelId}", + "notice.breaker.agentTripped": "{agent} breaker disparado (600s): {reason}", + "notice.breaker.accountingFailOpen": "contabilização de falhas fail-open: {exc}", + "notice.lane.scoringFallback": "scoring falhou, voltou à ordenação por regras: {exc}", + "notice.lane.backfillFailed": "falha no backfill do ranking (lane permanece vazia): {exc}", + "notice.matrix.favoritesScanNoChange": "favoritos/conjunto visível verificados: ativação inalterada (gen={generation}; sem recompute, sem re-probe)", + "notice.matrix.invalidModels": "conjunto visível/favoritos contém modelos inválidos (provider conhecido mas sem tal modelId, nenhum shell gerado): {modelList}", + "notice.matrix.persistFailOpen": "persistência da matriz de ativação fail-open: {exc}", + "notice.matrix.callbackFailOpen": "callback da matriz de ativação fail-open: {exc}", + "notice.matrix.configReadFailOpen": "leitura da superfície de config fail-open (tratada como vazia): {exc}", + "notice.matrix.watchError": "fs.watch({dir}) com erro, voltando ao polling mtime: {exc}", + "notice.matrix.watchStartFailed": "fs.watch({dir}) falhou ao iniciar, voltando ao polling mtime: {exc}", + "notice.matrix.recomputeFailOpen": "recompute fail-open: {exc}", + "notice.probe.failOpen": "probe fail-open: {exc}", + "notice.probe.incrementalFailOpen": "probe incremental fail-open: {exc}", + "notice.probe.copilotPoolExhausted": "pool mensal do Copilot esgotado (gateway segunda fonte de verdade), válido até reset_date", + "notice.probe.resultsDiscarded": "resultados do probe descartados (geração da matriz mudou {oldGen}->{newGen}; reagendado pelo recompute da nova geração)", + "notice.probe.matrixRefreshed": "matriz atualizada: {comboCount} combos, {okCount} ok (total {totalCount})", + "notice.probe.schedulingFailOpen": "agendamento do probe fail-open: {exc}", + "notice.scoring.decisionLogFailOpen": "log de decisões fail-open: {exc}", + "notice.selfupdate.checkFailOpen": "verificação de self-update fail-open: {exc}", + "notice.selfupdate.upgradeAssetsFailOpen": "assets do comando upgrade fail-open: {exc}", + "notice.dispatch.mirrorDisabled": "espelhamento de pane tmux desativado (init falhou): {message}", + "notice.dispatch.mirrorOpFailed": "op de espelhamento de pane tmux falhou (continuando): {message}", + "notice.dispatch.mirrorPaneFull": "espelhamento de pane tmux: coluna cheia ({slotCount} panes), ses_{sessionId} ({agent}) enfileirado", + "notice.dispatch.mirrorAllClosed": "espelhamento de pane tmux: todos os panes de subagents fechados, pane principal restaurado", + "notice.dispatch.mirrorDisplayed": "espelhamento de pane tmux: ses_{sessionId} ({agent}) exibido no pane {pane}", + "notice.dispatch.mirrorReconciling": "espelhamento de pane tmux: pane(s) fechado(s) detectado(s), reconciliando layout", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "Configuração necessária ({missing}) — execute /switchman-setup (ou /switchman-setup-chat); o dispatch fica bloqueado até configurar", + "sidebar.peakTag": " ·pico", + "sidebar.staleTag": " ·desatualizado", + "sidebar.observeOnlyTag": " ·somente-observar", + "sidebar.updateAvailable": " → {updateVersion}", + "sidebar.restartNeeded": " [REINÍCIO NECESSÁRIO]", + "sidebar.noneAvailable": "nenhum disponível", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "economia", + "sidebar.lane.mechanical": "mecânica", + "sidebar.lane.main": "principal", + "sidebar.lane.hard": "difícil", + "sidebar.lane.vision": "visão", + "sidebar.lane.review": "revisão", + "sidebar.noticeLabel": "aviso", + "dialog.pool.title": "Task pools (escolha um task pool; Esc para sair)", + "dialog.pool.laneRow": "{pinMark}{lane}", + "dialog.pool.manualSelection": "seleção manual: {selCount}/{totalCount} modelos participando", + "dialog.pool.notConfigured": "não configurado: padrão do sistema (todos os modelos disponíveis participam)", + "dialog.pool.toggleWriteFailed": "falha de escrita: {message}", + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} o pool {lane} (efeito imediato, sidebar atualiza)", + "dialog.pool.keepOneModel": "Mantenha ao menos um modelo participante; use \"Clear config\" para restaurar o padrão do sistema", + "dialog.pool.bulkWriteFailed": "falha de escrita: {message}", + "dialog.pool.allSelected": "pool {lane}: todos os modelos selecionados", + "dialog.pool.configCleared": "config do pool {lane} limpa (conjunto candidato padrão do sistema restaurado)", + "dialog.pool.allUnchecked": "pool {lane}: tudo desmarcado — marque os modelos a manter; sair sem nada marcado mantém a seleção anterior", + "dialog.pool.back": "← Voltar à lista de pools", + "dialog.pool.selectAll": "☑ Selecionar tudo", + "dialog.pool.uncheckAll": "☐ Desmarcar tudo (depois marque os poucos a manter; sair sem nada marcado mantém a lista antiga)", + "dialog.pool.clearConfig": "✕ Limpar config (padrão do sistema: todos os modelos disponíveis participam)", + "dialog.pool.modelRow": "{checkMark} {modelId}", + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + "dialog.pool.selectionTitle": "seleção do pool {lane} ({selCount}/{rowCount} participando; seleção alterna, duplicatas entre pools permitidas)", + "dialog.rank.openPoolSelection": "→ Abrir seleção de task-pool (escolha os modelos que cada pool pode usar, depois ordene-os)", + "dialog.rank.close": "✕ Fechar", + "dialog.rank.universeEmptyTitle": "Ranking de modelos desativado até configurar os task pools — só modelos selecionados em task pools podem ser ordenados, assim você nunca ordena modelos que não pode despachar", + "dialog.rank.alreadyAtEdge": "{modelName} já está em {edge} da lista unificada de capability", + "dialog.rank.moveWriteFailed": "falha de escrita: {message}", + "dialog.rank.pinnedOrMoved": "{verb} {modelName} para #{position} (score manual {tier}/{raw}, ancorado entre vizinhos; efeito imediato, sidebar atualiza)", + "dialog.rank.title": "Ranking de capability dos modelos — ordem unificada (#1 mais forte; escopo da seleção de task-pool; entradas manuais intercaladas com modelos de score base; ctrl+up/ctrl+down move uma posição; enter = ações por modelo)", + "dialog.rank.searchHint": "Buscar · alt+up/alt+down espelham ctrl+up/ctrl+down (também funcionam)", + "dialog.rank.row": "#{rankPadded} {modelId}", + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + "dialog.rank.removeWriteFailed": "falha de escrita: {message}", + "dialog.rank.removed": "{model} removido do ranking manual (volta ao score base de capability, efeito imediato, sidebar atualiza)", + "dialog.rank.pinTop": "▲ Fixar no topo (acima de todos os modelos)", + "dialog.rank.moveUp": "↑ Subir um (troca com o modelo acima; ancora um score manual entre vizinhos)", + "dialog.rank.moveDown": "↓ Descer um (troca com o modelo abaixo)", + "dialog.rank.remove": "✕ Remover do ranking (voltar ao score base)", + "dialog.rank.back": "← Voltar à lista de ranking", + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "configuração do switchman — task pools e ranking de capability", + "dialog.setup.intro": "Configuração guiada: escolha modelos para cada um dos 6 task pools e depois ordene-os (o mais forte primeiro). Esc sai a qualquer momento; os pools confirmados são salvos imediatamente.", + "dialog.setup.start": "Começar (primeira etapa não concluída)", + "dialog.setup.statePools": "pools configurados: {count}/6", + "dialog.setup.stateRank": "ranking: {state}", + "dialog.setup.laneTitle": "Task pool {index}/6 — {lane} ({count} selecionados; enter alterna, mínimo 1)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] Selecionar tudo", + "dialog.setup.clearAll": "[ ] Desmarcar tudo", + "dialog.setup.confirmLane": "Confirmar {lane} ({count} modelos) e continuar", + "dialog.setup.back": "Voltar", + "dialog.setup.keepOne": "Mantenha ao menos um modelo neste pool", + "dialog.setup.rankTitle": "Ranking de capability — escolha o n.º {n} (o mais forte primeiro, {remaining} modelos restantes)", + "dialog.setup.rankFinish": "Concluir o ranking ({count} escolhidos; o restante mantém os scores base do sistema)", + "dialog.setup.rankMinOne": "Ordene ao menos um modelo antes de concluir", + "dialog.setup.doneTitle": "Configuração concluída — ativa imediatamente (hot-reload)", + "dialog.setup.donePools": "Pools: {summary}", + "dialog.setup.doneRank": "Ranking: {order}", + "dialog.setup.restartHint": "Reinicie o opencode para registrar novo(s) provedor(es): {providers}", + "dialog.handover.noSession": "/handover: fora de sessão, nada a salvar", + "dialog.handover.inProgress": "/handover: salvando a sessão atual por completo e compactando…", + "dialog.handover.resultStay": "{resultMessage}; ainda na sessão original, sem troca", + "dialog.handover.result": "/handover {resultMessage}", + "palette.handover.title": "Salvar e compactar a sessão atual", + "palette.handover.desc": "Fork completo da sessão atual como backup (tag de título [backup]) mais compactação da sessão atual; sem troca de sessão (distinto do /fork built-in)", + "palette.category.label": "switchman", + "palette.poolConfig.title": "Seleção de task pool", + "palette.poolConfig.desc": "Escolha os modelos participantes por task pool (economy/mechanical/main/hard/vision/review)", + "palette.modelRank.title": "Ranking de capability dos modelos", + "palette.modelRank.desc": "Ranking manual de capability (prevalece sobre scores base; mais acima = mais forte)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "Configuração guiada (pools + ranking)", + "palette.setup.desc": "Assistente: selecione vários modelos por task pool e depois ordene-os — necessário antes do dispatch funcionar", + "quota.poolGlm": "GLM", + "quota.poolCopilot": "Copilot", + "quota.poolDeepSeek": "DeepSeek", + "quota.queryingNoData": "consultando/sem dados", + "quota.resetLater": "→depois", + "quota.resetTime": "→{hhmm}", + "quota.resetDate": "→{mmdd}", + "quota.resetDateTime": "→{mmdd} {hhmm}", + "quota.barPct": "{bar8} {pct}%", + "quota.row5h": "5h", + "quota.rowWeek": "semana", + "quota.rowMcp": "MCP", + "quota.noData": "sem dados de cota", + "quota.rowRefresh": "atualização", + "quota.rowCredits": "créditos", + "quota.monthlyExhausted": "pool mensal esgotado", + "quota.unlimited": "ilimitado{usedSuffix}", + "quota.exhaustedOverage": "esgotado·cobrança excedente{usage}", + "quota.barPctLeft": "{bar8} {pctTxt}% restante{usage}", + "quota.rowBalance": "saldo", + "quota.exhausted": "esgotado", + "quota.unknownPayg": "desconhecido (pay-as-you-go)", + "quota.barBalance": "{bar8} ¥{balance}", + "quota.balanceWarn": "(<¥{thr} alerta)", + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + "cli.config.unknownPool": "task pool desconhecido: {lane} (seis task pools: {laneList})", + "cli.config.poolHeader": "Seleção de task-pool (arquivo de config {poolConfigPath}; seleção = os modelos que participam daquele task pool; o mesmo modelo pode participar de vários pools; pools não configurados usam a decisão padrão do sistema)", + "cli.config.poolSection": "== {lane} == ({selection})", + "cli.config.poolSectionBrief": "== {lane} =={detail}", + "cli.config.poolListHint": "(ver a lista completa de um único pool com números: pool list <{laneList}>)", + "cli.config.indexOutOfRange": "índice fora do intervalo #{index} (lista tem {rowCount} itens)", + "cli.config.invalidModel": "nome de modelo inválido: {model}", + "cli.config.noManifest": "nenhum manifesto de modelos disponível (verifique as conexões de provider e o manifesto superset)", + "cli.config.poolRequiresArg": "pool {sub} requer um índice ou nome de modelo", + "cli.config.poolSelectionCleared": "seleção de task-pool {lane} limpa (de volta ao conjunto candidato padrão do sistema, efeito imediato, sidebar atualiza em sincronia)", + "cli.config.poolUpdated": "Seleção de task-pool {lane} atualizada ({modelCount} modelos participando, efeito imediato, sidebar atualiza em sincronia)", + "cli.config.poolConfigCleared": "Config de seleção de task-pool {lane} limpa (aquele pool volta ao conjunto candidato padrão do sistema, efeito imediato, sidebar atualiza em sincronia)", + "cli.config.unknownPoolSub": "subcomando desconhecido pool {sub} (list/add/remove/set/clear)", + "cli.config.rankDisabledUntilPools": "Ranking manual de capability (arquivo de config {capabilityRankPath}) desativado até configurar os task pools: só modelos selecionados em task pools podem ser ordenados.", + "cli.config.rankHowTo": "Execute /poolConfig (diálogo TUI) ou pool set <task-pool> <index|model...> aqui primeiro, depois ordene só os modelos que você realmente usa.", + "cli.config.legacyHeader": "== Entradas manuais legacy (só limpeza; rank remove/clear ainda funcionam, ou selecione os modelos em um task pool para ordená-los) ==", + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + "cli.config.rankHeader": "Ranking de capability dos modelos (arquivo de config {capabilityRankPath}; escopo dos {universeCount} modelos selecionados em task pools via /poolConfig — uma ordem unificada, entradas manuais intercaladas com modelos de score base pelo score efetivo; mais acima = mais forte)", + "cli.config.mergedHeader": "== Ordem unificada ({manualCount} manual{manualSuffix}; set/add da CLI ordenam entradas pela escada legacy, movimentos da TUI ancoram scores entre vizinhos) ==", + "cli.config.manualTag": "·manual{score}", + "cli.config.notInPoolTag": "·fora de qualquer task pool", + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + "cli.config.rankNoPools": "ainda sem seleção de task-pool — o ranking segue a seleção de pool; execute /poolConfig (ou pool set) primeiro", + "cli.config.rankRequiresArg": "rank {sub} requer um índice ou nome de modelo", + "cli.config.rankUpdated": "Ranking manual de capability atualizado ({modelCount} modelos, efeito imediato, sidebar atualiza em sincronia)", + "cli.config.rankCleared": "Ranking manual de capability limpo (tudo volta ao score base de capability, efeito imediato, sidebar atualiza em sincronia)", + "cli.config.unknownRankSub": "subcomando desconhecido rank {sub} (list/set/add/remove/clear)", + "cli.config.usage": "Uso: switchman-config <pool|rank> ...", + "cli.config.usagePoolList": " pool list [task-pool] Visão geral da seleção de pool (economy/mechanical/main/hard/vision/review; com nome de pool = lista completa com índices)", + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> Marca modelos que participam daquele task pool", + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> Desmarca participação", + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> Substitui por completo a lista de participação daquele pool (o mesmo modelo pode participar de vários pools)", + "cli.config.usagePoolClear": " pool clear <task-pool> Limpa a config daquele pool (de volta ao conjunto candidato padrão do sistema)", + "cli.config.usageRankList": " rank list Ver o ranking manual de capability (escopo da seleção de task-pool; orienta a /poolConfig quando nenhum pool está configurado)", + "cli.config.usageRankSet": " rank set <index|model...> Reordena por completo (na ordem dada, #1 é o mais forte; só modelos selecionados em pools)", + "cli.config.usageRankAdd": " rank add <index|model...> Anexa ao fim do ranking (só modelos selecionados em pools)", + "cli.config.usageRankRemove": " rank remove <index|model...> Remove do ranking", + "cli.config.usageRankClear": " rank clear Limpa o ranking (volta ao score base de capability)", + "cli.config.errorPrefix": "switchman-config: {message}", + "cli.doctor.usage": "Uso: switchman-doctor verifica a config do opencode-switchman; a env var OPENCODE_CONFIG_DIR seleciona o diretório de config; códigos de saída 0=sem problemas, 1=avisos, 2=erros", + "cli.doctor.unknownModelsHint": "{unknownCount} modelos não reconhecidos pelo sistema conhecido (grupo desconhecido, ordenados ao fim por coeficiente)", + "cli.doctor.approxModelsHint": "{approxCount} modelos classificados aproximadamente por prefixo/família", + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + "cli.doctor.noIssues": "opencode-switchman doctor: nenhum problema encontrado", + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/locales/ru.ts b/src/locales/ru.ts new file mode 100644 index 0000000..d4a9aae --- /dev/null +++ b/src/locales/ru.ts @@ -0,0 +1,273 @@ +// [2026-09-19]-[Russian message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const ru: Partial<Record<MsgKey, string>> = { + "notice.breaker.realCallIsolated": "{agent} real-call изолирован на {mins} мин ({category}): {reason}", + "notice.breaker.shellNotInjected": "shell не внедрён в opencode (изоляции нет): {agent} {reason}", + "notice.breaker.failOpen": "breaker fail-open: {exc}", + "notice.capability.snapshotCorrupted": "снапшот рангов capability повреждён (пропущен, откат к curated-таблице)", + "notice.capability.primarySourceFailed": "основной источник индекса capability AA недоступен ({exc}){nextStep}", + "notice.capability.backupSourceFailed": "резервный источник индекса capability OpenRouter недоступен ({exc}) -> сохранены последние ранги/bundled-значения по умолчанию", + "notice.capability.parsedEmpty": "индекс capability пуст после разбора ({source}) -> сохранены последние ранги/bundled-значения по умолчанию", + "notice.capability.refreshed": "индекс capability обновлён: {source}, {modelCount} моделей (version={version})", + "notice.capability.refreshFailOpen": "обновление индекса capability fail-open (сохранены последние ранги/bundled-значения по умолчанию): {exc}", + "notice.capability.lmarenaDisagreement": "перекрёстная проверка capability LMArena: совпадение tier-порядка и ELO-порядка лишь {rate}% ({overlapCount} общих моделей) -- источник данных может быть аномальным, рекомендуется ручная проверка", + "notice.capability.lmarenaFailOpen": "перекрёстная проверка capability LMArena fail-open (пропущена): {exc}", + "notice.catalog.unavailableNoCache": "каталог models.dev недоступен, кэша нет (деградация fail-open): {exc}", + "notice.copilot.shapeCacheRefreshed": "кэш форм thinking-параметра Copilot обновлён: {modelCount} моделей", + "notice.copilot.shapeRefreshFailOpen": "обновление кэша форм thinking-параметра Copilot fail-open: {exc}", + "notice.cost.refreshFailed": "не удалось обновить снапшот стоимости (сохранены устаревшие данные): {exc}", + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} — невалидный JSON, игнорируется (конфиг языка откатывается к маркеру AGENTS.md; \"dispatch\":\"off\" не применён)", + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile}: поле \"dispatch\" задано, но не равно строго \"off\" (получено: {rawValue}), — игнорируется, fleet-поведение", + "notice.ctx.paused": "ctx-контроль приостановлен для сессии {sid} (/ctx-pause): read gates + бюджет самопроверки + auto-handover приостановлены; измерение продолжается", + "notice.ctx.resumed": "ctx-контроль возобновлён для сессии {sid} (/ctx-resume): read gates + auto-handover снова активны", + "notice.workspace.created": "артефакт-workspace создан: {rel}", + "notice.workspace.renamed": "артефакт-workspace переименован: {oldRel} → {rel}", + "notice.dispatch.mirrorResumeReuse": "зеркалирование панелей tmux: resume-диспетчеризация ses_{taskId} ({shellName}) — повторное использование task_id, панель открыта напрямую (событие session.created не сработает)", + "notice.dispatch.mirrorResumeLookupFailed": "зеркалирование панелей tmux: resume-диспетчеризация ses_{taskId} ({shellName}) — поиск сессии не удался, fail-open панель", + "notice.capability.selectionChanged": "выбор ранга/пула задач capability изменён: баннер и сайдбар обновляются немедленно", + "notice.capability.overrideWatchError": "ошибка fs.watch({dir}) для override-конфига (запасной вариант — mtime polling): {exc}", + "notice.matrix.configSurfaceFailOpen": "чтение поверхности конфига fail-open: {exc}", + "notice.matrix.floorFreeModels": "floor = {floorCount} бесплатных моделей OpenCode Zen (каталог {catalogStatus})", + "notice.matrix.floorFallback": "floor откатился к статическому манифесту (каталог {catalogStatus}, 0 бесплатных моделей)", + "notice.matrix.invalidModelsUnknownProvider": "набор видимых/избранных содержит невалидные модели с неизвестным провайдером (провайдер не подключён; игнорируются, shell не построены): {modelList}", + "notice.provider.probeAttemptSucceeded": "попытка provider.list {attempt} удалась (предыдущие {prevAttempts} были не готовы)", + "notice.provider.probeAttemptBackoff": "попытка provider.list {attempt} не готова, откладываем: {exc}", + "notice.provider.unavailableCfgFallback": "provider.list недоступен (откат к {keyCount} ключам cfg.provider после {attemptCount} попыток): {exc}", + "notice.provider.probeNewProvider": "фоновая проверка provider.list: подключены новые провайдеры ({providers}) — перезапустите opencode для завершения регистрации shell", + "notice.provider.probeModelDrift": "фоновая проверка provider.list: список моделей изменился ({drift}) — суперсет-манифест перестроен, списки /modelRank //poolConfig обновлены{restartHint}", + "notice.provider.probeRebuildFailed": "фоновая проверка provider.list: не удалось перестроить суперсет (сохранён предыдущий манифест): {exc}", + "notice.probe.warmupFailOpen": "прогрев fail-open: {exc}", + "notice.skills.synced": "скиллы синхронизированы: установлено {installedCount}, обновлено {updatedCount}, удалено {removedCount} ({skillNames})", + "notice.skills.syncFailOpen": "синхронизация скиллов fail-open: {exc}", + "notice.banner.failOpen": "баннер fail-open: {exc}", + "notice.ctx.readBudgetContinuation": "продолжение бюджета чтения (файл {fileName}, +{granted} строк с {offset}, ход {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateCap": "ограничение read budget gate (чтение инструментом, файл {fileName}, оценка ~{totalTokens} -> лимит {suggestedLimit}, ход {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGate": "read budget gate {action} (инструмент {tool}, оценка ~{totalTokens}{contRem}, C~{wmTokens}, T_est≈{turnsToHard}, ход {turnUsed}/{turnBudget})", + "notice.ctx.readBudgetGateFailOpen": "read budget gate fail-open (разрешено): {exc}", + "notice.image.readGuardDenied": "защита чтения изображений: у модели {modelKey} нет vision-входа; чтение {fileName} отклонено (сессия {sid})", + "notice.image.readGuardFailOpen": "защита чтения изображений fail-open (разрешено): {exc}", + "notice.doctor.summary": "doctor нашёл {errorCount} ошибок / {warnCount} предупреждений; выполните /switchman-doctor для просмотра", + "notice.injection.legacyStaticMatrix": "внедрено {shellCount} модельных shell (агенты, legacy static matrix)", + "notice.provider.cacheUsed": "provider.list использует межперезапускной кэш ({providerCount} провайдеров, кэшировано в {cachedAt}); добавления проверяются в фоне", + "notice.provider.cacheStale": "кэш provider.list устарел (кэшировано в {cachedAt}), перед построением суперсета опрашиваем live", + "notice.matrix.recomputed": "матрица активации пересчитана (gen={generation}, активных shell {activeShellCount}, пробы {source}×{targetCount})", + "notice.injection.shellCount": "внедрено {shellCount} shell (mode={runMode}, поверхность внедрения={injectionMode}={fullSupersetCount}→{faceCount} после курирования, конфликтов {conflictCount}; gating активации включён)", + "notice.injection.configHookFailOpen": "config hook fail-open: {exc}", + "notice.lang.askLocale": "язык опроса locale={locale} ({source})", + "notice.banner.rulesFailOpen": "правила/баннер fail-open: {exc}", + "notice.relay.persisted": "ретрансляция изображений: у модели {modelKey} нет vision-входа; записано {written} изображений на диск ({relayed} частей изображений ретранслировано по истории сессии, сессия {sid})", + "notice.relay.failOpen": "ретрансляция изображений fail-open (пропущено): {exc}", + "notice.ctx.capToolDenied": "лимит контекста субагента: инструмент '{tool}' отклонён в завершённой сессии {sid}", + "notice.ctx.capResumeDenied": "лимит контекста субагента: resume завершённой сессии ses_{taskId} отклонён (навсегда)", + "notice.lang.gateDenied": "языковой gate: инструмент '{tool}' отклонён в ненастроенной проектной сессии {sid}", + "notice.search.clarifyFailOpen": "search clarify gate: fail-open после {maxDenies} отклонений без опроса — gate открыт для сессии {sid}", + "notice.search.clarifyDenied": "search clarify gate: инструмент '{tool}' отклонён (широкий поиск, сначала спросите) в сессии {sid} ({denyCount}/{maxDenies})", + "notice.dispatch.offUngoverned": "dispatch off: вызов задачи разрешён без управления (subagent_type='{subagentType}')", + "notice.dispatch.redirectUninjected": "автоперенаправление {agent} → {candidate} (невнедрённый shell; перенаправлено на кандидата в голове цепочки)", + "notice.dispatch.redirectBuiltinBlocked": "автоперенаправление {agent} → {candidate} (встроенный агент заблокирован)", + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] неизвестный subagent_type='{agent}': разрешён (не в списке shell; встроенные агенты маршрутизацией не управляются)", + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled, но статус матрицы={matrixStatus} (не down): fail-open, автокоррекция после следующего обновления проб", + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent}, статус матрицы={matrixStatus} (не down): не блокируется, пробы обновятся в следующем раунде", + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META отсутствует/повреждён — синтезирован из lane; объявите его, чтобы включить семантику review cross-family / source=user", + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED: нет кросс-семейного ревьюера — разрешено саморевью в том же семействе; объявите DOWNGRADED в заключении ревью", + "notice.dispatch.poolOverrideNote": "переопределение pool-config: явно выбрано в этот пул задач (минимальный уровень capability floor снят)", + "notice.dispatch.redirectDenied": "автоперенаправление {agent} → {redirect} ({deny})", + "notice.dispatch.gatesFailOpen": "шесть gates fail-open (разрешено): {exc}", + "notice.lang.prefsSaved": "языковые предпочтения проекта сохранены ({rel}): conversation={conversation} comments={comments} docs={docs}", + "notice.lang.gateWaived": "языковой gate: вопрос-маркер завершён без сохранённого конфига — gate снят для сессии {sid}", + "notice.search.scopeAskDone": "уточнение поиска: опрос области завершён — gate открыт для сессии {sid}", + "notice.ctx.readBudgetCharge": "списание бюджета чтения +{charge} (инструмент {tool}, ход {turnUsed}/{turnBudget})", + "notice.handover.autoTriggered": "auto-handover сработал (после {tool}, ~{wmTokens} превышает watermark принудительной компактификации): полное резервное копирование + компактификация текущей сессии в очереди", + "notice.handover.backupResult": "резервная копия auto-handover {outcome}: {message}", + "notice.handover.compactionAccepted": "компактификация auto-handover принята: session.summarize вернулся (компактификация выполнена в цикле сессии)", + "notice.handover.compactionRejected": "компактификация auto-handover не удалась: session.summarize отклонён (резервная копия сохранена)", + "notice.handover.compactionNoModel": "компактификация auto-handover не удалась: модель сессии не записана (chat.params ни разу не срабатывал); резервная копия сохранена", + "notice.handover.failOpen": "auto-handover fail-open: {exc}", + "notice.ctx.capTerminated": "лимит контекста субагента: сессия {sid}{agentSuffix} достигла ~{estTokens}k токенов (лимит {capTokens}k) — инструменты отклонены, запрошена сводка прогресса, сессия завершена (resume по task_id невозможен)", + "notice.provider.modelRetired": "модель выведена из эксплуатации (подряд 404), удалена из кандидатов: {provider}/{modelId}", + "notice.breaker.agentTripped": "сработал breaker {agent} (600s): {reason}", + "notice.breaker.accountingFailOpen": "учёт сбоев fail-open: {exc}", + "notice.lane.scoringFallback": "скоринг не удался, откат к упорядочиванию по правилам: {exc}", + "notice.lane.backfillFailed": "backfill-ранжирование не удалось (lane остаётся пустым): {exc}", + "notice.matrix.favoritesScanNoChange": "набор избранного/видимых просканирован: активация без изменений (gen={generation}; без пересчёта и повторных проб)", + "notice.matrix.invalidModels": "набор видимых/избранных содержит невалидные модели (провайдер известен, но такого modelId нет, shell не сгенерирован): {modelList}", + "notice.matrix.persistFailOpen": "сохранение матрицы активации fail-open: {exc}", + "notice.matrix.callbackFailOpen": "колбэк матрицы активации fail-open: {exc}", + "notice.matrix.configReadFailOpen": "чтение поверхности конфига fail-open (считается пустым): {exc}", + "notice.matrix.watchError": "ошибка fs.watch({dir}), переход на mtime polling: {exc}", + "notice.matrix.watchStartFailed": "не удалось запустить fs.watch({dir}), переход на mtime polling: {exc}", + "notice.matrix.recomputeFailOpen": "пересчёт fail-open: {exc}", + "notice.probe.failOpen": "проба fail-open: {exc}", + "notice.probe.incrementalFailOpen": "инкрементальная проба fail-open: {exc}", + "notice.probe.copilotPoolExhausted": "месячный пул Copilot исчерпан (gateway — второй источник истины), доверяем до reset_date", + "notice.probe.resultsDiscarded": "результаты проб отброшены (поколение матрицы сменилось {oldGen}->{newGen}; перепланировано пересчётом нового поколения)", + "notice.probe.matrixRefreshed": "матрица обновлена: {comboCount} комбинаций, {okCount} ок (всего {totalCount})", + "notice.probe.schedulingFailOpen": "планирование проб fail-open: {exc}", + "notice.scoring.decisionLogFailOpen": "журнал решений fail-open: {exc}", + "notice.selfupdate.checkFailOpen": "проверка самообновления fail-open: {exc}", + "notice.selfupdate.upgradeAssetsFailOpen": "ресурсы команды upgrade fail-open: {exc}", + "notice.dispatch.mirrorDisabled": "зеркалирование панелей tmux отключено (инициализация не удалась): {message}", + "notice.dispatch.mirrorOpFailed": "операция зеркалирования панелей tmux не удалась (продолжаем): {message}", + "notice.dispatch.mirrorPaneFull": "зеркалирование панелей tmux: колонка заполнена ({slotCount} панелей), в очереди ses_{sessionId} ({agent})", + "notice.dispatch.mirrorAllClosed": "зеркалирование панелей tmux: все панели субагентов закрыты, главная панель восстановлена", + "notice.dispatch.mirrorDisplayed": "зеркалирование панелей tmux: ses_{sessionId} ({agent}) показана в панели {pane}", + "notice.dispatch.mirrorReconciling": "зеркалирование панелей tmux: обнаружены закрытые панели, согласовываем раскладку", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "Требуется настройка ({missing}) — запустите /switchman-setup (или /switchman-setup-chat); диспетчеризация заблокирована до настройки", + "sidebar.peakTag": " ·peak", + "sidebar.staleTag": " ·stale", + "sidebar.observeOnlyTag": " ·observe-only", + "sidebar.updateAvailable": " → {updateVersion}", + "sidebar.restartNeeded": " [НУЖЕН РЕСТАРТ]", + "sidebar.noneAvailable": "нет доступных", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "экономия", + "sidebar.lane.mechanical": "механика", + "sidebar.lane.main": "основной", + "sidebar.lane.hard": "сложный", + "sidebar.lane.vision": "зрение", + "sidebar.lane.review": "ревью", + "sidebar.noticeLabel": "уведомление", + "dialog.pool.title": "Пулы задач (выберите пул; Esc — выход)", + "dialog.pool.laneRow": "{pinMark}{lane}", + "dialog.pool.manualSelection": "ручной выбор: участвует {selCount}/{totalCount} моделей", + "dialog.pool.notConfigured": "не настроено: системное значение по умолчанию (участвуют все доступные модели)", + "dialog.pool.toggleWriteFailed": "ошибка записи: {message}", + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} пула {lane} (вступает в силу немедленно, сайдбар обновляется)", + "dialog.pool.keepOneModel": "Оставьте хотя бы одну участвующую модель; используйте \"Clear config\" для возврата системного значения по умолчанию", + "dialog.pool.bulkWriteFailed": "ошибка записи: {message}", + "dialog.pool.allSelected": "пул {lane}: выбраны все модели", + "dialog.pool.configCleared": "конфиг пула {lane} очищен (восстановлен системный набор кандидатов по умолчанию)", + "dialog.pool.allUnchecked": "пул {lane}: все сняты — отметьте модели, которые нужно оставить; выход без отметок сохраняет предыдущий выбор", + "dialog.pool.back": "← Назад к списку пулов", + "dialog.pool.selectAll": "☑ Выбрать все", + "dialog.pool.uncheckAll": "☐ Снять все (затем отметьте те, что оставить; выход без отметок сохраняет старый список)", + "dialog.pool.clearConfig": "✕ Очистить конфиг (системное значение по умолчанию: участвуют все доступные модели)", + "dialog.pool.modelRow": "{checkMark} {modelId}", + "dialog.pool.rowMeta": "{tier}-tier{manualSuffix}", + "dialog.pool.selectionTitle": "выбор пула {lane} (участвует {selCount}/{rowCount}; выбор переключает, дубликаты в пулах разрешены)", + "dialog.rank.openPoolSelection": "→ Открыть выбор пулов задач (выберите модели для каждого пула, затем ранжируйте их)", + "dialog.rank.close": "✕ Закрыть", + "dialog.rank.universeEmptyTitle": "Ранжирование моделей отключено, пока не настроены пулы задач — ранжировать можно только модели, выбранные в пулы задач, поэтому вы никогда не ранжируете модели, которые нельзя диспетчеризировать", + "dialog.rank.alreadyAtEdge": "{modelName} уже на {edge} объединённого списка capability", + "dialog.rank.moveWriteFailed": "ошибка записи: {message}", + "dialog.rank.pinnedOrMoved": "{verb} {modelName} на #{position} (ручная оценка {tier}/{raw}, закреплена между соседями; вступает в силу немедленно, сайдбар обновляется)", + "dialog.rank.title": "Ранжирование capability моделей — объединённый порядок (#1 сильнейшая; в пределах выбора пулов задач; ручные записи перемежаются с моделями base-score; ctrl+up/ctrl+down — сдвиг на одну позицию; enter — действия с моделью)", + "dialog.rank.searchHint": "Поиск · alt+up/alt+down дублируют ctrl+up/ctrl+down (тоже работают)", + "dialog.rank.row": "#{rankPadded} {modelId}", + "dialog.rank.rowMeta": "{tier}-tier · {scoreSource}{poolSuffix}", + "dialog.rank.removeWriteFailed": "ошибка записи: {message}", + "dialog.rank.removed": "{model} удалена из ручного ранжирования (откат к базовому скору capability, вступает в силу немедленно, сайдбар обновляется)", + "dialog.rank.pinTop": "▲ Закрепить сверху (выше всех моделей)", + "dialog.rank.moveUp": "↑ На одну вверх (обмен с моделью выше; ручная оценка закрепляется между соседями)", + "dialog.rank.moveDown": "↓ На одну вниз (обмен с моделью ниже)", + "dialog.rank.remove": "✕ Удалить из ранжирования (откат к базовому скору)", + "dialog.rank.back": "← Назад к списку ранжирования", + "dialog.rank.detailTitle": "{model} ({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "настройка switchman — пулы задач и ранжирование capability", + "dialog.setup.intro": "Пошаговая настройка: выберите модели для каждого из 6 пулов задач, затем ранжируйте их (сильнейшие первыми). Esc завершает работу в любой момент; подтверждённые пулы сохраняются сразу.", + "dialog.setup.start": "Начать (с первого незавершённого шага)", + "dialog.setup.statePools": "пулов настроено: {count}/6", + "dialog.setup.stateRank": "ранжирование: {state}", + "dialog.setup.laneTitle": "Пул задач {index}/6 — {lane} (выбрано: {count}; enter переключает, минимум 1)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] Выбрать все", + "dialog.setup.clearAll": "[ ] Снять все", + "dialog.setup.confirmLane": "Подтвердить {lane} ({count} моделей) и продолжить", + "dialog.setup.back": "Назад", + "dialog.setup.keepOne": "Оставьте хотя бы одну модель в этом пуле", + "dialog.setup.rankTitle": "Ранжирование capability — выберите #{n} (сильнейшие первыми, осталось моделей: {remaining})", + "dialog.setup.rankFinish": "Завершить ранжирование (выбрано: {count}; остальные сохраняют системные базовые скоры)", + "dialog.setup.rankMinOne": "Проранжируйте хотя бы одну модель перед завершением", + "dialog.setup.doneTitle": "Настройка завершена — действует сразу (горячая перезагрузка)", + "dialog.setup.donePools": "Пулы: {summary}", + "dialog.setup.doneRank": "Ранжирование: {order}", + "dialog.setup.restartHint": "Перезапустите opencode для регистрации новых провайдеров: {providers}", + "dialog.handover.noSession": "/handover: вне сессии, копировать нечего", + "dialog.handover.inProgress": "/handover: полное резервное копирование текущей сессии и компактификация…", + "dialog.handover.resultStay": "{resultMessage}; вы остались в исходной сессии, переключения нет", + "dialog.handover.result": "/handover {resultMessage}", + "palette.handover.title": "Создать резервную копию и компактифицировать текущую сессию", + "palette.handover.desc": "Полный форк текущей сессии как резервная копия (тег заголовка [backup]) плюс компактификация текущей сессии; без переключения сессии (отличается от встроенного /fork)", + "palette.category.label": "switchman", + "palette.poolConfig.title": "Выбор пула задач", + "palette.poolConfig.desc": "Выберите участвующие модели для каждого пула задач (economy/mechanical/main/hard/vision/review)", + "palette.modelRank.title": "Ранжирование capability моделей", + "palette.modelRank.desc": "Ручное ранжирование capability (приоритет над базовыми скорами; чем раньше, тем сильнее)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "Пошаговая настройка (пулы + ранжирование)", + "palette.setup.desc": "Мастер: выберите несколько моделей для каждого пула задач, затем ранжируйте — обязательно до начала диспетчеризации", + "quota.poolGlm": "GLM", + "quota.poolCopilot": "Copilot", + "quota.poolDeepSeek": "DeepSeek", + "quota.queryingNoData": "запрос/нет данных", + "quota.resetLater": "→позже", + "quota.resetTime": "→{hhmm}", + "quota.resetDate": "→{mmdd}", + "quota.resetDateTime": "→{mmdd} {hhmm}", + "quota.barPct": "{bar8} {pct}%", + "quota.row5h": "5h", + "quota.rowWeek": "неделя", + "quota.rowMcp": "MCP", + "quota.noData": "нет данных квоты", + "quota.rowRefresh": "обновление", + "quota.rowCredits": "кредиты", + "quota.monthlyExhausted": "месячный пул исчерпан", + "quota.unlimited": "безлимит{usedSuffix}", + "quota.exhaustedOverage": "исчерпано·оплата overage{usage}", + "quota.barPctLeft": "{bar8} осталось {pctTxt}%{usage}", + "quota.rowBalance": "баланс", + "quota.exhausted": "исчерпано", + "quota.unknownPayg": "неизвестно (pay-as-you-go)", + "quota.barBalance": "{bar8} ¥{balance}", + "quota.balanceWarn": "(<¥{thr} предупреждение)", + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId} ({tier}-tier{manualTag})", + "cli.config.unknownPool": "неизвестный пул задач: {lane} (всего шесть пулов: {laneList})", + "cli.config.poolHeader": "Выбор пула задач (файл конфига {poolConfigPath}; выбор = модели, входящие в этот пул; одна модель может входить в несколько пулов; ненастроенные пулы используют системное решение по умолчанию)", + "cli.config.poolSection": "== {lane} == ({selection})", + "cli.config.poolSectionBrief": "== {lane} =={detail}", + "cli.config.poolListHint": "(полный пронумерованный список одного пула: pool list <{laneList}>)", + "cli.config.indexOutOfRange": "индекс вне диапазона #{index} (в списке {rowCount} элементов)", + "cli.config.invalidModel": "невалидное имя модели: {model}", + "cli.config.noManifest": "нет манифеста доступных моделей (проверьте подключения провайдеров и суперсет-манифест)", + "cli.config.poolRequiresArg": "pool {sub} требует индекс или имя модели", + "cli.config.poolSelectionCleared": "выбор пула задач {lane} очищен (возврат к системному набору кандидатов по умолчанию, вступает в силу немедленно, сайдбар синхронно обновляется)", + "cli.config.poolUpdated": "Выбор пула задач {lane} обновлён (участвует {modelCount} моделей, вступает в силу немедленно, сайдбар синхронно обновляется)", + "cli.config.poolConfigCleared": "Конфиг выбора пула задач {lane} очищен (пул возвращается к системному набору кандидатов по умолчанию, вступает в силу немедленно, сайдбар синхронно обновляется)", + "cli.config.unknownPoolSub": "неизвестная подкоманда pool {sub} (list/add/remove/set/clear)", + "cli.config.rankDisabledUntilPools": "Ручное ранжирование capability (файл конфига {capabilityRankPath}) отключено, пока не настроены пулы задач: ранжировать можно только модели, выбранные в пулы задач.", + "cli.config.rankHowTo": "Сначала выполните /poolConfig (TUI-диалог) или pool set <task-pool> <index|model...> здесь, затем ранжируйте только те модели, которые реально используете.", + "cli.config.legacyHeader": "== Legacy-ручные записи (только очистка; rank remove/clear по-прежнему работают, либо выберите модели в пул задач, чтобы ранжировать их) ==", + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + "cli.config.rankHeader": "Ранжирование capability моделей (файл конфига {capabilityRankPath}; в пределах {universeCount} моделей, выбранных в пулы задач через /poolConfig, — один объединённый порядок, ручные записи перемежаются с моделями base-score по эффективному скору; чем выше, тем сильнее)", + "cli.config.mergedHeader": "== Объединённый порядок ({manualCount} ручных{manualSuffix}; CLI set/add упорядочивает записи по legacy-лестнице, TUI-перемещения закрепляют скоры между соседями) ==", + "cli.config.manualTag": "·manual{score}", + "cli.config.notInPoolTag": "·вне пулов задач", + "cli.config.rankRow": "#{rankPadded} {modelId} ({tier}-tier{manualTag}{poolTag})", + "cli.config.rankNoPools": "выбор пула задач пока отсутствует — ранжирование следует за выбором пула; сначала выполните /poolConfig (или pool set)", + "cli.config.rankRequiresArg": "rank {sub} требует индекс или имя модели", + "cli.config.rankUpdated": "Ручное ранжирование capability обновлено ({modelCount} моделей, вступает в силу немедленно, сайдбар синхронно обновляется)", + "cli.config.rankCleared": "Ручное ранжирование capability очищено (всё откатывается к базовому скору capability, вступает в силу немедленно, сайдбар синхронно обновляется)", + "cli.config.unknownRankSub": "неизвестная подкоманда rank {sub} (list/set/add/remove/clear)", + "cli.config.usage": "Использование: switchman-config <pool|rank> ...", + "cli.config.usagePoolList": " pool list [task-pool] Обзор выбора пула (economy/mechanical/main/hard/vision/review; с именем пула = полный список с индексами)", + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> Отметить модели, входящие в этот пул задач", + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> Снять участие", + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> Полностью заменить список участников пула (одна модель может входить в несколько пулов)", + "cli.config.usagePoolClear": " pool clear <task-pool> Очистить конфиг пула (возврат к системному набору кандидатов по умолчанию)", + "cli.config.usageRankList": " rank list Просмотр ручного ранжирования capability (в пределах выбора пулов задач; при отсутствии пулов подскажет /poolConfig)", + "cli.config.usageRankSet": " rank set <index|model...> Полное переупорядочивание (в заданном порядке, #1 сильнейшая; только модели из пулов)", + "cli.config.usageRankAdd": " rank add <index|model...> Добавить в конец ранжирования (только модели из пулов)", + "cli.config.usageRankRemove": " rank remove <index|model...> Удалить из ранжирования", + "cli.config.usageRankClear": " rank clear Очистить ранжирование (откат к базовому скору capability)", + "cli.config.errorPrefix": "switchman-config: {message}", + "cli.doctor.usage": "Использование: switchman-doctor проверяет конфиг opencode-switchman; переменная окружения OPENCODE_CONFIG_DIR выбирает каталог конфига; коды выхода 0=без проблем, 1=предупреждения, 2=ошибки", + "cli.doctor.unknownModelsHint": "{unknownCount} моделей не сопоставлено известной системе (группа unknown, коэффициентом понижены в конец)", + "cli.doctor.approxModelsHint": "{approxCount} моделей классифицировано приблизительно по префиксу/семейству", + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + "cli.doctor.noIssues": "opencode-switchman doctor: проблем не найдено", + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.ts new file mode 100644 index 0000000..c4a312f --- /dev/null +++ b/src/locales/zh-CN.ts @@ -0,0 +1,527 @@ +// [2026-09-19]-[Simplified Chinese message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const zhCN: Partial<Record<MsgKey, string>> = { + // ---- notices (status log; appendStatusLog) ---- + + // src/breaker.ts:37 + "notice.breaker.realCallIsolated": "{agent} 真实调用已隔离 {mins} 分钟({category}):{reason}", + // src/breaker.ts:48 + "notice.breaker.shellNotInjected": "shell 未注入 opencode(无隔离):{agent} {reason}", + // src/breaker.ts:200 + "notice.breaker.failOpen": "断路器 fail-open:{exc}", + // src/capability.ts:246 + "notice.capability.snapshotCorrupted": "内置能力排名快照损坏(跳过,回退到精选表)", + // src/capability.ts:299 + "notice.capability.primarySourceFailed": "能力索引主来源 AA 失败({exc}){nextStep}", + // src/capability.ts:311 + "notice.capability.backupSourceFailed": "能力索引备用来源 OpenRouter 失败({exc})-> 保留最近可用/内置默认排名", + // src/capability.ts:316 + "notice.capability.parsedEmpty": "能力索引解析结果为空({source})-> 保留最近可用/内置默认排名", + // src/capability.ts:333 + "notice.capability.refreshed": "能力索引已刷新:{source} 共 {modelCount} 个模型(version={version})", + // src/capability.ts:336 + "notice.capability.refreshFailOpen": "能力索引刷新 fail-open(保留最近可用/内置默认排名):{exc}", + // src/capability.ts:372 + "notice.capability.lmarenaDisagreement": "能力 LMArena 交叉核对:层级排序与 ELO 排序一致率仅 {rate}%(重叠 {overlapCount} 个模型)-- 数据来源可能异常,建议人工复查", + // src/capability.ts:375 + "notice.capability.lmarenaFailOpen": "能力 LMArena 交叉核对 fail-open(已跳过):{exc}", + // src/catalog.ts:153 + "notice.catalog.unavailableNoCache": "models.dev 目录不可用且无缓存(fail-open 降级):{exc}", + // src/copilot-thinking.ts:71 + "notice.copilot.shapeCacheRefreshed": "Copilot 思考参数 shape 缓存已刷新:{modelCount} 个模型", + // src/copilot-thinking.ts:73 + "notice.copilot.shapeRefreshFailOpen": "Copilot 思考参数 shape 刷新 fail-open:{exc}", + // src/cost.ts:44 + "notice.cost.refreshFailed": "成本快照刷新失败(保留过期数据):{exc}", + // src/dispatch-mode.ts:60 (log callback defaults to appendStatusLog) + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} 不是有效的 JSON — 已忽略(lang 配置回退到 AGENTS.md 标记;\"dispatch\":\"off\" 未生效)", + // src/dispatch-mode.ts:66 (log callback defaults to appendStatusLog) + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} 存在 \"dispatch\" 但值不是精确的 \"off\"(实际值:{rawValue})— 已忽略,保持 fleet 行为", + // src/index.ts:262 + "notice.ctx.paused": "会话 {sid} 的 ctx 控制已暂停(/ctx-pause):读取闸门 + 自读预算 + 自动交接均已暂停;用量测量继续进行", + // src/index.ts:264 + "notice.ctx.resumed": "会话 {sid} 的 ctx 控制已恢复(/ctx-resume):读取闸门 + 自动交接重新生效", + // src/index.ts:467 + "notice.workspace.created": "产物工作区已创建:{rel}", + // src/index.ts:468 + "notice.workspace.renamed": "产物工作区已重命名:{oldRel} → {rel}", + // src/index.ts:542 + "notice.dispatch.mirrorResumeReuse": "tmux 面板镜像:恢复派发 ses_{taskId}({shellName})— task_id 复用,直接打开面板(不会触发 session.created)", + // src/index.ts:546 + "notice.dispatch.mirrorResumeLookupFailed": "tmux 面板镜像:恢复派发 ses_{taskId}({shellName})— 会话查找失败,fail-open 改开普通面板", + // src/index.ts:574 + "notice.capability.selectionChanged": "能力排名/任务池选择已变更:banner 与侧边栏立即刷新", + // src/index.ts:589 + "notice.capability.overrideWatchError": "fs.watch({dir}) 覆盖配置监听出错(回退 mtime 轮询):{exc}", + // src/index.ts:647 + "notice.matrix.configSurfaceFailOpen": "配置界面读取 fail-open:{exc}", + // src/index.ts:675 + "notice.matrix.floorFreeModels": "floor = {floorCount} 个 OpenCode Zen 免费模型(catalog {catalogStatus})", + // src/index.ts:676 + "notice.matrix.floorFallback": "floor 回退到静态清单(catalog {catalogStatus},0 个免费模型)", + // src/index.ts:680 + "notice.matrix.invalidModelsUnknownProvider": "可见集合/收藏包含 provider 未知的无效模型(provider 未连接;已忽略,未生成 shell):{modelList}", + // src/index.ts:778 + "notice.provider.probeAttemptSucceeded": "provider.list 第 {attempt} 次尝试成功(此前 {prevAttempts} 次尚未就绪)", + // src/index.ts:783 + "notice.provider.probeAttemptBackoff": "provider.list 第 {attempt} 次尝试尚未就绪,退避中:{exc}", + // src/index.ts:789 + "notice.provider.unavailableCfgFallback": "provider.list 不可用({attemptCount} 次尝试后回退到 {keyCount} 个 cfg.provider 配置键):{exc}", + // src/index.ts:814 (alert) + "notice.provider.probeNewProvider": "provider.list 后台探测:有新的 provider 连接({providers})— 请重启 opencode 以完成 shell 注册", + // src/index.ts:832 (alert) + "notice.provider.probeModelDrift": "provider.list 后台探测:模型列表已变动({drift})— 超集清单已重建,/modelRank //poolConfig 列表已更新{restartHint}", + // src/index.ts:834 + "notice.provider.probeRebuildFailed": "provider.list 后台探测:超集清单重建失败(保留原清单):{exc}", + // src/index.ts:886 + "notice.probe.warmupFailOpen": "预热 fail-open:{exc}", + // src/index.ts:900 + "notice.skills.synced": "skills 已同步:安装 {installedCount} 个、更新 {updatedCount} 个、移除 {removedCount} 个({skillNames})", + // src/index.ts:903 + "notice.skills.syncFailOpen": "skill 同步 fail-open:{exc}", + // src/index.ts:1145 + "notice.banner.failOpen": "banner fail-open:{exc}", + // src/index.ts:1241 + "notice.ctx.readBudgetContinuation": "读取预算续读完成(文件 {fileName},自 {offset} 起再读 +{granted} 行,回合 {turnUsed}/{turnBudget})", + // src/index.ts:1251 + "notice.ctx.readBudgetGateCap": "读取预算闸门上限(tool read,文件 {fileName},估计 ~{totalTokens} -> 上限 {suggestedLimit},回合 {turnUsed}/{turnBudget})", + // src/index.ts:1277 (template built at src/index.ts:1259 as denyLog) + "notice.ctx.readBudgetGate": "读取预算闸门 {action}(工具 {tool},估计 ~{totalTokens}{contRem},C~{wmTokens},T_est≈{turnsToHard},回合 {turnUsed}/{turnBudget})", + // src/index.ts:1281 + "notice.ctx.readBudgetGateFailOpen": "读取预算闸门 fail-open(放行):{exc}", + // src/index.ts:1306 + "notice.image.readGuardDenied": "图片读取防护:模型 {modelKey} 无视觉输入;拒绝读取 {fileName}(会话 {sid})", + // src/index.ts:1310 + "notice.image.readGuardFailOpen": "图片读取防护 fail-open(放行):{exc}", + // src/index.ts:1358 + "notice.doctor.summary": "doctor 发现 {errorCount} 个错误 / {warnCount} 个警告;运行 /switchman-doctor 查看", + // src/index.ts:1393 + "notice.injection.legacyStaticMatrix": "已注入 {shellCount} 个模型 shell(agents,旧版静态矩阵)", + // src/index.ts:1412 + "notice.provider.cacheUsed": "provider.list 使用跨重启缓存({providerCount} 个 provider,缓存于 {cachedAt});正在后台验证新增项", + // src/index.ts:1419 + "notice.provider.cacheStale": "provider.list 缓存已过期(缓存于 {cachedAt}),构建超集前先实时探测", + // src/index.ts:1469 + "notice.matrix.recomputed": "激活矩阵已重算(gen={generation},活跃 shell {activeShellCount} 个,探测 {source}×{targetCount})", + // src/index.ts:1474 + "notice.injection.shellCount": "已注入 {shellCount} 个 shell(mode={runMode},注入面={injectionMode} 精选后 {fullSupersetCount}→{faceCount},冲突 {conflictCount};激活闸控生效中)", + // src/index.ts:1479 + "notice.injection.configHookFailOpen": "config hook fail-open:{exc}", + // src/index.ts:1541 + "notice.lang.askLocale": "lang ask locale={locale}({source})", + // src/index.ts:1604 + "notice.banner.rulesFailOpen": "rules/banner fail-open:{exc}", + // src/index.ts:1677 + "notice.relay.persisted": "图片中继:模型 {modelKey} 无视觉输入;已将 {written} 张图片写入磁盘({relayed} 个图片分段经会话历史中继,会话 {sid})", + // src/index.ts:1679 + "notice.relay.failOpen": "图片中继 fail-open(直接放行):{exc}", + // src/index.ts:1694 + "notice.ctx.capToolDenied": "子代理 context 上限:已在已终止的会话 {sid} 中拒绝工具 '{tool}'", + // src/index.ts:1701 + "notice.ctx.capResumeDenied": "子代理 context 上限:拒绝恢复已终止的会话 ses_{taskId}(永久性)", + // src/index.ts:1727 + "notice.lang.gateDenied": "语言闸门:已在未配置项目的会话 {sid} 中拒绝工具 '{tool}'", + // src/index.ts:1751 + "notice.search.clarifyFailOpen": "搜索澄清闸门:连续 {maxDenies} 次拒绝且未提问后 fail-open — 会话 {sid} 闸门打开", + // src/index.ts:1754 + "notice.search.clarifyDenied": "搜索澄清闸门:已在会话 {sid} 中拒绝工具 '{tool}'(搜索范围过广,先提问)({denyCount}/{maxDenies})", + // src/index.ts:1774 + "notice.dispatch.offUngoverned": "dispatch 关闭:任务调用放行、不受治理(subagent_type='{subagentType}')", + // src/index.ts:1853 + "notice.dispatch.redirectUninjected": "自动转向 {agent} → {candidate}(shell 未注入;已转向链首候选)", + // src/index.ts:1874 + "notice.dispatch.redirectBuiltinBlocked": "自动转向 {agent} → {candidate}(内置 agent 已拦截)", + // src/index.ts:1883 (via src/gates.ts:331 noteUnknownAgent) + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] 未知 subagent_type='{agent}':放行(不在 shell 列表中;内置 agent 不受路由治理)", + // src/index.ts:1889 (r.note via src/gates.ts:156) + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled 但矩阵 status={matrixStatus}(非 down):fail-open,下次探测刷新后自动修正", + // src/index.ts:1889 (r.note via src/gates.ts:175) + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} 矩阵 status={matrixStatus}(非 down):未拦截,探测将在下一轮刷新", + // src/index.ts:1889 (r.note via src/gates.ts:63 ROUTE_META_SYNTH_NOTE) + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META 缺失/格式错误 — 已由 lane 合成;声明它以启用 review 跨家族 / source=user 语义", + // src/index.ts:1889 (r.note via src/gates.ts:240 REVIEW_SELF_REVIEW_NOTE) + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED:无跨家族审查者可用 — 允许同家族自审;请在审查结论中声明 DOWNGRADED", + // src/index.ts:1889 (r.note via src/gates.ts:288 poolOverrideNote) + "notice.dispatch.poolOverrideNote": "pool 配置覆盖:已明确选入此任务池(免除能力层级 floor 限制)", + // src/index.ts:1897 + "notice.dispatch.redirectDenied": "自动转向 {agent} → {redirect}({deny})", + // src/index.ts:1910 + "notice.dispatch.gatesFailOpen": "六道闸门 fail-open(放行):{exc}", + // src/index.ts:1934 + "notice.lang.prefsSaved": "项目语言偏好已保存({rel}):conversation={conversation} comments={comments} docs={docs}", + // src/index.ts:1937 + "notice.lang.gateWaived": "语言闸门:标记提问已完成但未保存配置 — 会话 {sid} 免除闸门", + // src/index.ts:1943 + "notice.search.scopeAskDone": "搜索澄清:范围提问已完成 — 会话 {sid} 闸门打开", + // src/index.ts:1956 + "notice.ctx.readBudgetCharge": "读取预算计费 +{charge}(工具 {tool},回合 {turnUsed}/{turnBudget})", + // src/index.ts:1970 + "notice.handover.autoTriggered": "自动交接已触发({tool} 之后,~{wmTokens} 超过强制压缩 watermark):完整备份 + 将当前会话的压缩排入队列", + // src/index.ts:1981 + "notice.handover.backupResult": "自动交接备份 {outcome}:{message}", + // src/index.ts:1996 (variant 1 of 3) + "notice.handover.compactionAccepted": "自动交接压缩已接受:session.summarize 已返回(压缩在会话循环上执行)", + // src/index.ts:1996 (variant 2 of 3) + "notice.handover.compactionRejected": "自动交接压缩失败:session.summarize 已拒绝(备份仍然有效)", + // src/index.ts:1996 (variant 3 of 3) + "notice.handover.compactionNoModel": "自动交接压缩失败:未记录会话模型(chat.params 从未触发);备份仍然有效", + // src/index.ts:2008 + "notice.handover.failOpen": "自动交接 fail-open:{exc}", + // src/index.ts:2114 + "notice.ctx.capTerminated": "子代理 context 上限:会话 {sid}{agentSuffix} 已达 ~{estTokens}k tokens(上限 {capTokens}k)— 工具已拒绝、已要求进度摘要、会话已终止(不得以 task_id 恢复)", + // src/index.ts:2205 + "notice.provider.modelRetired": "模型已退役(连续 404),已从候选中移除:{provider}/{modelId}", + // src/index.ts:2208 + "notice.breaker.agentTripped": "{agent} 断路器跳闸(600 秒):{reason}", + // src/index.ts:2210 + "notice.breaker.accountingFailOpen": "失败计数 fail-open:{exc}", + // src/lane.ts:410 + "notice.lane.scoringFallback": "评分失败,回退到规则排序:{exc}", + // src/lane.ts:494 + "notice.lane.backfillFailed": "回填排名失败(lane 保持为空):{exc}", + // src/matrix-manager.ts:196 + "notice.matrix.favoritesScanNoChange": "已扫描收藏/可见集合:激活状态不变(gen={generation};不重算、不重新探测)", + // src/matrix-manager.ts:204 + "notice.matrix.invalidModels": "可见集合/收藏包含无效模型(provider 存在但无此 modelId,未生成 shell):{modelList}", + // src/matrix-manager.ts:217 + "notice.matrix.persistFailOpen": "激活矩阵持久化 fail-open:{exc}", + // src/matrix-manager.ts:222 + "notice.matrix.callbackFailOpen": "激活矩阵回调 fail-open:{exc}", + // src/matrix-manager.ts:250 + "notice.matrix.configReadFailOpen": "配置界面读取 fail-open(视为空):{exc}", + // src/matrix-manager.ts:272 + "notice.matrix.watchError": "fs.watch({dir}) 出错,回退 mtime 轮询:{exc}", + // src/matrix-manager.ts:277 + "notice.matrix.watchStartFailed": "fs.watch({dir}) 启动失败,回退 mtime 轮询:{exc}", + // src/matrix-manager.ts:308 + "notice.matrix.recomputeFailOpen": "重算 fail-open:{exc}", + // src/probe.ts:144 + "notice.probe.failOpen": "探测 fail-open:{exc}", + // src/probe.ts:162 + "notice.probe.incrementalFailOpen": "增量探测 fail-open:{exc}", + // src/probe.ts:201 + "notice.probe.copilotPoolExhausted": "Copilot 月度额度池已用尽(网关为第二数据源),reset_date 前视为可信", + // src/probe.ts:207 + "notice.probe.resultsDiscarded": "探测结果已丢弃(矩阵 generation 已变更 {oldGen}->{newGen};由新 generation 的重算重新调度)", + // src/probe.ts:214 + "notice.probe.matrixRefreshed": "矩阵已刷新:{comboCount} 个组合中 {okCount} 个成功(共 {totalCount})", + // src/probe.ts:233 + "notice.probe.schedulingFailOpen": "探测调度 fail-open:{exc}", + // src/scoring.ts:399 + "notice.scoring.decisionLogFailOpen": "决策记录 fail-open:{exc}", + // src/selfupdate.ts:122 + "notice.selfupdate.checkFailOpen": "自更新检查 fail-open:{exc}", + // src/selfupdate.ts:255 + "notice.selfupdate.upgradeAssetsFailOpen": "upgrade 命令资产 fail-open:{exc}", + // src/tmux.ts:149 (via log callback wired to appendStatusLog at src/index.ts:236) + "notice.dispatch.mirrorDisabled": "tmux 面板镜像已禁用(初始化失败):{message}", + // src/tmux.ts:221 + "notice.dispatch.mirrorOpFailed": "tmux 面板镜像操作失败(继续执行):{message}", + // src/tmux.ts:230 + "notice.dispatch.mirrorPaneFull": "tmux 面板镜像:列已满({slotCount} 个面板),ses_{sessionId}({agent})已排队", + // src/tmux.ts:280 + "notice.dispatch.mirrorAllClosed": "tmux 面板镜像:所有子代理面板已关闭,主面板已恢复", + // src/tmux.ts:290 + "notice.dispatch.mirrorDisplayed": "tmux 面板镜像:ses_{sessionId}({agent})显示于面板 {pane}", + // src/tmux.ts:303 + "notice.dispatch.mirrorReconciling": "tmux 面板镜像:检测到已关闭的面板,正在重新校准布局", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "需要先完成设置({missing})— 请运行 /switchman-setup(或 /switchman-setup-chat);配置完成前派发被阻止", + + // ---- sidebar (tui.tsx sidebar chrome) ---- + // [2026-09-19]-[sidebar.restartHintPattern (the old RESTART_HINT_RE regex) deliberately NOT a message key: the + // structured alert flag on status-log entries replaces regex highlighting; keys are translatable prose only] + + // src/tui.tsx:308 + "sidebar.peakTag": " ·峰值", + // src/tui.tsx:309 + "sidebar.staleTag": " ·过期", + // src/tui.tsx:310 + "sidebar.observeOnlyTag": " ·仅观察", + // src/tui.tsx:346 + "sidebar.updateAvailable": " → {updateVersion}", + // src/tui.tsx:351 + "sidebar.restartNeeded": " [需重启]", + // src/tui.tsx:358 + "sidebar.noneAvailable": "无可用项", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "经济", + "sidebar.lane.mechanical": "机械", + "sidebar.lane.main": "主力", + "sidebar.lane.hard": "困难", + "sidebar.lane.vision": "视觉", + "sidebar.lane.review": "评审", + // src/tui.tsx:368 + "sidebar.noticeLabel": "通知", + + // ---- dialogs (tui.tsx: pool picker / pool models / rank / handover) ---- + + // src/tui.tsx:426 (pool picker title) + "dialog.pool.title": "任务池(选择一个任务池;按 Esc 退出)", + // src/tui.tsx:428 (pool picker lane row) + "dialog.pool.laneRow": "{pinMark}{lane}", + // src/tui.tsx:431 (pool picker option description) + "dialog.pool.manualSelection": "手动选择:{selCount}/{totalCount} 个模型参与", + // src/tui.tsx:432 (pool picker option description) + "dialog.pool.notConfigured": "未配置:系统默认(所有可用模型均参与)", + // src/tui.tsx:453 (pool models dialog, toggle persist) + "dialog.pool.toggleWriteFailed": "写入失败:{message}", + // src/tui.tsx:458 (pool models dialog, toggle toast) + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} {lane} 任务池(立即生效,侧边栏刷新)", + // src/tui.tsx:469 (pool models dialog, min-selection guard toast) + "dialog.pool.keepOneModel": "至少保留一个参与模型;使用“清除配置”可恢复系统默认", + // src/tui.tsx:482 (pool models dialog, bulk select-all persist) + "dialog.pool.bulkWriteFailed": "写入失败:{message}", + // src/tui.tsx:485 (pool models dialog, bulk toast) + "dialog.pool.allSelected": "{lane} 任务池:已选择所有模型", + // src/tui.tsx:490 (pool models dialog, clear-config toast) + "dialog.pool.configCleared": "{lane} 任务池配置已清除(已恢复系统默认候选集)", + // src/tui.tsx:499 (pool models dialog, uncheck-all toast) + "dialog.pool.allUnchecked": "{lane} 任务池:已全部取消勾选 — 请勾选要保留的模型;全部未勾选时退出将保持原选择", + // src/tui.tsx:503 (pool models dialog option) + "dialog.pool.back": "← 返回任务池列表", + // src/tui.tsx:504 (pool models dialog option) + "dialog.pool.selectAll": "☑ 全选", + // src/tui.tsx:505 (pool models dialog option) + "dialog.pool.uncheckAll": "☐ 全部取消勾选(之后勾选少数要保留的;全部未勾选时退出将保留原列表)", + // src/tui.tsx:506 (pool models dialog option) + "dialog.pool.clearConfig": "✕ 清除配置(系统默认:所有可用模型均参与)", + // src/tui.tsx:508 (pool models dialog model row) + "dialog.pool.modelRow": "{checkMark} {modelId}", + // src/tui.tsx:510 (pool models dialog row description) + "dialog.pool.rowMeta": "{tier} 级{manualSuffix}", + // src/tui.tsx:516 (pool models dialog title) + "dialog.pool.selectionTitle": "{lane} 任务池选择({selCount}/{rowCount} 个参与;点击切换,允许跨池重复)", + // src/tui.tsx:538 (rank universe-empty dialog option) + "dialog.rank.openPoolSelection": "→ 打开任务池选择(先挑选各任务池可用的模型,再进行排名)", + // src/tui.tsx:539 (rank universe-empty dialog option) + "dialog.rank.close": "✕ 关闭", + // src/tui.tsx:543 (rank universe-empty dialog title) + "dialog.rank.universeEmptyTitle": "配置任务池之前模型排名不可用 — 只有被选入任务池的模型才能排名,绝不会为无法派发的模型排名", + // src/tui.tsx:561 (rank move at edge toast) + "dialog.rank.alreadyAtEdge": "{modelName} 已位于合并能力列表的{edge}端", + // src/tui.tsx:568 (rank move persist) + "dialog.rank.moveWriteFailed": "写入失败:{message}", + // src/tui.tsx:573 (rank move/pin toast) + "dialog.rank.pinnedOrMoved": "{verb} {modelName} 至 #{position}(手动分数 {tier}/{raw},锚定于相邻模型之间;立即生效,侧边栏刷新)", + // src/tui.tsx:627 (rank picker title) + "dialog.rank.title": "模型能力排名 — 合并顺序(#1 最强;范围限任务池选择;手动条目与基础分数模型交错排列;ctrl+up/ctrl+down 移动一位;enter = 单模型操作)", + // src/tui.tsx:628 (rank picker placeholder) + "dialog.rank.searchHint": "搜索 · alt+up/alt+down 与 ctrl+up/ctrl+down 等效(同样可用)", + // src/tui.tsx:630 (rank picker row) + "dialog.rank.row": "#{rankPadded} {modelId}", + // src/tui.tsx:632 (rank picker row description) + "dialog.rank.rowMeta": "{tier} 级 · {scoreSource}{poolSuffix}", + // src/tui.tsx:662 (rank actions, remove persist) + "dialog.rank.removeWriteFailed": "写入失败:{message}", + // src/tui.tsx:665 (rank actions, remove toast) + "dialog.rank.removed": "已将 {model} 从手动排名中移除(回退到基础能力分数,立即生效,侧边栏刷新)", + // src/tui.tsx:669 (rank actions option) + "dialog.rank.pinTop": "▲ 置顶(高于所有模型)", + // src/tui.tsx:670 (rank actions option) + "dialog.rank.moveUp": "↑ 上移一位(与上方模型交换;将手动分数锚定于相邻模型之间)", + // src/tui.tsx:671 (rank actions option) + "dialog.rank.moveDown": "↓ 下移一位(与下方模型交换)", + // src/tui.tsx:673 (rank actions option) + "dialog.rank.remove": "✕ 从排名中移除(回退到基础分数)", + // src/tui.tsx:675 (rank actions option) + "dialog.rank.back": "← 返回排名列表", + // src/tui.tsx:680 (rank actions title) + "dialog.rank.detailTitle": "{model}({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "switchman 设置 — 任务池与能力排名", + "dialog.setup.intro": "引导式设置:为 6 个任务池分别挑选模型,然后进行排名(最强在前)。随时按 Esc 退出;已确认的任务池会立即保存。", + "dialog.setup.start": "开始(第一个未完成的步骤)", + "dialog.setup.statePools": "已配置任务池:{count}/6", + "dialog.setup.stateRank": "排名:{state}", + "dialog.setup.laneTitle": "任务池 {index}/6 — {lane}(已选 {count} 个;按 Enter 切换,至少 1 个)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] 全选", + "dialog.setup.clearAll": "[ ] 全部取消勾选", + "dialog.setup.confirmLane": "确认 {lane}({count} 个模型)并继续", + "dialog.setup.back": "返回", + "dialog.setup.keepOne": "此任务池至少保留一个模型", + "dialog.setup.rankTitle": "能力排名 — 选择第 {n} 名(最强在前,还剩 {remaining} 个模型)", + "dialog.setup.rankFinish": "完成排名(已选 {count} 个;其余模型保留系统基础分数)", + "dialog.setup.rankMinOne": "完成前请至少排名一个模型", + "dialog.setup.doneTitle": "设置完成 — 立即生效(热重载)", + "dialog.setup.donePools": "任务池:{summary}", + "dialog.setup.doneRank": "排名:{order}", + "dialog.setup.restartHint": "请重启 opencode 以注册新的提供商:{providers}", + // src/tui.tsx:734 (handover toast) + "dialog.handover.noSession": "/handover:不在会话中,没有可备份的内容", + // src/tui.tsx:739 (handover toast) + "dialog.handover.inProgress": "/handover:正在完整备份当前会话并压缩…", + // src/tui.tsx:744 (handover toast) + "dialog.handover.resultStay": "{resultMessage};仍在原会话,未切换", + // src/tui.tsx:747 (handover toast) + "dialog.handover.result": "/handover {resultMessage}", + + // ---- palette (command palette entries) ---- + + // src/tui.tsx:770 + "palette.handover.title": "备份并压缩当前会话", + // src/tui.tsx:771 + "palette.handover.desc": "完整分叉(fork)当前会话作为备份(标题附加 [backup] 标签),并对当前会话进行压缩;不切换会话(有别于内置 /fork)", + // src/tui.tsx:772 (palette category label) + "palette.category.label": "switchman", + // src/tui.tsx:779 + "palette.poolConfig.title": "任务池选择", + // src/tui.tsx:780 + "palette.poolConfig.desc": "为每个任务池挑选参与的模型(economy/mechanical/main/hard/vision/review)", + // src/tui.tsx:788 + "palette.modelRank.title": "模型能力排名", + // src/tui.tsx:789 + "palette.modelRank.desc": "手动能力排名(优先于基础分数;越靠前 = 越强)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "引导式设置(任务池 + 排名)", + "palette.setup.desc": "向导:为每个任务池多选模型,然后排名 — 派发正常工作前必须完成", + + // ---- quota (quota-brief.json rows; banner.ts builders) ---- + + // src/banner.ts:142 (POOL_LABEL) + "quota.poolGlm": "GLM", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolCopilot": "Copilot", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolDeepSeek": "DeepSeek", + // src/banner.ts:166 + "quota.queryingNoData": "查询中/无数据", + // src/banner.ts:173 + "quota.resetLater": "→稍后", + // src/banner.ts:173 + "quota.resetTime": "→{hhmm}", + // src/banner.ts:173 + "quota.resetDate": "→{mmdd}", + // src/banner.ts:173 + "quota.resetDateTime": "→{mmdd} {hhmm}", + // src/banner.ts:174 + "quota.barPct": "{bar8} {pct}%", + // src/banner.ts:177 (row label) + "quota.row5h": "5h", + // src/banner.ts:178 (row label) + "quota.rowWeek": "周", + // src/banner.ts:180 (row label) + "quota.rowMcp": "MCP", + // src/banner.ts:181 + "quota.noData": "无额度数据", + // src/banner.ts:187 (row label) + "quota.rowRefresh": "刷新", + // src/banner.ts:188 (row label) + "quota.rowCredits": "积分", + // src/banner.ts:188 + "quota.monthlyExhausted": "月度额度已用尽", + // src/banner.ts:193 + "quota.unlimited": "无上限{usedSuffix}", + // src/banner.ts:199 + "quota.exhaustedOverage": "已用尽·超额计费{usage}", + // src/banner.ts:202 + "quota.barPctLeft": "{bar8} 剩余 {pctTxt}%{usage}", + // src/banner.ts:207 (row label) + "quota.rowBalance": "余额", + // src/banner.ts:207 + "quota.exhausted": "已用尽", + // src/banner.ts:209 + "quota.unknownPayg": "未知(按量付费)", + // src/banner.ts:213 + "quota.barBalance": "{bar8} ¥{balance}", + // src/banner.ts:213 + "quota.balanceWarn": "(<¥{thr} 警告)", + + // ---- cli (switchman-config / switchman-doctor) ---- + + // src/config-cli.ts:67 (fmtRow, printed at :87) + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId}({tier} 级{manualTag})", + // src/config-cli.ts:73 (thrown, surfaced via console.error at :267) + "cli.config.unknownPool": "未知任务池:{lane}(六个任务池:{laneList})", + // src/config-cli.ts:81 (head, printed at :85/:90) + "cli.config.poolHeader": "任务池选择(配置文件 {poolConfigPath};选择 = 加入该任务池的模型;同一模型可加入多个任务池;未配置的任务池采用系统默认决策)", + // src/config-cli.ts:86 + "cli.config.poolSection": "== {lane} ==({selection})", + // src/config-cli.ts:93 + "cli.config.poolSectionBrief": "== {lane} =={detail}", + // src/config-cli.ts:95 + "cli.config.poolListHint": "(查看单个任务池带编号的完整列表:pool list <{laneList}>)", + // src/config-cli.ts:105 (thrown, surfaced via console.error at :267) + "cli.config.indexOutOfRange": "索引超出范围 #{index}(列表共 {rowCount} 项)", + // src/config-cli.ts:110 (thrown, surfaced via console.error at :267) + "cli.config.invalidModel": "无效的模型名称:{model}", + // src/config-cli.ts:124 (thrown, surfaced via console.error at :267) + "cli.config.noManifest": "没有可用的模型清单(请检查 provider 连接与超集清单)", + // src/config-cli.ts:129 (thrown, surfaced via console.error at :267) + "cli.config.poolRequiresArg": "pool {sub} 需要索引或模型名称", + // src/config-cli.ts:138 + "cli.config.poolSelectionCleared": "{lane} 任务池选择已清除(回到系统默认候选集,立即生效,侧边栏同步刷新)", + // src/config-cli.ts:139 + "cli.config.poolUpdated": "已更新 {lane} 任务池选择({modelCount} 个模型参与,立即生效,侧边栏同步刷新)", + // src/config-cli.ts:145 + "cli.config.poolConfigCleared": "已清除 {lane} 任务池选择配置(该任务池回到系统默认候选集,立即生效,侧边栏同步刷新)", + // src/config-cli.ts:148 (thrown, surfaced via console.error at :267) + "cli.config.unknownPoolSub": "未知子命令 pool {sub}(list/add/remove/set/clear)", + // src/config-cli.ts:186 + "cli.config.rankDisabledUntilPools": "配置任务池之前,手动能力排名(配置文件 {capabilityRankPath})处于禁用状态:只有被选入任务池的模型才能排名。", + // src/config-cli.ts:187 + "cli.config.rankHowTo": "请先在此运行 /poolConfig(TUI 对话框)或 pool set <task-pool> <index|model...>,再只为实际使用的模型排名。", + // src/config-cli.ts:190 + "cli.config.legacyHeader": "== 旧版手动条目(仅用于清理;rank remove/clear 仍可用,或将模型选入任务池以排名)==", + // src/config-cli.ts:191 + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + // src/config-cli.ts:197 + "cli.config.rankHeader": "模型能力排名(配置文件 {capabilityRankPath};范围限通过 /poolConfig 选入任务池的 {universeCount} 个模型 — 单一合并排序,手动条目按有效分数与基础分数模型交错排列;越靠上 = 越强)", + // src/config-cli.ts:198 + "cli.config.mergedHeader": "== 合并排序({manualCount} 个手动{manualSuffix};CLI set/add 按旧版阶梯为条目排序,TUI 将锚定分数移至相邻模型之间)==", + // src/config-cli.ts:201 + "cli.config.manualTag": "·手动{score}", + // src/config-cli.ts:203 + "cli.config.notInPoolTag": "·未加入任何任务池", + // src/config-cli.ts:204 + "cli.config.rankRow": "#{rankPadded} {modelId}({tier} 级{manualTag}{poolTag})", + // src/config-cli.ts:210 (thrown, surfaced via console.error at :267) + "cli.config.rankNoPools": "尚未进行任务池选择 — 排名遵循任务池选择;请先运行 /poolConfig(或 pool set)", + // src/config-cli.ts:212 (thrown, surfaced via console.error at :267) + "cli.config.rankRequiresArg": "rank {sub} 需要索引或模型名称", + // src/config-cli.ts:237 + "cli.config.rankUpdated": "已更新手动能力排名({modelCount} 个模型,立即生效,侧边栏同步刷新)", + // src/config-cli.ts:242 + "cli.config.rankCleared": "已清除手动能力排名(全部回退到基础能力分数,立即生效,侧边栏同步刷新)", + // src/config-cli.ts:245 (thrown, surfaced via console.error at :267) + "cli.config.unknownRankSub": "未知子命令 rank {sub}(list/set/add/remove/clear)", + // src/config-cli.ts:254 + "cli.config.usage": "用法:switchman-config <pool|rank> ...", + // src/config-cli.ts:255 + "cli.config.usagePoolList": " pool list [task-pool] 任务池选择概览(economy/mechanical/main/hard/vision/review;带池名 = 显示带索引的完整列表)", + // src/config-cli.ts:256 + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> 勾选加入该任务池的模型", + // src/config-cli.ts:257 + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> 取消勾选参与", + // src/config-cli.ts:258 + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> 完全替换该任务池的参与列表(同一模型可加入多个任务池)", + // src/config-cli.ts:259 + "cli.config.usagePoolClear": " pool clear <task-pool> 清除该任务池的配置(回到系统默认候选集)", + // src/config-cli.ts:260 + "cli.config.usageRankList": " rank list 查看手动能力排名(范围限任务池选择;未配置任务池时引导至 /poolConfig)", + // src/config-cli.ts:261 + "cli.config.usageRankSet": " rank set <index|model...> 完全重排(按给定顺序,#1 最强;仅限已选入任务池的模型)", + // src/config-cli.ts:262 + "cli.config.usageRankAdd": " rank add <index|model...> 追加到排名末尾(仅限已选入任务池的模型)", + // src/config-cli.ts:263 + "cli.config.usageRankRemove": " rank remove <index|model...> 从排名中移除", + // src/config-cli.ts:264 + "cli.config.usageRankClear": " rank clear 清除排名(回退到基础能力分数)", + // src/config-cli.ts:267 + "cli.config.errorPrefix": "switchman-config: {message}", + // src/doctor-cli.ts:5 + "cli.doctor.usage": "用法:switchman-doctor 检查 opencode-switchman 配置;通过 OPENCODE_CONFIG_DIR 环境变量选择配置目录;退出码 0=无问题、1=警告、2=错误", + // src/doctor.ts:56 (SWM060 hint) + "cli.doctor.unknownModelsHint": "{unknownCount} 个模型未被已知系统匹配(未知分组,按系数排到最后)", + // src/doctor.ts:58 (SWM062 hint) + "cli.doctor.approxModelsHint": "{approxCount} 个模型按前缀/家族近似分类", + // src/doctor.ts:72 (SWM044 hint) + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + // src/doctor.ts:87 + "cli.doctor.noIssues": "opencode-switchman doctor:未发现问题", + // src/doctor.ts:89 + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/locales/zh-TW.ts b/src/locales/zh-TW.ts new file mode 100644 index 0000000..9e19c5f --- /dev/null +++ b/src/locales/zh-TW.ts @@ -0,0 +1,527 @@ +// [2026-09-19]-[Traditional Chinese message catalog: full-coverage translation of src/locales/en.ts; +// key completeness and {param} parity are enforced by test/i18n.test.ts] +import type { MsgKey } from "../i18n" + +export const zhTW: Partial<Record<MsgKey, string>> = { + // ---- notices (status log; appendStatusLog) ---- + + // src/breaker.ts:37 + "notice.breaker.realCallIsolated": "{agent} 實際呼叫已隔離 {mins} 分鐘({category}):{reason}", + // src/breaker.ts:48 + "notice.breaker.shellNotInjected": "shell 未注入 opencode(無隔離):{agent} {reason}", + // src/breaker.ts:200 + "notice.breaker.failOpen": "斷路器 fail-open:{exc}", + // src/capability.ts:246 + "notice.capability.snapshotCorrupted": "內建能力排名快照損毀(略過,改用精選表)", + // src/capability.ts:299 + "notice.capability.primarySourceFailed": "能力索引主來源 AA 失敗({exc}){nextStep}", + // src/capability.ts:311 + "notice.capability.backupSourceFailed": "能力索引備援來源 OpenRouter 失敗({exc})-> 保留最近可用/內建預設排名", + // src/capability.ts:316 + "notice.capability.parsedEmpty": "能力索引解析結果為空({source})-> 保留最近可用/內建預設排名", + // src/capability.ts:333 + "notice.capability.refreshed": "能力索引已重新整理:{source} 共 {modelCount} 個模型(version={version})", + // src/capability.ts:336 + "notice.capability.refreshFailOpen": "能力索引重新整理 fail-open(保留最近可用/內建預設排名):{exc}", + // src/capability.ts:372 + "notice.capability.lmarenaDisagreement": "能力 LMArena 交叉檢核:層級排序與 ELO 排序一致率僅 {rate}%(重疊 {overlapCount} 個模型)-- 資料來源可能異常,建議人工檢查", + // src/capability.ts:375 + "notice.capability.lmarenaFailOpen": "能力 LMArena 交叉檢核 fail-open(已略過):{exc}", + // src/catalog.ts:153 + "notice.catalog.unavailableNoCache": "models.dev 目錄無法使用且無快取(fail-open 降級):{exc}", + // src/copilot-thinking.ts:71 + "notice.copilot.shapeCacheRefreshed": "Copilot 思考參數 shape 快取已重新整理:{modelCount} 個模型", + // src/copilot-thinking.ts:73 + "notice.copilot.shapeRefreshFailOpen": "Copilot 思考參數 shape 重新整理 fail-open:{exc}", + // src/cost.ts:44 + "notice.cost.refreshFailed": "成本快照重新整理失敗(保留過期資料):{exc}", + // src/dispatch-mode.ts:60 (log callback defaults to appendStatusLog) + "notice.lang.settingsInvalidJson": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} 不是有效的 JSON — 已忽略(語言設定退回 AGENTS.md 標記;\"dispatch\":\"off\" 未套用)", + // src/dispatch-mode.ts:66 (log callback defaults to appendStatusLog) + "notice.lang.dispatchNotOff": "[opencode-switchman] {workspaceDirname}/{langSettingsFile} 有 \"dispatch\" 但值不是精確的 \"off\"(實際值:{rawValue})— 已忽略,維持 fleet 行為", + // src/index.ts:262 + "notice.ctx.paused": "工作階段 {sid} 的 ctx 控制已暫停(/ctx-pause):讀取閘門 + 自我讀取預算 + 自動交接均已暫停;用量量測持續進行", + // src/index.ts:264 + "notice.ctx.resumed": "工作階段 {sid} 的 ctx 控制已恢復(/ctx-resume):讀取閘門 + 自動交接重新生效", + // src/index.ts:467 + "notice.workspace.created": "產物工作區已建立:{rel}", + // src/index.ts:468 + "notice.workspace.renamed": "產物工作區已重新命名:{oldRel} → {rel}", + // src/index.ts:542 + "notice.dispatch.mirrorResumeReuse": "tmux 窗格鏡射:恢復派發 ses_{taskId}({shellName})— task_id 重複使用,直接開啟窗格(不會觸發 session.created)", + // src/index.ts:546 + "notice.dispatch.mirrorResumeLookupFailed": "tmux 窗格鏡射:恢復派發 ses_{taskId}({shellName})— 查找工作階段失敗,fail-open 改開一般窗格", + // src/index.ts:574 + "notice.capability.selectionChanged": "能力排名/任務池選擇已變更:banner 與側邊欄立即重新整理", + // src/index.ts:589 + "notice.capability.overrideWatchError": "fs.watch({dir}) 覆寫設定監看錯誤(退回 mtime 輪詢):{exc}", + // src/index.ts:647 + "notice.matrix.configSurfaceFailOpen": "設定介面讀取 fail-open:{exc}", + // src/index.ts:675 + "notice.matrix.floorFreeModels": "floor = {floorCount} 個 OpenCode Zen 免費模型(catalog {catalogStatus})", + // src/index.ts:676 + "notice.matrix.floorFallback": "floor 退回靜態資訊清單(catalog {catalogStatus},0 個免費模型)", + // src/index.ts:680 + "notice.matrix.invalidModelsUnknownProvider": "可見集合/最愛包含提供者未知的無效模型(provider 未連線;已忽略,未建立 shell):{modelList}", + // src/index.ts:778 + "notice.provider.probeAttemptSucceeded": "provider.list 第 {attempt} 次嘗試成功(前 {prevAttempts} 次尚未就緒)", + // src/index.ts:783 + "notice.provider.probeAttemptBackoff": "provider.list 第 {attempt} 次嘗試尚未就緒,退避中:{exc}", + // src/index.ts:789 + "notice.provider.unavailableCfgFallback": "provider.list 無法使用({attemptCount} 次嘗試後退回 {keyCount} 個 cfg.provider 設定鍵):{exc}", + // src/index.ts:814 (alert) + "notice.provider.probeNewProvider": "provider.list 背景探測:有新的 provider 連上({providers})— 請重新啟動 opencode 以完成 shell 註冊", + // src/index.ts:832 (alert) + "notice.provider.probeModelDrift": "provider.list 背景探測:模型清單已變動({drift})— 超集資訊清單已重建,/modelRank //poolConfig 清單已更新{restartHint}", + // src/index.ts:834 + "notice.provider.probeRebuildFailed": "provider.list 背景探測:超集資訊清單重建失敗(保留原資訊清單):{exc}", + // src/index.ts:886 + "notice.probe.warmupFailOpen": "預熱 fail-open:{exc}", + // src/index.ts:900 + "notice.skills.synced": "skills 已同步:已安裝 {installedCount} 個、已更新 {updatedCount} 個、已移除 {removedCount} 個({skillNames})", + // src/index.ts:903 + "notice.skills.syncFailOpen": "skill 同步 fail-open:{exc}", + // src/index.ts:1145 + "notice.banner.failOpen": "banner fail-open:{exc}", + // src/index.ts:1241 + "notice.ctx.readBudgetContinuation": "讀取預算續讀完成(檔案 {fileName},自 {offset} 起再 +{granted} 行,回合 {turnUsed}/{turnBudget})", + // src/index.ts:1251 + "notice.ctx.readBudgetGateCap": "讀取預算閘門上限(tool read,檔案 {fileName},估計 ~{totalTokens} -> 上限 {suggestedLimit},回合 {turnUsed}/{turnBudget})", + // src/index.ts:1277 (template built at src/index.ts:1259 as denyLog) + "notice.ctx.readBudgetGate": "讀取預算閘門 {action}(工具 {tool},估計 ~{totalTokens}{contRem},C~{wmTokens},T_est≈{turnsToHard},回合 {turnUsed}/{turnBudget})", + // src/index.ts:1281 + "notice.ctx.readBudgetGateFailOpen": "讀取預算閘門 fail-open(放行):{exc}", + // src/index.ts:1306 + "notice.image.readGuardDenied": "圖片讀取防護:模型 {modelKey} 不支援視覺輸入;拒絕讀取 {fileName}(工作階段 {sid})", + // src/index.ts:1310 + "notice.image.readGuardFailOpen": "圖片讀取防護 fail-open(放行):{exc}", + // src/index.ts:1358 + "notice.doctor.summary": "doctor 發現 {errorCount} 個錯誤 / {warnCount} 個警告;執行 /switchman-doctor 檢視", + // src/index.ts:1393 + "notice.injection.legacyStaticMatrix": "已注入 {shellCount} 個模型 shell(agents,舊版靜態矩陣)", + // src/index.ts:1412 + "notice.provider.cacheUsed": "provider.list 使用跨重啟快取({providerCount} 個 provider,快取於 {cachedAt});正在背景驗證新增項目", + // src/index.ts:1419 + "notice.provider.cacheStale": "provider.list 快取已過期(快取於 {cachedAt}),建立超集前先即時探測", + // src/index.ts:1469 + "notice.matrix.recomputed": "啟用矩陣已重算(gen={generation},作用中 shell {activeShellCount} 個,探測 {source}×{targetCount})", + // src/index.ts:1474 + "notice.injection.shellCount": "已注入 {shellCount} 個 shell(mode={runMode},注入面={injectionMode} 精選後 {fullSupersetCount}→{faceCount},衝突 {conflictCount};啟用閘控生效中)", + // src/index.ts:1479 + "notice.injection.configHookFailOpen": "config hook fail-open:{exc}", + // src/index.ts:1541 + "notice.lang.askLocale": "lang ask locale={locale}({source})", + // src/index.ts:1604 + "notice.banner.rulesFailOpen": "rules/banner fail-open:{exc}", + // src/index.ts:1677 + "notice.relay.persisted": "圖片中繼:模型 {modelKey} 不支援視覺輸入;已將 {written} 張圖片存入磁碟({relayed} 個圖片區段跨工作階段歷史中繼,工作階段 {sid})", + // src/index.ts:1679 + "notice.relay.failOpen": "圖片中繼 fail-open(直接放行):{exc}", + // src/index.ts:1694 + "notice.ctx.capToolDenied": "子代理 context 上限:已終止的工作階段 {sid} 中拒絕工具 '{tool}'", + // src/index.ts:1701 + "notice.ctx.capResumeDenied": "子代理 context 上限:拒絕恢復已終止的工作階段 ses_{taskId}(永久性)", + // src/index.ts:1727 + "notice.lang.gateDenied": "語言閘門:未設定專案的工作階段 {sid} 中拒絕工具 '{tool}'", + // src/index.ts:1751 + "notice.search.clarifyFailOpen": "搜尋釐清閘門:連續 {maxDenies} 次拒絕且未提問後 fail-open — 工作階段 {sid} 閘門開啟", + // src/index.ts:1754 + "notice.search.clarifyDenied": "搜尋釐清閘門:工作階段 {sid} 中拒絕工具 '{tool}'(搜尋範圍過廣,先提問)({denyCount}/{maxDenies})", + // src/index.ts:1774 + "notice.dispatch.offUngoverned": "dispatch 關閉:任務呼叫放行、不受治理(subagent_type='{subagentType}')", + // src/index.ts:1853 + "notice.dispatch.redirectUninjected": "自動轉向 {agent} → {candidate}(shell 未注入;已轉向鏈首候選)", + // src/index.ts:1874 + "notice.dispatch.redirectBuiltinBlocked": "自動轉向 {agent} → {candidate}(內建 agent 已阻擋)", + // src/index.ts:1883 (via src/gates.ts:331 noteUnknownAgent) + "notice.dispatch.unknownAgentAllowed": "[opencode-switchman] 未知 subagent_type='{agent}':放行(不在 shell 清單中;內建 agent 不受路由治理)", + // src/index.ts:1889 (r.note via src/gates.ts:156) + "notice.dispatch.registryDisabledNote": "[opencode-switchman] {agent} registry=disabled 但矩陣 status={matrixStatus}(非 down):fail-open,下次探測重新整理後自動修正", + // src/index.ts:1889 (r.note via src/gates.ts:175) + "notice.dispatch.matrixStatusNote": "[opencode-switchman] {agent} 矩陣 status={matrixStatus}(非 down):未阻擋,探測將於下一輪重新整理", + // src/index.ts:1889 (r.note via src/gates.ts:63 ROUTE_META_SYNTH_NOTE) + "notice.dispatch.routeMetaSynthNote": "[opencode-switchman] ROUTE_META 缺失/格式錯誤 — 已由 lane 合成;宣告它以啟用 review 跨家族 / source=user 語意", + // src/index.ts:1889 (r.note via src/gates.ts:240 REVIEW_SELF_REVIEW_NOTE) + "notice.dispatch.reviewSelfNote": "[opencode-switchman] DOWNGRADED:無跨家族審查者可用 — 允許同家族自我審查;請在審查結論中宣告 DOWNGRADED", + // src/index.ts:1889 (r.note via src/gates.ts:288 poolOverrideNote) + "notice.dispatch.poolOverrideNote": "pool 設定覆寫:已明確選入此任務池(免除能力層級 floor 限制)", + // src/index.ts:1897 + "notice.dispatch.redirectDenied": "自動轉向 {agent} → {redirect}({deny})", + // src/index.ts:1910 + "notice.dispatch.gatesFailOpen": "六道閘門 fail-open(放行):{exc}", + // src/index.ts:1934 + "notice.lang.prefsSaved": "專案語言偏好已儲存({rel}):conversation={conversation} comments={comments} docs={docs}", + // src/index.ts:1937 + "notice.lang.gateWaived": "語言閘門:已完成標記提問但未儲存設定 — 工作階段 {sid} 免除閘門", + // src/index.ts:1943 + "notice.search.scopeAskDone": "搜尋釐清:範圍提問已完成 — 工作階段 {sid} 閘門開啟", + // src/index.ts:1956 + "notice.ctx.readBudgetCharge": "讀取預算計費 +{charge}(工具 {tool},回合 {turnUsed}/{turnBudget})", + // src/index.ts:1970 + "notice.handover.autoTriggered": "自動交接已觸發({tool} 之後,~{wmTokens} 超過強制壓縮 watermark):完整備份 + 將目前工作階段的壓縮排入佇列", + // src/index.ts:1981 + "notice.handover.backupResult": "自動交接備份 {outcome}:{message}", + // src/index.ts:1996 (variant 1 of 3) + "notice.handover.compactionAccepted": "自動交接壓縮已接受:session.summarize 已回傳(壓縮在工作階段迴圈上執行)", + // src/index.ts:1996 (variant 2 of 3) + "notice.handover.compactionRejected": "自動交接壓縮失敗:session.summarize 已拒絕(備份仍有效)", + // src/index.ts:1996 (variant 3 of 3) + "notice.handover.compactionNoModel": "自動交接壓縮失敗:未記錄工作階段模型(chat.params 從未觸發);備份仍有效", + // src/index.ts:2008 + "notice.handover.failOpen": "自動交接 fail-open:{exc}", + // src/index.ts:2114 + "notice.ctx.capTerminated": "子代理 context 上限:工作階段 {sid}{agentSuffix} 已達 ~{estTokens}k tokens(上限 {capTokens}k)— 工具已拒絕、要求進度摘要、工作階段已終止(不得以 task_id 恢復)", + // src/index.ts:2205 + "notice.provider.modelRetired": "模型已除役(連續 404),自候選中移除:{provider}/{modelId}", + // src/index.ts:2208 + "notice.breaker.agentTripped": "{agent} 斷路器跳脫(600 秒):{reason}", + // src/index.ts:2210 + "notice.breaker.accountingFailOpen": "失敗計數 fail-open:{exc}", + // src/lane.ts:410 + "notice.lane.scoringFallback": "評分失敗,退回規則排序:{exc}", + // src/lane.ts:494 + "notice.lane.backfillFailed": "回填排名失敗(lane 維持空白):{exc}", + // src/matrix-manager.ts:196 + "notice.matrix.favoritesScanNoChange": "已掃描最愛/可見集合:啟用狀態不變(gen={generation};不重算、不重新探測)", + // src/matrix-manager.ts:204 + "notice.matrix.invalidModels": "可見集合/最愛包含無效模型(provider 存在但無此 modelId,未產生 shell):{modelList}", + // src/matrix-manager.ts:217 + "notice.matrix.persistFailOpen": "啟用矩陣持久化 fail-open:{exc}", + // src/matrix-manager.ts:222 + "notice.matrix.callbackFailOpen": "啟用矩陣回呼 fail-open:{exc}", + // src/matrix-manager.ts:250 + "notice.matrix.configReadFailOpen": "設定介面讀取 fail-open(視為空):{exc}", + // src/matrix-manager.ts:272 + "notice.matrix.watchError": "fs.watch({dir}) 發生錯誤,退回 mtime 輪詢:{exc}", + // src/matrix-manager.ts:277 + "notice.matrix.watchStartFailed": "fs.watch({dir}) 無法啟動,退回 mtime 輪詢:{exc}", + // src/matrix-manager.ts:308 + "notice.matrix.recomputeFailOpen": "重算 fail-open:{exc}", + // src/probe.ts:144 + "notice.probe.failOpen": "探測 fail-open:{exc}", + // src/probe.ts:162 + "notice.probe.incrementalFailOpen": "增量探測 fail-open:{exc}", + // src/probe.ts:201 + "notice.probe.copilotPoolExhausted": "Copilot 每月額度池已用盡(閘道為第二資料來源),reset_date 前視為可信", + // src/probe.ts:207 + "notice.probe.resultsDiscarded": "探測結果已捨棄(矩陣 generation 已變更 {oldGen}->{newGen};由新 generation 重算重新排程)", + // src/probe.ts:214 + "notice.probe.matrixRefreshed": "矩陣已重新整理:{comboCount} 個組合中 {okCount} 個成功(共 {totalCount})", + // src/probe.ts:233 + "notice.probe.schedulingFailOpen": "探測排程 fail-open:{exc}", + // src/scoring.ts:399 + "notice.scoring.decisionLogFailOpen": "決策記錄 fail-open:{exc}", + // src/selfupdate.ts:122 + "notice.selfupdate.checkFailOpen": "自我更新檢查 fail-open:{exc}", + // src/selfupdate.ts:255 + "notice.selfupdate.upgradeAssetsFailOpen": "upgrade 指令資產 fail-open:{exc}", + // src/tmux.ts:149 (via log callback wired to appendStatusLog at src/index.ts:236) + "notice.dispatch.mirrorDisabled": "tmux 窗格鏡射已停用(初始化失敗):{message}", + // src/tmux.ts:221 + "notice.dispatch.mirrorOpFailed": "tmux 窗格鏡射操作失敗(繼續執行):{message}", + // src/tmux.ts:230 + "notice.dispatch.mirrorPaneFull": "tmux 窗格鏡射:欄位已滿({slotCount} 個窗格),ses_{sessionId}({agent})已排入佇列", + // src/tmux.ts:280 + "notice.dispatch.mirrorAllClosed": "tmux 窗格鏡射:所有子代理窗格已關閉,主窗格已還原", + // src/tmux.ts:290 + "notice.dispatch.mirrorDisplayed": "tmux 窗格鏡射:ses_{sessionId}({agent})顯示於窗格 {pane}", + // src/tmux.ts:303 + "notice.dispatch.mirrorReconciling": "tmux 窗格鏡射:偵測到已關閉的窗格,正在重新校準版面", + // src/index.ts (setup gate) + "notice.setup.gateDenied": "需要先完成設定({missing})— 請執行 /switchman-setup(或 /switchman-setup-chat);設定完成前無法派發", + + // ---- sidebar (tui.tsx sidebar chrome) ---- + // [2026-09-19]-[sidebar.restartHintPattern (the old RESTART_HINT_RE regex) deliberately NOT a message key: the + // structured alert flag on status-log entries replaces regex highlighting; keys are translatable prose only] + + // src/tui.tsx:308 + "sidebar.peakTag": " ·尖峰", + // src/tui.tsx:309 + "sidebar.staleTag": " ·過期", + // src/tui.tsx:310 + "sidebar.observeOnlyTag": " ·僅觀察", + // src/tui.tsx:346 + "sidebar.updateAvailable": " → {updateVersion}", + // src/tui.tsx:351 + "sidebar.restartNeeded": " [需重新啟動]", + // src/tui.tsx:358 + "sidebar.noneAvailable": "無可用項目", + // src/tui.tsx:391 (six-lane panel labels — display-only; runtime lane identifiers/config keys stay English) + "sidebar.lane.economy": "經濟", + "sidebar.lane.mechanical": "機械", + "sidebar.lane.main": "主力", + "sidebar.lane.hard": "困難", + "sidebar.lane.vision": "視覺", + "sidebar.lane.review": "評審", + // src/tui.tsx:368 + "sidebar.noticeLabel": "通知", + + // ---- dialogs (tui.tsx: pool picker / pool models / rank / handover) ---- + + // src/tui.tsx:426 (pool picker title) + "dialog.pool.title": "任務池(選擇一個任務池;按 Esc 結束)", + // src/tui.tsx:428 (pool picker lane row) + "dialog.pool.laneRow": "{pinMark}{lane}", + // src/tui.tsx:431 (pool picker option description) + "dialog.pool.manualSelection": "手動選擇:{selCount}/{totalCount} 個模型參與", + // src/tui.tsx:432 (pool picker option description) + "dialog.pool.notConfigured": "未設定:系統預設(所有可用模型皆參與)", + // src/tui.tsx:453 (pool models dialog, toggle persist) + "dialog.pool.toggleWriteFailed": "寫入失敗:{message}", + // src/tui.tsx:458 (pool models dialog, toggle toast) + "dialog.pool.modelToggled": "{verb} {modelKey} {direction} {lane} 任務池(立即生效,側邊欄重新整理)", + // src/tui.tsx:469 (pool models dialog, min-selection guard toast) + "dialog.pool.keepOneModel": "至少須保留一個參與模型;使用「清除設定」可還原系統預設", + // src/tui.tsx:482 (pool models dialog, bulk select-all persist) + "dialog.pool.bulkWriteFailed": "寫入失敗:{message}", + // src/tui.tsx:485 (pool models dialog, bulk toast) + "dialog.pool.allSelected": "{lane} 任務池:已選取所有模型", + // src/tui.tsx:490 (pool models dialog, clear-config toast) + "dialog.pool.configCleared": "{lane} 任務池設定已清除(已還原系統預設候選集)", + // src/tui.tsx:499 (pool models dialog, uncheck-all toast) + "dialog.pool.allUnchecked": "{lane} 任務池:已全部取消勾選 — 請勾選要保留的模型;全部未勾選時結束將維持原選擇", + // src/tui.tsx:503 (pool models dialog option) + "dialog.pool.back": "← 返回任務池清單", + // src/tui.tsx:504 (pool models dialog option) + "dialog.pool.selectAll": "☑ 全選", + // src/tui.tsx:505 (pool models dialog option) + "dialog.pool.uncheckAll": "☐ 全部取消勾選(之後勾選少數要保留的;全部未勾選時結束將保留原清單)", + // src/tui.tsx:506 (pool models dialog option) + "dialog.pool.clearConfig": "✕ 清除設定(系統預設:所有可用模型皆參與)", + // src/tui.tsx:508 (pool models dialog model row) + "dialog.pool.modelRow": "{checkMark} {modelId}", + // src/tui.tsx:510 (pool models dialog row description) + "dialog.pool.rowMeta": "{tier} 層級{manualSuffix}", + // src/tui.tsx:516 (pool models dialog title) + "dialog.pool.selectionTitle": "{lane} 任務池選擇({selCount}/{rowCount} 個參與;點選即切換,允許跨池重複)", + // src/tui.tsx:538 (rank universe-empty dialog option) + "dialog.rank.openPoolSelection": "→ 開啟任務池選擇(先挑選各任務池可用的模型,再進行排名)", + // src/tui.tsx:539 (rank universe-empty dialog option) + "dialog.rank.close": "✕ 關閉", + // src/tui.tsx:543 (rank universe-empty dialog title) + "dialog.rank.universeEmptyTitle": "設定任務池之前無法使用模型排名 — 只有獲選進入任務池的模型才能排名,因此不會排到無法派發的模型", + // src/tui.tsx:561 (rank move at edge toast) + "dialog.rank.alreadyAtEdge": "{modelName} 已位於合併能力清單的{edge}端", + // src/tui.tsx:568 (rank move persist) + "dialog.rank.moveWriteFailed": "寫入失敗:{message}", + // src/tui.tsx:573 (rank move/pin toast) + "dialog.rank.pinnedOrMoved": "{verb} {modelName} 至 #{position}(手動分數 {tier}/{raw},錨定於相鄰模型之間;立即生效,側邊欄重新整理)", + // src/tui.tsx:627 (rank picker title) + "dialog.rank.title": "模型能力排名 — 合併順序(#1 最強;範圍限任務池選擇;手動項目與基礎分數模型交錯排列;ctrl+up/ctrl+down 移動一位;enter = 開啟個別模型動作)", + // src/tui.tsx:628 (rank picker placeholder) + "dialog.rank.searchHint": "搜尋 · alt+up/alt+down 與 ctrl+up/ctrl+down 同義(同樣有效)", + // src/tui.tsx:630 (rank picker row) + "dialog.rank.row": "#{rankPadded} {modelId}", + // src/tui.tsx:632 (rank picker row description) + "dialog.rank.rowMeta": "{tier} 層級 · {scoreSource}{poolSuffix}", + // src/tui.tsx:662 (rank actions, remove persist) + "dialog.rank.removeWriteFailed": "寫入失敗:{message}", + // src/tui.tsx:665 (rank actions, remove toast) + "dialog.rank.removed": "已將 {model} 自手動排名移除(退回基礎能力分數,立即生效,側邊欄重新整理)", + // src/tui.tsx:669 (rank actions option) + "dialog.rank.pinTop": "▲ 釘選至頂端(高於所有模型)", + // src/tui.tsx:670 (rank actions option) + "dialog.rank.moveUp": "↑ 上移一位(與上方模型交換;將手動分數錨定於相鄰模型之間)", + // src/tui.tsx:671 (rank actions option) + "dialog.rank.moveDown": "↓ 下移一位(與下方模型交換)", + // src/tui.tsx:673 (rank actions option) + "dialog.rank.remove": "✕ 自排名移除(退回基礎分數)", + // src/tui.tsx:675 (rank actions option) + "dialog.rank.back": "← 返回排名清單", + // src/tui.tsx:680 (rank actions title) + "dialog.rank.detailTitle": "{model}({rankState})", + // src/tui.tsx (setup wizard) + "dialog.setup.title": "switchman 設定 — 任務池與能力排名", + "dialog.setup.intro": "引導式設定:為 6 個任務池分別挑選模型,然後進行排名(最強在前)。隨時按 Esc 結束;已確認的任務池會立即儲存。", + "dialog.setup.start": "開始(第一個未完成的步驟)", + "dialog.setup.statePools": "已設定任務池:{count}/6", + "dialog.setup.stateRank": "排名:{state}", + "dialog.setup.laneTitle": "任務池 {index}/6 — {lane}(已選 {count} 個;按 Enter 切換,至少 1 個)", + "dialog.setup.laneRow": "{checkMark} {modelId}", + "dialog.setup.selectAll": "[*] 全選", + "dialog.setup.clearAll": "[ ] 全部取消勾選", + "dialog.setup.confirmLane": "確認 {lane}({count} 個模型)並繼續", + "dialog.setup.back": "返回", + "dialog.setup.keepOne": "此任務池至少保留一個模型", + "dialog.setup.rankTitle": "能力排名 — 選擇第 {n} 名(最強在前,剩餘 {remaining} 個模型)", + "dialog.setup.rankFinish": "完成排名(已選 {count} 個;其餘模型保留系統基礎分數)", + "dialog.setup.rankMinOne": "完成前請至少排名一個模型", + "dialog.setup.doneTitle": "設定完成 — 立即生效(熱重載)", + "dialog.setup.donePools": "任務池:{summary}", + "dialog.setup.doneRank": "排名:{order}", + "dialog.setup.restartHint": "請重新啟動 opencode 以註冊新的供應商:{providers}", + // src/tui.tsx:734 (handover toast) + "dialog.handover.noSession": "/handover:不在工作階段中,沒有可備份的內容", + // src/tui.tsx:739 (handover toast) + "dialog.handover.inProgress": "/handover:正在完整備份目前工作階段並壓縮…", + // src/tui.tsx:744 (handover toast) + "dialog.handover.resultStay": "{resultMessage};仍在原工作階段,未切換", + // src/tui.tsx:747 (handover toast) + "dialog.handover.result": "/handover {resultMessage}", + + // ---- palette (command palette entries) ---- + + // src/tui.tsx:770 + "palette.handover.title": "備份並壓縮目前的工作階段", + // src/tui.tsx:771 + "palette.handover.desc": "完整分支(fork)目前工作階段作為備份(標題附加 [backup] 標籤),並對目前工作階段進行壓縮;不切換工作階段(有別於內建 /fork)", + // src/tui.tsx:772 (palette category label) + "palette.category.label": "switchman", + // src/tui.tsx:779 + "palette.poolConfig.title": "任務池選擇", + // src/tui.tsx:780 + "palette.poolConfig.desc": "為每個任務池挑選參與的模型(economy/mechanical/main/hard/vision/review)", + // src/tui.tsx:788 + "palette.modelRank.title": "模型能力排名", + // src/tui.tsx:789 + "palette.modelRank.desc": "手動能力排名(優先於基礎分數;越前面 = 越強)", + // src/tui.tsx (setup wizard) + "palette.setup.title": "引導式設定(任務池 + 排名)", + "palette.setup.desc": "精靈:為每個任務池多選模型,然後排名 — 派發正常運作前必須完成", + + // ---- quota (quota-brief.json rows; banner.ts builders) ---- + + // src/banner.ts:142 (POOL_LABEL) + "quota.poolGlm": "GLM", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolCopilot": "Copilot", + // src/banner.ts:142 (POOL_LABEL) + "quota.poolDeepSeek": "DeepSeek", + // src/banner.ts:166 + "quota.queryingNoData": "查詢中/無資料", + // src/banner.ts:173 + "quota.resetLater": "→稍後", + // src/banner.ts:173 + "quota.resetTime": "→{hhmm}", + // src/banner.ts:173 + "quota.resetDate": "→{mmdd}", + // src/banner.ts:173 + "quota.resetDateTime": "→{mmdd} {hhmm}", + // src/banner.ts:174 + "quota.barPct": "{bar8} {pct}%", + // src/banner.ts:177 (row label) + "quota.row5h": "5h", + // src/banner.ts:178 (row label) + "quota.rowWeek": "週", + // src/banner.ts:180 (row label) + "quota.rowMcp": "MCP", + // src/banner.ts:181 + "quota.noData": "無額度資料", + // src/banner.ts:187 (row label) + "quota.rowRefresh": "重新整理", + // src/banner.ts:188 (row label) + "quota.rowCredits": "點數", + // src/banner.ts:188 + "quota.monthlyExhausted": "每月額度已用盡", + // src/banner.ts:193 + "quota.unlimited": "無上限{usedSuffix}", + // src/banner.ts:199 + "quota.exhaustedOverage": "已用盡·超額計費{usage}", + // src/banner.ts:202 + "quota.barPctLeft": "{bar8} 剩餘 {pctTxt}%{usage}", + // src/banner.ts:207 (row label) + "quota.rowBalance": "餘額", + // src/banner.ts:207 + "quota.exhausted": "已用盡", + // src/banner.ts:209 + "quota.unknownPayg": "未知(隨用隨付)", + // src/banner.ts:213 + "quota.barBalance": "{bar8} ¥{balance}", + // src/banner.ts:213 + "quota.balanceWarn": "(<¥{thr} 警告)", + + // ---- cli (switchman-config / switchman-doctor) ---- + + // src/config-cli.ts:67 (fmtRow, printed at :87) + "cli.config.poolRow": "#{rankPadded} {checkMark} {modelId}({tier} 層級{manualTag})", + // src/config-cli.ts:73 (thrown, surfaced via console.error at :267) + "cli.config.unknownPool": "未知任務池:{lane}(六個任務池:{laneList})", + // src/config-cli.ts:81 (head, printed at :85/:90) + "cli.config.poolHeader": "任務池選擇(設定檔 {poolConfigPath};選擇 = 加入該任務池的模型;同一模型可加入多個任務池;未設定的任務池採系統預設決策)", + // src/config-cli.ts:86 + "cli.config.poolSection": "== {lane} ==({selection})", + // src/config-cli.ts:93 + "cli.config.poolSectionBrief": "== {lane} =={detail}", + // src/config-cli.ts:95 + "cli.config.poolListHint": "(以編號檢視單一任務池的完整清單:pool list <{laneList}>)", + // src/config-cli.ts:105 (thrown, surfaced via console.error at :267) + "cli.config.indexOutOfRange": "索引超出範圍 #{index}(清單共 {rowCount} 項)", + // src/config-cli.ts:110 (thrown, surfaced via console.error at :267) + "cli.config.invalidModel": "無效的模型名稱:{model}", + // src/config-cli.ts:124 (thrown, surfaced via console.error at :267) + "cli.config.noManifest": "沒有可用的模型資訊清單(請檢查 provider 連線與超集資訊清單)", + // src/config-cli.ts:129 (thrown, surfaced via console.error at :267) + "cli.config.poolRequiresArg": "pool {sub} 需要索引或模型名稱", + // src/config-cli.ts:138 + "cli.config.poolSelectionCleared": "{lane} 任務池選擇已清除(回到系統預設候選集,立即生效,側邊欄同步重新整理)", + // src/config-cli.ts:139 + "cli.config.poolUpdated": "已更新 {lane} 任務池選擇({modelCount} 個模型參與,立即生效,側邊欄同步重新整理)", + // src/config-cli.ts:145 + "cli.config.poolConfigCleared": "已清除 {lane} 任務池選擇設定(該任務池回到系統預設候選集,立即生效,側邊欄同步重新整理)", + // src/config-cli.ts:148 (thrown, surfaced via console.error at :267) + "cli.config.unknownPoolSub": "未知子指令 pool {sub}(list/add/remove/set/clear)", + // src/config-cli.ts:186 + "cli.config.rankDisabledUntilPools": "在設定任務池之前,手動能力排名(設定檔 {capabilityRankPath})為停用:只有獲選進入任務池的模型才能排名。", + // src/config-cli.ts:187 + "cli.config.rankHowTo": "先在此執行 /poolConfig(TUI 對話框)或 pool set <task-pool> <index|model...>,再只為實際使用的模型排名。", + // src/config-cli.ts:190 + "cli.config.legacyHeader": "== 舊版手動項目(僅供清理;rank remove/clear 仍可使用,或將模型選入任務池以進行排名)==", + // src/config-cli.ts:191 + "cli.config.legacyRow": "#{rankPadded} {modelKey}", + // src/config-cli.ts:197 + "cli.config.rankHeader": "模型能力排名(設定檔 {capabilityRankPath};範圍限透過 /poolConfig 選入任務池的 {universeCount} 個模型 — 單一合併排序,手動項目依有效分數與基礎分數模型交錯排列;越上面 = 越強)", + // src/config-cli.ts:198 + "cli.config.mergedHeader": "== 合併排序({manualCount} 個手動{manualSuffix};CLI set/add 依舊版階梯排序項目,TUI 則將分數錨定於相鄰模型之間)==", + // src/config-cli.ts:201 + "cli.config.manualTag": "·手動{score}", + // src/config-cli.ts:203 + "cli.config.notInPoolTag": "·未加入任何任務池", + // src/config-cli.ts:204 + "cli.config.rankRow": "#{rankPadded} {modelId}({tier} 層級{manualTag}{poolTag})", + // src/config-cli.ts:210 (thrown, surfaced via console.error at :267) + "cli.config.rankNoPools": "尚未選擇任務池 — 排名遵循任務池選擇;請先執行 /poolConfig(或 pool set)", + // src/config-cli.ts:212 (thrown, surfaced via console.error at :267) + "cli.config.rankRequiresArg": "rank {sub} 需要索引或模型名稱", + // src/config-cli.ts:237 + "cli.config.rankUpdated": "已更新手動能力排名({modelCount} 個模型,立即生效,側邊欄同步重新整理)", + // src/config-cli.ts:242 + "cli.config.rankCleared": "已清除手動能力排名(全部退回基礎能力分數,立即生效,側邊欄同步重新整理)", + // src/config-cli.ts:245 (thrown, surfaced via console.error at :267) + "cli.config.unknownRankSub": "未知子指令 rank {sub}(list/set/add/remove/clear)", + // src/config-cli.ts:254 + "cli.config.usage": "用法:switchman-config <pool|rank> ...", + // src/config-cli.ts:255 + "cli.config.usagePoolList": " pool list [task-pool] 任務池選擇總覽(economy/mechanical/main/hard/vision/review;加上任務池名稱 = 顯示含編號的完整清單)", + // src/config-cli.ts:256 + "cli.config.usagePoolAdd": " pool add <task-pool> <index|model...> 勾選加入該任務池的模型", + // src/config-cli.ts:257 + "cli.config.usagePoolRemove": " pool remove <task-pool> <index|model...> 取消勾選參與", + // src/config-cli.ts:258 + "cli.config.usagePoolSet": " pool set <task-pool> <index|model...> 完整取代該任務池的參與清單(同一模型可加入多個任務池)", + // src/config-cli.ts:259 + "cli.config.usagePoolClear": " pool clear <task-pool> 清除該任務池的設定(回到系統預設候選集)", + // src/config-cli.ts:260 + "cli.config.usageRankList": " rank list 檢視手動能力排名(範圍限任務池選擇;未設定任務池時會引導至 /poolConfig)", + // src/config-cli.ts:261 + "cli.config.usageRankSet": " rank set <index|model...> 完整重排(依給定順序,#1 最強;僅限已選入任務池的模型)", + // src/config-cli.ts:262 + "cli.config.usageRankAdd": " rank add <index|model...> 附加到排名尾端(僅限已選入任務池的模型)", + // src/config-cli.ts:263 + "cli.config.usageRankRemove": " rank remove <index|model...> 自排名移除", + // src/config-cli.ts:264 + "cli.config.usageRankClear": " rank clear 清除排名(退回基礎能力分數)", + // src/config-cli.ts:267 + "cli.config.errorPrefix": "switchman-config: {message}", + // src/doctor-cli.ts:5 + "cli.doctor.usage": "用法:switchman-doctor 會檢查 opencode-switchman 設定;以 OPENCODE_CONFIG_DIR 環境變數選擇設定目錄;結束代碼 0=無問題、1=警告、2=錯誤", + // src/doctor.ts:56 (SWM060 hint) + "cli.doctor.unknownModelsHint": "{unknownCount} 個模型未被已知系統比對到(未知群組,依係數排到最後)", + // src/doctor.ts:58 (SWM062 hint) + "cli.doctor.approxModelsHint": "{approxCount} 個模型以前綴/家族近似分類", + // src/doctor.ts:72 (SWM044 hint) + "cli.doctor.configFileHint": "opencode-switchman.jsonc", + // src/doctor.ts:87 + "cli.doctor.noIssues": "opencode-switchman doctor:未發現問題", + // src/doctor.ts:89 + "cli.doctor.findingLine": "{level} {code}{pathPart}{hintPart}", +} diff --git a/src/matrix-manager.ts b/src/matrix-manager.ts index f85bd17..57cec02 100644 --- a/src/matrix-manager.ts +++ b/src/matrix-manager.ts @@ -193,7 +193,8 @@ export class MatrixManager { // sources are internal scheduling and stay silent] if (source === "config" && Date.now() - this.lastConfigNoopNoticeMs > 10_000) { this.lastConfigNoopNoticeMs = Date.now() - appendStatusLog(`favorites/visible set scanned: activation unchanged (gen=${this.current_.generation}; no recompute, no re-probe)`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.matrix.favoritesScanNoChange", { generation: this.current_.generation }) } return this.current_ } @@ -201,7 +202,7 @@ export class MatrixManager { // [2026-09-01]-[hardening: dirty data in favorites/visible set where the provider is known but no shell exists for the // modelId (e.g. accidentally favoriting "provider/not-a-model") was silently dropped with no diagnosis; sameActivation // already short-circuits dedup, so log once only on a real change, no spam] - appendStatusLog(`visible set/favorites contain invalid models (provider known but no such modelId, no shell generated): ${next.invalidConfigured.join(", ")}`) + appendStatusLog("notice.matrix.invalidModels", { modelList: next.invalidConfigured.join(", ") }) } const prevKeys = new Set(this.lastActiveKeys) const activeKeys = new Set(this.activeMatrixKeysOf(next)) @@ -214,12 +215,12 @@ export class MatrixManager { const m = readJson<Record<string, unknown>>(paths().matrix) writeJsonAtomic(paths().matrix, { ...(m ?? {}), active_keys: [...activeKeys], target_generation: next.generation }) } catch (exc) { - appendStatusLog(`activation matrix persist fail-open: ${exc}`) + appendStatusLog("notice.matrix.persistFailOpen", { exc: String(exc) }) } try { this.opts.onRecompute?.(next, newTargets, source) } catch (exc) { - appendStatusLog(`activation matrix callback fail-open: ${exc}`) + appendStatusLog("notice.matrix.callbackFailOpen", { exc: String(exc) }) } return next } @@ -247,7 +248,7 @@ export class MatrixManager { try { return readConfigured(this.opts.stateRoot, this.opts.mode) } catch (exc) { - appendStatusLog(`config surface read fail-open (treated as empty): ${exc}`) + appendStatusLog("notice.matrix.configReadFailOpen", { exc: String(exc) }) return { configStatus: "empty", models: [] } } } @@ -269,12 +270,12 @@ export class MatrixManager { if (WATCH_FILENAMES.has(String(filename))) this.scheduleRecompute() }) // [2026-09-02]-[log runtime errors: previously swallowed in pure silence, undiagnosable when fs.watch does not deliver inside the host]-[observability] - w.on("error", (exc) => appendStatusLog(`fs.watch(${dir}) errored, falling back to mtime polling: ${exc}`)) + w.on("error", (exc) => appendStatusLog("notice.matrix.watchError", { dir, exc: String(exc) })) this.watchers.push(w) } catch (exc) { // Dir missing (the other host form naturally lacks this file) -> silently skip with the polling fallback; dir exists but watch failed to start (e.g. fd exhaustion) -> log try { - if (statSync(dir).isDirectory()) appendStatusLog(`fs.watch(${dir}) failed to start, falling back to mtime polling: ${exc}`) + if (statSync(dir).isDirectory()) appendStatusLog("notice.matrix.watchStartFailed", { dir, exc: String(exc) }) } catch { /* dir missing: expected, silent */ } } } @@ -305,7 +306,7 @@ export class MatrixManager { if (this.debounceTimer) clearTimeout(this.debounceTimer) this.debounceTimer = setTimeout(() => { this.debounceTimer = null - this.recomputeWithRetry().catch((exc) => appendStatusLog(`recompute fail-open: ${exc}`)) + this.recomputeWithRetry().catch((exc) => appendStatusLog("notice.matrix.recomputeFailOpen", { exc: String(exc) })) this.refreshMtimes() }, delay ?? this.opts.debounceMs) unref(this.debounceTimer) diff --git a/src/probe.ts b/src/probe.ts index f8cd851..81afd57 100644 --- a/src/probe.ts +++ b/src/probe.ts @@ -141,7 +141,8 @@ export async function refreshMatrix(eps: ProbeEndpoints): Promise<number | null> } return await probeTargets([...targets.keys()], eps, targets) } catch (exc) { - appendStatusLog(`probe fail-open: ${exc}`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.probe.failOpen", { exc: String(exc) }) return null } } @@ -159,7 +160,7 @@ export async function probeKeys(keys: string[], eps: ProbeEndpoints): Promise<nu } return await probeTargets([...targets.keys()], eps, targets) } catch (exc) { - appendStatusLog(`incremental probe fail-open: ${exc}`) + appendStatusLog("notice.probe.incrementalFailOpen", { exc: String(exc) }) return null } } @@ -198,24 +199,24 @@ async function probeTargets( // [2026-08-28]-[402 is the monthly-pool-exhausted truth (429 is concurrency noise); threshold lowered from 50% to >=3 combos to mark exhaustion] if (cpKeys.length > 0 && cp402.length >= 3) { markCopilotGatewayExhausted(`probe ${cp402.length}/${cpKeys.length} combos 402 monthly pool exhausted`) - appendStatusLog(`Copilot monthly pool exhausted (gateway second source of truth), trusted until reset_date`) + appendStatusLog("notice.probe.copilotPoolExhausted") } return await withPathLock(paths().matrix, () => { const cur = loadMatrix() ?? ({} as Matrix) if ((cur.target_generation ?? undefined) !== (gen0 ?? undefined)) { // [2026-08-31]-[switched to persisting via the status-log for tui.tsx sidebar rendering, no longer spamming stderr over the input box] - appendStatusLog(`probe results discarded (matrix generation changed ${gen0 ?? "n/a"}->${cur.target_generation ?? "n/a"}; rescheduled by the new generation recompute)`) + appendStatusLog("notice.probe.resultsDiscarded", { oldGen: gen0 ?? "n/a", newGen: cur.target_generation ?? "n/a" }) return null } // Merge on top of the latest disk state at write time (keeps concurrently written combos and active_keys/target_generation, no lost updates) const matrix: Matrix = { ...cur, combos: { ...(cur.combos ?? {}), ...results }, generated_at: new Date().toISOString() } writeJsonAtomic(paths().matrix, matrix) const ok = Object.values(matrix.combos).filter((c) => c.status === "ok").length - appendStatusLog(`matrix refreshed: ${sorted.length} combos ${ok} ok (total ${Object.keys(matrix.combos).length})`) + appendStatusLog("notice.probe.matrixRefreshed", { comboCount: sorted.length, okCount: ok, totalCount: Object.keys(matrix.combos).length }) return ok }) } catch (exc) { - appendStatusLog(`probe fail-open: ${exc}`) + appendStatusLog("notice.probe.failOpen", { exc: String(exc) }) return null } } @@ -230,7 +231,7 @@ export async function refreshMatrixIfStale(eps: ProbeEndpoints): Promise<void> { } await refreshMatrix(eps) } catch (exc) { - appendStatusLog(`probe scheduling fail-open: ${exc}`) + appendStatusLog("notice.probe.schedulingFailOpen", { exc: String(exc) }) } } @@ -245,6 +246,6 @@ export async function refreshActiveMatrixIfStale(eps: ProbeEndpoints, activeKeys } await probeKeys(activeKeys, eps) } catch (exc) { - appendStatusLog(`probe scheduling fail-open: ${exc}`) + appendStatusLog("notice.probe.schedulingFailOpen", { exc: String(exc) }) } } diff --git a/src/provider-config.ts b/src/provider-config.ts index 67570cc..e6e017c 100644 --- a/src/provider-config.ts +++ b/src/provider-config.ts @@ -129,7 +129,7 @@ export function renderDefaultConfigJsonc(): string { "rules": { "enabled": true }, // Measured session-context budget (optional; the whole section may be omitted — factory defaults apply). // "context": { - // "readBudgetTokens": 1500, // per-call self-read budget in tokens (200..20000): oversized reads get auto-bounded or denied with bounded-retry params + // "readBudgetTokens": 1500, // per-call self-read budget in tokens (200..20000): reads within the turn headroom (~2x) are granted one-shot; oversized reads get auto-bounded or denied with bounded-retry params // }, // Custom six-lane candidate chains (override builtin preference order); keys=economy/mechanical/main/hard/vision/review, values are arrays of shell names. "lanes": {}, diff --git a/src/scoring.ts b/src/scoring.ts index 804905a..7121132 100644 --- a/src/scoring.ts +++ b/src/scoring.ts @@ -193,6 +193,15 @@ export interface RankContext { * a lane whose seated candidates all died at runtime. Structural gates (modality / capability) and the policy-gated * quota-exhaustion / retirement gates stay active — illegitimate candidates are never resurrected.]-[impact: isGated only] */ relaxHealthGates?: boolean + /** [2026-09-18]-[pool lane manual ordering: true when the lane has an explicit task-pool selection — explicit + * membership is the user's qualification verdict, so the capability level floor (selectGroup primary/fallback + * filtering) yields for every survivor; health/structural hard gates stay unchanged] */ + poolOrdered?: boolean + /** [2026-09-18]-[pool lane manual ordering: shell key → manual rank index (0 = strongest, from capability-rank.json + * models order, prefix-matched like manualRankResult). When present on a poolOrdered lane the rank index becomes the + * ABSOLUTE first comparator key (ahead of family/off-partition/tier/level grouping; unranked pool members sort after + * ranked ones by the existing comparator) — the manual /modelRank order is the dispatch priority, not a score] */ + manualOrder?: ReadonlyMap<string, number> | null } /** Hard gates: matrix down (strained is not down) / breaker / exhaustion / retirement / real-call isolation / semantic gates (same source as computeLane) */ @@ -275,8 +284,26 @@ export function rankCandidates<T extends Rankable>( if (targetLevel === null) return null return Math.abs(CAPABILITY_LEVEL_RANK[capabilityLevelOf(baseScoreDynamic(s.modelId).tier, baseScoreDynamic(s.modelId).source)] - CAPABILITY_LEVEL_RANK[targetLevel]) } + // [2026-09-18]-[pool lane manual ordering: rankOrdered = the lane has a pool selection AND at least one member holds + // a manual rank — the manual order then rules absolutely (partitions, level floors, family preference and the score + // product only tiebreak). poolOrdered without manualOrder keeps the level-floor exemption (explicit membership = + // qualification) but preserves the system ordering otherwise (fail-open for unranked pool lanes)] + const rankOrdered = Boolean(ctx.poolOrdered && ctx.manualOrder && ctx.manualOrder.size > 0) + const manualRankOf = (s: T): number => (rankOrdered ? (ctx.manualOrder!.get(s.key) ?? Number.POSITIVE_INFINITY) : 0) + // Infinity-safe comparator: two unranked members tie (NaN from Infinity−Infinity would corrupt the sort) + const rankCompare = (a: T, b: T): number => { + const ra = manualRankOf(a) + const rb = manualRankOf(b) + if (ra === rb) return 0 + if (ra === Number.POSITIVE_INFINITY) return 1 + if (rb === Number.POSITIVE_INFINITY) return -1 + return ra - rb + } // Within-partition same-level first: same-level survivors win; only when the level is wiped out take the top-2 fallbacks from the nearest level. const selectGroup = (pool: T[]): T[] => { + // [2026-09-18]-[pool-config membership = qualification: an explicitly pool-selected model is its own level verdict — + // no primary/fallback filtering, no top-2 slicing (the full member set forms the chain)] + if (ctx.poolOrdered) return pool const primary = pool.filter((s) => isPrimaryCandidate(ctx.lane, baseScoreDynamic(s.modelId))) if (primary.length > 0) return primary const fallbackPool = pool.filter((s) => isFallbackCandidate(ctx.lane, baseScoreDynamic(s.modelId))) @@ -292,11 +319,17 @@ export function rankCandidates<T extends Rankable>( if (ctx.lane === "review" && fallbackPool.length === 0) return pool.slice(0, 2) return fallbackPool.slice(0, 2) } - survivors.length = 0 - survivors.push(...selectGroup(thinking), ...selectGroup(offPool)) + // [2026-09-18]-[rank-ordered pool lanes skip the thinking/off partition too: the manual order is absolute across + // partitions (a ranked off-effort shell may lead), so survivors stay unpartitioned and the sorts below carry the + // rank key first; unranked pool lanes (poolOrdered without manualOrder) keep the partition baseline] + if (!rankOrdered) { + survivors.length = 0 + survivors.push(...selectGroup(thinking), ...selectGroup(offPool)) + } const inputOrder = new Map(survivors.map((s, i) => [s.key, i])) if (ctx.immediate) { survivors.sort((a, b) => + rankCompare(a, b) || famClassOf(a) - famClassOf(b) || offClassOf(a) - offClassOf(b) || (a.latencyMs ?? Number.POSITIVE_INFINITY) - (b.latencyMs ?? Number.POSITIVE_INFINITY) || @@ -309,6 +342,10 @@ export function rankCandidates<T extends Rankable>( return typeof v === "number" ? v : Number.POSITIVE_INFINITY } survivors.sort((a, b) => { + // [2026-09-18]-[pool lane manual ordering: the manual rank index is the ABSOLUTE first key — explicit + // /modelRank order beats family preference, off-partitions, tier grouping and the product score] + const rankDiff = rankCompare(a, b) + if (rankDiff !== 0) return rankDiff // [2026-09-05]-[review family deprioritization: cross-family first, same-family sinks to the chain tail (no effect without producerFamily)] const famDiff = famClassOf(a) - famClassOf(b) if (famDiff !== 0) return famDiff @@ -359,7 +396,8 @@ export function logDecision(records: DecisionRecord[]): Promise<void> { const kept = prev.slice(-MAX_DECISION_LINES) writeFileSync(p, `${kept.join("\n")}\n`) } catch (exc) { - appendStatusLog(`decision log fail-open: ${exc}`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.scoring.decisionLogFailOpen", { exc: String(exc) }) } }) } diff --git a/src/selfupdate.ts b/src/selfupdate.ts index 23bb463..87ce186 100644 --- a/src/selfupdate.ts +++ b/src/selfupdate.ts @@ -119,7 +119,8 @@ export async function refreshSelfUpdate(): Promise<SelfUpdateState | null> { writeJsonAtomic(path, state) return state } catch (exc) { - appendStatusLog(`self-update check fail-open: ${exc}`) + // [2026-09-19]-[i18n: status-log notices now keyed (en.ts catalog renders at sidebar display time)] + appendStatusLog("notice.selfupdate.checkFailOpen", { exc: String(exc) }) return null } }) @@ -252,7 +253,7 @@ export function ensureUpdateCommands(mode: LoadMode, baseDir = resolveOpencodeCo } write("switchman-doctor.md", doctorCommandMd(cliPath ?? join(moduleDir(), "switchman-doctor.js"))) } catch (exc) { - appendStatusLog(`upgrade command assets fail-open: ${exc}`) + appendStatusLog("notice.selfupdate.upgradeAssetsFailOpen", { exc: String(exc) }) } } diff --git a/src/setup-gate.ts b/src/setup-gate.ts new file mode 100644 index 0000000..8b7df8e --- /dev/null +++ b/src/setup-gate.ts @@ -0,0 +1,71 @@ +// [2026-09-19]-[setup gate: switchman no longer defaults to all models when unconfigured — task dispatch is denied +// until all 6 task pools have >=1 selected model and the capability ranking has >=1 ranked model. Pure helpers + +// thin IO wrappers (mtime-cached reads, so a config written by /switchman-setup opens the gate immediately without +// a restart); model-facing copy stays English by design (byte-stable across locales, the [LANG] rule makes the +// model relay the remedy in the user's conversation language) — wiring in src/index.ts, guided wizard in src/tui.tsx, +// chat fallback template in src/commands-md.ts] +import { LANE_ORDER, type Lane } from "./types" +import { loadCapabilityRank, loadPoolConfig } from "./user-overrides" + +export interface SetupCompletion { + complete: boolean + /** Lanes with no pool selection, in LANE_ORDER order; empty when all 6 are configured */ + missingLanes: Lane[] + /** Count of configured lanes (0..6) */ + configuredLanes: number + /** capability-rank.json absent or its models list is empty */ + missingRank: boolean +} + +/** Pure completion evaluation from injected state (test-friendly; a lane with an empty selection counts as missing) */ +export function evaluateSetup( + poolCfg: Record<string, ReadonlySet<string>> | null | undefined, + rankModels: readonly string[] | null | undefined, +): SetupCompletion { + const missingLanes = LANE_ORDER.filter((lane) => { + const sel = poolCfg?.[lane] + return !sel || sel.size === 0 + }) + const missingRank = !rankModels || rankModels.length === 0 + return { + complete: missingLanes.length === 0 && !missingRank, + missingLanes, + configuredLanes: LANE_ORDER.length - missingLanes.length, + missingRank, + } +} + +/** Live completion (fresh mtime-cached reads; fail-open reads yield "unconfigured") */ +export function setupCompletionNow(): SetupCompletion { + return evaluateSetup(loadPoolConfig(), loadCapabilityRank()?.models ?? null) +} + +/** Model-facing deny (English, byte-stable by design); the model relays the remedy in the user's conversation language */ +export function setupDenyMessage(c: SetupCompletion): string { + const parts: string[] = [] + if (c.missingLanes.length > 0) { + parts.push(c.missingLanes.length === LANE_ORDER.length + ? `task-pool selection for all ${LANE_ORDER.length} pools (${LANE_ORDER.join(", ")})` + : `task-pool selection for pools: ${c.missingLanes.join(", ")}`) + } + if (c.missingRank) parts.push("capability ranking (at least one ranked model)") + return "[opencode-switchman] BLOCKED (setup required): dispatch is denied until switchman is configured — unconfigured no longer defaults to all models. Missing: " + + parts.join("; ") + + ". Ask the user to run /switchman-setup (TUI slash command), or /switchman-setup-chat here when the TUI plugin is not installed, then retry — relay this guidance in the user's conversation language. Setup saves pool-config.json / capability-rank.json and takes effect immediately via hot-reload." +} + +/** Directive body pushed into the system prompt each user turn while setup is incomplete (English by design) */ +export function setupDirective(c: SetupCompletion): string { + const parts: string[] = [] + if (c.missingLanes.length > 0) parts.push(`task pools configured ${c.configuredLanes}/${LANE_ORDER.length}`) + if (c.missingRank) parts.push("capability ranking missing") + return `[SETUP] switchman setup incomplete (${parts.join(", ")}). Tell the user (in their conversation language) to run /switchman-setup in the TUI, or /switchman-setup-chat here. HARD GATE: every task call is denied until all ${LANE_ORDER.length} task pools have at least one model selected and the capability ranking has at least one ranked model.` +} + +/** Short English brief for the sidebar notice `{missing}` param */ +export function setupMissingBrief(c: SetupCompletion): string { + const parts: string[] = [] + if (c.missingLanes.length > 0) parts.push(`pools ${c.configuredLanes}/${LANE_ORDER.length}`) + if (c.missingRank) parts.push("rank missing") + return parts.join(", ") +} diff --git a/src/shells.json b/src/shells.json index a3d6f4f..7859679 100644 --- a/src/shells.json +++ b/src/shells.json @@ -1,6 +1,6 @@ { "_note": "opencode-switchman full matrix: authoritative enabled surface (models enabled in model management, scripts/visible-models.txt) × all declared thinking efforts (models.dev reasoning_options, toggle→off). Generated by scripts/gen-shells.ts — do not edit by hand; after model on/off changes, sync the pin file and re-run bun run gen:shells. The six lane chains are computed from capability score × lane affinity × structural gate × billing factor (api billing 0.85, unknown group 0.75, sunk by coefficient; no vendor-reserved seats).", - "generated_at": "2026-09-17T13:56:26.846Z", + "generated_at": "2026-09-19T12:20:53.892Z", "counts": { "shells": 104, "visible_models": 13 @@ -1153,8 +1153,8 @@ ], "lanes": { "economy": [ - "ds-mx-v4fv-low", - "copilot-mx-luna-low", + "ds-mx-v4fv-high", + "copilot-mx-luna-medium", "copilot-mx-haiku45-off" ], "mechanical": [ diff --git a/src/state.ts b/src/state.ts index 4cea3b3..671dd45 100644 --- a/src/state.ts +++ b/src/state.ts @@ -5,6 +5,7 @@ import { mkdirSync, readFileSync, writeFileSync, renameSync, statSync, existsSyn import { homedir } from "node:os" import { join } from "node:path" import manifestDefault from "./shells.json" +import type { MsgKey } from "./i18n" import type { ShellManifestEntry, ShellRegEntry, Matrix, Routing, MatrixEntry, SwitchmanOptions, } from "./types" @@ -56,17 +57,28 @@ export const paths = () => { routeSnapshot: join(dir, "route-snapshot.json"), // [2026-09-01]-[TUI sidebar new "provider watermark/peak" panel: same source as the [WATERMARK] banner, always visible, polled by tui.tsx] quotaBrief: join(dir, "quota-brief.json"), + // [2026-09-19]-[i18n wiring step 1: render-time locale inputs — global UI locale (from plugin config "ui"."lang") + // and workspace dirname (from config "workspace"."dirname"); read by the i18n locale chain, written once per startup] + uiLocale: join(dir, "ui-locale.json"), + workspaceMeta: join(dir, "workspace-meta.json"), } } // [2026-08-31]-[TUI sidebar live status ring log: keeps at most STATUS_LOG_MAX entries, polled by tui.tsx] +// [2026-09-19]-[i18n: entries are now structured {key, params, alert} — the sidebar translates at render time via +// renderNotice(); legacy prose-only rows (text, no key) still render verbatim, and not-yet-migrated callers passing +// prose as the key also render verbatim through the unknown-key fallback; `key` is typed string for now and will be +// tightened to MsgKey once all emitters are migrated] +// [2026-09-19]-[i18n cleanup: tighten the status-log writer to MsgKey (all emitters migrated to catalog keys; +// legacy prose-only rows still read back via the optional text field; no runtime import — type-only, no cycle)] export const STATUS_LOG_MAX = 20 -export type StatusLogEntry = { ts: string; text: string } -export function appendStatusLog(text: string): void { +export type StatusLogEntry = { ts: string; key?: MsgKey; params?: Record<string, string | number>; alert?: boolean; text?: string } +export function appendStatusLog(key: MsgKey, params?: Record<string, string | number>, alert?: boolean): void { try { const p = paths().statusLog const prev = readJson<StatusLogEntry[]>(p) ?? [] - const next = [...prev, { ts: nowIso(), text }].slice(-STATUS_LOG_MAX) + const entry: StatusLogEntry = { ts: nowIso(), key, ...(params ? { params } : {}), ...(alert ? { alert: true } : {}) } + const next = [...prev, entry].slice(-STATUS_LOG_MAX) writeJsonAtomic(p, next) } catch { /* fail-open: status log failure never blocks the main flow */ } } @@ -82,14 +94,55 @@ export function writeRouteSnapshot(entries: RouteSnapshotEntry[]): void { // [2026-09-01]-[provider watermark/peak snapshot: whole overwrite, renders the sidebar "watermark" panel; shape shares the same // source as banner.ts providerStatusEntries (providers with observe=false are filtered by the caller and never appear here). // [2026-09-02]-[v2: one entry block per provider + rows sub-rows (progress bar/reset time), replacing the single-line text]] -export type QuotaBriefRow = { label: string; text: string; usedPct: number | null; tail?: string } -export type QuotaBriefEntry = { pool: string; label: string; rows: QuotaBriefRow[]; observeOnly: boolean; peakActive: boolean; stale: boolean } +// [2026-09-19]-[P4 render-time quota i18n: rows carry key+params as the future TUI render source (t(locale, key, params) +// against the quota.* catalog); label/text/tail stay as debug/legacy English until the TUI migration renders via key] +// [2026-09-19]-[quota i18n labels/tails: rows additionally carry labelKey+labelParams (quota.row5h/rowWeek/rowMcp/ +// rowCredits/rowBalance; rowRefresh stays as the main key since the refresh text is raw data) and tailKey+tailParams +// (quota.resetLater/resetTime/resetDate/resetDateTime with {hhmm}/{mmdd}, quota.balanceWarn with {thr}); entries +// carry key+params for the pool label (quota.poolGlm/poolCopilot/poolDeepSeek, params empty); legacy label/text/tail +// unchanged; fail-open behavior unchanged] +export type QuotaBriefRow = { key?: string; params?: Record<string, string | number>; labelKey?: string; labelParams?: Record<string, string | number>; tailKey?: string; tailParams?: Record<string, string | number>; usedPct: number | null; label?: string; text?: string; tail?: string } +export type QuotaBriefEntry = { pool: string; label: string; key?: string; params?: Record<string, string | number>; rows: QuotaBriefRow[]; observeOnly: boolean; peakActive: boolean; stale: boolean } +// [2026-09-19]-[P4: signature and fail-open behavior unchanged; entries now flow through with row key+params (see QuotaBriefRow)] export function writeQuotaBrief(entries: QuotaBriefEntry[]): void { try { writeJsonAtomic(paths().quotaBrief, { ts: nowIso(), entries }) } catch { /* fail-open: snapshot write failure never blocks the main flow */ } } +// [2026-09-19]-[i18n wiring step 1: global UI locale snapshot (normalized tag or null) for the render-time locale chain +// (see src/i18n.ts resolveDisplayLocale); null overwrites any previous value; fail-open everywhere] +export function writeUiLocale(lang: string | null): void { + try { + writeJsonAtomic(paths().uiLocale, { v: 1, lang }) + } catch { /* fail-open: locale snapshot failure never blocks the main flow */ } +} + +/** Read the persisted UI locale back; missing/corrupt/non-string → null (caller falls through the locale chain) */ +export function readUiLocale(): string | null { + try { + const data = readJson<{ lang?: unknown }>(paths().uiLocale) + return typeof data?.lang === "string" ? data.lang : null + } catch { return null } +} + +// [2026-09-19]-[i18n wiring step 1: workspace dirname snapshot so render-time readers resolve the project settings path +// without the plugin config; fail-open everywhere] +export function writeWorkspaceMeta(dirname: string): void { + try { + writeJsonAtomic(paths().workspaceMeta, { v: 1, dirname }) + } catch { /* fail-open: meta snapshot failure never blocks the main flow */ } +} + +/** Read the persisted workspace dirname back; missing/corrupt/empty → ".switchman" */ +export function readWorkspaceDirname(): string { + try { + const data = readJson<{ dirname?: unknown }>(paths().workspaceMeta) + if (typeof data?.dirname === "string" && data.dirname.trim()) return data.dirname + return ".switchman" + } catch { return ".switchman" } +} + // ---- constants ---- export const FAIL_WINDOW = 600 diff --git a/src/tmux.ts b/src/tmux.ts index 88fea35..9137c9b 100644 --- a/src/tmux.ts +++ b/src/tmux.ts @@ -6,6 +6,7 @@ // stay untouched. Everything is fail-open: any tmux/IO error only logs and never blocks dispatch.] import { execFile } from "node:child_process" import type { TmuxOptions } from "./types" +import type { MsgKey } from "./i18n" export interface TmuxResolvedOptions { enabled: boolean @@ -89,7 +90,10 @@ export interface TmuxPaneManagerDeps { dir: string bin?: string exec?: (args: string[]) => Promise<string> - log?: (message: string) => void + // [2026-09-19]-[P3c status-log i18n: the log callback carries structured (key, params) (index.ts forwards to + // appendStatusLog); English only, no behavior change] + // [2026-09-19]-[i18n cleanup: tighten the log callback key to MsgKey (all tmux sites use catalog keys)] + log?: (key: MsgKey, params?: Record<string, string | number>) => void } interface Child { id: string; agent: string; main: string } @@ -106,7 +110,7 @@ export class TmuxPaneManager { private dir: string private bin?: string private exec: (args: string[]) => Promise<string> - private log: (message: string) => void + private log: (key: MsgKey, params?: Record<string, string | number>) => void private home = "" private win = "" @@ -146,7 +150,7 @@ export class TmuxPaneManager { this.ready = true } catch (exc) { this.ready = false - this.log(`tmux pane mirroring disabled (init failed): ${exc instanceof Error ? exc.message : exc}`) + this.log("notice.dispatch.mirrorDisabled", { message: exc instanceof Error ? exc.message : String(exc) }) } } @@ -218,7 +222,7 @@ export class TmuxPaneManager { private enqueue(job: () => Promise<void>): void { this.chain = this.chain .then(job) - .catch((exc) => this.log(`tmux pane mirroring op failed (continuing): ${exc instanceof Error ? exc.message : exc}`)) + .catch((exc) => this.log("notice.dispatch.mirrorOpFailed", { message: exc instanceof Error ? exc.message : String(exc) })) } /** Show a child in a new right-column pane (grow by one) or queue it when the column is full */ @@ -227,7 +231,7 @@ export class TmuxPaneManager { const max = this.optionsOf().maxPanes if (this.slots.length >= max) { this.queue.push(child) - this.log(`tmux pane mirroring: column full (${this.slots.length} panes), queued ses_${child.id.slice(-6)} (${child.agent})`) + this.log("notice.dispatch.mirrorPaneFull", { slotCount: this.slots.length, sessionId: child.id.slice(-6), agent: child.agent }) return } await this.withFocus(async () => { @@ -277,7 +281,7 @@ export class TmuxPaneManager { await this.exec(resizePaneArgs({ target: this.slots[0].pane, height: Math.floor(total / this.slots.length) })).catch(() => {}) } } - if (this.slots.length === 0) this.log("tmux pane mirroring: all subagent panes closed, main pane restored") + if (this.slots.length === 0) this.log("notice.dispatch.mirrorAllClosed") this.syncPoll() } @@ -287,7 +291,7 @@ export class TmuxPaneManager { const cmd = viewerCommand({ origin: this.origin, sessionId: child.id, dir: this.dir, mini: opts.mini, bin: this.bin }) await this.exec(respawnPaneArgs({ target: pane, dir: this.dir, command: cmd })) await this.exec(setPaneTitleArgs({ target: pane, title: `${TMUX_PANE_MARKER}${child.agent}` })).catch(() => {}) - this.log(`tmux pane mirroring: ses_${child.id.slice(-6)} (${child.agent}) displayed in pane ${pane}`) + this.log("notice.dispatch.mirrorDisplayed", { sessionId: child.id.slice(-6), agent: child.agent, pane }) } /** Drop slots whose pane vanished (viewer exited / user killed the pane); queued children then backfill */ @@ -300,12 +304,12 @@ export class TmuxPaneManager { } } if (dropped) { - this.log("tmux pane mirroring: detected closed pane(s), reconciling layout") + this.log("notice.dispatch.mirrorReconciling") while (this.slots.length < this.optionsOf().maxPanes && this.queue.length > 0) { const next = this.queue.shift() if (next) await this.displayChild(next) } - if (this.slots.length === 0) this.log("tmux pane mirroring: all subagent panes closed, main pane restored") + if (this.slots.length === 0) this.log("notice.dispatch.mirrorAllClosed") } } diff --git a/src/tui.tsx b/src/tui.tsx index 6322f02..edbf534 100644 --- a/src/tui.tsx +++ b/src/tui.tsx @@ -8,20 +8,27 @@ // [2026-09-01]-[Notice area narrowed to the last entry only; best-candidate panel added, stacked above the notice area] // [2026-09-04]-[English localization: translate panel/dialog copy and comments; RESTART_HINT_RE now matches the English // "restart opencode" notice (emitters were localized in the same sweep); no other behavior change] +// [2026-09-19]-[render-time TUI localization sweep: sidebar chrome, notices (structured alert flag via renderNotice, +// replacing the RESTART_HINT_RE regex highlight), quota rows, /poolConfig //modelRank //handover dialogs and palette +// entries all render via t() against the locale catalogs; the display locale resolves per poll tick (session project +// lang → global ui.lang → terminal env); marquee title, colors, hotkeys, symbols and layout unchanged] import type { TuiPlugin, TuiPluginModule, TuiPluginApi } from "@opencode-ai/plugin/tui" // [2026-09-02]-[solid-js must be imported bare: the host runtime-plugin only rewrites exact specifiers // ("solid-js"/"@opentui/solid") at runtime (opentui:runtime-module:* → host instance); the deep path "solid-js/dist/solid.js" // misses the rewrite rule and loads a second solid instance → two reactive graphs that never subscribe to each other → // the whole panel freezes after mount. Build-time misresolution of server.js is handled by the onLoad redirect in // @opentui/solid/bun-plugin (server.js → solid.js client build)]-[impacts live refresh of the TUI panel] -import { createSignal, createMemo, onCleanup, For } from "solid-js" +import { createSignal, createMemo, onCleanup, onMount, For } from "solid-js" import { readFileSync, statSync } from "node:fs" import { homedir } from "node:os" import { join, relative, isAbsolute, sep, dirname } from "node:path" // [2026-09-03]-[/poolConfig //modelRank interactive dialogs: task-pool pick lists and capability ranking read/write the // user override layer (pool-config.json / capability-rank.json) directly, taking effect in sync with the plugin main // process mtime hot reload] -import { loadPoolConfig, writePoolConfig, resetPoolConfig, loadCapabilityRank, writeCapabilityRank, applyRankMove } from "./user-overrides" +import { loadPoolConfig, writePoolConfig, resetPoolConfig, loadCapabilityRank, writeCapabilityRank, applyRankMove, poolUniverse } from "./user-overrides" +// [2026-09-19]-[/switchman-setup wizard reads live setup completion (mtime-cached reads) so the intro state lines and +// the Start jump target reflect the config as of dialog open] +import { setupCompletionNow } from "./setup-gate" // [2026-09-07]-[version line next to the marquee: reuse the selfupdate state/flag readers so the sidebar shares the // exact same sources and TTL semantics as the update banner] import { readSelfUpdateState, flagSemantics, installedPluginVersion, versionBrief } from "./selfupdate" @@ -29,13 +36,17 @@ import { PLUGIN_VERSION } from "./version" import { allModelRows, rankViewRows } from "./config-cli" import { LANE_ORDER, type Lane } from "./types" import { runHandover, type HandoverPort } from "./handover-core" +import { t, resolveDisplayLocale, renderNotice, type LocaleTag, type MsgKey } from "./i18n" +import { readUiLocale, readWorkspaceDirname } from "./state" -type StatusLogEntry = { ts: string; text: string } +type StatusLogEntry = { ts: string; text?: string; key?: string; params?: Record<string, string | number>; alert?: boolean } type RouteSnapshotEntry = { lane: string; best: string | null; degraded: boolean } type RouteSnapshot = { ts: string; entries: RouteSnapshotEntry[] } // [2026-09-02]-[v2: one block per provider plus rows sub-lines (progress bar / reset time), isomorphic to providerStatusEntries in banner.ts] -type QuotaBriefRow = { label: string; text: string; usedPct: number | null; tail?: string } -type QuotaBriefEntry = { pool: string; label: string; rows: QuotaBriefRow[]; observeOnly: boolean; peakActive: boolean; stale: boolean } +// [2026-09-19]-[render-time quota i18n: rows/entry blocks carry key+params as the TUI render source (t(locale, key, params) +// against the quota.* catalog); legacy label/text/tail stay as the fallback when a key is absent] +type QuotaBriefRow = { key?: string; params?: Record<string, string | number>; labelKey?: string; labelParams?: Record<string, string | number>; tailKey?: string; tailParams?: Record<string, string | number>; usedPct: number | null; label?: string; text?: string; tail?: string } +type QuotaBriefEntry = { pool: string; label: string; key?: string; params?: Record<string, string | number>; rows: QuotaBriefRow[]; observeOnly: boolean; peakActive: boolean; stale: boolean } type QuotaBrief = { ts: string; entries: QuotaBriefEntry[] } function statusLogPath(): string { @@ -86,7 +97,6 @@ function readRestartRequired(): string[] { const POLL_MS = 2000 const SHOW_LAST = 1 -const RESTART_HINT_RE = /restart opencode[^;]*/gi const MARQUEE_MS = 150 const TITLE = "switchman" // [2026-09-07]-[version/restart flags are session-scoped: mtime later than this process's start = active, matching @@ -163,24 +173,45 @@ function hsvToHex(h: number, s: number, v: number): string { return `#${hex(to255(r))}${hex(to255(g))}${hex(to255(b))}` } -// [2026-09-01]-[When a notice carries a "restart opencode" hint (restartRequired / provider.list background probe), -// highlight it in error color to tell "manual restart needed" apart from ordinary status chatter at a glance; -// rendered by plain string splitting, no markdown/ansi parsing] -function noticeSegments(text: string): { text: string; alert: boolean }[] { - const matches = [...text.matchAll(RESTART_HINT_RE)] - if (matches.length === 0) return [{ text, alert: false }] - const segments: { text: string; alert: boolean }[] = [] - let cursor = 0 - for (const m of matches) { - const idx = m.index ?? 0 - if (idx > cursor) segments.push({ text: text.slice(cursor, idx), alert: false }) - segments.push({ text: m[0], alert: true }) - cursor = idx + m[0].length +// [2026-09-19]-[render-time locale: resolved per poll tick so language switches apply live; session directory first +// with the TUI directory as the sync fallback (same pattern as refreshBranch/location below; a thenable session.get +// result degrades to the fallback), then the workspace dirname snapshot, the global ui.lang snapshot, and finally the +// terminal env inside resolveDisplayLocale; all reads are cheap sync fs] +function resolveTuiLocale(api: TuiPluginApi, sessionID?: string): LocaleTag { + let sid = sessionID + if (!sid) { + try { + const route = api.route.current + if (route.name === "session" && typeof route.params?.sessionID === "string") sid = route.params.sessionID + } catch { /* fail-open: fall through without a session project step */ } } - if (cursor < text.length) segments.push({ text: text.slice(cursor), alert: false }) - return segments + let sessionDir: string | null = null + try { + if (sid) { + const s = api.state.session.get(sid) as unknown as { directory?: unknown; then?: unknown } | null + if (s && typeof s.then !== "function" && typeof s.directory === "string" && s.directory) { + sessionDir = s.directory + } + } + } catch { /* fail-open: fall through to the directory fallback */ } + if (!sessionDir) { + try { + const fallback = api.state.path.directory + sessionDir = typeof fallback === "string" ? fallback : null + } catch { sessionDir = null } + } + return resolveDisplayLocale({ + sessionDir, + workspaceDirname: readWorkspaceDirname(), + uiLang: readUiLocale(), + env: process.env, + }) } +// [2026-09-19]-[alert-flag notices: entries carry a structured `alert` flag (see src/state.ts) rendered in error color +// to tell "manual restart needed" apart from ordinary status chatter at a glance; text renders via renderNotice() +// (keyed entries translate, legacy prose passes through verbatim)] + // [2026-09-02]-[Restore the built-in footer content shadowed by this panel's single_winner: project path + git branch // + version line. This plugin's default order 0 < the built-in internal:sidebar-footer's 100, and the sidebar_footer // slot's single_winner only renders the chain head, so the built-in path:branch/version lines vanish entirely; @@ -233,6 +264,8 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { const [updateFlags, setUpdateFlags] = createSignal(flagSemantics(statusLogPath(), PROCESS_START)) const [installedVersion, setInstalledVersion] = createSignal<string | null>(installedPluginVersion()) const [tick, setTick] = createSignal(0) + // [2026-09-19]-[display locale signal: refreshed inside the poll tick below so language switches apply live] + const [locale, setLocale] = createSignal<LocaleTag>(resolveTuiLocale(props.api, props.sessionID)) // [2026-09-02]-[Branch signal: re-read .git/HEAD every poll cycle (session directory first, TUI directory as // fallback); also subscribes to vcs.branch.updated for instant refresh when the event chain works, with polling as // the safety net; falls back to api.state.vcs when the direct read fails] @@ -250,6 +283,7 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { setSelfUpdate(readSelfUpdateState()) setUpdateFlags(flagSemantics(statusLogPath(), PROCESS_START)) setInstalledVersion(installedPluginVersion()) + setLocale(resolveTuiLocale(props.api, props.sessionID)) refreshBranch() }, POLL_MS) // [2026-09-02]-[The title rainbow marquee needs its own heartbeat far faster than data polling; separate duties and @@ -304,22 +338,25 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { <box flexDirection="column" gap={0}> <text> {!q.observeOnly && <span style={{ fg: MODEL_COLOR }}>✓ </span>} - <b><span style={{ fg: theme().text }}>{q.label}</span></b> - {q.peakActive && <span style={{ fg: theme().warning }}> ·peak</span>} - {q.stale && <span style={{ fg: theme().warning }}> ·stale</span>} - {q.observeOnly && !allObserve && <span style={{ fg: theme().textMuted }}> ·observe-only</span>} + <b><span style={{ fg: theme().text }}>{q.key ? t(locale(), q.key as MsgKey, q.params) : q.label}</span></b> + {q.peakActive && <span style={{ fg: theme().warning }}>{t(locale(), "sidebar.peakTag")}</span>} + {q.stale && <span style={{ fg: theme().warning }}>{t(locale(), "sidebar.staleTag")}</span>} + {q.observeOnly && !allObserve && <span style={{ fg: theme().textMuted }}>{t(locale(), "sidebar.observeOnlyTag")}</span>} </text> <For each={q.rows}> {(r) => { - const { fill, track, rest } = splitBarText(r.text) + const rowText = r.key ? t(locale(), r.key as MsgKey, r.params) : (r.text ?? "") + const rowLabel = r.labelKey ? t(locale(), r.labelKey as MsgKey, r.labelParams) : (r.label ?? "") + const rowTail = r.tailKey ? t(locale(), r.tailKey as MsgKey, r.tailParams) : r.tail + const { fill, track, rest } = splitBarText(rowText) const value = waterColor(r.usedPct) return ( <text> - <span style={{ fg: theme().textMuted }}>{r.label ? ` ${padEndW(r.label, 8)}` : " "}</span> + <span style={{ fg: theme().textMuted }}>{rowLabel ? ` ${padEndW(rowLabel, 8)}` : " "}</span> <span style={{ fg: value ?? theme().textMuted }}>{fill}</span> <span style={{ fg: theme().textMuted }}>{track}</span> <span style={{ fg: value ?? theme().textMuted }}>{rest}</span> - {r.tail && <span style={{ fg: theme().textMuted }}> {r.tail}</span>} + {rowTail && <span style={{ fg: theme().textMuted }}> {rowTail}</span>} </text> ) }} @@ -343,19 +380,23 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { shell-registration restartRequired with upgrade-pending (upgraded.flag / prod disk-version mismatch); fail-open unchanged: missing state renders just the bare running version]-[impacts the sidebar title row only] */} <span style={{ fg: theme().textMuted }}> {version().running}</span> - {version().update !== null && <span style={{ fg: MODEL_COLOR }}> → {version().update}</span>} + {version().update !== null && <span style={{ fg: MODEL_COLOR }}>{t(locale(), "sidebar.updateAvailable", { updateVersion: version().update! })}</span>} {/* [2026-09-06]-[blinking restart tag: ~600ms on/off via the 150ms marquee heartbeat (tick/4 parity), bold red — a pending shell-registration restart used to render as a static tag that was easy to stop seeing; fail-open unchanged: empty restartRequired list renders nothing]-[impacts the sidebar title row only] */} {restartPending() && Math.floor(tick() / 4) % 2 === 0 && ( - <span style={{ fg: theme().error }}><b> [RESTART NEEDED]</b></span> + <span style={{ fg: theme().error }}><b>{t(locale(), "sidebar.restartNeeded")}</b></span> )} </text> <For each={routes()}> {(r: RouteSnapshotEntry) => ( <text fg={theme().textMuted}> - <span style={{ fg: LANE_COLOR }}>{r.lane.padEnd(10)} </span> - <span style={{ fg: MODEL_COLOR }}>{r.best ?? "none available"}</span> + {/* [2026-09-19]-[lane labels localized for DISPLAY ONLY: t() falls back to the raw lane identifier + (unknown/custom lanes render verbatim), so runtime LANE_ORDER, pool-config.json keys, [ROUTES] and + the protocol keep the hardcoded English identifiers; padEndW keeps CJK labels column-aligned]} + -[display-layer change, zero runtime impact] */} + <span style={{ fg: LANE_COLOR }}>{padEndW(t(locale(), `sidebar.lane.${r.lane}` as MsgKey, undefined, r.lane), 10)} </span> + <span style={{ fg: MODEL_COLOR }}>{r.best ?? t(locale(), "sidebar.noneAvailable")}</span> {r.degraded ? <span style={{ fg: theme().warning }}>*</span> : ""} </text> )} @@ -365,15 +406,13 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { {recent().length > 0 && ( <box paddingTop={1} flexDirection="column" gap={0}> <text fg={theme().textMuted}> - <b>notice</b> + <b>{t(locale(), "sidebar.noticeLabel")}</b> </text> <For each={recent()}> {(item: StatusLogEntry) => ( <text fg={theme().textMuted}> <span style={{ fg: theme().textMuted }}>{item.ts.slice(11, 19)} </span> - <For each={noticeSegments(item.text)}> - {(seg: { text: string; alert: boolean }) => <span style={{ fg: seg.alert ? theme().error : theme().text }}><b>{seg.text}</b></span>} - </For> + <span style={{ fg: item.alert ? theme().error : theme().text }}><b>{renderNotice(item, locale())}</b></span> </text> )} </For> @@ -410,6 +449,8 @@ function openPoolConfigDialog(api: TuiPluginApi): void { } function PoolPickerDialog(props: { api: TuiPluginApi }) { + // [2026-09-19]-[dialogs resolve the display locale once at mount (transient UI; the sidebar signal covers live switches)] + const loc = resolveTuiLocale(props.api) // [2026-09-03 semantic fix]-[Pool = task lane (economy/mechanical/main/hard/vision/review), not a provider pool: // pick the participating models per lane so the six-lane candidates differ; the same model may join multiple lanes] const lanes = createMemo(() => { @@ -423,13 +464,13 @@ function PoolPickerDialog(props: { api: TuiPluginApi }) { }) return ( <props.api.ui.DialogSelect - title="Task pools (pick a task pool; Esc to exit)" + title={t(loc, "dialog.pool.title")} options={lanes().map((p) => ({ - title: `${p.sel ? "✎ " : ""}${p.lane}`, + title: t(loc, "dialog.pool.laneRow", { pinMark: p.sel ? "✎ " : "", lane: p.lane }), value: p.lane, description: p.sel - ? `manual selection: ${p.sel.size}/${p.total} models participating` - : "not configured: system default (all available models participate)", + ? t(loc, "dialog.pool.manualSelection", { selCount: p.sel.size, totalCount: p.total }) + : t(loc, "dialog.pool.notConfigured"), onSelect: () => props.api.ui.dialog.replace(() => <PoolModelsDialog api={props.api} lane={p.lane} />), }))} /> @@ -437,6 +478,7 @@ function PoolPickerDialog(props: { api: TuiPluginApi }) { } function PoolModelsDialog(props: { api: TuiPluginApi; lane: Lane }) { + const loc = resolveTuiLocale(props.api) const rows = createMemo(() => allModelRows()) // Initial checkboxes: manually configured → the configured list; unconfigured → system default full set (the first // toggle materializes it as an explicit list) @@ -450,12 +492,17 @@ function PoolModelsDialog(props: { api: TuiPluginApi; lane: Lane }) { } catch (exc) { // Defensive: unknown lane/IO errors must not break the dialog (current lanes come from LANE_ORDER so this is // unreachable; guards future changes) - props.api.ui.toast({ variant: "error", message: `write failed: ${exc instanceof Error ? exc.message : exc}` }) + props.api.ui.toast({ variant: "error", message: t(loc, "dialog.pool.toggleWriteFailed", { message: exc instanceof Error ? exc.message : String(exc) }) }) return } props.api.ui.toast({ variant: added ? "success" : "info", - message: `${added ? "Added" : "Removed"} ${key} ${added ? "to" : "from"} the ${props.lane} pool (effective immediately, sidebar refreshes)`, + message: t(loc, "dialog.pool.modelToggled", { + verb: added ? "Added" : "Removed", + modelKey: key, + direction: added ? "to" : "from", + lane: props.lane, + }), }) } const toggle = (key: string) => { @@ -466,7 +513,7 @@ function PoolModelsDialog(props: { api: TuiPluginApi; lane: Lane }) { // Keep at least one participating model; to restore the system default use "Clear config" (empty list = // unconfigured = default full set) if (cur.size <= 1) { - props.api.ui.toast({ variant: "warning", message: 'Keep at least one participating model; use "Clear config" to restore the system default' }) + props.api.ui.toast({ variant: "warning", message: t(loc, "dialog.pool.keepOneModel") }) return } cur.delete(key) @@ -479,15 +526,15 @@ function PoolModelsDialog(props: { api: TuiPluginApi; lane: Lane }) { try { writePoolConfig(props.lane, [...cur]) } catch (exc) { - props.api.ui.toast({ variant: "error", message: `write failed: ${exc instanceof Error ? exc.message : exc}` }) + props.api.ui.toast({ variant: "error", message: t(loc, "dialog.pool.bulkWriteFailed", { message: exc instanceof Error ? exc.message : String(exc) }) }) return } - props.api.ui.toast({ variant: "success", message: `${props.lane} pool: all models selected` }) + props.api.ui.toast({ variant: "success", message: t(loc, "dialog.pool.allSelected", { lane: props.lane }) }) } const reset = () => { resetPoolConfig(props.lane) setSelected(new Set(rows().map((r) => r.key))) - props.api.ui.toast({ variant: "success", message: `${props.lane} pool config cleared (system default candidate set restored)` }) + props.api.ui.toast({ variant: "success", message: t(loc, "dialog.pool.configCleared", { lane: props.lane }) }) } // [2026-09-06]-[Uncheck-all shortcut: clears the checkbox state in place (no disk write) so a short list can be // built by checking a few models instead of unchecking the rest one by one; while nothing is checked the previous @@ -496,24 +543,24 @@ function PoolModelsDialog(props: { api: TuiPluginApi; lane: Lane }) { const uncheckAll = () => { if (selected().size === 0) return setSelected(new Set<string>()) - props.api.ui.toast({ variant: "info", message: `${props.lane} pool: all unchecked — check the models to keep; exiting with none checked keeps the previous selection` }) + props.api.ui.toast({ variant: "info", message: t(loc, "dialog.pool.allUnchecked", { lane: props.lane }) }) } const nSel = () => selected().size const options = createMemo(() => [ - { title: "← Back to pool list", value: "__back", onSelect: () => props.api.ui.dialog.replace(() => <PoolPickerDialog api={props.api} />) }, - { title: "☑ Select all", value: "__all", onSelect: () => bulk() }, - { title: "☐ Uncheck all (then check the few to keep; exit with none checked keeps the old list)", value: "__uncheckAll", onSelect: uncheckAll }, - { title: "✕ Clear config (system default: all available models participate)", value: "__reset", onSelect: reset }, + { title: t(loc, "dialog.pool.back"), value: "__back", onSelect: () => props.api.ui.dialog.replace(() => <PoolPickerDialog api={props.api} />) }, + { title: t(loc, "dialog.pool.selectAll"), value: "__all", onSelect: () => bulk() }, + { title: t(loc, "dialog.pool.uncheckAll"), value: "__uncheckAll", onSelect: uncheckAll }, + { title: t(loc, "dialog.pool.clearConfig"), value: "__reset", onSelect: reset }, ...rows().map((r) => ({ - title: `${selected().has(r.key) ? "[x]" : "[ ]"} ${r.modelId}`, + title: t(loc, "dialog.pool.modelRow", { checkMark: selected().has(r.key) ? "[x]" : "[ ]", modelId: r.modelId }), value: r.key, - description: `${r.tier}-tier${r.source === "manual" ? " · manual rank" : ""}`, + description: t(loc, "dialog.pool.rowMeta", { tier: r.tier, manualSuffix: r.source === "manual" ? " · manual rank" : "" }), onSelect: () => toggle(r.key), })), ]) return ( <props.api.ui.DialogSelect - title={`${props.lane} pool selection (${nSel()}/${rows().length} participating; select toggles, duplicates across pools allowed)`} + title={t(loc, "dialog.pool.selectionTitle", { lane: props.lane, selCount: nSel(), rowCount: rows().length })} options={options()} flat /> @@ -521,13 +568,38 @@ function PoolModelsDialog(props: { api: TuiPluginApi; lane: Lane }) { } function openModelRankDialog(api: TuiPluginApi): void { - api.ui.dialog.replace(() => <RankPickerDialog api={api} />) + // [2026-09-18]-[rank universe = pool selection: with no task pool configured there is nothing to rank — guide to + // /poolConfig instead of offering a full-superset ranking list (the config flow is poolConfig → modelRank)] + api.ui.dialog.replace(() => + poolUniverse().size === 0 + ? <RankUniverseEmptyDialog api={api} /> + : <RankPickerDialog api={api} /> + ) +} + +// ---- [2026-09-18]-[/modelRank empty state: no task-pool selection yet — one action jumps straight into the pool +// picker so the two-step config flow (poolConfig → modelRank) stays a single round trip]---- + +function RankUniverseEmptyDialog(props: { api: TuiPluginApi }) { + const loc = resolveTuiLocale(props.api) + const options = createMemo(() => [ + { title: t(loc, "dialog.rank.openPoolSelection"), value: "__pools", onSelect: () => props.api.ui.dialog.replace(() => <PoolPickerDialog api={props.api} />) }, + { title: t(loc, "dialog.rank.close"), value: "__close", onSelect: () => props.api.ui.dialog.clear() }, + ]) + return ( + <props.api.ui.DialogSelect + title={t(loc, "dialog.rank.universeEmptyTitle")} + options={options()} + flat + /> + ) } // ---- [2026-09-10]-[interleaved move plumbing: one shared path for the list hotkeys and the per-model actions dialog — // loads the rank file, applies applyRankMove against the merged view, persists models+scores, toasts the anchored result]---- function rankMoveApply(api: TuiPluginApi, key: string, delta: -1 | 0 | 1): boolean { + const loc = resolveTuiLocale(api) const rank = loadCapabilityRank() const view = rankViewRows() const name = view.find((r) => r.key === key)?.modelId ?? key @@ -535,19 +607,25 @@ function rankMoveApply(api: TuiPluginApi, key: string, delta: -1 | 0 | 1): boole if (!res) { api.ui.toast({ variant: "info", - message: `${name} is already at the ${delta === 1 ? "bottom" : "top"} of the merged capability list`, + message: t(loc, "dialog.rank.alreadyAtEdge", { modelName: name, edge: delta === 1 ? "bottom" : "top" }), }) return false } try { writeCapabilityRank(res.models, res.scores) } catch (exc) { - api.ui.toast({ variant: "error", message: `write failed: ${exc instanceof Error ? exc.message : exc}` }) + api.ui.toast({ variant: "error", message: t(loc, "dialog.rank.moveWriteFailed", { message: exc instanceof Error ? exc.message : String(exc) }) }) return false } api.ui.toast({ variant: "success", - message: `${delta === 0 ? "Pinned" : "Moved"} ${name} to #${res.position + 1} (manual score ${res.score.tier}/${res.score.raw}, anchored between its neighbors; effective immediately, sidebar refreshes)`, + message: t(loc, "dialog.rank.pinnedOrMoved", { + verb: delta === 0 ? "Pinned" : "Moved", + modelName: name, + position: res.position + 1, + tier: res.score.tier, + raw: res.score.raw, + }), }) return true } @@ -561,6 +639,7 @@ type RankHotkeyClaim = { move: (delta: -1 | 1) => void } let rankHotkeyClaim: RankHotkeyClaim | null = null function RankPickerDialog(props: { api: TuiPluginApi }) { + const loc = resolveTuiLocale(props.api) // rev bumps on every hotkey write so rows() re-reads the rank file and re-sorts the list in place (enter-action // flows keep using dialog.replace instead, which rebuilds the component from scratch) const [rev, setRev] = createSignal(0) @@ -601,12 +680,16 @@ function RankPickerDialog(props: { api: TuiPluginApi }) { }) return ( <props.api.ui.DialogSelect - title="Model capability ranking — merged order (#1 strongest; manual entries interleave with base-score models; ctrl+up/ctrl+down move one spot; enter = per-model actions)" - placeholder="Search · alt+up/alt+down mirror ctrl+up/ctrl+down (also work)" + title={t(loc, "dialog.rank.title")} + placeholder={t(loc, "dialog.rank.searchHint")} options={rows().map((r, i) => ({ - title: `#${String(i + 1).padStart(2, "0")} ${r.modelId}`, + title: t(loc, "dialog.rank.row", { rankPadded: String(i + 1).padStart(2, "0"), modelId: r.modelId }), value: r.key, - description: `${r.tier}-tier · ${r.source === "manual" ? `manual${r.raw !== null ? ` ${r.raw}` : ""}` : "base capability score"}`, + description: t(loc, "dialog.rank.rowMeta", { + tier: r.tier, + scoreSource: r.source === "manual" ? `manual${r.raw !== null ? ` ${r.raw}` : ""}` : "base capability score", + poolSuffix: r.poolMember === false ? " · not in any task pool" : "", + }), onSelect: () => props.api.ui.dialog.replace(() => <RankActionsDialog api={props.api} model={r.modelId} modelKey={r.key} />), }))} current={cursor() ?? undefined} @@ -617,6 +700,7 @@ function RankPickerDialog(props: { api: TuiPluginApi }) { } function RankActionsDialog(props: { api: TuiPluginApi; model: string; modelKey: string }) { + const loc = resolveTuiLocale(props.api) // [2026-09-10]-[interleaved semantics: up/down/pin act on the merged view via the shared rankMoveApply path (any // model can move — unranked ones materialize an anchored manual score between their neighbors); the obsolete // "add at the end" action is gone; remove strips both the membership and the anchored score] @@ -636,25 +720,211 @@ function RankActionsDialog(props: { api: TuiPluginApi; model: string; modelKey: try { writeCapabilityRank(nextModels, Object.keys(nextScores).length > 0 ? nextScores : undefined) } catch (exc) { - props.api.ui.toast({ variant: "error", message: `write failed: ${exc instanceof Error ? exc.message : exc}` }) + props.api.ui.toast({ variant: "error", message: t(loc, "dialog.rank.removeWriteFailed", { message: exc instanceof Error ? exc.message : String(exc) }) }) return } - props.api.ui.toast({ variant: "success", message: `Removed ${props.model} from the manual ranking (falls back to the base capability score, effective immediately, sidebar refreshes)` }) + props.api.ui.toast({ variant: "success", message: t(loc, "dialog.rank.removed", { model: props.model }) }) props.api.ui.dialog.replace(() => <RankPickerDialog api={props.api} />) } const options = createMemo(() => [ - { title: "▲ Pin to top (above every model)", value: "top", onSelect: () => move(0) }, - { title: "↑ Move up one (swaps with the model above; anchors a manual score between neighbors)", value: "up", onSelect: () => move(-1) }, - { title: "↓ Move down one (swaps with the model below)", value: "down", onSelect: () => move(1) }, + { title: t(loc, "dialog.rank.pinTop"), value: "top", onSelect: () => move(0) }, + { title: t(loc, "dialog.rank.moveUp"), value: "up", onSelect: () => move(-1) }, + { title: t(loc, "dialog.rank.moveDown"), value: "down", onSelect: () => move(1) }, ...(ranked() - ? [{ title: "✕ Remove from ranking (fall back to the base score)", value: "out", onSelect: remove }] + ? [{ title: t(loc, "dialog.rank.remove"), value: "out", onSelect: remove }] : []), - { title: "← Back to ranking list", value: "__back", onSelect: () => props.api.ui.dialog.replace(() => <RankPickerDialog api={props.api} />) }, + { title: t(loc, "dialog.rank.back"), value: "__back", onSelect: () => props.api.ui.dialog.replace(() => <RankPickerDialog api={props.api} />) }, ]) const a = anchored() return ( <props.api.ui.DialogSelect - title={`${props.model} (${ranked() ? `manually ranked${a ? `, anchored score ${a.tier}/${a.raw}` : " (legacy ladder order)"}` : "not manually ranked"})`} + title={t(loc, "dialog.rank.detailTitle", { + model: props.model, + rankState: ranked() ? `manually ranked${a ? `, anchored score ${a.tier}/${a.raw}` : " (legacy ladder order)"}` : "not manually ranked", + })} + options={options()} + flat + /> + ) +} + +// ---- [2026-09-19]-[/switchman-setup guided wizard: replaces the old default-all behavior (unconfigured pools no +// longer fall back to every model). Flow: intro (current state + jump to the first unfinished step) → one dialog per +// task lane in LANE_ORDER order (deliberate curation: selection starts EMPTY even when the lane is unconfigured; +// Enter toggles in memory only, the per-lane confirm persists to pool-config.json so every save hot-reloads the +// running plugin and the wizard stays resumable lane-by-lane) → sequential capability-rank pick (min 1 model) → +// done screen reporting the hot effect plus any providers still flagged restartRequired. Dialog family mirrors +// PoolPickerDialog/PoolModelsDialog/RankPickerDialog: locale resolved once at mount, Set-based toggles with +// [x]/[ ] baked into titles, dialog.replace navigation, Esc handled by the host. Locale keys: dialog.setup.* / +// palette.setup.*]---- + +function openSetupWizard(api: TuiPluginApi): void { + api.ui.dialog.replace(() => <SetupIntroDialog api={api} />) +} + +function SetupIntroDialog(props: { api: TuiPluginApi }) { + const loc = resolveTuiLocale(props.api) + // Completion is frozen at open (transient dialog); Start re-evaluates so it always jumps to the first unfinished step + const state = setupCompletionNow() + // {state} has no localized word pair yet — plain "ok"/"missing" strings + const rankState = state.missingRank ? "missing" : "ok" + const start = () => { + const c = setupCompletionNow() + // First lane in LANE_ORDER order whose selection is empty (missingLanes preserves LANE_ORDER order) + const laneIdx = LANE_ORDER.findIndex((lane) => c.missingLanes.includes(lane)) + if (laneIdx >= 0) props.api.ui.dialog.replace(() => <SetupLaneDialog api={props.api} laneIdx={laneIdx} />) + else if (c.missingRank) props.api.ui.dialog.replace(() => <SetupRankDialog api={props.api} />) + else props.api.ui.dialog.replace(() => <SetupDoneDialog api={props.api} />) + } + const options = createMemo(() => [ + { title: t(loc, "dialog.setup.start"), value: "__start", description: t(loc, "dialog.setup.intro"), onSelect: start }, + { title: t(loc, "dialog.rank.close"), value: "__cancel", onSelect: () => props.api.ui.dialog.clear() }, + // Footer-ish info rows (disabled): current pools/rank state at open time + { title: t(loc, "dialog.setup.statePools", { count: state.configuredLanes }), value: "__statePools", disabled: true }, + { title: t(loc, "dialog.setup.stateRank", { state: rankState }), value: "__stateRank", disabled: true }, + ]) + return ( + <props.api.ui.DialogSelect + title={t(loc, "dialog.setup.title")} + options={options()} + flat + /> + ) +} + +function SetupLaneDialog(props: { api: TuiPluginApi; laneIdx: number }) { + const loc = resolveTuiLocale(props.api) + const lane = LANE_ORDER[props.laneIdx] + const rows = createMemo(() => allModelRows()) + // Deliberate curation: resume the configured list when present, otherwise start EMPTY (no default-all — that is + // exactly the behavior this wizard replaces) + const [selected, setSelected] = createSignal<ReadonlySet<string>>( + new Set(loadPoolConfig()[lane] ?? []), + ) + // Select-all / clear-all stay in memory: nothing is written until the explicit confirm below + const bulkAll = () => setSelected(new Set(rows().map((r) => r.key))) + const bulkClear = () => setSelected(new Set<string>()) + const toggle = (key: string) => { + const cur = new Set(selected()) + if (cur.has(key)) cur.delete(key) + else cur.add(key) + setSelected(cur) + } + const back = () => { + if (props.laneIdx > 0) props.api.ui.dialog.replace(() => <SetupLaneDialog api={props.api} laneIdx={props.laneIdx - 1} />) + else props.api.ui.dialog.replace(() => <SetupIntroDialog api={props.api} />) + } + const confirm = () => { + if (selected().size === 0) { + props.api.ui.toast({ variant: "warning", message: t(loc, "dialog.setup.keepOne") }) + return + } + try { + writePoolConfig(lane, [...selected()]) + } catch (exc) { + // Same fail-open semantics as PoolModelsDialog: an IO error must not break the dialog + props.api.ui.toast({ variant: "error", message: t(loc, "dialog.pool.toggleWriteFailed", { message: exc instanceof Error ? exc.message : String(exc) }) }) + return + } + // Receipt reuses statePools with the fresh configured count (mtime-cached read sees this write immediately) + props.api.ui.toast({ variant: "success", message: t(loc, "dialog.setup.statePools", { count: setupCompletionNow().configuredLanes }) }) + if (props.laneIdx + 1 < LANE_ORDER.length) props.api.ui.dialog.replace(() => <SetupLaneDialog api={props.api} laneIdx={props.laneIdx + 1} />) + else props.api.ui.dialog.replace(() => <SetupRankDialog api={props.api} />) + } + const options = createMemo(() => [ + { title: t(loc, "dialog.setup.selectAll"), value: "__all", onSelect: bulkAll }, + { title: t(loc, "dialog.setup.clearAll"), value: "__clear", onSelect: bulkClear }, + { title: t(loc, "dialog.setup.back"), value: "__back", onSelect: back }, + { title: t(loc, "dialog.setup.confirmLane", { lane, count: selected().size }), value: "__confirm", onSelect: confirm }, + ...rows().map((r) => ({ + title: t(loc, "dialog.setup.laneRow", { checkMark: selected().has(r.key) ? "[x]" : "[ ]", modelId: r.modelId }), + value: r.key, + description: t(loc, "dialog.pool.rowMeta", { tier: r.tier, manualSuffix: r.source === "manual" ? " · manual rank" : "" }), + onSelect: () => toggle(r.key), + })), + ]) + return ( + <props.api.ui.DialogSelect + title={t(loc, "dialog.setup.laneTitle", { index: props.laneIdx + 1, lane, count: selected().size })} + options={options()} + flat + /> + ) +} + +function SetupRankDialog(props: { api: TuiPluginApi }) { + const loc = resolveTuiLocale(props.api) + // Sequential pick: every selection appends to `picked` and the dialog rebuilds with the next pick number + // (rev bumps like RankPickerDialog so the remaining-rows memo re-reads the universe) + const [rev, setRev] = createSignal(0) + const [picked, setPicked] = createSignal<string[]>([]) + const remaining = createMemo(() => { + rev() + const uni = poolUniverse() + const done = new Set(picked()) + return allModelRows().filter((r) => uni.has(r.key) && !done.has(r.key)) + }) + // Guard: an empty rank universe should be unreachable (pools were just configured), divert to the intro instead of + // stranding the user on an action-less list + onMount(() => { + if (poolUniverse().size === 0) { + props.api.ui.toast({ variant: "warning", message: t(loc, "dialog.setup.keepOne") }) + props.api.ui.dialog.replace(() => <SetupIntroDialog api={props.api} />) + } + }) + const finish = () => { + if (picked().length === 0) { + props.api.ui.toast({ variant: "warning", message: t(loc, "dialog.setup.rankMinOne") }) + return + } + try { + writeCapabilityRank(picked(), undefined) + } catch (exc) { + props.api.ui.toast({ variant: "error", message: t(loc, "dialog.rank.moveWriteFailed", { message: exc instanceof Error ? exc.message : String(exc) }) }) + return + } + props.api.ui.toast({ variant: "success", message: t(loc, "dialog.setup.rankFinish", { count: picked().length }) }) + props.api.ui.dialog.replace(() => <SetupDoneDialog api={props.api} />) + } + const pick = (key: string) => { + setPicked((cur) => (cur.includes(key) ? cur : [...cur, key])) + setRev((v) => v + 1) + } + const options = createMemo(() => [ + { title: t(loc, "dialog.setup.rankFinish", { count: picked().length }), value: "__finish", onSelect: finish }, + ...remaining().map((r) => ({ + title: t(loc, "dialog.setup.laneRow", { checkMark: "→", modelId: r.modelId }), + value: r.key, + description: t(loc, "dialog.pool.rowMeta", { tier: r.tier, manualSuffix: r.source === "manual" ? " · manual rank" : "" }), + onSelect: () => pick(r.key), + })), + ]) + return ( + <props.api.ui.DialogSelect + title={t(loc, "dialog.setup.rankTitle", { n: picked().length + 1, remaining: remaining().length })} + options={options()} + flat + /> + ) +} + +function SetupDoneDialog(props: { api: TuiPluginApi }) { + const loc = resolveTuiLocale(props.api) + const poolCfg = loadPoolConfig() + const summary = LANE_ORDER.map((lane) => `${lane} ${poolCfg[lane]?.size ?? 0}`).join(", ") + const order = (loadCapabilityRank()?.models ?? []).join(" > ") + const restart = readRestartRequired() + const options = createMemo(() => [ + { title: t(loc, "dialog.setup.donePools", { summary }), value: "__pools", disabled: true }, + { title: t(loc, "dialog.setup.doneRank", { order }), value: "__rank", disabled: true }, + ...(restart.length > 0 + ? [{ title: t(loc, "dialog.setup.restartHint", { providers: restart.join(", ") }), value: "__restart", disabled: true }] + : []), + { title: t(loc, "dialog.rank.close"), value: "__close", onSelect: () => props.api.ui.dialog.clear() }, + ]) + return ( + <props.api.ui.DialogSelect + title={t(loc, "dialog.setup.doneTitle")} options={options()} flat /> @@ -707,21 +977,22 @@ function v2HandoverPort(api: TuiPluginApi): HandoverPort { async function runHandoverBackup(api: TuiPluginApi): Promise<void> { const route = api.route.current const sessionID = route.name === "session" && typeof route.params?.sessionID === "string" ? route.params.sessionID : undefined + const loc = resolveTuiLocale(api, sessionID) if (!sessionID) { - api.ui.toast({ variant: "error", message: "/handover: not in a session, nothing to back up" }) + api.ui.toast({ variant: "error", message: t(loc, "dialog.handover.noSession") }) return } const session = api.state.session.get(sessionID) const directory = session?.directory || api.state.path.directory - api.ui.toast({ variant: "info", message: "/handover: backing up the current session in full and compacting…" }) + api.ui.toast({ variant: "info", message: t(loc, "dialog.handover.inProgress") }) const result = await runHandover(v2HandoverPort(api), sessionID, directory) if (result.ok) { api.ui.toast({ variant: "success", - message: `${result.message}; still in the original session, not switched`, + message: t(loc, "dialog.handover.resultStay", { resultMessage: result.message }), }) } else { - api.ui.toast({ variant: "error", message: `/handover ${result.message}` }) + api.ui.toast({ variant: "error", message: t(loc, "dialog.handover.result", { resultMessage: result.message }) }) } } @@ -739,36 +1010,47 @@ const tui: TuiPlugin = async (api) => { // registerLayer, fail-open = only the dialog entry goes missing (the chat cfg.command variants are unaffected) // [2026-09-04]-[/handover: direct execution (fork backup + compaction of the current session, no session switch), // no AI interaction, no chat variant] + // [2026-09-19]-[palette copy resolves the display locale once at registration (static host strings)] + const paletteLoc = resolveTuiLocale(api) try { api.keymap.registerLayer({ commands: [ { name: "switchman.handover", - title: "Back up and compact the current session", - desc: "Full fork of the current session as a backup ([backup] title tag) plus compaction of the current session; no session switch (distinct from built-in /fork)", - category: "switchman", + title: t(paletteLoc, "palette.handover.title"), + desc: t(paletteLoc, "palette.handover.desc"), + category: t(paletteLoc, "palette.category.label"), namespace: "palette", slashName: "handover", run: () => void runHandoverBackup(api), }, { name: "switchman.pool-config", - title: "Task pool selection", - desc: "Pick the participating models per task pool (economy/mechanical/main/hard/vision/review)", - category: "switchman", + title: t(paletteLoc, "palette.poolConfig.title"), + desc: t(paletteLoc, "palette.poolConfig.desc"), + category: t(paletteLoc, "palette.category.label"), namespace: "palette", slashName: "poolConfig", run: () => openPoolConfigDialog(api), }, { name: "switchman.model-rank", - title: "Model capability ranking", - desc: "Manual capability ranking (takes precedence over base scores; earlier = stronger)", - category: "switchman", + title: t(paletteLoc, "palette.modelRank.title"), + desc: t(paletteLoc, "palette.modelRank.desc"), + category: t(paletteLoc, "palette.category.label"), namespace: "palette", slashName: "modelRank", run: () => openModelRankDialog(api), }, + { + name: "switchman.setup", + title: t(paletteLoc, "palette.setup.title"), + desc: t(paletteLoc, "palette.setup.desc"), + category: t(paletteLoc, "palette.category.label"), + namespace: "palette", + slashName: "switchman-setup", + run: () => void openSetupWizard(api), + }, ], bindings: [], }) diff --git a/src/types.ts b/src/types.ts index 5883c0a..097ecf5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -292,7 +292,7 @@ export interface ContextOptions { /** [2026-09-04]-[After exceeding the force-compaction watermark, tool.execute.after auto-triggers /handover (fork backup + compact the current session; * the task continues automatically with summary context); default true; false = banner hint only, relying on manual /handover] */ autoHandover?: boolean - /** Per-call self-read budget R* in tokens: reads estimated above this are auto-bounded or denied with bounded-retry params; default 1500 (clamped 200..20000) */ + /** Per-call self-read budget R* in tokens: reads within R*+tolerance or the remaining turn headroom (2×R* fresh) are granted one-shot; above that auto-bounded or denied with bounded-retry params; default 1500 (clamped 200..20000) */ readBudgetTokens?: number /** [2026-09-06]-[subagent hard cap (tokens): when a shell subagent's measured context reaches it, every further tool * call in that session is denied with a wrap-up order (the next text-only answer = detailed progress summary = task diff --git a/src/user-overrides.ts b/src/user-overrides.ts index 6ee442a..40eb767 100644 --- a/src/user-overrides.ts +++ b/src/user-overrides.ts @@ -155,10 +155,19 @@ export function poolAllowlist(lane: string): ReadonlySet<string> | null { return loadPoolConfig()[lane] ?? null } -/** Manual override summary (banner/doctor display: rank entry count + number of task pools with selection lists configured) */ -export function overrideSummary(): { rankModels: number; poolLanes: number } { +/** [2026-09-18]-[rank universe = pool selection: union of the models selected into ANY task-pool lane. The /modelRank + * surfaces (TUI dialog, rank CLI) list only this universe (+ existing manual entries as removable dead keys), so users + * never rank models they cannot dispatch; empty set = no pool configured yet (surfaces guide to /poolConfig first)] */ +export function poolUniverse(): ReadonlySet<string> { + const out = new Set<string>() + for (const ids of Object.values(loadPoolConfig())) for (const id of ids) out.add(id) + return out +} + +/** Manual override summary (banner/doctor display: rank entry count + task pools with selection lists + rank-universe size) */ +export function overrideSummary(): { rankModels: number; poolLanes: number; universeModels: number } { const rank = loadCapabilityRank() - return { rankModels: rank?.models.length ?? 0, poolLanes: Object.keys(loadPoolConfig()).length } + return { rankModels: rank?.models.length ?? 0, poolLanes: Object.keys(loadPoolConfig()).length, universeModels: poolUniverse().size } } // ---- Pure manual-ranking move (shared semantics for the TUI /modelRank dialog: enter actions and ctrl+up/ctrl+down hotkeys) ---- @@ -264,7 +273,13 @@ export function applyRankMove( // ---- Writes (shared by CLI/TUI; atomic replacement + cache invalidation; empty list = delete key/file back to default) ---- export function writeCapabilityRank(models: string[], scores?: Record<string, RankScoreOverride>): CapabilityRankFile { - const file = validateCapabilityRank({ models, scores })! + // [2026-09-18]-[auto-prune on write: dead manual keys converge away — with a non-empty pool universe, entries outside + // it (and their anchored scores, dropped by validateCapabilityRank keeping only model-listed keys) are removed on + // every rank write (CLI set/add/remove, TUI move/remove — all persist through here). Empty-universe writes stay + // untouched so the no-pool cleanup path (rank remove/clear of legacy entries) still works] + const universe = poolUniverse() + const kept = universe.size > 0 ? models.filter((k) => universe.has(k)) : models + const file = validateCapabilityRank({ models: kept, scores })! writeJsonAtomic(paths().capabilityRank, { ...file, updated_at: nowIso() }) mtimeCache.delete(paths().capabilityRank) return file diff --git a/src/version.ts b/src/version.ts index 8879019..de7542e 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,2 +1,2 @@ // Generated at build time: run bun scripts/gen-version.ts -export const PLUGIN_VERSION = "1.1.1" +export const PLUGIN_VERSION = "1.2.0" diff --git a/test/activation.test.ts b/test/activation.test.ts index d4447df..b553d52 100644 --- a/test/activation.test.ts +++ b/test/activation.test.ts @@ -536,9 +536,9 @@ describe("lane completion policy", () => { } const visionChain = laneBaseChain("vision", { builtin: [], activeShells: active, shells: attrs }) expect(visionChain.every((n) => attrs.get(n)!.vision)).toBe(true) - // economy prefers low tiers, hard prefers high tiers + // [2026-09-18]-[economy order medium→high→low→minimal: glm-5.3-flash (low/high/max, no medium) takes its high face as the economy head] const eco = laneBaseChain("economy", { builtin: [], activeShells: active, shells: attrs }) - expect(eco[0]).toBe("glm-mx-53f-low") + expect(eco[0]).toBe("glm-mx-53f-high") const hard = laneBaseChain("hard", { builtin: [], activeShells: active, shells: attrs }) expect(hard[0]).toBe("glm-mx-53f-high") // the model's highest tier // review prefers the -ro alias diff --git a/test/auto-handover.test.ts b/test/auto-handover.test.ts index 1004fc5..753d351 100644 --- a/test/auto-handover.test.ts +++ b/test/auto-handover.test.ts @@ -16,10 +16,17 @@ process.env.SWITCHMAN_STATE = stateDir writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) import { SwitchmanPlugin } from "../src/index" +import { renderNotice } from "../src/i18n" function readStatusLog(): string { const p = join(stateDir, "status-log.json") - return existsSync(p) ? readFileSync(p, "utf8") : "" + if (!existsSync(p)) return "" + // [2026-09-19]-[i18n cleanup: entries are structured {key, params} — render English for the prose assertions] + try { + const data = JSON.parse(readFileSync(p, "utf8")) + if (Array.isArray(data)) return data.map((e: { key?: string; params?: Record<string, string | number>; text?: string }) => renderNotice(e, "en")).join("\n") + } catch { /* fail-open: fall through to raw text */ } + return readFileSync(p, "utf8") } test("auto-handover: backup leg bounded, compaction fired detached, cooldown guards refork", async () => { diff --git a/test/auto-redirect.test.ts b/test/auto-redirect.test.ts index 5d57fb6..8033463 100644 --- a/test/auto-redirect.test.ts +++ b/test/auto-redirect.test.ts @@ -40,6 +40,11 @@ for (const [file, body] of Object.entries({ } as Record<string, unknown>)) { writeFileSync(join(process.env.SWITCHMAN_STATE, file), JSON.stringify(body)) } +// [2026-09-19]-[setup hard gate fixture: seed a COMPLETE setup before any hook call — all 6 task pools carry the +// full manifest model universe (gate 5.5 membership = allow-all, identical to the old unconfigured fail-open +// semantics) and the rank holds one fixture key that prefix-matches no real modelId (scoring/ordering untouched). +// Without this the new setup gate denies every task call before reaching the gates under test]- +seedCompleteSetup(process.env.SWITCHMAN_STATE!, manifestModelUniverse()) afterAll(() => { if (prevState === undefined) delete process.env.SWITCHMAN_STATE else process.env.SWITCHMAN_STATE = prevState @@ -49,6 +54,7 @@ afterAll(() => { import { SwitchmanPlugin } from "../src/index" import { loadManifest, stateDir } from "../src/state" +import { seedCompleteSetup, manifestModelUniverse } from "./setup-seed" type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> diff --git a/test/candidates-cli.test.ts b/test/candidates-cli.test.ts index f67cb41..7f325ce 100644 --- a/test/candidates-cli.test.ts +++ b/test/candidates-cli.test.ts @@ -1,11 +1,15 @@ // [2026-09-10]-[candidate surface widening: /modelRank //poolConfig lists read candidates (full superset) first, falling // back to the injection-face shells, then the bundled manifest; anchors the read path of shell-superset.json] -import { describe, expect, test, beforeAll, afterAll } from "bun:test" +import { describe, expect, test, beforeAll, afterAll, afterEach } from "bun:test" import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs" import { join } from "node:path" import { tmpdir } from "node:os" import { paths } from "../src/state" -import { allModelRows } from "../src/config-cli" +import { allModelRows, rankViewRows, runCli } from "../src/config-cli" +import { + writeCapabilityRank, clearCapabilityRank, loadCapabilityRank, + writePoolConfig, resetPoolConfig, +} from "../src/user-overrides" process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-candcli-")) const stateDir: string = process.env.SWITCHMAN_STATE @@ -16,6 +20,23 @@ const entry = (modelId: string, name: string) => ({ family: "openai", capability: "rw", vision: false, matrixKey: `github-copilot|${modelId}|high`, }) +// console.log/error are swapped for the duration of each runCli call and restored in finally (output capture only) +function captureCli(argv: string[]): { code: number; out: string; err: string } { + const out: string[] = [] + const err: string[] = [] + const origLog = console.log + const origErr = console.error + console.log = (msg?: unknown) => { out.push(String(msg)) } + console.error = (msg?: unknown) => { err.push(String(msg)) } + try { + const code = runCli(argv) + return { code, out: out.join("\n"), err: err.join("\n") } + } finally { + console.log = origLog + console.error = origErr + } +} + beforeAll(() => { // Pin the base-score source so tier/sort assertions do not drift with realtime capability data writeFileSync(join(stateDir, "capability.json"), JSON.stringify({ version: 1 })) @@ -65,4 +86,113 @@ describe("allModelRows (candidate source precedence)", () => { }) }) +// [2026-09-18]-[rank universe = pool selection, dead keys pruned: rankViewRows shows EXACTLY the pool-selected universe +// when one exists (dead manual keys are gone from the view AND from the rank file after any write — auto-prune in +// writeCapabilityRank); with NO pool configured the view degenerates to the manual entries alone (cleanup-only) and +// writes stay untouched. Fixtures reuse the file's shellSuperset helper; each test restores the default (unconfigured) +// state in afterEach]-[impact: pins rankViewRows scoping + write-path auto-prune; no src change here] +describe("rankViewRows (pool-universe scoping)", () => { + // loadSupersetShells requires a non-empty `shells` array even when `candidates` feeds the rows (src/state.ts) + const supersetOnly = () => writeFileSync(paths().shellSuperset, JSON.stringify({ + generated_at: new Date().toISOString(), + counts: { superset_models: 3, shells: 1, full_shells: 3 }, + candidates: [entry("glm-5.3", "cp-mx-glm53-high"), entry("kimi-k3", "cp-mx-kimik3-high"), entry("solo-model", "cp-mx-solo-high")], + shells: [entry("glm-5.3", "cp-mx-glm53-high")], + })) + + afterEach(() => { + clearCapabilityRank() + resetPoolConfig("main") + }) + + test("with a pool configured: EXACTLY the pool universe is listed; dead manual keys are absent from the view", () => { + supersetOnly() + writePoolConfig("main", ["glm-5.3", "kimi-k3"]) + writeCapabilityRank(["glm-5.3", "ghost-model"]) // dead key pruned on write (non-empty universe) + const keys = rankViewRows().map((r) => r.key).sort() + expect(keys).toEqual(["glm-5.3", "kimi-k3"]) + expect(keys).not.toContain("ghost-model") // dead manual key: no longer listed + expect(keys).not.toContain("solo-model") // superset model in no pool and not manually ranked: absent + }) + + test("poolMember flags: every listed row is a pool member (true)", () => { + supersetOnly() + writePoolConfig("main", ["glm-5.3", "kimi-k3"]) + writeCapabilityRank(["glm-5.3"]) + const rows = rankViewRows() + expect(rows.length).toBeGreaterThan(0) + expect(rows.every((r) => r.poolMember === true)).toBe(true) + }) + + test("no pool configured: the view degenerates to the manual entries alone (cleanup-only, base rows filtered out)", () => { + supersetOnly() + writeCapabilityRank(["glm-5.3", "ghost-model"]) + resetPoolConfig("main") // universe empty + const rows = rankViewRows() + expect(rows.map((r) => r.key)).toEqual(["glm-5.3", "ghost-model"]) + }) + + test("auto-prune on write: a legacy dead key (seeded stale file) converges away on the next rank add", () => { + supersetOnly() + writePoolConfig("main", ["glm-5.3", "kimi-k3"]) + // Seed a stale file bypassing the pruning writer (simulates a pre-existing rank file with dead entries) + writeFileSync(paths().capabilityRank, JSON.stringify({ + version: 1, + updated_at: "2026-09-17T00:00:00+0800", + models: ["kimi-k3", "ghost-model"], + scores: { "kimi-k3": { tier: "B", raw: 50 }, "ghost-model": { tier: "S", raw: 90 } }, + })) + const { code } = captureCli(["rank", "add", "kimi-k3"]) + expect(code).toBe(0) + expect(loadCapabilityRank()?.models).toEqual(["kimi-k3"]) // ghost-model pruned + expect(loadCapabilityRank()?.scores?.["ghost-model"]).toBeUndefined() // its anchored score dropped too + expect(loadCapabilityRank()?.scores?.["kimi-k3"]?.tier).toBe("B") // surviving score kept + }) + + test("auto-prune is gated on the universe: an empty-universe write stays untouched (cleanup path intact)", () => { + supersetOnly() + resetPoolConfig("main") // universe empty + writeCapabilityRank(["ghost-model"]) + expect(loadCapabilityRank()?.models).toEqual(["ghost-model"]) // no prune, legacy cleanup still possible + }) +}) + +// [2026-09-18]-[rank CLI gating without a pool config: `rank list` guides to /poolConfig (exit 0); `rank set`/`add` +// refuse with exit 1 ("no task-pool selection yet"); `rank remove` keeps working as the cleanup path against the +// legacy manual entries]-[impact: pins runCli/cmdRank gating; no src change here] +describe("runCli rank gating (no pool configured)", () => { + afterEach(() => { + clearCapabilityRank() + resetPoolConfig("main") + }) + + test("rank list prints the no-pool guidance (exit 0) and lists legacy entries as cleanup-only", () => { + resetPoolConfig("main") + writeCapabilityRank(["glm-5.3"]) + const { code, out } = captureCli(["rank", "list"]) + expect(code).toBe(0) + expect(out).toContain("disabled until task pools are configured") + expect(out).toContain("Legacy manual entries") + expect(out).toContain("glm-5.3") + }) + + test("rank set / rank add refuse with exit 1 while no pool is configured", () => { + resetPoolConfig("main") + clearCapabilityRank() + for (const sub of ["set", "add"] as const) { + const { code, err } = captureCli(["rank", sub, "glm-5.3"]) + expect(code).toBe(1) + expect(err).toContain("no task-pool selection yet") + } + }) + + test("rank remove still works without a pool config (cleanup path resolves against legacy manual entries)", () => { + resetPoolConfig("main") + writeCapabilityRank(["glm-5.3", "ghost-model"]) + const { code } = captureCli(["rank", "remove", "ghost-model"]) + expect(code).toBe(0) + expect(loadCapabilityRank()?.models).toEqual(["glm-5.3"]) + }) +}) + afterAll(() => rmSync(stateDir, { recursive: true, force: true })) diff --git a/test/ctx-pause.test.ts b/test/ctx-pause.test.ts index ed747a5..e97df7d 100644 --- a/test/ctx-pause.test.ts +++ b/test/ctx-pause.test.ts @@ -16,13 +16,23 @@ process.env.SWITCHMAN_STATE = stateDir // catalog entry present from module load (the model-catalog index is cached at first read; a mid-file rewrite would // never be seen) — harmless for the other tests: their sessions carry no model face, so no threshold clamping occurs writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: { "copilot/glm-5.3": { contextWindow: 128_000 } } })) +// [2026-09-19]-[hermetic capability seed: see test/index-options.test.ts — prevents the startup refresh's async write-back +// from landing in a later file's sandbox after SWITCHMAN_STATE switches mid-flight (CI-only flake on fast networks)] +writeFileSync(join(stateDir, "capability.json"), JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} })) import { SwitchmanPlugin } from "../src/index" import { CTX_PAUSE_MARKER, CTX_RESUME_MARKER, ctxControlMarkerOf, pausedWindowWarning } from "../src/context-watch" +import { renderNotice } from "../src/i18n" function readStatusLog(): string { const p = join(stateDir, "status-log.json") - return existsSync(p) ? readFileSync(p, "utf8") : "" + if (!existsSync(p)) return "" + // [2026-09-19]-[i18n cleanup: entries are structured {key, params} — render English for the prose assertions] + try { + const data = JSON.parse(readFileSync(p, "utf8")) + if (Array.isArray(data)) return data.map((e: { key?: string; params?: Record<string, string | number>; text?: string }) => renderNotice(e, "en")).join("\n") + } catch { /* fail-open: fall through to raw text */ } + return readFileSync(p, "utf8") } const fakeClient = { diff --git a/test/dispatch-gates.test.ts b/test/dispatch-gates.test.ts index 711d42b..415522f 100644 --- a/test/dispatch-gates.test.ts +++ b/test/dispatch-gates.test.ts @@ -6,6 +6,7 @@ import { READ_CLASS_TOOLS, estimateContextTokens, thresholdsOf, watermarkLevel, isVerificationBash, budgetGateDecision, readBudgetOf, turnBudgetOf, estimateReadRange, estimateOutputTokens, capThresholdsByWindow, + matchContinuation, DENY_RETRY_OVERHEAD_TOKENS, } from "../src/context-watch" import { builtinAgentDeny, checkShell } from "../src/gates" import { firstCandidate } from "../src/lane" @@ -46,10 +47,11 @@ describe("context-watch: token estimation and watermark levels", () => { // [2026-09-05]-[v1 read budget: budgetGateDecision matrix replaces the readGateDecision nudge tests — the gate is // deterministic per call (the alreadyNudged coupon is gone) and always-on from turn 1; watermarks keep only // lifecycle duties (hard/force = wrap-up deny)] +// [2026-09-18]-[v1.1 anti-fragmentation: tolerance band + need-aware grant ceiling + continuation completion cases] describe("context-watch: read-budget gate decisions", () => { const RB = 1500 - const estOf = (totalTokens: number, hasLimit: boolean, suggestedLimit = 200, offset = 1) => ({ - totalTokens, tokensPerLine: 7.5, suggestedLimit, hasLimit, requestedLimit: hasLimit ? 300 : undefined, offset, + const estOf = (totalTokens: number, hasLimit: boolean, suggestedLimit = 200, offset = 1, grantTokens = 1500, requestedEndLine = offset + 300 - 1) => ({ + totalTokens, tokensPerLine: 7.5, suggestedLimit, hasLimit, requestedLimit: hasLimit ? 300 : undefined, offset, grantTokens, requestedEndLine, }) test("ok level: reads under budget pass; over-budget reads are capped (no limit) or denied (limit set); un-estimable read-class fails open; non-read-class passes", () => { expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(400, false) })).toBe("allow") @@ -98,6 +100,52 @@ describe("context-watch: read-budget gate decisions", () => { expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 3000, est: estOf(400, false) })).toBe("deny-turn") expect(budgetGateDecision({ tool: "glob", level: "ok", readBudget: RB, turnUsed: 3000 })).toBe("deny-turn") }) + // [2026-09-18]-[v1.1 tolerance band: a deny round trip (error text + re-issued call + re-reasoning) costs ≈ the + // overshoot it saves, and the model reads the rest anyway in fragments — barely-over-budget reads pass outright] + test("v1.1 tolerance band: reads within R* + deny-retry overhead pass outright (band edge inclusive)", () => { + const band = RB + DENY_RETRY_OVERHEAD_TOKENS + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(band, true) })).toBe("allow") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(band, false) })).toBe("allow") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(band + 1, true) })).toBe("deny-budget") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(band + 1, false) })).toBe("cap") + }) + // [2026-09-18]-[v1.1 need-aware sizing: the grant ceiling rides the remaining turn headroom — a demonstrated-range + // read lands one-shot instead of deny → partial read → continuation fragments] + test("v1.1 need-aware sizing: reads up to the grant ceiling land one-shot; above it cap/deny-budget as before", () => { + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(2500, true, 200, 1, 3000) })).toBe("allow") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(3000, false, 200, 1, 3000) })).toBe("allow") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(3001, true, 200, 1, 3000) })).toBe("deny-budget") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(3001, false, 200, 1, 3000) })).toBe("cap") + // a partially spent turn shrinks the ceiling (max(R*, headroom)) — 200 left still grants R*-shaped reads + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 2800, est: estOf(1500, true, 200, 1, 1500) })).toBe("allow") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 2800, est: estOf(2000, true, 200, 1, 1500) })).toBe("deny-budget") + }) + // [2026-09-18]-[v1.1 continuation merge: an in-band remainder of the last granted window completes the demonstrated + // want in one shot even past the spent turn budget (delegating a ≤band fragment costs more than the fragment); + // out-of-band remainders and wrap-up tiers keep the old verdicts; the completion path is read-tool only] + test("v1.1 continuation completion: in-band remainder allowed past the turn wall; out-of-band denied; hard/force wins; read-tool only", () => { + const contIn = { offset: 301, wantRemainderLines: 100, wantRemainderTokens: 900 } + const contOut = { offset: 301, wantRemainderLines: 400, wantRemainderTokens: 3000 } + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 3000, est: estOf(900, true), cont: contIn })).toBe("allow") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 0, est: estOf(900, true), cont: contIn })).toBe("allow") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 3000, est: estOf(3000, true), cont: contOut })).toBe("deny-turn") + expect(budgetGateDecision({ tool: "read", level: "hard", readBudget: RB, turnUsed: 3000, est: estOf(900, true), cont: contIn })).toBe("deny-hard") + expect(budgetGateDecision({ tool: "read", level: "ok", readBudget: RB, turnUsed: 3000, est: estOf(RB + DENY_RETRY_OVERHEAD_TOKENS, true), cont: { offset: 301, wantRemainderLines: 253, wantRemainderTokens: RB + DENY_RETRY_OVERHEAD_TOKENS } })).toBe("allow") + expect(budgetGateDecision({ tool: "glob", level: "ok", readBudget: RB, turnUsed: 3000, cont: contIn })).toBe("deny-turn") + }) + // [2026-09-18]-[v1.1 continuation matcher: same file + offset resuming within slack of the granted window's end] + test("matchContinuation: near-end same-file resumes match with the want remainder; far offsets, other files, exhausted wants, and offset-less calls do not", () => { + const prev = { filePath: "a.ts", grantedEndLine: 300, wantEndLine: 400 } + expect(matchContinuation(prev, { filePath: "a.ts", offset: 301 }, 7.5)).toEqual({ offset: 301, wantRemainderLines: 100, wantRemainderTokens: 750 }) + expect(matchContinuation(prev, { filePath: "a.ts", offset: 295 }, 7.5)?.wantRemainderLines).toBe(106) // overlap re-read + expect(matchContinuation(prev, { filePath: "a.ts", offset: 310 }, 7.5)?.wantRemainderLines).toBe(91) // slack upper edge + expect(matchContinuation(prev, { filePath: "a.ts", offset: 311 }, 7.5)).toBeNull() + expect(matchContinuation(prev, { filePath: "a.ts", offset: 289 }, 7.5)).toBeNull() + expect(matchContinuation(prev, { filePath: "b.ts", offset: 301 }, 7.5)).toBeNull() + expect(matchContinuation(prev, { filePath: "a.ts", offset: 500 }, 7.5)).toBeNull() // past both slack and want + expect(matchContinuation(undefined, { filePath: "a.ts", offset: 301 }, 7.5)).toBeNull() + expect(matchContinuation(prev, { filePath: "a.ts" }, 7.5)).toBeNull() // no offset → a fresh head read, not a continuation + }) test("readBudgetOf: default 1500, clamped to [200, 20000]", () => { expect(readBudgetOf(undefined)).toBe(1500) expect(readBudgetOf({})).toBe(1500) @@ -135,6 +183,20 @@ describe("context-watch: read-budget gate decisions", () => { expect(estimateOutputTokens(350)).toBe(100) expect(estimateOutputTokens(351)).toBe(101) }) + // [2026-09-18]-[v1.1: grantTokens (turn headroom) sizes the suggested limit; requestedEndLine records the demonstrated want] + test("estimateReadRange v1.1: grantTokens sizes suggestedLimit; requestedEndLine tracks the effective requested range", () => { + const sample = { path: "a.ts", bytes: 65536, sampleBytes: 65536, newlines: 1023 } // 64 B/line → 18.2857 tok/line + const headroom = estimateReadRange(sample, undefined, 1500, 3000) + expect(headroom.suggestedLimit).toBe(164) // floor(3000/18.2857) + expect(headroom.grantTokens).toBe(3000) + expect(headroom.requestedEndLine).toBe(1024) // unbounded → whole file + const bounded = estimateReadRange(sample, { limit: 400, offset: 100 }, 1500, 3000) + expect(bounded.requestedEndLine).toBe(499) // offset + effective lines - 1 + expect(bounded.totalTokens).toBe(Math.ceil((64 / 3.5) * 400)) + const tail = estimateReadRange(sample, { limit: 400, offset: 1000 }, 1500, 3000) + expect(tail.requestedEndLine).toBe(1024) // clamped to file end + expect(tail.totalTokens).toBe(Math.ceil((64 / 3.5) * 25)) + }) test("READ_CLASS_TOOLS covers read/glob/grep/list", () => { for (const t of ["read", "glob", "grep", "list"]) expect(READ_CLASS_TOOLS.has(t)).toBe(true) expect(READ_CLASS_TOOLS.has("bash")).toBe(false) @@ -286,6 +348,42 @@ describe("gates: GateResult.redirect (autoRedirect)", () => { }) }) +// [2026-09-18]-[pool-config membership = qualification at the dispatch gate: a model explicitly selected into the +// lane's task pool passes the capability-level floor gate (deny null; the allow note records the "pool-config +// override"), while the same below-floor model with no pool selection is still denied "capability level too low". +// Fixture uses a C-tier (L2) model on the hard lane (minimum L4): C/L2 is neither primary nor fallback there, so the +// plain capability gate (not the cross-level top-2 check) carries both verdicts. Synthetic registry, matrix=null — +// zero state dependencies, same pattern as the redirect fixtures above]-[impact: pins gates.ts poolMember exemption] +describe("gates: capability-level floor vs pool-config override (hard lane)", () => { + const airShell: ShellRegEntry = { + name: "glm-mx-air-high", pool: "glm", provider: "zhipuai-coding-plan", modelId: "glm-4.5-air", + effort: "high", family: "glm", capability: "rw", vision: false, + matrixKey: "zhipuai-coding-plan|glm-4.5-air|high", comboKey: "zhipuai-coding-plan|glm-4.5-air|high", + status: "enabled", + } + const HARD_META = 'ROUTE_META {"lane":"hard","role":"planner","producer_family":"claude","capability":"rw","modality":"text","source":"auto"}' + const snap = (over: Partial<GateSnapshot> = {}): GateSnapshot & { lanes: Record<string, string[]> } => ({ + registry: { [airShell.name]: airShell }, + matrix: null, + routing: { down_agents: {}, down_expiry: {} }, + quotaExhausted: {}, + lanes: { hard: [airShell.name] }, + ...over, + }) + + test("a below-floor model selected into the lane's task pool passes the capability gate (note records the override)", () => { + const r = checkShell(airShell.name, airShell, HARD_META, snap({ poolConfig: { hard: new Set(["glm-4.5-air"]) } })) + expect(r.deny).toBeNull() + expect(r.note).toContain("pool-config override") + }) + + test("the same below-floor model without a pool selection is still denied (capability level too low)", () => { + const r = checkShell(airShell.name, airShell, HARD_META, snap({ poolConfig: {} })) + expect(r.deny).toContain("capability level too low") + expect(r.note).toBeNull() + }) +}) + // [2026-09-14]-[D3 dispatch:"off" stand-down fixtures: a project that set the top-level "dispatch":"off" in // .switchman/settings.json gets its task calls allowed UNGOVERNED — every task deny class (breaker, gate 7 rw/ro, // built-in blocking, dynamic uninjected deny) stands down, while the non-dispatch surfaces stay on: the subagent cap diff --git a/test/dispatch-mode.test.ts b/test/dispatch-mode.test.ts index 034def6..17c0504 100644 --- a/test/dispatch-mode.test.ts +++ b/test/dispatch-mode.test.ts @@ -6,6 +6,8 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { loadDispatchMode, parseDispatchMode } from "../src/dispatch-mode" +import { t } from "../src/i18n" +import type { MsgKey } from "../src/i18n" function sandboxProject(): string { const dir = mkdtempSync(join(tmpdir(), "switchman-dispatch-mode-")) @@ -42,42 +44,46 @@ describe("dispatch-mode: loadDispatchMode (per-call disk read, never throws)", ( test("settings.json with dispatch:\"off\" → off; missing file → fleet; no log noise", () => { const offDir = sandboxProject() writeFileSync(join(offDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, dispatch: "off" })) - const logs: string[] = [] - expect(loadDispatchMode(offDir, ".switchman", (m) => logs.push(m))).toBe("off") + const logs: Array<{ key: string; params?: Record<string, string | number> }> = [] + expect(loadDispatchMode(offDir, ".switchman", (k, p) => logs.push({ key: k, params: p }))).toBe("off") expect(logs).toEqual([]) const emptyDir = sandboxProject() - expect(loadDispatchMode(emptyDir, ".switchman", (m) => logs.push(m))).toBe("fleet") + expect(loadDispatchMode(emptyDir, ".switchman", (k, p) => logs.push({ key: k, params: p }))).toBe("fleet") expect(logs).toEqual([]) }) test("present-but-invalid value → one note, fleet behavior; the note fires once per process per path", () => { const dir = sandboxProject() writeFileSync(join(dir, ".switchman", "settings.json"), JSON.stringify({ dispatch: "OFF" })) - const logs: string[] = [] - const log = (m: string) => logs.push(m) + const logs: Array<{ key: string; params?: Record<string, string | number> }> = [] + // [2026-09-19]-[i18n cleanup: the log mock now receives structured (key, params) — assert the pair directly] + const log = (k: string, p?: Record<string, string | number>) => logs.push({ key: k, params: p }) expect(loadDispatchMode(dir, ".switchman", log)).toBe("fleet") expect(loadDispatchMode(dir, ".switchman", log)).toBe("fleet") expect(loadDispatchMode(dir, ".switchman", log)).toBe("fleet") expect(logs.length).toBe(1) - expect(logs[0]).toContain('.switchman/settings.json "dispatch" present but not exactly "off"') - expect(logs[0]).toContain("OFF") - expect(logs[0]).toContain("fleet behavior") + expect(logs[0]!.key).toBe("notice.lang.dispatchNotOff") + expect(logs[0]!.params?.rawValue).toBe("OFF") + expect(t("en", logs[0]!.key as MsgKey, logs[0]!.params)).toContain("fleet behavior") }) test("broken settings.json → warning with the exact copy, once per process per path; a second path warns separately", () => { const dirA = sandboxProject() const dirB = sandboxProject() writeFileSync(join(dirA, ".switchman", "settings.json"), "{not json") writeFileSync(join(dirB, ".switchman", "settings.json"), "{also broken") - const logs: string[] = [] - const log = (m: string) => logs.push(m) + const logs: Array<{ key: string; params?: Record<string, string | number> }> = [] + // [2026-09-19]-[i18n cleanup: the log mock now receives structured (key, params) — assert the pair directly] + const log = (k: string, p?: Record<string, string | number>) => logs.push({ key: k, params: p }) // fleet behavior, warning emitted once per path (three reads of A, one of B) expect(loadDispatchMode(dirA, ".switchman", log)).toBe("fleet") expect(loadDispatchMode(dirA, ".switchman", log)).toBe("fleet") expect(loadDispatchMode(dirB, ".switchman", log)).toBe("fleet") expect(loadDispatchMode(dirA, ".switchman", log)).toBe("fleet") expect(logs.length).toBe(2) - expect(logs[0]).toBe('[opencode-switchman] .switchman/settings.json is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)') - expect(logs[1]).toBe('[opencode-switchman] .switchman/settings.json is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)') + expect(logs[0]!.key).toBe("notice.lang.settingsInvalidJson") + expect(logs[1]!.key).toBe("notice.lang.settingsInvalidJson") + expect(t("en", logs[0]!.key as MsgKey, logs[0]!.params)).toBe('[opencode-switchman] .switchman/settings.json is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)') + expect(t("en", logs[1]!.key as MsgKey, logs[1]!.params)).toBe('[opencode-switchman] .switchman/settings.json is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)') }) test("coexistence: a lang block and dispatch:\"off\" in the same file both parse (extra top-level fields ignored by the lang parser)", () => { const dir = sandboxProject() @@ -86,8 +92,8 @@ describe("dispatch-mode: loadDispatchMode (per-call disk read, never throws)", ( lang: { conversation: "zh-CN", comments: "en", docs: "en" }, dispatch: "off", })) - const logs: string[] = [] - expect(loadDispatchMode(dir, ".switchman", (m) => logs.push(m))).toBe("off") + const logs: Array<{ key: string; params?: Record<string, string | number> }> = [] + expect(loadDispatchMode(dir, ".switchman", (k, p) => logs.push({ key: k, params: p }))).toBe("off") expect(logs).toEqual([]) }) }) diff --git a/test/expert-command.test.ts b/test/expert-command.test.ts index bee98ee..929c36a 100644 --- a/test/expert-command.test.ts +++ b/test/expert-command.test.ts @@ -9,6 +9,9 @@ import { join } from "node:path" process.env.OPENCODE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "switchman-expert-config-")) process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-expert-state-")) writeFileSync(join(process.env.SWITCHMAN_STATE, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +// [2026-09-19]-[hermetic capability seed: see test/index-options.test.ts — prevents the startup refresh's async write-back +// from landing in a later file's sandbox after SWITCHMAN_STATE switches mid-flight (CI-only flake on fast networks)] +writeFileSync(join(process.env.SWITCHMAN_STATE, "capability.json"), JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} })) import { expertCommandMd } from "../src/commands-md" import { SwitchmanPlugin } from "../src/index" diff --git a/test/failclass.test.ts b/test/failclass.test.ts index b40b57d..df409ef 100644 --- a/test/failclass.test.ts +++ b/test/failclass.test.ts @@ -75,25 +75,27 @@ describe("failure classification classifyFailure", () => { }) }) -// ================= 2. rate_limit short TTL vs default long TTL ================= +// ================= 2. rate_limit TTL vs default TTL ================= +// [2026-09-19]-[REAL_FAIL_TTL_MS 30m -> 5m: the default mark now expires BEFORE the 10-min rate-limit mark; +// test rewritten for the inverted hierarchy (each TTL path stays independently correct)] describe("real-call failure TTL separation", () => { - test("rate-limit short mark expires after 10 minutes, real-failure long mark persists", () => { + test("real-failure default mark expires after 5 minutes, rate-limit mark holds to its 10-min TTL", () => { const now = Date.now() markRealFailure("rl|combo", now, RATE_LIMIT_TTL_MS) markRealFailure("lf|combo", now) expect(isRealFailedCombo("rl|combo", now)).toBe(true) expect(isRealFailedCombo("lf|combo", now)).toBe(true) - // After the short TTL: the rate-limit mark expired, the long-lived mark still holds - expect(isRealFailedCombo("rl|combo", now + RATE_LIMIT_TTL_MS + 1)).toBe(false) - expect(isRealFailedCombo("lf|combo", now + RATE_LIMIT_TTL_MS + 1)).toBe(true) - // After the long TTL: both expired + // After the default 5-min TTL: the real-failure mark expired, the 10-min rate-limit mark still holds expect(isRealFailedCombo("lf|combo", now + REAL_FAIL_TTL_MS + 1)).toBe(false) + expect(isRealFailedCombo("rl|combo", now + REAL_FAIL_TTL_MS + 1)).toBe(true) + // After the rate-limit TTL: both expired + expect(isRealFailedCombo("rl|combo", now + RATE_LIMIT_TTL_MS + 1)).toBe(false) }) // [2026-09-01]-[endpoint 6h long TTL; remaining-ms query (banner TTL display)] test("endpoint long TTL and realFailedRemainingMs", () => { const now = Date.now() markRealFailure("ep|combo", now, ENDPOINT_TTL_MS) - expect(isRealFailedCombo("ep|combo", now + REAL_FAIL_TTL_MS + 1)).toBe(true) // still held after 30m + expect(isRealFailedCombo("ep|combo", now + REAL_FAIL_TTL_MS + 1)).toBe(true) // still held after 5m expect(isRealFailedCombo("ep|combo", now + ENDPOINT_TTL_MS + 1)).toBe(false) // expired after 6h markRealFailure("rem|combo", now, 60_000) expect(realFailedRemainingMs("rem|combo", now + 20_000)).toBe(40_000) diff --git a/test/i18n.test.ts b/test/i18n.test.ts new file mode 100644 index 0000000..9320215 --- /dev/null +++ b/test/i18n.test.ts @@ -0,0 +1,111 @@ +// [2026-09-19]-[i18n behavioral contract: catalog completeness (every locale covers every English key), +// placeholder parity (translations keep the exact {param} set), t() interpolation/fallback semantics, +// display-locale resolution chain, and legacy-compat notice rendering] +import { describe, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { CATALOGS, LOCALE_TAGS, renderNotice, resolveDisplayLocale, t, type MsgKey } from "../src/i18n" + +const enKeys = Object.keys(CATALOGS.en!) as MsgKey[] +const paramsOf = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort().join(",") + +describe("i18n catalog", () => { + test("every locale covers every English key with a non-empty string", () => { + expect(enKeys.length).toBeGreaterThan(0) + for (const tag of LOCALE_TAGS) { + if (tag === "en") continue + const cat = CATALOGS[tag]! + const missing = enKeys.filter((k) => typeof cat[k] !== "string" || cat[k]!.length === 0) + expect(missing).toEqual([]) + } + }) + + test("placeholder sets match English in every locale", () => { + for (const tag of LOCALE_TAGS) { + if (tag === "en") continue + const cat = CATALOGS[tag]! + for (const k of enKeys) expect(paramsOf(cat[k]!)).toBe(paramsOf(CATALOGS.en![k]!)) + } + }) +}) + +describe("t()", () => { + test("interpolates params", () => { + expect(t("en", "quota.pctLeft" as MsgKey, undefined, "{n}% left")).toBe("{n}% left") + expect(t("en", "quota.pctLeft" as MsgKey, { n: 42 }, "{n}% left")).toBe("42% left") + }) + + test("missing param stays literal; unknown locale falls back to English", () => { + expect(t("en", "quota.pctLeft" as MsgKey, undefined, "a {x} b")).toBe("a {x} b") + expect(t("xx-ZZ", "quota.pctLeft" as MsgKey, { x: 1 }, "a {x} b")).toBe("a 1 b") + }) + + test("unknown key falls back to the provided fallback, then the key itself", () => { + expect(t("en", "not.a.real.key" as MsgKey, undefined, "fallback!")).toBe("fallback!") + expect(t("en", "not.a.real.key" as MsgKey)).toBe("not.a.real.key") + }) + + test("real keys translate without fallback", () => { + const k = enKeys[0]! + expect(t("en", k)).toBe(CATALOGS.en![k]!) + expect(t("zh-CN", k)).toBe(CATALOGS["zh-CN"]![k]!) + }) +}) + +describe("resolveDisplayLocale()", () => { + const withTempDir = (fn: (dir: string) => void) => { + const dir = mkdtempSync(join(tmpdir(), "swm-i18n-")) + try { fn(dir) } finally { rmSync(dir, { recursive: true, force: true }) } + } + const writeSettings = (dir: string, conversation: string) => { + mkdirSync(join(dir, ".switchman"), { recursive: true }) + writeFileSync(join(dir, ".switchman", "settings.json"), JSON.stringify({ lang: { conversation, comments: "en", docs: "en" } })) + } + + test("project settings.json lang.conversation wins over uiLang and env", () => { + withTempDir((dir) => { + writeSettings(dir, "zh-CN") + expect(resolveDisplayLocale({ sessionDir: dir, uiLang: "ja", env: { LC_ALL: "ko_KR.UTF-8" } })).toBe("zh-CN") + }) + }) + + test("custom workspaceDirname is honored; AGENTS.md marker is the project fallback", () => { + withTempDir((dir) => { + mkdirSync(join(dir, ".arts"), { recursive: true }) + writeFileSync(join(dir, ".arts", "settings.json"), JSON.stringify({ lang: { conversation: "fr", comments: "en", docs: "en" } })) + writeFileSync(join(dir, "AGENTS.md"), "switchman:lang conversation=zh-TW comments=en docs=en\n") + expect(resolveDisplayLocale({ sessionDir: dir, workspaceDirname: ".arts", env: {} })).toBe("fr") + expect(resolveDisplayLocale({ sessionDir: dir, env: {} })).toBe("zh-TW") + }) + }) + + test("uiLang beats env; env wins when project and uiLang are absent; default en", () => { + expect(resolveDisplayLocale({ uiLang: "de", env: { LC_ALL: "fr_FR.UTF-8" } })).toBe("de") + expect(resolveDisplayLocale({ env: { LC_ALL: "fr_FR.UTF-8" } })).toBe("fr") + expect(resolveDisplayLocale({ env: {} })).toBe("en") + }) + + test("unnormalizable project conversation value falls through to the next chain step", () => { + withTempDir((dir) => { + writeSettings(dir, "klingon") + expect(resolveDisplayLocale({ sessionDir: dir, uiLang: "ru", env: {} })).toBe("ru") + }) + }) +}) + +describe("renderNotice()", () => { + test("legacy text-only entry passes through verbatim", () => { + expect(renderNotice({ text: "old prose entry" }, "zh-CN")).toBe("old prose entry") + }) + + test("keyed entry translates with params", () => { + const k = enKeys[0]! + expect(renderNotice({ key: k }, "zh-CN")).toBe(CATALOGS["zh-CN"]![k]!) + }) + + test("unknown runtime key falls back to the stored text, then the key", () => { + expect(renderNotice({ key: "notice.gone", text: "stored text" }, "en")).toBe("stored text") + expect(renderNotice({ key: "notice.gone" }, "en")).toBe("notice.gone") + }) +}) diff --git a/test/index-options.test.ts b/test/index-options.test.ts index fc5c5a2..9fef580 100644 --- a/test/index-options.test.ts +++ b/test/index-options.test.ts @@ -7,6 +7,10 @@ import { join } from "node:path" process.env.OPENCODE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "switchman-options-config-")) process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-options-state-")) writeFileSync(join(process.env.SWITCHMAN_STATE, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +// [2026-09-19]-[hermetic capability seed: without it the plugin's startup refresh fires a real network fetch whose async +// write-back can land in a LATER test file's SWITCHMAN_STATE sandbox (env-switched mid-flight) and poison its empty-pin +// capability.json — CI-only flake on fast networks; the empty pin pins base scores to the curated table] +writeFileSync(join(process.env.SWITCHMAN_STATE, "capability.json"), JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} })) import { SwitchmanPlugin } from "../src/index" import { parseJsonc, validateUserConfig } from "../src/config" diff --git a/test/pane-resume.test.ts b/test/pane-resume.test.ts index 1656619..e9b98eb 100644 --- a/test/pane-resume.test.ts +++ b/test/pane-resume.test.ts @@ -37,6 +37,10 @@ for (const [file, body] of Object.entries({ } as Record<string, unknown>)) { writeFileSync(join(process.env.SWITCHMAN_STATE, file), JSON.stringify(body)) } +// [2026-09-19]-[setup hard gate fixture: seed a COMPLETE setup before any hook call (all 6 task pools = full +// manifest model universe → gate 5.5 membership allow-all; rank = one fixture key matching no real modelId), or +// the new setup gate denies every task call before the resume wiring under test can fire]- +seedCompleteSetup(process.env.SWITCHMAN_STATE!, manifestModelUniverse()) afterAll(() => { if (prevState === undefined) delete process.env.SWITCHMAN_STATE else process.env.SWITCHMAN_STATE = prevState @@ -46,6 +50,8 @@ afterAll(() => { import { SwitchmanPlugin } from "../src/index" import { loadManifest, stateDir } from "../src/state" +import { seedCompleteSetup, manifestModelUniverse } from "./setup-seed" +import { renderNotice } from "../src/i18n" import { rmSync } from "node:fs" type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> @@ -89,7 +95,8 @@ function statusLogText(): string { const p = join(stateDir(), "status-log.json") if (!existsSync(p)) return "" const data = JSON.parse(readFileSync(p, "utf8")) - return (Array.isArray(data) ? data : []).map((e: { text?: string }) => String(e?.text ?? "")).join("\n") + // [2026-09-19]-[i18n cleanup: entries are structured {key, params} — render English for the prose assertions] + return (Array.isArray(data) ? data : []).map((e: { key?: string; params?: Record<string, string | number>; text?: string }) => renderNotice(e, "en")).join("\n") } /** status-log persists across tests in the shared state dir — truncate for per-test isolation */ diff --git a/test/scoring.test.ts b/test/scoring.test.ts index a930318..0fef642 100644 --- a/test/scoring.test.ts +++ b/test/scoring.test.ts @@ -347,6 +347,72 @@ describe("rankCandidates", () => { }) }) +// [2026-09-18]-[pool lane manual ordering: poolOrdered + manualOrder (new RankContext fields) make the manual +// /modelRank order the ABSOLUTE first comparator key — explicit user order beats tier grouping, the thinking/off +// partition and the product score; unranked pool members sink after all ranked ones; health hard gates are unchanged; +// poolOrdered without manualOrder keeps only the level-floor exemption; the control case pins the baseline shape]- +// [impact: pins rankCandidates/rankOrdered semantics; no production change in this file] +describe("[2026-09-18] pool lane manual ordering (poolOrdered + manualOrder)", () => { + test("manual order beats tier grouping: the lower-tier shell holding manual rank 0 leads", () => { + const shells = [ + rankable({ key: "a", modelId: "glm-5.3", latencyMs: 5 }), // A(L4) — higher tier + rankable({ key: "b", modelId: "glm-5.3-flash", latencyMs: 1 }), // B(L3) — lower tier + ] + const r = rankCandidates(shells, ctx({ poolOrdered: true, manualOrder: new Map([["a", 1], ["b", 0]]) })) + // manual rank is the first comparator key: b (rank 0) first although its tier/product score is worse + expect(r.ranked.map((s) => s.key)).toEqual(["b", "a"]) + }) + + test("unranked pool member sorts after all ranked members despite a higher tier and better score", () => { + const shells = [ + rankable({ key: "s-unranked", modelId: "gpt-5.6", pool: "copilot", family: "gpt", latencyMs: 1 }), // S, absent from manualOrder + rankable({ key: "b-rank0", modelId: "glm-5.3-flash", latencyMs: 500 }), // B, rank 0 + rankable({ key: "a-rank1", modelId: "glm-5.3", latencyMs: 400 }), // A, rank 1 + ] + const r = rankCandidates(shells, ctx({ poolOrdered: true, manualOrder: new Map([["b-rank0", 0], ["a-rank1", 1]]) })) + expect(r.ranked.map((s) => s.key)).toEqual(["b-rank0", "a-rank1", "s-unranked"]) + }) + + test("health gates still apply: a matrix-down or breaker-down shell is eliminated even at manual rank 0", () => { + const shells = [ + rankable({ key: "rank0-down", modelId: "glm-5.3", matrixStatus: "down" }), + rankable({ key: "rank0-breaker", modelId: "glm-5.3-flash" }), + rankable({ key: "rank1-ok", modelId: "glm-4.5-air", latencyMs: 900 }), + ] + const registry = { + "rank0-breaker": shellReg({ name: "rank0-breaker", modelId: "glm-5.3-flash", comboKey: "breaker-combo", matrixKey: "breaker-combo" }), + } + const r = rankCandidates(shells, ctx({ + poolOrdered: true, + manualOrder: new Map([["rank0-down", 0], ["rank0-breaker", 0], ["rank1-ok", 1]]), + registry, + routing: { down_agents: { "breaker-combo": "consecutive failures" }, down_expiry: {} }, + })) + expect(r.ranked.map((s) => s.key)).toEqual(["rank1-ok"]) + expect(r.breakdowns.has("rank0-down")).toBe(false) + expect(r.breakdowns.has("rank0-breaker")).toBe(false) + }) + + test("poolOrdered without manualOrder: level-floor exemption holds (below-floor survivor kept) but tier/level ordering stays", () => { + const shells = [ + rankable({ key: "a4", modelId: "glm-5.3", latencyMs: 50 }), // A(L4) — hard's minimum level + rankable({ key: "c-low", modelId: "glm-4.5-air", latencyMs: 1 }), // C(L2) — below the floor, not a hard fallback + ] + // with poolOrdered the whole survivor set forms the chain: the below-floor shell is NOT filtered out by selectGroup + const r = rankCandidates(shells, ctx({ lane: "hard", poolOrdered: true })) + expect(r.ranked.map((s) => s.key)).toEqual(["a4", "c-low"]) + }) + + test("control: neither flag set — baseline behavior (below-floor non-fallback filtered by the level floor)", () => { + const shells = [ + rankable({ key: "a4", modelId: "glm-5.3", latencyMs: 50 }), + rankable({ key: "c-low", modelId: "glm-4.5-air", latencyMs: 1 }), + ] + const r = rankCandidates(shells, ctx({ lane: "hard" })) + expect(r.ranked.map((s) => s.key)).toEqual(["a4"]) + }) +}) + // ================= 4. Decision log ================= describe("decision log logDecision", () => { beforeAll(() => { diff --git a/test/search-clarify.test.ts b/test/search-clarify.test.ts index c6095ca..3d0c5e0 100644 --- a/test/search-clarify.test.ts +++ b/test/search-clarify.test.ts @@ -12,16 +12,26 @@ const stateDir = mkdtempSync(join(tmpdir(), "switchman-srch-state-")) const projectDir = mkdtempSync(join(tmpdir(), "switchman-srch-project-")) process.env.OPENCODE_CONFIG_DIR = configDir process.env.SWITCHMAN_STATE = stateDir +// [2026-09-19]-[hermetic capability seed: see test/index-options.test.ts — prevents the startup refresh's async write-back +// from landing in a later file's sandbox after SWITCHMAN_STATE switches mid-flight (CI-only flake on fast networks)] +writeFileSync(join(stateDir, "capability.json"), JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} })) // project language preference pre-configured so the lang hard gate never masks the search gate in bash cases mkdirSync(join(projectDir, ".switchman"), { recursive: true }) writeFileSync(join(projectDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, lang: { conversation: "en", comments: "en", docs: "en" } })) import { SwitchmanPlugin } from "../src/index" import { SEARCH_ASK_MARKER, describeSearchCall, hasSearchMarkerQuestion, isBroadSearchCall, searchClarifyDenyMessage } from "../src/search-clarify" +import { renderNotice } from "../src/i18n" function readStatusLog(): string { const p = join(stateDir, "status-log.json") - return existsSync(p) ? readFileSync(p, "utf8") : "" + if (!existsSync(p)) return "" + // [2026-09-19]-[i18n cleanup: entries are structured {key, params} — render English for the prose assertions] + try { + const data = JSON.parse(readFileSync(p, "utf8")) + if (Array.isArray(data)) return data.map((e: { key?: string; params?: Record<string, string | number>; text?: string }) => renderNotice(e, "en")).join("\n") + } catch { /* fail-open: fall through to raw text */ } + return readFileSync(p, "utf8") } const fakeClient = { diff --git a/test/setup-gate.test.ts b/test/setup-gate.test.ts new file mode 100644 index 0000000..2ada5dc --- /dev/null +++ b/test/setup-gate.test.ts @@ -0,0 +1,233 @@ +// [2026-09-19]-[setup hard gate fixture: evaluateSetup pure states + model-facing copy (deny message / [SETUP] +// directive / sidebar brief) + the [LIMITS] banner setup-required segment + one index-level wiring test proving +// the gate denies task with the setup message while unconfigured and opens by hot-reload once a complete setup is +// seeded (mtime cache re-read, no restart). Style follows lang-config.test.ts / rank-move.test.ts; the wiring +// group reuses the auto-redirect/pane-resume hermetic fixture pattern] +import { describe, expect, test, afterAll } from "bun:test" +import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +import { LANE_ORDER } from "../src/types" +import { evaluateSetup, setupDenyMessage, setupDirective, setupMissingBrief, setupCompletionNow } from "../src/setup-gate" +import { buildBanner, type BannerInput } from "../src/banner" + +// ---- pure-function helpers ---- + +const poolSets = (spec: Record<string, string[]>): Record<string, ReadonlySet<string>> => + Object.fromEntries(Object.entries(spec).map(([k, v]) => [k, new Set(v)])) +const ALL_LANES_SET = Object.fromEntries(LANE_ORDER.map((lane) => [lane, ["fixture-m1"]])) + +describe("evaluateSetup (pure completion states)", () => { + test("null/null → incomplete, all 6 lanes missing, missingRank", () => { + for (const c of [evaluateSetup(null, null), evaluateSetup(undefined, undefined)]) { + expect(c.complete).toBe(false) + expect(c.missingLanes).toEqual([...LANE_ORDER]) // LANE_ORDER order preserved + expect(c.configuredLanes).toBe(0) + expect(c.missingRank).toBe(true) + } + }) + + test("partial lanes (main+hard set, no rank) → the other 4 lanes missing in LANE_ORDER order", () => { + const c = evaluateSetup(poolSets({ main: ["m1"], hard: ["m1"] }), null) + expect(c.complete).toBe(false) + expect(c.missingLanes).toEqual(["economy", "mechanical", "vision", "review"]) + expect(c.configuredLanes).toBe(2) + expect(c.missingRank).toBe(true) + }) + + test("all lanes set but rank empty/null → missingRank only", () => { + for (const rank of [null, undefined, []]) { + const c = evaluateSetup(poolSets(ALL_LANES_SET), rank) + expect(c.complete).toBe(false) + expect(c.missingLanes).toEqual([]) + expect(c.configuredLanes).toBe(6) + expect(c.missingRank).toBe(true) + } + }) + + test("complete state (all 6 lanes non-empty + rank ≥1) → complete", () => { + const c = evaluateSetup(poolSets(ALL_LANES_SET), ["zz-setup-fixture-model"]) + expect(c.complete).toBe(true) + expect(c.missingLanes).toEqual([]) + expect(c.configuredLanes).toBe(6) + expect(c.missingRank).toBe(false) + }) + + test("an empty-Set lane counts as missing", () => { + const c = evaluateSetup(poolSets({ ...ALL_LANES_SET, vision: [] }), ["zz-setup-fixture-model"]) + expect(c.complete).toBe(false) + expect(c.missingLanes).toEqual(["vision"]) + expect(c.configuredLanes).toBe(5) + expect(c.missingRank).toBe(false) + }) +}) + +describe("setupDenyMessage (model-facing deny copy)", () => { + test("full-missing variant: BLOCKED header, all-6-pools phrasing, lane names, both slash commands, hot-reload", () => { + const msg = setupDenyMessage(evaluateSetup(null, null)) + expect(msg).toContain("BLOCKED (setup required)") + expect(msg).toContain(`task-pool selection for all ${LANE_ORDER.length} pools (${LANE_ORDER.join(", ")})`) + for (const lane of LANE_ORDER) expect(msg).toContain(lane) + expect(msg).toContain("capability ranking (at least one ranked model)") + expect(msg).toContain("/switchman-setup") + expect(msg).toContain("/switchman-setup-chat") + expect(msg).toContain("hot-reload") + }) + + test("partial variant: lists only the missing pools, no all-6 phrasing, no rank clause when ranked", () => { + const msg = setupDenyMessage(evaluateSetup(poolSets({ main: ["m1"], hard: ["m1"], economy: ["m1"], mechanical: ["m1"] }), ["m1"])) + expect(msg).toContain("BLOCKED (setup required)") + expect(msg).toContain("task-pool selection for pools: vision, review") + expect(msg).not.toContain("all 6 pools") + expect(msg).not.toContain("capability ranking") + }) +}) + +describe("setupDirective (system-prompt [SETUP] directive)", () => { + test("partial 3/6 + rank missing → starts with [SETUP], carries the 3/6 fraction, HARD GATE and both commands", () => { + const d = setupDirective(evaluateSetup(poolSets({ main: ["m1"], hard: ["m1"], economy: ["m1"] }), null)) + expect(d.startsWith("[SETUP]")).toBe(true) + expect(d).toContain("task pools configured 3/6") + expect(d).toContain("capability ranking missing") + expect(d).toContain("HARD GATE") + expect(d).toContain("/switchman-setup") + expect(d).toContain("/switchman-setup-chat") + }) + + test("all lanes set, rank missing → no pools fraction, rank clause only", () => { + const d = setupDirective(evaluateSetup(poolSets(ALL_LANES_SET), [])) + expect(d.startsWith("[SETUP]")).toBe(true) + expect(d).toContain("capability ranking missing") + expect(d).not.toContain("task pools configured") + }) +}) + +describe("setupMissingBrief (sidebar {missing} brief)", () => { + test("partial + rank missing → 'pools 3/6, rank missing' shape", () => { + expect(setupMissingBrief(evaluateSetup(poolSets({ main: ["m1"], hard: ["m1"], economy: ["m1"] }), null))) + .toBe("pools 3/6, rank missing") + }) + test("complete → empty brief; rank-only missing → 'rank missing'", () => { + expect(setupMissingBrief(evaluateSetup(poolSets(ALL_LANES_SET), ["m1"]))).toBe("") + expect(setupMissingBrief(evaluateSetup(poolSets(ALL_LANES_SET), null))).toBe("rank missing") + }) +}) + +// ---- [LIMITS] banner setup-required segment (limitLine is module-private → assert through buildBanner) ---- + +describe("banner limitLine setup-required segment", () => { + const base: BannerInput = { + lanes: null, + down: [], + quota: { glm: null, copilot: null }, + states: {}, + billing: { glmPeak: false, dsPeak: false, glmLabel: "GLM off-peak", dsLabel: "DS idle 50%" }, + } + + test("incomplete setup → line carries 'setup required: pools n/6', rank clause and the /switchman-setup remedy", () => { + const lines = buildBanner({ + ...base, + overrides: { rankModels: 0, poolLanes: 3, setup: { configuredLanes: 3, missingRank: true, complete: false } }, + }) + expect(lines[2]).toContain("setup required: pools 3/6") + expect(lines[2]).toContain(", rank missing") + expect(lines[2]).toContain("(/switchman-setup)") + const rankOk = buildBanner({ + ...base, + overrides: { rankModels: 0, poolLanes: 3, setup: { configuredLanes: 3, missingRank: false, complete: false } }, + }) + expect(rankOk[2]).toContain("setup required: pools 3/6") + expect(rankOk[2]).not.toContain("rank missing") + }) + + test("complete or absent setup input → no setup-required segment", () => { + const complete = buildBanner({ + ...base, + overrides: { rankModels: 2, poolLanes: 6, setup: { configuredLanes: 6, missingRank: false, complete: true } }, + }) + expect(complete[2]).not.toContain("setup required") + const absent = buildBanner(base) + expect(absent[2]).not.toContain("setup required") + }) +}) + +// ---- index-level wiring: gate denies while unconfigured, opens by hot-reload after seeding ---- + +const prevState = process.env.SWITCHMAN_STATE +const prevConfigDir = process.env.OPENCODE_CONFIG_DIR +const stateDir = mkdtempSync(join(tmpdir(), "switchman-setupgate-state-")) +process.env.SWITCHMAN_STATE = stateDir +process.env.OPENCODE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "switchman-setupgate-cfg-")) +mkdirSync(stateDir, { recursive: true }) +// lang-configured sandbox project: the setup gate only fires when the project language config exists +const projectDir = mkdtempSync(join(tmpdir(), "switchman-setupgate-proj-")) +mkdirSync(join(projectDir, ".switchman"), { recursive: true }) +writeFileSync(join(projectDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, configuredAt: "x", lang: { conversation: "en", comments: "en", docs: "en" } })) +// hermetic TTL seeds (same trick as routing/pane-resume): pre-seed every cache so no network is touched +writeFileSync( + join(stateDir, "capability.json"), + JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} }), +) +writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +for (const [file, body] of Object.entries({ + "model-matrix.json": { + generated_at: new Date().toISOString(), + combos: Object.fromEntries(loadManifest().shells.map((s) => [s.matrixKey, { status: "ok", latency_ms: 100, checked_at: new Date().toISOString() }])), + }, + "costs.json": { scores: {}, fetched_at: Date.now() / 1000 }, + "selfupdate.json": { checked_at: new Date().toISOString(), mode: "prod", current: "0.0.0-test", latest: "0.0.0-test", outdated: false }, + "glm-quota.json": { status: "ok", fetched_at: Date.now() / 1000 }, + "copilot-quota.json": { status: "ok", fetched_at: Date.now() / 1000 }, + "ds-balance.json": { status: "ok", fetched_at: Date.now() / 1000 }, +} as Record<string, unknown>)) { + writeFileSync(join(stateDir, file), JSON.stringify(body)) +} +afterAll(() => { + if (prevState === undefined) delete process.env.SWITCHMAN_STATE + else process.env.SWITCHMAN_STATE = prevState + if (prevConfigDir === undefined) delete process.env.OPENCODE_CONFIG_DIR + else process.env.OPENCODE_CONFIG_DIR = prevConfigDir +}) + +import { SwitchmanPlugin } from "../src/index" +import { loadManifest } from "../src/state" +import { seedCompleteSetup, manifestModelUniverse } from "./setup-seed" + +type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> +const pluginInput = { client: { provider: { list: async () => [] } }, directory: projectDir } as any + +async function makeHooks(): Promise<Hooks> { + const hooks = await SwitchmanPlugin(pluginInput, { matrix: { mode: "legacy" } } as any) + const cfg: Record<string, unknown> = {} + await hooks.config!(cfg) + return { ...hooks, _cfg: cfg } as any +} + +/** task call with an unknown non-builtin agent: fail-open allowed once the setup gate is open (no other gates fire) */ +async function runTask(hooks: Hooks, callID: string): Promise<void> { + const output: any = { args: { subagent_type: "mystery-agent", prompt: "hello" } } + await hooks["tool.execute.before"]!({ tool: "task", sessionID: "s-setup", callID } as any, output) +} + +describe("setup gate wiring (index-level, hot-reload)", () => { + let hooks: Hooks + test("unconfigured + lang configured → task denied with the setup message", async () => { + hooks = await makeHooks() + expect(setupCompletionNow().complete).toBe(false) + let msg = "" + try { + await runTask(hooks, "sg-deny") + } catch (exc) { + msg = String((exc as Error).message ?? exc) + } + expect(msg).toContain("BLOCKED (setup required)") + expect(msg).toContain("all 6 pools") + }, 20_000) + + test("seeding a complete setup opens the gate immediately on the same hooks instance (mtime hot-reload, no restart)", async () => { + seedCompleteSetup(stateDir, manifestModelUniverse()) + expect(setupCompletionNow().complete).toBe(true) + await runTask(hooks, "sg-allow") // no throw = gate open (unknown non-builtin agent is fail-open allowed) + }, 20_000) +}) diff --git a/test/setup-seed.ts b/test/setup-seed.ts new file mode 100644 index 0000000..3d0592d --- /dev/null +++ b/test/setup-seed.ts @@ -0,0 +1,29 @@ +// [2026-09-19]-[setup hard gate fixture helper: seeds a COMPLETE switchman setup (pool-config.json with all 6 task +// pools + capability-rank.json) into a test state dir so index-level hook harnesses pass the setup gate and reach +// the gates they actually test. Pool lists = the full model universe of the harness superset → gate 5.5 membership +// is allow-all (identical to the old unconfigured fail-open semantics; no lane filtering, no poolOrdered manual +// ordering because the fixture rank key prefix-matches nothing). Writes raw JSON (not the src write helpers) to +// stay decoupled from writeCapabilityRank's pool-universe auto-prune, then drops the mtime cache so the next read +// is fresh] +import { writeFileSync } from "node:fs" +import { join } from "node:path" +import { LANE_ORDER } from "../src/types" +import { loadManifest } from "../src/state" +import { resetUserOverridesCache } from "../src/user-overrides" + +/** Fixture rank entry: normalizes to itself and prefix-matches no real modelId in any test shell universe */ +export const SETUP_FIXTURE_RANK_MODEL = "zz-setup-fixture-model" + +/** All distinct modelIds in the static shell manifest (the superset every index-level harness draws its shells from) */ +export function manifestModelUniverse(): string[] { + return [...new Set(loadManifest().shells.map((s) => s.modelId))] +} + +/** Write pool-config.json (every lane = the full universe → membership allow-all) + capability-rank.json (1 fixture model) */ +export function seedCompleteSetup(stateDir: string, modelIds: readonly string[]): void { + const updated_at = new Date().toISOString() + const pools = Object.fromEntries(LANE_ORDER.map((lane) => [lane, [...modelIds]])) + writeFileSync(join(stateDir, "pool-config.json"), JSON.stringify({ version: 1, updated_at, pools })) + writeFileSync(join(stateDir, "capability-rank.json"), JSON.stringify({ version: 1, updated_at, models: [SETUP_FIXTURE_RANK_MODEL] })) + resetUserOverridesCache() +} diff --git a/test/shell-context-advisory.test.ts b/test/shell-context-advisory.test.ts index e5e3bcc..faad61e 100644 --- a/test/shell-context-advisory.test.ts +++ b/test/shell-context-advisory.test.ts @@ -15,6 +15,9 @@ const projectDir = mkdtempSync(join(tmpdir(), "switchman-shelladv-project-")) process.env.OPENCODE_CONFIG_DIR = configDir process.env.SWITCHMAN_STATE = stateDir writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +// [2026-09-19]-[hermetic capability seed: see test/index-options.test.ts — prevents the startup refresh's async write-back +// from landing in a later file's sandbox after SWITCHMAN_STATE switches mid-flight (CI-only flake on fast networks)] +writeFileSync(join(stateDir, "capability.json"), JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} })) import { SwitchmanPlugin } from "../src/index" diff --git a/test/subagent-cap.test.ts b/test/subagent-cap.test.ts index 0fd7d0e..1dd1599 100644 --- a/test/subagent-cap.test.ts +++ b/test/subagent-cap.test.ts @@ -13,6 +13,9 @@ process.env.OPENCODE_CONFIG_DIR = configDir process.env.SWITCHMAN_STATE = stateDir // [2026-09-06]-[model catalog stub: message.updated model-key recording consults the runtime index for the window cap] writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +// [2026-09-19]-[hermetic capability seed: see test/index-options.test.ts — prevents the startup refresh's async write-back +// from landing in a later file's sandbox after SWITCHMAN_STATE switches mid-flight (CI-only flake on fast networks)] +writeFileSync(join(stateDir, "capability.json"), JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} })) // [2026-09-07]-[lang hard gate fixture: sandbox project counts as lang-configured] const projectDir = mkdtempSync(join(tmpdir(), "switchman-lang-fix-")) mkdirSync(join(projectDir, ".switchman"), { recursive: true }) @@ -24,12 +27,19 @@ import { subagentCapOf, capByWindow, subagentCapDenyMessage, subagentResumeDenyMessage, subagentSoftTiersOf, shellSoftTier, shellSoftTierMessage, shellSoftTierDecision, } from "../src/context-watch" +import { renderNotice } from "../src/i18n" type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> function readStatusLog(): string { const p = join(stateDir, "status-log.json") - return existsSync(p) ? readFileSync(p, "utf8") : "" + if (!existsSync(p)) return "" + // [2026-09-19]-[i18n cleanup: entries are structured {key, params} — render English for the prose assertions] + try { + const data = JSON.parse(readFileSync(p, "utf8")) + if (Array.isArray(data)) return data.map((e: { key?: string; params?: Record<string, string | number>; text?: string }) => renderNotice(e, "en")).join("\n") + } catch { /* fail-open: fall through to raw text */ } + return readFileSync(p, "utf8") } function assistantTokens(input: number): { role: "assistant"; tokens: { input: number; output: number; reasoning: number; cache: { read: number } } } { diff --git a/test/user-overrides.test.ts b/test/user-overrides.test.ts index 71e18aa..532f765 100644 --- a/test/user-overrides.test.ts +++ b/test/user-overrides.test.ts @@ -243,3 +243,39 @@ describe("pool-config.json (task-pool selection)", () => { expect(paths().capabilityRank.endsWith("capability-rank.json")).toBe(true) }) }) + +// [2026-09-18]-[pool lane manual ordering wiring: computeLane builds manualOrder from capability-rank.json (prefix- +// matched via manualRankIndexOf) for a lane with an explicit task-pool selection and hands poolOrdered+manualOrder to +// rankCandidates — the manual order becomes the dispatch priority (beats tier grouping); with nothing ranked the lane +// keeps the existing comparator (and the level-floor exemption keeps below-floor members seated). Empty matrix {} +// keeps the scoring path active (missing combos fail-open as health 1.0); all fixtures cleaned up at the end]- +// [impact: pins the computeLane → rankCandidates contract] +describe("computeLane pool lane manual ordering ([2026-09-18])", () => { + test("ranked pool members follow the manual order (lower tier first); unranked pool lanes keep the baseline comparator + floor exemption", () => { + // leg 1 — manual rank: flash (#1) above glm-5.3 (#2): explicit order wins over the A>B tier grouping on main + writePoolConfig("main", ["glm-5.3", "glm-5.3-flash"]) + writeCapabilityRank(["glm-5.3-flash", "glm-5.3"]) + const ordered = computeLane("main", BASE, { registry: REGISTRY, matrix: {}, routing: null, poolConfig: loadPoolConfig() }) + expect(ordered.dropped).toEqual([]) + expect(ordered.chain.map((c) => c.shell)).toEqual(["glm-mx-glm-53-flash-high", "glm-mx-glm-53-high"]) + // leg 2 — no manual rank on a pool lane: existing comparator applies (level distance = tier grouping here) and + // the below-floor C(L2) member stays seated (poolOrdered floor exemption) + const air = shellReg({ + name: "glm-mx-air-high", modelId: "glm-4.5-air", + matrixKey: "zhipuai-coding-plan|glm-4.5-air|high", comboKey: "zhipuai-coding-plan|glm-4.5-air|high", + }) + const hardReg = { ...REGISTRY, "glm-mx-air-high": air } + writePoolConfig("hard", ["glm-5.3", "glm-4.5-air"]) + clearCapabilityRank() + const hardPool = computeLane("hard", ["glm-mx-glm-53-high", "glm-mx-air-high"], { registry: hardReg, matrix: {}, routing: null, poolConfig: loadPoolConfig() }) + expect(hardPool.dropped).toEqual([]) + expect(hardPool.chain.map((c) => c.shell)).toEqual(["glm-mx-glm-53-high", "glm-mx-air-high"]) + // leg 3 — control, same lane without the pool selection: the level floor filters the below-floor shell again + resetPoolConfig("hard") + const hardDefault = computeLane("hard", ["glm-mx-glm-53-high", "glm-mx-air-high"], { registry: hardReg, matrix: {}, routing: null, poolConfig: loadPoolConfig() }) + expect(hardDefault.chain.map((c) => c.shell)).toEqual(["glm-mx-glm-53-high"]) + // cleanup: restore the default (unconfigured) state for any later fixture + resetPoolConfig("main") + expect(loadPoolConfig()).toEqual({}) + }) +})