diff --git a/README.md b/README.md index f974d9d..2328baf 100644 --- a/README.md +++ b/README.md @@ -1,446 +1,116 @@ # opencode-switchman -**English** | [Chinese](./README.zh.md) +**English** | [中文](./README.zh.md) -> ### 🎯 Fully-automated model matrix + autonomous decisions = every token lands exactly where it matters. Not one wasted. +> Context on a meter. Tasks dispatch themselves. -> **🎬 [Live Presentation Deck](https://mrzturn.github.io/opencode-switchman/)**(GitHub Pages, works on desktop & mobile) -> -> [![opencode-switchman capability overview](docs/assets/preview-en.png)](https://mrzturn.github.io/opencode-switchman/) +![opencode-switchman — the context water level drives the switchman and throws the route](docs/assets/hero.svg) -A six-lane shell-matrix orchestration plugin for OpenCode — turns your primary model into a dispatcher that delegates tasks by cognitive tier to bare subagent shells across any opencode provider, while the plugin layer enforces deterministic gating, weighted model scoring, traceable routing decisions, and self-healing failure isolation; glm / deepseek / copilot additionally get quota-aware routing. +> Interactive demo deck: [opencode-switchman in action](https://mrzturn.github.io/opencode-switchman/) -If you hold multiple model subscriptions (GitHub Copilot premium credits, Zhipu GLM Coding Plan, DeepSeek pay-as-you-go balance) but keep burning a single model forever, blind to water levels and peak pricing — opencode-switchman is built for you. +An orchestration plugin for [OpenCode](https://opencode.ai). It does two things, and does them well: -## Installation & Usage +**1. Context water-level control.** Your session's context is measured every turn. Reads run against a per-turn budget, so the model can't quietly gulp the whole repo; soft / hard / force watermarks trigger advice, then wrap-up, then an automatic backup-and-compact handover; every dispatched subagent carries its own hard cap. Context stops snowballing — a session can run all day without tokens being devoured by its own history. -### Recommended: let your AI install it for you +**2. Automated decision dispatching.** Your primary model becomes a dispatcher: it profiles each task and delegates it to subagent shells across six cognitive lanes (economy / mechanical / main / hard / vision / review). The plugin enforces deterministic gates, weighted model scoring, and self-healing failure isolation, and logs every routing decision. -In the AI era, we strongly recommend letting an AI perform the installation and configuration for you — it reads your real environment, writes the correct values, and verifies the result itself, which is far less error-prone than manual copy-pasting. +On top of that: -Just copy the prompt below and paste it to the AI you are currently using, and let it install opencode-switchman for you: +- **Multiple models or subscriptions? This plugin was built for you.** GitHub Copilot, GLM Coding Plan, DeepSeek — or any opencode provider — get orchestrated as one pool: quota-aware ordering, peak-window avoidance, forced cross-family review. +- **Only one model? Still worth it.** The context control and smart dispatch alone keep a single model usable indefinitely — no matter how long the session runs, the context never balloons. -```text -Please install and configure the opencode-switchman plugin for my opencode, strictly following its official instructions. - -Official sources (authoritative, do not guess from memory): -- GitHub repo: https://github.com/mrzturn/opencode-switchman -- npm package: https://www.npmjs.com/package/opencode-switchman -Read the repo README's "Installation & Usage" section and follow it exactly. - -Steps: -1. Install the latest version published on npm: run `npx -y opencode-switchman@latest` (or `bunx opencode-switchman@latest`) — it rewrites the `plugin` entry in my opencode config to the exact latest version (it also works in the project-level `opencode.json` if that is what I use). -2. Complete the functional configuration: all plugin settings live in the standalone `opencode-switchman.jsonc` in my opencode config directory, auto-generated with defaults and inline comments on first start; check it against my providers (e.g. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) and adjust as needed. -3. Verify correctness so opencode loads, starts, and runs the plugin: run `/switchman-doctor` inside opencode for a local credential-free diagnostic report and fix every error it reports; then restart opencode and confirm the plugin actually loaded — the log should contain `[opencode-switchman] injected N model shells (agents)` and my primary model's system prompt should carry the live `[ROUTES]/[WATERMARK]/[LIMITS]` banner block. - -Do not declare success until all three steps pass; report what you changed and show the verification evidence. -``` - -### Prerequisites - -- [opencode](https://opencode.ai) — **the CLI/TUI is the strongly recommended interface** (the plugin's operational surface — sidebar status panel, `/poolConfig` / `/modelRank` dialogs, live banners — is richest there): configure everything in the TUI first, then optionally switch to the desktop app for a GUI experience; both share the same config and state -- Any opencode provider works out of the box; the following three additionally get quota control (any combination, all optional): - - **GitHub Copilot**: just sign in via GitHub in opencode (`/connect`) - - **GLM**: custom provider (`zhipuai-coding-plan`, baseURL `https://open.bigmodel.cn/api/coding/paas/v4` + apiKey) - - **DeepSeek**: custom provider (`deepseek` + apiKey) -- Zero-config credentials: the plugin reads them **read-only** from opencode's auth layer (auth.json / provider options / env vars) — it never stores secrets or refreshes tokens itself - -### Install / update (two one-command paths) +## Install -Both commands cover first install and later updates (idempotent, safe to re-run): they rewrite the `plugin` entry in your opencode config and `tui.jsonc` to the exact latest version `opencode-switchman@x.y.z` (JSONC comments preserved), prune stale plugin caches (`~/.cache/opencode/packages/opencode-switchman*`), and on upgrade flag the "upgraded, restart required" banner — **restart opencode to take effect**. - -**One-line script (recommended)** +One command — covers first install and later updates. Restart opencode afterwards. ```bash curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash ``` -**npx / bunx** +or ```bash -npx -y opencode-switchman@latest # or: bunx opencode-switchman@latest -``` - -> The npx path is available once ≥0.2.1 is published (the package ships an `update` bin entry). - -> **Why the entry is an exact version instead of a bare name / `@latest`**: OpenCode ≤1.18.x pins its plugin cache to a per-spec directory (e.g. `~/.cache/opencode/packages/opencode-switchman`) and never re-queries npm after the first install — bare names and `@latest` keep reusing the stale cache (observed pinned at 0.0.1). Exact versions get their own cache directory, so the updater rewrites the version instead. - -The in-plugin `/switchman-update` command now invokes the same updater (the old `npm install` approach never affected the path OpenCode actually loads). - -### Option 1: npm (manual) - -Add to your opencode config (`~/.config/opencode/opencode.json` or project `opencode.json`): - -```json -{ - "plugin": ["opencode-switchman"] -} +npx -y opencode-switchman@latest ``` -opencode installs and loads the npm package automatically via Bun at startup, no other steps needed. For later updates use the one-liner above or `/switchman-update` inside opencode. - -> **Nothing else goes into your opencode config**: all plugin configuration (water levels, billing, peaks, thresholds, banner, matrix, custom lanes, etc.) lives in the standalone `opencode-switchman.jsonc` file (see below) — auto-generated on first start with inline comments. The legacy tuple-options form (`["opencode-switchman", {...}]`) is deprecated and kept compatible for one release (explicit values still win; `/switchman-doctor` flags them as SWM044 and suggests migrating). - -### Option 2: from source +or ```bash -git clone https://github.com/mrzturn/opencode-switchman.git -cd opencode-switchman -bun install -bun run build # produces dist/opencode-switchman.js -``` - -Then pick one of two loading methods: - -**a) Config reference (recommended, follows the repo)** — point the `plugin` array at the repo directory via `file://`: - -```json -{ - "plugin": ["file:///absolute/path/to/opencode-switchman"] -} -``` - -The plugin loads the repo's `dist` bundle directly; after `git pull`, re-run `bun run build` and restart opencode to upgrade. **Choose either this or the plugins-directory deployment** — using both double-loads the plugin. - -**b) Single-file deploy** — `bun run deploy` builds and copies into the global plugin directory `~/.config/opencode/plugins/opencode-switchman.js`, which is auto-loaded. The desktop app's embedded core runs on Node, which is exactly what the single-file `deploy` bundle targets. - -> **Note**: a `file://` entry in the `plugin` array and a plugins-directory deployment must not coexist (the same plugin loads twice). Once published to npm, replace the `file://...` entry with `"opencode-switchman"` to switch to npm installation. Restart opencode to take effect. - -> **Upgrading from the pre-rename plugin (switchman.js)**: delete the old `~/.config/opencode/plugins/switchman.js` to avoid double injection. The state directory has moved to `~/.config/opencode/opencode-switchman/` (the old one can be removed; all state self-heals). - -### Configuration: opencode-switchman.jsonc - -**Apart from the plugin registration itself (the `plugin` array in your opencode config), every plugin setting lives in the standalone `opencode-switchman.jsonc`** — auto-created on first startup in the OpenCode config directory (`OPENCODE_CONFIG_DIR`, then `$XDG_CONFIG_HOME/opencode`, then `~/.config/opencode`) with a `$schema` for editor hints and per-key comments; invalid values fail open to defaults. Edit the file and re-run config (or restart opencode) to apply; `/switchman-doctor` produces a local, credential-free diagnostic report. - -**providers — per-provider policy**: it ships with the stable provider keys `deepseek`, `zhipuai-coding-plan`, and `github-copilot` (matching OpenCode's own official provider IDs), but **any opencode official or custom provider key is legal** — unknown keys are treated as custom providers (routed with generic defaults; near-miss spellings of the built-in keys get a doctor warning). `observe` controls quota lookup/banner display; `enabled` independently opts a provider into routing water-level, peak, and exhaustion rules (both default to `true`/`false` respectively). `billing` declares the cost structure — `subscription` (score boost 1.0) or `api` (0.85, sinks within its capability tier); it is the only source of billing priority (never inferred from models.dev or auth). `peak` ranges use ISO weekdays (`1`–`7`) and `[start,end)` `HH:mm` ranges; defaults are GLM weekdays 14:00–18:00 and DeepSeek weekdays 09:00–12:00 plus 14:00–18:00. - -**Behavior sections** (`quota` / `cost` / `capability` / `matrix` / `banner` / `rules` / `lanes`): see the Options table below — same file, nowhere else. - -### Verify the installation - -After starting opencode, every system prompt of the primary model carries a live banner block (the dispatcher's ground truth): - -``` -[ROUTES] economy: glm-53f-low→glm-47-off→glm-5t-off | mechanical: glm-53f-high→glm-47-off | main: glm-53f-high | hard: glm-53-high | vision: glm-53f-high | review: glm-53-high-ro -[WATERMARK] GLM 5h 10% weekly 38% (refreshed 09-11 10:00) | Copilot credits 0% left (refreshes 2026-10-01) | DeepSeek balance exhausted | advice: ... -[WATERMARK:SESSION] measured session context ~37k (soft 60k/hard 80k/force 100k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 -[LIMITS] down: none | reviewer prefers cross-family (same-family self-review = DOWNGRADED, allowed only when no cross-family reviewer exists) | api-billed & unknown models sink by coefficient (explicit billing=subscription wins) | matrix: cli·watch/ok | manual capability rank: 9 models, task-pool selection: 6 pools active (/modelRank /poolConfig to adjust) -[TODO] 0/6 done · in_progress: draft the README section — keep todowrite current (update as each item starts/finishes) -[LANG] conversation=en comments=en docs=en (source: project settings) — reply and reason in the conversation language; code comments, commit messages, and generated docs follow their own settings -[UPDATE] new version available: /switchman-update or /switchman-ignore +bunx opencode-switchman@latest ``` -The log also shows `[opencode-switchman] injected N model shells (agents)` — N varies dynamically with the model surface of credentialed providers. Lane candidates are generated algorithmically from capability score × effort affinity × billing/unknown coefficients, with vision/review structural gates and no vendor-specific seats; runtime health, quota, and cost rules then select the current first candidate. - -### Sidebar status panel (TUI plugin, optional) - -v0.2.0 adds a live `switchman` panel at the bottom of the OpenCode TUI sidebar; v1.0.0 polishes it into a fully aligned, English-localized operational view. Observed provider water levels render as gradient bars on a globally aligned 8-column grid (labels, bars, and reset times line up across provider blocks; any non-zero quota paints at least one filled cell), with peak-period warnings, per-provider observe-only tags (collapsed when every provider observes), the current head candidate for each of the six lanes, restart-required badges for newly detected models/providers, a version line on the marquee row (the running version — local builds append the checked commit short SHA — plus a green `→ v` when the update check reports a newer release, `→ origin/main` for local builds; the blinking `[RESTART NEEDED]` tag also lights up while an installed upgrade awaits a restart), and the most recent status notice. The panel polls local state every 2 seconds; non-banner notices never flood `stderr` or cover the input box. It is a separate TUI Slot plugin (`src/tui.tsx`, exported at `opencode-switchman/tui`) and is independent of the server-side hook plugin above. - -> **Recommended workflow**: set the plugin up in the TUI first — pick model favorites, tune `/poolConfig` and `/modelRank`, and watch the sidebar while it routes. The desktop app is an optional alternative afterwards (it shares the same config and state); the TUI is simply where the operational surface — dialogs, sidebar, banners — is richest. - -![Switchman sidebar: quotas, peak periods, lane candidates, and status notice](docs/assets/tui-sidebar-status.png) - -![OpenCode model picker alongside the Switchman TUI integration](docs/assets/tui-model-picker.png) - -Since TUI plugins have no directory auto-discovery, add the same package spec to your **`tui.jsonc`/`tui.json`** `plugin` array (npm install and `opencode plugin ` do this automatically; only needed manually if you hand-edit config or use `mode:local`/`mode:prod` from source): - -```json -{ - "plugin": ["opencode-switchman"] -} -``` - -## Quick Start — five steps to a working matrix - -Installed? Five steps and you're done (full walkthrough with screenshots and exact scope/conditions: **[docs/quick-start.md](./docs/quick-start.md)** / 中文 **[docs/quick-start.zh.md](./docs/quick-start.zh.md)**): - -1. **Connect providers** — run `/connect` in the TUI: sign in to GitHub Copilot (OAuth), paste your DeepSeek API key; for the GLM Coding Plan add the `zhipuai-coding-plan` custom provider (baseURL + apiKey) to `opencode.json`. Any opencode provider works; these three additionally get quota-aware routing. -2. **Pick the models that join orchestration** — TUI: `/models` then `ctrl+f` to favorite; desktop app: "Manage models" toggles. Favorites/visible models form the activation surface and sync bidirectionally (nothing picked → active session models fill in). -3. **(Optional) `/modelRank`** — pin your own capability ranking (TUI dialog, or conversational `/modelRank-chat`); a manual rank overrides base capability scores everywhere. -4. **(Optional) `/poolConfig`** — curate per-pool candidate lists for the six task pools (TUI dialog, or `/poolConfig-chat`); a pool's manual list replaces the system default candidates. -5. **Restart, verify, watch** — restart opencode, confirm the `[ROUTES]`/`[LIMITS]` banner and the sidebar `switchman` panel, run `/switchman-doctor` if anything looks off, then just use opencode normally. - -## Manual overrides: /poolConfig and /modelRank (new in v0.2.5) - -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: - -### /poolConfig — per-lane model assignment (manual dialog; conversational: /poolConfig-chat) - -- **TUI (/poolConfig)**: a native select dialog (same interaction as the model/thinking-level pickers) — pick a task pool (economy / mechanical / main / hard / vision / review), then toggle models up and down the list: select to include, select again to exclude, with a capability tier shown per model. Shortcuts: "Select all" and "Uncheck all" (rebuild mode — check just the few to keep; exiting with none checked keeps the previous selection, the first check after a clear writes the new list). Changes are written through immediately with a toast receipt. -- **Non-TUI / in-session (/poolConfig-chat)**: a conversational flow — it injects a per-pool assignment overview (use a pool name to get the full `[x]/[ ]` list); reply "main: keep only 3 5" or "economy: add 1, drop 2" and the agent calls the bundled `switchman-config.js` CLI to persist. -- **Semantics**: assignment = making each task pool's candidate models **deliberately different** (e.g. lightweight models only for economy, heavy thinkers only for hard) — a pool's manual list **overrides the system default candidate set**, and models inside it are still recommended by capability level; **the same model may join multiple pools**; pools without a configured (or with an empty) list keep the system default. "Clear config" restores the system default for that pool. -- **Config file**: `~/.config/opencode/opencode-switchman/pool-config.json` (key = task pool name, value = array of participating modelIds). - -![/poolConfig step 1 — pick a task pool, each lane showing how many models participate](docs/assets/tui-pool-config-pools.png) - -![/poolConfig step 2 — toggle models per pool with capability tiers and select-all / uncheck-all / clear shortcuts](docs/assets/tui-pool-config-models.png) - -### /modelRank — model capability ranking (manual dialog; conversational: /modelRank-chat) - -- **TUI (/modelRank)**: a dialog listing models by effective capability — manual entries interleave with base-score models in one merged ordering; moving a model up/down anchors it a manual score between its new neighbors (one-spot nudges, no need to rank everything above), plus pin-to-top / remove; effective immediately. -- **Non-TUI / in-session (/modelRank-chat)**: a conversational flow — it injects the current ranking and a reference ordering; reply "pin glm-5.3 to top" or "clear the ranking" and the agent translates that into `rank` CLI calls to persist. -- **Semantics**: manual ranking **takes priority over the base capability score** (realtime index → bundled snapshot → curated table all yield) — matched models (including their prefix variants) get a rank-position score and S/A/B/C tier: rankings with ≤4 entries map positions to S/A/B/C in order; ≥5 entries use quantile buckets (top 20% S / next 20% A / next 20% B / rest C, same semantics as the OpenRouter rank source); within a tier, the linear rank position breaks ties. Unranked models are unaffected. The ranking feeds every decision surface: lane chains, effort affinity, capability-level gates, and deny hints. -- **Config file**: `~/.config/opencode/opencode-switchman/capability-rank.json` (`models` array order = strongest first). - -![/modelRank — capability ranking with manual-rank vs base-score provenance](docs/assets/tui-model-rank.png) - -### /expert — expert consultation (conversational) - -- Usage: `/expert ` — the description is passed verbatim to the expert; with no description the agent asks first. -- 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: (review)`). +Either path rewrites the `plugin` entry in your opencode config to the exact latest version and prunes stale caches. Manual npm install, from-source build, and the "why exact versions" note: [Installation details](./docs/reference.md#installation). -Both commands can also be driven directly via the bundled CLI: `node /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"). +Prefer hands-off? Let your AI do the installation — paste this prompt into the AI you're using: -## What's New +
+AI-assisted install prompt -### v1.x — deterministic context governance & richer overrides (post-1.0.0) - -- **Shell subagent context hard cap**: every shell subagent session now has a hard context cap (`context.subagentForceTokens`, default 100k tokens) — past the cap every tool call is denied with a wrap-up order, the subagent hands back a detailed progress summary as its task result, and the session can never be resumed via `task_id` (persistent registry); configured via `context.subagentCap` (see [Subagent context hard cap](#subagent-context-hard-cap)). -- **Always-on per-call read budget (core routing algorithm update)**: the old per-tool one-time nudge (a coupon models rationally burned via retry/probing) is replaced by a deterministic budget gate. Every read is costed against `context.readBudgetTokens` (default 1500, clamped 200..20000) from turn 1 — over-budget reads are auto-bounded (a `limit` is appended in place) or denied with exact bounded-retry params; a per-turn 2× self-read cap (resetting on user turns) stops read chains; un-estimable tool outputs are charged post-hoc. Watermarks keep lifecycle duties only (soft = advice, hard = wrap-up deny, force = auto-handover). Delivery/verification bash (git, test/lint, build) passes at every tier; unbounded archaeology (`git log -p` without `-n`) is denied at every tier with a scoping hint. -- **Per-project language preference**: a per-turn `[LANG]` iron-rule line pins the conversation / comments & commits / docs languages, captured by a first-use ask (re-surfaced at the start of every user turn until configured, and enforced by a hard gate — write/edit/bash/task calls are denied with an ask-first error while the project is unconfigured; the user's decline waives the gate for that session), persisted per project, adjustable via `/switchman-lang`. -- **Todo discipline**: protocol §0.7 plus a per-turn `[TODO]` status line keeps the main session's todo list real-time current (delegated-shell results included). -- **/expert expert consultation** and **bundled agent skills**: dispatch requirements to the strongest cross-family expert; opinionated skills sync into the opencode global skills dir at startup (add/overwrite-only, marker-gated cleanup, fail-open). -- **Review-lane last resort**: with no cross-family read-only shell alive, the chain keeps the best ro shells and same-family review is allowed with a `DOWNGRADED` note instead of an empty chain. -- **Auto-handover robustness**: numbered `[backup]` sessions (survives restarts, never recycles numbers), compaction routed through the same channel as the manual `/compact`, and a detached compaction leg that can no longer deadlock the session. -- **Sidebar version line**: the marquee row shows the running version and, when the update check reports a newer release, the latest version; the blinking `[RESTART NEEDED]` tag now also covers installed-but-not-loaded upgrades (see [Sidebar status panel](#sidebar-status-panel-tui-plugin-optional)). -- **tmux pane mirroring**: when the opencode server itself runs inside tmux, every dispatched subagent opens as a live `opencode attach` pane stacked in a right-hand column of the home tmux window — capped visible panes with a FIFO queue, in-place respawn, auto re-evening on completion, and full fail-open safety (see [tmux pane mirroring](#tmux-pane-mirroring-optional)). - -### v1.0.0 — English-first stable release - -- English localization across protocol assets, runtime messages, code comments, and docs; banner anchors renamed to `[ROUTES]` / `[WATERMARK]` / `[WATERMARK:SESSION]` / `[LIMITS]` / `[UPDATE]`. -- TUI sidebar layout/color polish: 8-column aligned quota grid, gradient watermark fills over muted tracks, brightened 400-level lane/model palette, collapsed observe-only tags. - -### v0.2.0 — live, capability-aware orchestration - -v0.2.0 evolves switchman from a fixed multi-provider dispatcher into a live, capability-aware orchestration layer. - -- **TUI operations view**: optional sidebar panel for water levels, peak windows, the six lane leaders, restart-required state, and the latest runtime notice. -- **Dynamic activation matrix**: synchronizes desktop visible models and CLI/TUI favorites, falls back to active session models, and refreshes probes immediately when the model surface changes. -- **Capability-aware routing**: dynamically classifies models into capability tiers, keeps stronger tiers ahead of weaker tiers, then uses effort fit, health, water level, peak timing, explicit billing, and unknown-model confidence as transparent tie-breakers. -- **Provider-neutral policy**: any official or custom OpenCode provider can participate. Explicit `billing: "subscription" | "api"` replaces vendor-specific routing preferences. -- **Safer live operations**: real-dispatch isolation, retirement of repeatedly missing models, route-decision audit logs, and clearer restart/update guidance make routing failures observable and self-healing. -- **Simpler configuration and upgrades**: all plugin settings now live in generated `opencode-switchman.jsonc`; legacy tuple options are diagnosed and supported for one compatibility release. `/handover` runs directly (no AI round-trip): it forks the full current session into a `[backup]`-titled backup and compacts the current session in place, staying in the same session (unlike the built-in `/fork`, which switches to the forked session). Crossing the force watermark also fires it automatically (`context.autoHandover`, default on), letting an unfinished task continue on the compacted context. - -See the complete, user-facing release notes and migration guide in [CHANGELOG.md](./CHANGELOG.md). - -### Options (opencode-switchman.jsonc) - -| Key | Default | Description | -|---|---|---| -| `providers..enabled / observe / billing / peak` | `false / true / factory / factory` | Provider policy: routing participation, quota observation, cost structure (subscription=1.0 / api=0.85), peak windows (see above) | -| `quota.glmFiveHourReservePct` | `90` | GLM 5-hour window reserve water level (%): hard-block GLM shells once reached (avoid 429); weekly still only blocks at 100% | -| `quota.deepseekLowBalanceWarnCny` | `10` | DeepSeek balance warning threshold (CNY): the banner water-level line warns below it (warning only, no hard block, pay-as-you-go) | -| `cost.enabled` | `true` | models.dev pricing snapshot as one coefficient in weighted model scoring | -| `capability.enabled / source / apiKey / tierThresholds / lmarenaCheck` | `true / auto / – / built-in quantile / false` | Dynamic capability tiers: `auto` = Artificial Analysis first when apiKey present, otherwise OpenRouter; key may also come from `ARTIFICIAL_ANALYSIS_API_KEY` env | -| `matrix.mode / watch` | `auto / true` | Activation matrix: `auto` by host (desktop = visible models / CLI/TUI = favorites), `app`/`tui` force a mode, `legacy` restores the static matrix; `watch` recomputes and fully refreshes probes on surface changes (mode/watch are startup-level; restart to apply) | -| `banner.enabled` | `true` | Four-line banner injection | -| `rules.enabled / delegationFloor` | `true / 3000` | Bundled dispatcher rules (AGENTS.md) injection; `delegationFloor` is the self-do token floor interpolated into the rules (dispatch by default below it is a violation) | -| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 60000 / 80000 / 120000 / 1500 / true` | **Measured session watermark + self-read budget**: the plugin measures each main session's context from message token usage and injects a live `[WATERMARK:SESSION]` line every turn (with per-turn growth and remaining-turns-to-hard estimates). Every self-read is costed against `readBudgetTokens` from turn 1: over-budget reads are auto-bounded (a `limit` is auto-appended) or denied with exact bounded-retry params, and a per-turn 2× cap stops read chains; un-estimable tool outputs are charged post-hoc. Verification/delivery bash (git, test/lint, build) always passes; unbounded history dumps (`git log -p` without `-n`) are always denied with a scoping hint; past `hardTokens` read-class closes (wrap-up mode); past `forceTokens` the banner demands compaction and, with `autoHandover: true` (default), `/handover` fires automatically: full fork backup + compaction, the running task continues on the summarized context. Shell subagent sessions are exempt from this watermark and get their own single hard cap instead (see `context.subagentForceTokens` / `context.subagentCap` below); all three thresholds are additionally capped at 90% of the current session model's context window when known (models.dev) | -| `context.subagentForceTokens / subagentCap` | `100000 / true` | **Subagent context hard cap**: shell subagent sessions get a single hard cap (measured = input + output + reasoning + cache.read of the latest assistant message, same estimator as the session watermark), clamped 20k..1M and additionally capped at 90% of the shell model's context window. On crossing, every further tool call in that subagent session is denied with a wrap-up order; the subagent's next text-only answer (a detailed work-progress summary) becomes the task result returned to the delegating session and the session is permanently terminated. Later `task` calls resuming it via `task_id` are denied permanently (persistent registry `~/.config/opencode/opencode-switchman/subagent-cap.json`); fresh dispatches without `task_id` are unaffected; `subagentCap: false` prevents new terminations only — already-terminated sessions stay dead | -| `builtinAgents.mode` | `deny` | Built-in `explore`/`general` subagents compete with shell routing and were previously fail-open; `deny` blocks them with an economy/main re-dispatch hint (the task-tool description from opencode core actively advertises them), `allow` restores the old pass-through | -| `injection.mode` | `chain` | Shell injection face: `chain` = six lane chains ∪ favorites/visible models (saves ~6-10k tokens of task-tool description per session; naming an off-chain model gets a `denyUninjected` hint to enable it in model management), `all` = every usable model (old behavior). Startup-level: restart to apply | -| `dispatch.autoRedirect` | `true` | On a dispatch deny, rewrite `subagent_type` in-flight to the chain-head candidate the deny message already names (single hop, same-snapshot guard re-check) — the first dispatch lands on the best available shell instead of burning deny-and-retry rounds; `false` restores deny-and-retry | -| `relay.image` | `true` | Vision-less main models: user-attached images are decoded to disk and replaced with path text + reading guidance (delegate a vision-lane shell or an MCP vision tool); local paths / http URLs pass through; fully fail-open | -| `lang.enabled / ask / candidates` | `true / true / factory list` | Per-project language preference: per-turn `[LANG]` iron-rule line (conversation / comments & commits / docs), first-use ask re-surfaced every user turn until configured and enforced by a hard gate (write/edit/bash/task denied while unconfigured; decline waives per session), persisted to `.switchman/settings.json` (AGENTS.md marker as read-only fallback), `/switchman-lang` re-asks | -| `lanes` | built-in chains | Custom per-lane shell chains (override built-in preference order); keys = economy/mechanical/main/hard/vision/review | -| `workspace.enabled / dirname` | `true / ".switchman"` | Artifact workspace: per main session, a `/.switchman//-/` folder whose path is injected into the dispatcher protocol every turn; holds `SESSION.md` / `dispatches.jsonl` / `media/`. Disabled = no folders created and the protocol section is neutralized | -| `tmux.enabled / rightPct / maxPanes / mini` | `true / 60 / 3 / false` | tmux pane mirroring (effective only when the opencode server itself runs inside tmux): every dispatched subagent opens as a live `opencode attach` pane in a right-hand column of the home tmux window; `rightPct` = right column width percent (10..90, main pane keeps the rest), `maxPanes` = max visible subagent panes (1..4; extra dispatches wait in a FIFO queue), `mini` = minimal attach interface instead of the full TUI | - -> **Migrating legacy tuple options**: `quota.*.enabled` → `providers.<id>.observe` (SWM042), `billingWindow.*` → `providers.<id>.peak` (SWM043), and the remaining behavior sections (`quota` thresholds / `cost` / `capability` / `matrix` / `banner` / `rules` / `lanes`) → same-named jsonc sections (SWM044); `providers.glm/deepseek` (credential-collection lists) never took effect and have been removed. Explicit tuple values stay honored for one compatibility release, then will be dropped. - -## Dynamic Activation Matrix - -The shell matrix is no longer a static list — it is built at runtime and updated in real time: - -- **Desktop app** visible models and **CLI/TUI** favorites are bidirectionally synchronized. `mtime` decides the fresher side; a same-millisecond tie does not write either side, and the default CLI path is used as fallback when needed. -- With neither surface configured, it falls back to "the models your live sessions are actually using"; concurrent sessions are unioned, and any model switch is followed in real time on the next request. -- Model-management / favorites changes are watched live (fs.watch + mtime polling fallback). Any surface change recomputes the active matrix and triggers a **full probe refresh immediately** instead of waiting for TTL; the 10-minute periodic refresh still keeps the matrix self-healing. -- Newly added providers are detected in real time with a banner notice (the agent registry is immutable at runtime, so their shells are **registered automatically after restarting opencode** — zero manual maintenance). -- A superset of shells (every conversation-capable model of credentialed providers × models.dev tiers) is injected at startup; `matrix.mode=legacy` fully restores the old static behavior. - -## Model Scoring Engine - -Routing is now an explicit, traceable score rather than a hidden preference list: - -- **Base capability dominates**: curated S/A/B/C capability grades are matched by exact model id → prefix → family → global fallback, and the match route is recorded for audit. Tier groups are irreversible: a lower tier can never outrank a higher tier. -- **Weighted coefficients**: final score multiplies `effortFit × health × water × costBias × peak × billingBoost × unknownPenalty`. Health is `ok=1.0` / `strained=0.6`; water uses the tighter of the two windows and can boost Copilot when surplus credits are near expiry; peak applies `×0.93` to any provider whose configured peak window is active, as a same-tier yield that never ejects a stronger model across capability tiers. `billingBoost` is driven solely by the explicit `billing` field in `opencode-switchman.jsonc` (`subscription=1.0`, `api=0.85`) — no vendor is hardcoded in the routing rules. `unknownPenalty=0.75` applies to models that miss the whole classification cascade (exact → prefix → family), sinking them behind known models within the same tier. -- **Hard gates do not score**: down, breaker-open, pool-exhausted, retired, and real-dispatch-isolated combos are removed before scoring. `immediate` urgency sorts by probe latency instead of economics. -- **Decision log**: every banner rebuild writes lane candidates and the six-factor score breakdown to `state/routing-decisions.jsonl` as a 200-line ring buffer. - -## Artifact workspace (.switchman) - -For every main session the plugin auto-creates a per-project folder `<project-root>/.switchman/<yyyy-mm-dd>/<sessionId>-<title>/` (date = session creation day; the title slug part renames itself when the session title is generated or edited). The injected dispatcher protocol gets this folder path interpolated every turn, so plans, implementation progress, process-control notes, design docs, and other intermediate artifacts default to the session folder instead of scattering across the repo or being dumped into chat. Plugin-maintained files inside the folder: - -- `SESSION.md` — session metadata (id / title / project / timestamps) -- `dispatches.jsonl` — one JSON line per allowed task delegation (ts / shell / lane / role / source / redirected) -- `media/` — images relayed for vision delegation (moved here from the old global state directory, fail-open fallback) - -Configured by `workspace.enabled` / `workspace.dirname` in `opencode-switchman.jsonc` (defaults `true` / `".switchman"`); when disabled, no folders are created and the protocol section is neutralized. - -## tmux pane mirroring (optional) - -When the opencode server itself runs inside tmux, every dispatched subagent session opens as a live `opencode attach <server> -s <session>` pane, stacked in a right-hand column of the home tmux window (main pane keeps the left share — default 40% — the subagent column takes the right 60%). The window is only ever split at the home pane (the pane the server was launched in, `TMUX_PANE` at startup): your own sidebar panes and the tmux status line are never touched, and TUI clients attached from other panes still see the subagent panes there. - -![tmux pane mirroring: main session left, live subagent panes stacked on the right](docs/assets/tmux-pane-mirroring.png) - -> Works out of the box — no configuration needed. The only requirement: run opencode inside a tmux session; outside tmux the feature stays completely inert. - -- **Visibility cap + FIFO**: at most 3 subagent panes are visible (`tmux.maxPanes`, 1..4); extra concurrent dispatches wait in a FIFO queue, and when a visible subagent finishes, a queued one takes over its pane in place (in-place respawn, pane count unchanged). Each completion shrinks the column again and re-evens the layout: 3→2 even halves → 1 full right pane → 0 = main pane alone (full width restored). -- **Hygiene**: panes are labeled `swm:<agent-name>` via pane title; leftover panes from a crashed previous run are swept (killed) at plugin startup (matched by title prefix or the attach start command). The window's active pane is restored after every layout op (focus preservation). -- **Safe by construction**: inert outside tmux and when `tmux.enabled=false`; all tmux failures are fail-open — status log only, never blocks dispatch. -- **Viewer etiquette**: the pane is a real interactive TUI attached to the subagent session — don't type into it (keystrokes go to the subagent session). Quitting a viewer pane just removes the display; the subagent keeps running. - -Configured by the optional `tmux` section in `opencode-switchman.jsonc` (`enabled` / `rightPct` / `maxPanes` / `mini`, defaults `true` / `60` / `3` / `false`). - -## Subagent context hard cap - -Main sessions get the three-tier watermark (soft / hard / force) plus auto-handover; dispatched shell subagent sessions previously had no context control at all and could run past 180k tokens. Now every shell subagent session gets a single hard cap (`context.subagentForceTokens`, default 100,000 tokens, clamped 20k..1M and additionally capped at 90% of the shell model's context window), measured with the same estimator as the session watermark: input + output + reasoning + cache.read of the latest assistant message. On crossing, the plugin denies every further tool call in that subagent session with a wrap-up order; the subagent's next text-only answer — a detailed work-progress summary (completed / key findings with file:line evidence / remaining work / next steps) — becomes the task result returned to the delegating session, and the session is permanently terminated (terminations are recorded in the status log). Compliance is pre-armed on both sides: shell rule 6 of the subagent system prompt (stop at the first cap deny, hand back the summary), and bundled dispatcher protocol section 2 on the orchestrator side (never retry a terminated session; start a fresh dispatch re-seeding only needed context). - -Termination is permanent by design: any later `task` call resuming that session via `task_id` is denied permanently (persistent registry `~/.config/opencode/opencode-switchman/subagent-cap.json`, survives restarts), while fresh dispatches without `task_id` are unaffected. Rationale: a subagent is a reproducible worker (its spec lives in the delegation prompt), so terminate-and-hand-back beats compaction-continuation. `context.subagentCap: false` prevents new terminations only — already-terminated sessions stay dead. - -Configured by `context.subagentForceTokens` (default `100000`) / `context.subagentCap` (default `true`) in `opencode-switchman.jsonc` (see the Options table). - -## Core Ideas - -### The problem - -Real pain points of juggling multiple subscriptions: - -1. **Cognitive mismatch**: flagship models doing scan-and-count chores (tokens wasted), or lightweight models doing architecture design (rework is the most expensive token of all) -2. **Flying blind on water levels**: hammering GLM after the 5-hour window is exhausted, letting Copilot premium credits expire unused at month's end, discovering an empty DeepSeek balance only at failure -3. **Single-family blind spots**: reviewing with the same model family that produced the code — same blind spots, nothing found -4. **Loose delegation**: "hey, take a look at this" prompts carry no structure and no validation - -### The solution: dispatcher + shell matrix + deterministic gating - -opencode-switchman splits orchestration into three layers: - -| Layer | Vehicle | Responsibility | -|---|---|---| -| **Cognitive** | Primary model (dispatcher) + bundled dispatcher rules | Four-dimension task profiling (cognitive intensity × mechanicalness × context size × urgency), self-do vs. delegate, lane & shell choice, writing DELEGATION_V1 prompts | -| **Execution** | "model × effort" bare shells (e.g. `glm-mx-53-high`) | Bind only model and reasoning effort; roles are assigned dynamically by the delegation prompt (14 roles: programmer/tester/reviewer/…) | -| **Deterministic** | The plugin | Six-gate interception, ROUTE_META hard validation, weighted model scoring, quota/cost-aware chain computation, probe / breaker / real-dispatch isolation, live four-line banner | - -**Token economics is the first principle**: rework is the most expensive token. Hence six cognitive lanes: - -| Lane | Typical roles | Uses | -|---|---|---| -| economy | clerk / scouter scanning | cheapest lightweight model, low→medium→high effort | -| 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 | -| vision | observer image reading | vision-capable models, medium→high→xhigh→max effort | -| review | reviewer / expert panel | **forced hetero-family** (against same-family blind spots), high→xhigh→max effort | - -Effort preference is a routing layer of its own: each lane prefers the thinking levels listed above (first supported level is the default), and `off`-effort shells serve only as lane-level fallback — they enter a chain only when no thinking-level candidate is available (e.g. models that only support on/off), never ahead of one. Shells are likewise partitioned by capability face before ranking: the review lane draws only from `ro` (read-only) shells, all other lanes only from `rw` shells, with cross-face fallback only when a lane's own pool is empty. - -Water levels only affect ordering (use it, don't waste it); the only hard block is "this call cannot possibly succeed" (quota definitively exhausted or hard gate hit). Pay-as-you-go (`billing: "api"`) providers are never denied for auto routing — they sink within their capability tier via the 0.85 coefficient, and unknown-provider models sink via the 0.75 penalty, so no vendor-specific tail-seat or deny rule is needed. +```text +Please install and configure the opencode-switchman plugin for my opencode, strictly following its official instructions. -## How It Works +Official sources (authoritative, do not guess from memory): +- GitHub repo: https://github.com/mrzturn/opencode-switchman +- npm package: https://www.npmjs.com/package/opencode-switchman +Read the repo README's "Installation" section and follow it exactly. -### Lifecycle +Steps: +1. Install the latest version published on npm: run `npx -y opencode-switchman@latest` (or `bunx opencode-switchman@latest`) — it rewrites the `plugin` entry in my opencode config to the exact latest version (it also works in the project-level `opencode.json` if that is what I use). +2. Complete the functional configuration: all plugin settings live in the standalone `opencode-switchman.jsonc` in my opencode config directory, auto-generated with defaults and inline comments on first start; check it against my providers (e.g. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) and adjust as needed. +3. Verify correctness so opencode loads, starts, and runs the plugin: run `/switchman-doctor` inside opencode for a local credential-free diagnostic report and fix every error it reports; then restart opencode and confirm the plugin actually loaded — the log should contain `[opencode-switchman] injected N model shells (agents)` and my primary model's system prompt should carry the live `[ROUTES]/[WATERMARK]/[LIMITS]` banner block. -```mermaid -flowchart TD - A[opencode starts] --> B[config hook<br/>inject full shell matrix into cfg.agent<br/>+ credential collection] - B --> C[background warm-up<br/>probe matrix / pool quotas / pricing snapshot<br/>10-min self-healing refresh] - C --> D[primary model works<br/>guided by dispatcher rules] - D --> E{self-do or delegate?} - E -->|small task| Z[primary model does it directly] - E -->|delegate| F[pick lane & shell<br/>write DELEGATION_V1 + ROUTE_META] - F --> G[task dispatch<br/>intercepted at tool.execute.before] - G --> H{six-gate check} - H -->|pass| I[shell subagent executes] - H -->|deny| J[error with reason + reroute candidate<br/>dispatcher follows the chain] - I --> K{outcome} - K -->|success| L[summary returns to dispatcher] - K -->|failure| M[event hook accounting<br/>classifyFailure + isolation<br/>≥2 failures in 600s → breaker 600s] - M --> D - J --> D - D -.every LLM request.-> N[system.transform<br/>inject dispatcher rules + four-line banner<br/>live routing / quota / limits] +Do not declare success until all three steps pass; report what you changed and show the verification evidence. ``` -### The six gates (order = priority) - -On every subagent dispatch, the plugin runs deterministic checks before the task tool executes; any hit denies with a reroute candidate: - -| Gate | Check | Meaning | -|---|---|---| -| 1 Registry | shell not enabled / unprobed | unregistered surfaces cannot be dispatched | -| 2 Probe matrix | combo measured down / retired | block the clearly unavailable; consecutive 404 retires a vanished model | -| 3 Breaker / isolation | ≥2 failures within 600s or real-dispatch isolation active | "tripping, auto-recovers in ~10 min" / "isolated after real dispatch failure" | -| 4 Pool exhausted | quota says the call must fail | human-readable reason (GLM 100% / Copilot definitively out / DS overdrawn) | -| 5 Protocol | ROUTE_META missing / illegal | deny with sample & legal values | -| 6 Semantics | same-family review / rw→ro shell / image→non-vision | "review needs a hetero-family lens", etc. | - -ROUTE_META is a single-line protocol embedded in the delegation prompt, six keys, validated field by field: - -``` -ROUTE_META {"lane":"main","role":"programmer","producer_family":"glm","capability":"rw","modality":"text","source":"auto"} -``` +</details> -### Data plane (fully automatic, fail-open) +**Prerequisites**: [opencode](https://opencode.ai), CLI/TUI recommended (dialogs, sidebar, and banners are richest there; the desktop app shares the same config and state). Any provider works; Copilot / GLM / DeepSeek additionally get quota-aware routing. Credentials are read-only from opencode's own auth — the plugin never stores secrets. -- **Probe**: fires real requests against the three quota pools (other providers fail open), persists a matrix (TTL 600s). A surface change triggers a full refresh immediately; otherwise the 10-minute cycle self-heals. -- **Quotas**: direct queries — GLM monitor / DeepSeek balance / Copilot `copilot_internal/user` — no proxy, tiered TTL caches. -- **Failure classification**: vendor-neutral `classifyFailure` normalizes `rate_limit / quota / auth / not_found / server / network / unknown`. Probe 429 becomes `strained` (score down, still in chain); real 429 no longer marks Copilot exhausted, while 402 or 403 with quota wording does. Three consecutive 404s in a 1-hour window retire the model: chain excluded, gate denied, and banner marked. -- **Real-dispatch isolation**: if a combo probes OK but actual delegation fails, it is isolated in memory for 30 minutes (10 minutes for `rate_limit`), immediately visible to all sessions and cleared on restart. This runs alongside the existing 600s breaker. -- **Costs and scoring**: models.dev pricing and curated capability grades feed the weighted score; hard-gated candidates are excluded before scoring. -- **Decision log**: each banner rebuild writes candidate chains plus factor scores to `state/routing-decisions.jsonl` (ring buffer, 200 lines). -- **Banner**: `[ROUTES][WATERMARK][LIMITS][UPDATE]` four lines injected into every system prompt, keeping the dispatcher informed. `[LIMITS]` includes retired-model counts and downgrade marks; `[UPDATE]` exposes upgrade / ignore commands when a new version is detected. -- **Self-update**: startup checks are cached for 24h. Production installs compare against npm registry and can run `/switchman-update` for silent upgrade, then show "upgraded, restart required"; `/switchman-ignore` suppresses the notice for the current session only. Local mode compares against `origin/main`, shows manual update guidance, and only registers `/switchman-ignore`. -- **Fail-open iron law**: any hook error only writes to stderr and never blocks the main flow; unknown quotas never hard-block — breaker, probe, and dispatch isolation are independent sources of truth. +## Quick start -### State directory +Five steps. Full walkthrough with screenshots: **[docs/quick-start.md](./docs/quick-start.md)** / [中文](./docs/quick-start.zh.md). -`~/.config/opencode/opencode-switchman/`: `shells.json` (optional custom override; the bundled matrix is the default), `model-matrix.json` (probe), `routing.json` (breaker), `routing-decisions.jsonl` (200-line scoring audit ring), `failures.log` (accounting), `*-quota.json` / `ds-balance.json` (quota caches), `costs.json` (pricing), `delegation-template.md` (full DELEGATION_V1 template). +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. *(Optional)* **`/modelRank`** — pin your own capability ranking; it overrides system scoring everywhere. +4. *(Optional)* **`/poolConfig`** — curate per-pool candidate lists for the six task pools. +5. **Restart and verify** — check the `[ROUTES]`/`[LIMITS]` banner and the sidebar `switchman` panel; run `/switchman-doctor` if anything looks off. Then just use opencode normally. -## Maintaining the model matrix +## What you get -By default (`matrix.mode=auto`) the matrix is built at runtime: desktop visible models and TUI favorites synchronize automatically, session models fill the gap, and any surface change triggers a full probe recomputation — zero upkeep. Temporary model outages self-heal via probes (10-minute background refresh, automatic degradation/breaking), while repeated 404s retire vanished models until the surface changes again. +**Core** -The superset floor is **opencode's built-in free models** (OpenCode Zen: models under the models.dev `opencode` provider with the `-free` suffix plus the `big-pickle` exception, excluding those marked `status=deprecated` — i.e. the "available today" set), rolling with the catalog every 24h — no manual upkeep. If the catalog is unreachable (offline cold start), it fail-opens back to the bundled static list. +- **Context water-level control** — live session measurement (`[WATERMARK:SESSION]`), soft/hard/force thresholds, a per-turn read budget that auto-bounds over-eager reads, a hard cap with summary-and-terminate for every subagent, and an auto handover (full backup fork + compaction) at force level. +- **Automated decision dispatching** — a bundled dispatcher protocol turns your primary model into a dispatcher; six cognitive lanes route work to the right model at the right effort; six deterministic gates check every dispatch; failures trip breakers and isolation, and the system heals itself. -The bundled static matrix serves only `legacy` mode and the offline fallback. To customize that legacy surface: +**Extras** -```bash -# 1. Sync the authoritative enabled surface (models visible in opencode model management, one provider/model-id per line) -$EDITOR scripts/visible-models.txt -# 2. Regenerate the bundled matrix (fetches effort tiers from models.dev) -bun run gen:shells -# 3. Restart opencode (takes effect in legacy mode) -``` +- **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`, `/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. -## Development & Verification +Full options table, architecture, and internals: [docs/reference.md](./docs/reference.md) (中文: [docs/reference.zh.md](./docs/reference.zh.md)). -```bash -bun install -bun test # 174 behavioral contract fixtures (META / gates / chains / scoring / breaker / quota / update) -bunx tsc --noEmit # type check -bun run build # regenerate matrix and bundle the single-file build -``` +## Documentation -For local plugin development versus the published package, use the idempotent mode switchers and restart opencode after switching: +- Quick start (illustrated): [English](./docs/quick-start.md) · [中文](./docs/quick-start.zh.md) +- Full manual (config, commands, architecture): [English](./docs/reference.md) · [中文](./docs/reference.zh.md) +- Technical spec (contracts / algorithms / field-test notes): [docs/2026-08-28-opencode-switchman-technical-design.md](./docs/2026-08-28-opencode-switchman-technical-design.md) +- Release notes: [CHANGELOG.md](./CHANGELOG.md) -```bash -bun run mode:local # build + switch all three configs to file:// this repo (root auto-detected) -bun run mode:prod # fetch npm latest, switch to a pinned version entry + prune old caches + upgrade banner -bun run mode:prod --version 0.2.0 # pin a specific version (no network needed) -``` +## Roadmap -Both commands sync three configs (line-level surgery that preserves comments and third-party plugins; idempotent): +Near-term: quota support for more providers — more subscription plans and pay-as-you-go pools beyond Copilot / GLM / DeepSeek. If your provider isn't covered yet, [open an issue](https://github.com/mrzturn/opencode-switchman/issues): real usage decides what gets built next. Suggestions and bug reports are equally welcome. -- the `plugin` arrays in `opencode.jsonc`/`opencode.json` and `tui.jsonc`/`tui.json` (tui is created if missing, so the sidebar status panel switches sources together with the hook plugin) -- the `$schema` in the main config `opencode-switchman.jsonc` (local points at the in-repo schema, prod at GitHub main) +## Support the author -`prod` shares the rewrite/cache-prune logic with the one-shot installer (`scripts/update-cli.mjs`); for long-term production use prefer `npx -y opencode-switchman@latest`. +This plugin is open source and free to use, and it will stay that way. Keeping it alive isn't free, though: supporting and testing adapter compatibility across providers means holding multiple subscriptions and debugging them one by one — every round costs real money. -## Documentation +If the plugin has genuinely helped you and your budget allows, buy me a coffee. Thank you — sincerely. -- [Technical spec (contracts / algorithms / field-test notes)](./docs/2026-08-28-opencode-switchman-technical-design.md) -- Dispatcher rules: bundled in [`src/assets/agents-md.ts`](./src/assets/agents-md.ts) and injected via system prompt (English-only, no manual install needed; the repo's own [AGENTS.md](./AGENTS.md) is a dev-only contribution guide) -- DELEGATION_V1 template: see `delegation-template.md` in the state directory after installation +| Alipay | WeChat Pay | Scan with WeChat to give him a like | +|:---:|:---:|:---:| +| ![Alipay](docs/pay/alipay.png) | ![WeChat Pay](docs/pay/wechat_pay.jpg) | ![WeChat Pay](docs/pay/wechat_pay_2.jpg) | ## License diff --git a/README.zh.md b/README.zh.md index 8b532ef..dd77a77 100644 --- a/README.zh.md +++ b/README.zh.md @@ -2,445 +2,115 @@ [English](./README.md) | **中文** -> ### 🎯 全自动模型矩阵 + 自主决策 = 让每一个 token 都花在最该花的地方,一个都不浪费 +> 上下文有水位,任务自己派。 -> **🎬 [在线演示文稿 · 能力全览](https://mrzturn.github.io/opencode-switchman/index.zh.html)**(GitHub Pages,支持手机滑动翻页) -> -> [![opencode-switchman 能力介绍演示](docs/assets/preview.png)](https://mrzturn.github.io/opencode-switchman/index.zh.html) +![opencode-switchman —— 上下文水位驱动扳道工自动扳道](docs/assets/hero.svg) -OpenCode 六档壳矩阵编排插件——让主模型成为调度员,把任务按「认知档位」委派给跨任意 opencode 供应商的子代理空壳,插件层做确定性拦截、加权模型评分、可追溯路由决策与失败自愈隔离;glm / deepseek / copilot 三池额外享有配额感知路由。 +> 交互式演示:[opencode-switchman 宣传页](https://mrzturn.github.io/opencode-switchman/index.zh.html) -如果你同时持有多个模型订阅(GitHub Copilot premium 积分、智谱 GLM Coding Plan、DeepSeek 按量余额),却总是一个模型用到天荒地老、水位盲飞、高峰全价硬扛——opencode-switchman 就是为你准备的。 +一个 [OpenCode](https://opencode.ai) 编排插件,核心就两件事: -## 安装与使用 +**1. 上下文水位控制。** 插件每轮实测你的会话上下文:自读有预算闸,模型没法闷头把整个仓库吞进上下文;软/硬/压三档水位依次触发提醒、收尾、自动备份压缩交接;派出去的每个子代理各有一条硬顶。上下文不再滚雪球——会话跑一整天,token 也不会被自己的历史累积一口口吃掉。 -### 推荐方式:让 AI 替你安装 +**2. 自动化决策调度。** 主模型转型调度员:给任务画像,按六个认知档位(economy / mechanical / main / hard / vision / review)派给子代理空壳执行;插件做确定性拦截、加权评分、失败自愈隔离,每一条路由决策都可追溯。 -AI 时代强烈推荐由 AI 自主完成安装配置——AI 能读取你的真实环境、写入正确的值,并自行验证结果,比手动复制粘贴更不容易出错。 +在此之上: -把下面这段话直接复制给你当前使用的 AI,让它帮你装: +- **有多个模型或多个订阅?这个插件就是为你准备的。** GitHub Copilot、智谱 GLM Coding Plan、DeepSeek——或任意 opencode 供应商——会被编排成一个池子统一调度:配额感知排序、高峰避让、强制跨家族评审。 +- **只有一个模型?照样好用。** 光是上下文控制与智能派发,就够你把这一个模型用到天荒地老——会话再久,上下文也不会失控膨胀。 -```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)`(注入 N 只模型空壳),且主模型的系统提示中应带有实时 `[ROUTES]/[WATERMARK]/[LIMITS]` 横幅块。 - -三个步骤全部通过才算完成;请汇报你做的改动并给出验证证据。 -``` - -### 前置条件 - -- [opencode](https://opencode.ai)——**强烈推荐以 CLI/TUI 为主力界面**(插件的操作面——侧栏状态面板、`/poolConfig` / `/modelRank` 弹窗、实时横幅——在 TUI 里最完整):建议先用 TUI 完成全部配置,之后可自行选择是否换用桌面端体验;两端共享同一份配置与状态 -- 任意 opencode 供应商均可接入,以下三池额外享有额度控制(可任意组合,全部可选): - - **GitHub Copilot**:opencode 内 GitHub 登录(`/connect`)即可 - - **GLM**:自定义 provider(`zhipuai-coding-plan`,baseURL `https://open.bigmodel.cn/api/coding/paas/v4` + apiKey) - - **DeepSeek**:自定义 provider(`deepseek` + apiKey) -- 凭证零配置:插件从 opencode 鉴权层(auth.json / provider options / 环境变量)**只读**获取,不另存密钥、绝不自行刷新 token - -### 安装 / 更新(两条一键路径) - -两条命令均同时覆盖首次安装与后续更新(幂等,可重复执行):自动把 opencode 配置与 `tui.jsonc` 的 `plugin` 条目改写为最新精确版本 `opencode-switchman@x.y.z`(JSONC 注释原样保留)、清理旧插件缓存(`~/.cache/opencode/packages/opencode-switchman*`),升级场景在横幅标记「已升级待重启」——**重启 opencode 后生效**。 +## 安装 -**一键脚本(推荐)** +一条命令,首次安装与后续更新通吃。装完重启 opencode。 ```bash curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bash ``` -**npx / bunx** +或 ```bash -npx -y opencode-switchman@latest # 或:bunx opencode-switchman@latest +npx -y opencode-switchman@latest ``` -> npx 路径自 ≥0.2.1 发布起可用(包内自带 `update` bin 入口)。 - -> **为什么条目是精确版本,而不是裸包名 / `@latest`**:opencode ≤1.18.x 的插件缓存按 spec 名固定目录(如 `~/.cache/opencode/packages/opencode-switchman`),首次装入后不再向 npm 查询新版本——裸名与 `@latest` 会一直复用旧缓存(实测从 0.0.1 钉死不升级)。精确版本号每个版本一个独立缓存目录,所以更新器直接改写版本号。 - -插件内升级入口 `/switchman-update` 已改为调用同一更新器(旧版直接 `npm install` 的方式对 opencode 实际加载路径无效)。 - -### 方式一:npm 安装(手动) - -在 opencode 配置(`~/.config/opencode/opencode.json` 或项目 `opencode.json`)中添加: - -```json -{ - "plugin": ["opencode-switchman"] -} -``` - -opencode 启动时会自动经 Bun 安装并加载该 npm 包,无需其他步骤。后续升级请用上面的「一键更新」,或在 opencode 内执行 `/switchman-update`。 - -> **除插件安装外无需改 opencode 配置**:全部插件配置(水位、计费、高峰、阈值、横幅、矩阵、自定义档链等)都在独立文件 `opencode-switchman.jsonc` 中(见下节),首启自动生成、带中文注释。旧的元组 options(`["opencode-switchman", {...}]` 第二项)已弃用,兼容保留一代(显式值仍优先,`/switchman-doctor` 会提示 SWM044 并建议迁移)。 - -### 方式二:源码安装 +或 ```bash -git clone https://github.com/mrzturn/opencode-switchman.git -cd opencode-switchman -bun install -bun run build # 生成 dist/opencode-switchman.js -``` - -然后二选一: - -**a) 配置引用(推荐,随仓库更新)**——在 opencode 配置的 `plugin` 数组中用 `file://` 指向仓库目录: - -```json -{ - "plugin": ["file:///absolute/path/to/opencode-switchman"] -} +bunx opencode-switchman@latest ``` -插件直接加载仓库内的 `dist` 产物;`git pull` 后重跑 `bun run build` 并重启 opencode 即完成升级。此方式与 plugins 目录部署**二选一**,同时使用会双重注入。 - -**b) 部署单文件**——`bun run deploy` 构建并复制到全局插件目录 `~/.config/opencode/plugins/opencode-switchman.js`,自动加载。桌面端内嵌核心跑 Node 运行时,`deploy` 产出的单文件 bundle 即为此设计。 - -> **注意**:`plugin` 数组中的 `file://` 引用与 plugins 目录部署不可并存(同名插件会加载两份);发布 npm 后,把 `file://...` 换成 `"opencode-switchman"` 即可切换为 npm 安装。重启 opencode 生效。 - -> **从旧版(switchman.js)升级**:请删除旧的 `~/.config/opencode/plugins/switchman.js`,避免新旧两份插件同时注入;状态目录已迁移至 `~/.config/opencode/opencode-switchman/`(旧目录可删,全部状态自动重建)。 - -### 统一配置:opencode-switchman.jsonc - -**除插件安装(opencode 配置的 `plugin` 数组)外,插件全部配置都在独立文件 `opencode-switchman.jsonc`**——首次启动在 OpenCode 配置目录自动生成(优先级:`OPENCODE_CONFIG_DIR`、`$XDG_CONFIG_HOME/opencode`、`~/.config/opencode`),带 `$schema` 编辑器提示与逐键中文注释,坏值 fail-open 回退缺省;改文件后在 opencode 内重跑一次配置(或重启)即生效,`/switchman-doctor` 可出本地、脱敏且不联网的诊断报告。 - -**providers——供应商策略段**:随包内置稳定键 `deepseek`、`zhipuai-coding-plan`、`github-copilot`(与 opencode 官方 provider ID 一致),且**任意 opencode 官方/自定义 provider 键均合法**——未知键按自定义 provider 处理(通用缺省参与编排;对内置键的近似拼写 doctor 会给 warn 建议)。`observe` 控制配额查询与横幅展示,`enabled` 独立控制水位、高峰和耗尽是否参与路由(默认分别为 `true`、`false`)。`billing` 显式声明计费结构——`subscription`(评分系数 1.0)或 `api`(0.85,同 tier 内沉底);这是计费优先级的唯一来源(不从 models.dev/auth 推断)。`peak` 高峰区间使用 ISO 周日 `1`–`7` 与 `[start,end)` 的 `HH:mm`;出厂缺省 GLM 工作日 14:00–18:00、DeepSeek 工作日 09:00–12:00 与 14:00–18:00。 - -**行为段**(`quota` / `cost` / `capability` / `matrix` / `banner` / `rules` / `lanes`):详见下方「配置项」表——同样只写这一个文件。 - -### 验证安装 - -启动 opencode 后,主模型每轮系统提示中会出现实时横幅(即调度依据): - -``` -[ROUTES] economy: glm-53f-low→glm-47-off→glm-5t-off | mechanical: glm-53f-high→glm-47-off | main: glm-53f-high | hard: glm-53-high | vision: glm-53f-high | review: glm-53-high-ro -[WATERMARK] GLM 5h 10% weekly 38% (refreshed 09-11 10:00) | Copilot credits 0% left (refreshes 2026-10-01) | DeepSeek balance exhausted | advice: ... -[WATERMARK:SESSION] measured session context ~37k (soft 60k/hard 80k/force 100k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 -[LIMITS] down: none | reviewer prefers cross-family (same-family self-review = DOWNGRADED, allowed only when no cross-family reviewer exists) | api-billed & unknown models sink by coefficient (explicit billing=subscription wins) | matrix: cli·watch/ok | manual capability rank: 9 models, task-pool selection: 6 pools active (/modelRank /poolConfig to adjust) -[TODO] 0/6 done · in_progress: 撰写 README 章节 — keep todowrite current (update as each item starts/finishes) -[LANG] conversation=zh-CN comments=en docs=en (source: project settings) — 用会话语言回复与推理;代码注释、提交信息与生成文档各随其设置 -[UPDATE] new version available: /switchman-update or /switchman-ignore -``` - -同时日志可见 `[opencode-switchman] 已注入 N 只模型空壳(agent)`——N 随有凭证 provider 的模型面动态变化。六档候选由能力分×档位亲和×计费/未知组系数算法生成,并经 vision/review 结构门过滤,无任何厂商预留席位;运行期再按健康、水位与成本选出当前链首。 - -### 侧边栏状态面板(TUI 插件,可选) - -v0.2.0 在 OpenCode TUI 侧边栏底部新增实时 `switchman` 面板,v1.0.0 又做了全面的排版与配色打磨(并完成英文本地化):各家 provider 的水位以渐变条呈现、对齐到全局 8 列网格(标签、进度条与刷新时间跨块对齐,非零小额配额也保证至少一格填充),带高峰标记、observe-only 折叠标签、六个任务档位当前链首、新增模型/provider 的「需要重启」标记、走马灯行上的版本信息(当前运行版本——本地构建会附上所在提交短 SHA——更新检查发现新版本时以绿色显示 `→ v<最新版>`,本地构建显示 `→ origin/main`;已安装升级待重启时闪烁 `[RESTART NEEDED]` 标记),以及最新一条运行通知。面板每 2 秒轮询本地状态;非横幅 `stderr` 通知不会刷屏或遮挡输入框。这是一套独立的 TUI Slot 插件(`src/tui.tsx`,导出路径 `opencode-switchman/tui`),与上面的 server 端 hook 插件互相独立。 - -> **推荐工作流**:先用 TUI 完成全部配置——选好模型收藏、调好 `/poolConfig` 与 `/modelRank`、盯着侧栏看它路由;之后可自行选择是否换用桌面端(强烈推荐 TUI:两端共享同一份配置与状态,而弹窗、侧栏、横幅等操作面在 TUI 里最完整)。 - -![Switchman 侧边栏:水位、高峰、任务档位候选与状态通知](docs/assets/tui-sidebar-status.png) - -![OpenCode 模型选择器与 Switchman TUI 集成](docs/assets/tui-model-picker.png) - -TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** 的 `plugin` 数组里加入同一个包 spec(npm 安装或 `opencode plugin <spec>` 会自动完成;只有手改配置或从源码用 `mode:local`/`mode:prod` 时才需要手动确认): - -```json -{ - "plugin": ["opencode-switchman"] -} -``` - -## 快速上手 — 五步跑通矩阵 - -装好了?五步即可(完整图文版,含截图与确切生效范围:**[docs/quick-start.zh.md](./docs/quick-start.zh.md)** / English **[docs/quick-start.md](./docs/quick-start.md)**): - -1. **连接 provider** —— 在 TUI 运行 `/connect`:GitHub Copilot 走 OAuth 登录、DeepSeek 粘贴 API key;GLM Coding Plan 在 `opencode.json` 里加 `zhipuai-coding-plan` 自定义 provider(baseURL + apiKey)。任意 opencode provider 均可;这三家额外获得配额感知路由。 -2. **挑选参与编排的模型** —— TUI:`/models` 后按 `ctrl+f` 收藏;桌面 app:「管理模型」开关。收藏/可见模型构成启用面且双向同步(都不选 → 回落活跃会话模型)。 -3. **(可选)`/modelRank`** —— 固定你自己的能力排名(TUI 弹窗,或会话式 `/modelRank-chat`);手动排名在所有决策面压过基础能力分。 -4. **(可选)`/poolConfig`** —— 为六个任务池定制候选清单(TUI 弹窗,或 `/poolConfig-chat`);某池的手动清单替换系统默认候选。 -5. **重启、验证、观察** —— 重启 opencode,确认 `[ROUTES]`/`[LIMITS]` 横幅与侧栏 `switchman` 面板,有不对劲就跑 `/switchman-doctor`,之后正常使用即可。 - -## 手动覆盖层:/poolConfig 与 /modelRank(v0.2.5 新增) - -两个手动配置命令让你用配置压过系统默认决策,全部状态落盘、可手改、保存即热加载(mtime 感知,即时生效,侧栏同步刷新)。会话式(AI 交互换算 CLI)版本为同名的 `-chat` 后缀命令: - -### /poolConfig —— 任务池选配(手动弹窗;会话式用 /poolConfig-chat) - -- **TUI(/poolConfig)**:弹出选择框(与选模型/思考等级同款交互)——先选任务池(economy / mechanical / main / hard / vision / review),再对全部可用模型上下勾选:选中即参与该池、再选即移出,附能力档标注。快捷项:「全选」与「全部取消」(重建模式——只勾选想保留的几个;一个都没勾就退出则保持原选配不变,清空后第一次勾选即写入新清单)。改动实时落盘并 toast 回执。 -- **非 TUI / 会话内(/poolConfig-chat)**:会话式流程——注入各池选配总览(带池名可看 `[x]/[ ]` 完整清单),回复「main 只留 3 5」「economy 勾 1、取消 2」由 agent 调 `switchman-config.js` 落盘。 -- **语义**:选配=让各任务池的候选模型**体现差异化**(如 economy 只配轻量模型、hard 只配重思考模型)——某池的手动清单**优先于系统默认候选集**,清单内模型仍按能力等级排序推荐;**同一模型可重复参与多个池**;未配置/空清单的池走系统默认决策。「清除配置」=恢复该池系统默认。 -- **配置文件**:`~/.config/opencode/opencode-switchman/pool-config.json`(键=任务池名,值=参与该池的 modelId 数组)。 - -![/poolConfig 第一步——选择任务池,各池显示已参与模型数](docs/assets/tui-pool-config-pools.png) - -![/poolConfig 第二步——按能力档逐个勾选模型,支持全选/全部取消/清除快捷项](docs/assets/tui-pool-config-models.png) - -### /modelRank —— 模型能力排名(手动弹窗;会话式用 /modelRank-chat) - -- **TUI(/modelRank)**:弹窗按有效能力给出单一合并排序——手动条目与基础分模型交错排列;上移/下移会给模型锚定一个介于新上下邻居之间的手动分(一次挪一格,无需把上面的模型全排一遍),另有置顶/移出排名,即时生效。 -- **非 TUI / 会话内(/modelRank-chat)**:会话式流程——注入当前排名与参考排序,回复「把 glm-5.3 排到最前」「清空排名」由 agent 换算 `rank` 命令落盘。 -- **语义**:手动排名**优先于基础能力分**(实时第三方指数 → 内置快照 → 策展表全部让位)——命中模型(含其前缀变体)按排名序位取能力分与 S/A/B/C 档:排名 ≤4 项时依次 S/A/B/C;≥5 项按分位口径(top20% S / 次20% A / 次20% B / 其余 C,与 OpenRouter 序位派生同口径);同档内按序位线性分细排。未排名模型不受影响。排名参与所有决策面:六档链排序、档位亲和、能力等级闸与 deny 改派建议。 -- **配置文件**:`~/.config/opencode/opencode-switchman/capability-rank.json`(`models` 数组顺序=能力降序,#1 最强)。 - -![/modelRank——模型能力排名:手动命中优先于基础能力分](docs/assets/tui-model-rank.png) - -### /expert —— 专家咨询(会话式) - -- 用法:`/expert <你的需求或设计问题>` — 描述会原样传给专家;不带描述时代理会先询问。 -- 行为:把需求派发给当前最强的可用专家——优先 **review** 链头(跨家族专家席位,只读壳);review 池无可用候选时降级到 **hard** 链头的只读(`-ro`)壳,并声明 `DOWNGRADED`。 -- 专家结论完整转述,末尾注明所用壳与车道(如 `expert: <shell> (review)`)。 +两种方式都会把 opencode 配置里的 `plugin` 条目改写为最新精确版本,并清理旧插件缓存。手动 npm 安装、源码构建、以及「为什么必须精确版本号」的说明:[安装细节](./docs/reference.zh.md#安装)。 -两命令亦可用随包 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` 输出)。横幅 `[限制]` 行会标注当前生效的手动覆盖(「手动能力排名 N 模型 / 任务池选配 M 池」)。 +嫌麻烦?让 AI 替你装——把下面这段话复制给你正在用的 AI: -## 更新内容 +<details open> +<summary><strong>AI 代安装提示词</strong></summary> -### v1.x——确定性上下文治理与更强的手动覆盖(1.0.0 之后) - -- **壳子代理上下文硬顶**:每条壳子代理会话现在都有硬性上下文上限(`context.subagentForceTokens`,默认 100k token)——越过上限后每次工具调用都会被拒绝并附收尾指令,子代理以一份详细的进度总结作为任务结果交回主会话,且该会话永远无法再经 `task_id` 续接(持久化注册表);经 `context.subagentCap` 配置(详见 [子代理上下文硬顶](#子代理上下文硬顶))。 -- **常开逐次调用读预算(核心算法更新)**:用确定性预算闸取代旧的「每工具一次性提醒」(那种优惠券式提醒会被模型用重试/试探理性烧掉)。自第 1 轮起,每次读取都按 `context.readBudgetTokens`(默认 1500,钳制 200..20000)计费——预估超限的读取就地追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮 2× 自读上限(用户发言即重置)阻断连续读取链;无法预估的工具输出事后记账。水位只保留生命周期职责(软=建议、硬=收尾拒绝、压=自动交接)。交付/验证类 bash(git、测试/lint、构建)任何水位放行;无界翻史(不带 `-n` 的 `git log -p`)任何水位拦截并附收窄提示。 -- **项目级语言偏好**:每轮注入 `[LANG]` 铁律行(会话 / 注释与提交 / 文档三种语言),首次使用时询问并按项目落盘(未配置则每轮用户输入都会重新询问,且写入/编辑/bash/派发调用会被硬闸门拒绝并指回问卷;用户明确拒绝则本会话豁免),`/switchman-lang` 可随时修改。 -- **待办纪律**:规程 §0.7 + 每轮 `[TODO]` 状态行,主会话待办实时更新(含委派壳的结果)。 -- **/expert 专家咨询与随包 agent skills**:需求一键派给当前最强跨家族专家;开箱技能启动时同步进 opencode 全局技能目录(只增改不删、标记门控清理、fail-open)。 -- **review 档兜底**:跨家族只读壳全灭时保留最优 ro 壳、允许同族评审并标注 `DOWNGRADED`,不再出现空链。 -- **自动交接健壮性**:`[backup]` 备份自行编号(重启不乱、编号不回收)、压缩走与手动 `/compact` 相同通道、压缩腿异步化不再死锁会话。 -- **侧栏版本行**:走马灯行显示当前运行版本,更新检查发现新版本时同时显示最新版本;闪烁的 `[RESTART NEEDED]` 标记现在也覆盖「已安装升级但未生效」的场景(详见 [侧边栏状态面板](#侧边栏状态面板tui-插件可选))。 -- **tmux 窗格镜像**:opencode 服务器自身跑在 tmux 里时,每条被委派的子代理都会在主 tmux 窗口右侧列以实时 `opencode attach` 窗格打开——可见窗格封顶+FIFO 队列、原地接管、完成即重新均分布局,全程 fail-open(详见 [tmux 窗格镜像](#tmux-窗格镜像可选))。 - -### v1.0.0——英文优先的稳定版 - -- 协议资产、运行期消息、代码注释与文档全面英文化;横幅锚点更名为 `[ROUTES]` / `[WATERMARK]` / `[WATERMARK:SESSION]` / `[LIMITS]` / `[UPDATE]`。 -- TUI 侧栏排版配色打磨:8 列对齐的配额网格、渐变水位条叠于暗色轨道、400 级亮色系、observe-only 折叠标签。 - -### v0.2.0——实时能力感知编排 - -v0.2.0 将 switchman 从固定多供应商调度器升级为实时、能力感知的编排层。 - -- **TUI 运行视图**:可选侧边栏面板集中展示水位、高峰窗口、六档链首、待重启状态和最新运行通知。 -- **动态激活矩阵**:双向同步 desktop 可见模型和 CLI/TUI favorites;未配置时以活跃会话模型兜底;模型面变化即刻重算并刷新探针。 -- **能力感知路由**:运行期动态分级,强模型优先于低级模型;再以档位亲和、健康、水位、高峰、显式计费和未知模型置信度做可追溯的同级排序。 -- **供应商中立策略**:任意 OpenCode 官方或自定义 provider 都可参与;由显式 `billing: "subscription" | "api"` 取代厂商专属路由偏好。 -- **更可靠的在线运行**:新增实调失败隔离、重复缺失模型下线、路由决策审计日志和更清晰的重启/更新提示,让失败可观察、可自愈。 -- **更简单的配置与升级**:全部插件配置统一到自动生成的 `opencode-switchman.jsonc`;旧元组 options 会被诊断,并再兼容一个版本。`/handover` 可在新会话中保留当前模型、agent 与思考档位。 - -完整的用户向发布说明与升级指南见 [CHANGELOG.md](./CHANGELOG.md)。 - -### 配置项(opencode-switchman.jsonc) - -| 键 | 默认 | 说明 | -|---|---|---| -| `providers.<id>.enabled / observe / billing / peak` | `false / true / 见出厂 / 见出厂` | 供应商策略:路由参与、配额观察、计费结构(subscription=1.0 / api=0.85)、高峰窗口(详见上节) | -| `quota.glmFiveHourReservePct` | `90` | GLM 5 小时窗预留水位(%):达到即硬拦 GLM 壳避免用满 429;周额度仍只认 100% | -| `quota.deepseekLowBalanceWarnCny` | `10` | DeepSeek 余额预警阈值(元):低于该值横幅 [水位] 提示(仅预警不硬拦,按量计费) | -| `cost.enabled` | `true` | models.dev 计价快照作为加权模型评分的一个系数 | -| `capability.enabled / source / apiKey / tierThresholds / lmarenaCheck` | `true / auto / – / 内置分位 / false` | 动态能力分级:`auto`=有 apiKey 先 Artificial Analysis、失败/无 key 转 OpenRouter;key 也可走环境变量 `ARTIFICIAL_ANALYSIS_API_KEY` | -| `matrix.mode / watch` | `auto / true` | 激活矩阵:`auto` 按宿主自动(desktop=可见模型 / CLI/TUI=favorites),`app`/`tui` 强制指定,`legacy` 旧静态矩阵;`watch`=配置面变化即重算并全量刷新探针(mode/watch 为启动级,重启生效) | -| `banner.enabled` | `true` | 四行横幅注入开关 | -| `rules.enabled / delegationFloor` | `true / 3000` | 调度员规程(AGENTS.md)随包注入开关;`delegationFloor`=自做底价(token),注入规程时插值 | -| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens` | `true / 60000 / 80000 / 120000 / 1500` | **会话上下文水位实测+自读预算闸**:插件从消息 token usage 实测主会话上下文并每轮注入 `[水位·会话]` 行(附每轮增速与距硬水位剩余轮数估算)。自读从第 1 轮起按 `readBudgetTokens` 计费:预估超限的读取自动追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮另有 2× 上限阻断连续读取,无法预估的工具输出事后记账。验证/交付类 bash(git、测试/lint、构建)全水位放行;无界历史翻查(如不带 `-n` 的 `git log -p`)任何水位一律拦截并附收窄提示;超硬水位读取类关闭(收尾模式);超压水位横幅强制立即压缩。壳子代理会话不适用本水位,改走自身的单道硬顶(见 `context.subagentForceTokens` / `context.subagentCap`);三档水位在可知时额外以当前会话模型上下文窗口(models.dev)的 90% 封顶 | -| `context.subagentForceTokens / subagentCap` | `100000 / true` | **子代理上下文硬顶**:壳子代理会话只有一道硬顶(实测=最新 assistant 消息的 input + output + reasoning + cache.read,与会话水位同口径),钳制 20k..1M 并额外以壳模型上下文窗口的 90% 封顶。触顶即拒绝该会话所有后续工具调用并下达收尾指令,子代理的下一份纯文本答复(详细的工作进度总结)直接作为任务结果返回委派方,会话永久终止;此后带 `task_id` 恢复该会话的 `task` 调用一律永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响;`subagentCap: false` 只阻止新的终止——已终止的会话不复活 | -| `dispatch.autoRedirect` | `true` | 派发被拒时在途改写 `subagent_type` 到拒绝消息已点名的链首候选(单跳、同快照守卫复检)——首次派发直接落在最优可用壳上,不再烧「拒绝-重试」轮次;`false` 恢复拒绝-重试 | -| `relay.image` | `true` | 无视觉主模型:用户附带图片自动落盘并替换为路径文本+阅读指引(委托 vision 壳或交给 MCP 视觉工具);本地路径 / http URL 原样透传;全程 fail-open | -| `lang.enabled / ask / candidates` | `true / true / 出厂清单` | 项目级语言偏好:每轮 `[LANG]` 铁律行(会话 / 注释与提交 / 文档),首次询问未完成配置则每轮用户输入重新询问,未配置期间写入/编辑/bash/派发被硬闸门拒绝(拒绝问卷则本会话豁免),落盘 `.switchman/settings.json`(AGENTS.md 标记为只读回退),`/switchman-lang` 重新询问 | -| `builtinAgents.mode` | `deny` | 内置 explore/general 与壳路由抢任务且此前放行;`deny`=拦截附 economy/main 改派建议,`allow`=恢复放行 | -| `injection.mode` | `chain` | 壳注入面:`chain`=六档链精选∪favorites/可见集(task 工具描述每会话省约 6-10k token,链外模型点名走 denyUninjected 提示);`all`=可用全集(旧行为)。启动级,重启生效 | -| `lanes` | 内置六档链 | 自定义各档壳链(覆盖内置偏好序);键=economy/mechanical/main/hard/vision/review | -| `workspace.enabled / dirname` | `true / ".switchman"` | 工件工作区:每个主会话自动创建 `<project-root>/.switchman/<yyyy-mm-dd>/<sessionId>-<title>/` 目录,路径每轮注入调度员规程;目录内含 `SESSION.md` / `dispatches.jsonl` / `media/`。关闭后不再创建目录,规程段落同步失效 | -| `tmux.enabled / rightPct / maxPanes / mini` | `true / 60 / 3 / false` | tmux 窗格镜像(仅当 opencode 服务器自身运行在 tmux 中时生效):每条被委派的子代理在主 tmux 窗口右侧列实时打开一个 `opencode attach` 窗格;`rightPct`=右列宽度百分比(10..90,主窗格占其余),`maxPanes`=可见子代理窗格上限(1..4;超出的派发在 FIFO 队列等待),`mini`=用极简 attach 界面取代完整 TUI | - -> **旧元组 options 迁移**:`quota.*.enabled`→`providers.<id>.observe`(SWM042)、`billingWindow.*`→`providers.<id>.peak`(SWM043)、其余行为段(`quota` 阈值/`cost`/`capability`/`matrix`/`banner`/`rules`/`lanes`)→同名 jsonc 段(SWM044);`providers.glm/deepseek`(凭证收集清单)从未实际生效,已删除。元组显式配置兼容一代(值仍优先),下个大版本移除。 - -## 动态激活矩阵 - -壳矩阵不再是静态清单,而是运行期动态构建、实时更新: - -- **desktop app** 可见模型与 **CLI/TUI** favorites 双向同步。`mtime` 决定更新方向;同毫秒平局不写任一侧,必要时使用默认 CLI 路径兜底。 -- 两者皆未设置时,自动回退为「当前活跃会话正在使用的模型」;多会话并行取并集,任何会话切换模型,矩阵在下一请求实时跟进。 -- 模型管理 / favorites 变更实时监听(fs.watch + mtime 轮询兜底)。任一配置面变化都会立即重算激活矩阵并触发**全量探针刷新**,不等待 TTL;10 分钟周期刷新继续负责自愈。 -- 新增 provider 实时检测并横幅提示(agent 注册表运行期不可变,对应壳**重启 opencode 后自动纳入**,无需手动维护)。 -- 启动即注入超集壳(有凭证 provider 的全部可对话模型 × models.dev 档位),`matrix.mode=legacy` 可完整回退旧静态矩阵行为。 - -## 模型评分引擎 - -路由现在是显式、可追溯的评分,而不是隐藏偏好序: - -- **base 能力分主导**:策展的 S/A/B/C 能力分按 exact 模型 id → 前缀 → family → global fallback 四路匹配,并记录命中路径。tier 分组不可逆:低档永远压不过高档。 -- **加权系数**:最终分数乘以 `effortFit × health × water × costBias × peak × billingBoost × unknownPenalty`。health 为 `ok=1.0` / `strained=0.6`;water 取两个窗口中更吃紧者,并会在 Copilot 富余且临期时反向提权烧积分;peak 对任意 provider 的高峰窗口做同档 `×0.93` 让位,绝不跨能力级出局。`billingBoost` 只由 `opencode-switchman.jsonc` 显式 `billing` 字段驱动(`subscription=1.0`、`api=0.85`)——编排规则零厂商硬编码;`unknownPenalty=0.75` 施加给精确→前缀→family 全链未命中的未知组模型,同 tier 排已知模型之后。 -- **硬门不参与打分**:down、熔断、池耗尽、retired、实调隔离中的组合先出局再评分。`immediate` 紧急档改按探针延迟排序。 -- **决策日志**:每次横幅重建都会把各档候选与六因子评分写入 `state/routing-decisions.jsonl`,保留 200 行环形日志。 - -## 工件工作区(.switchman) - -每个主会话(main)创建时,插件都会自动建立项目内目录 `<project-root>/.switchman/<yyyy-mm-dd>/<sessionId>-<title>/`(日期取会话创建当天;标题 slug 段会在会话标题生成或修改时自动重命名)。注入的调度员规程每轮插值该目录路径,方案、实现进度、过程管控笔记、设计文档等中间工件默认落到会话目录,不再散落仓库各处或堆进对话。插件同时在目录内维护以下文件: - -- `SESSION.md` — 会话元数据(id / 标题 / 项目 / 时间戳) -- `dispatches.jsonl` — 每条被放行的任务委派一行 JSON(ts / shell / lane / role / source / redirected) -- `media/` — 视觉委派中转的图片(已从旧全局状态目录迁来,fail-open 兜底) - -由 `opencode-switchman.jsonc` 的 `workspace.enabled` / `workspace.dirname` 配置(默认 `true` / `".switchman"`);关闭后不再创建任何目录,规程中的对应段落同步失效。 - -## tmux 窗格镜像(可选) - -opencode 服务器自身运行在 tmux 中时,每条被委派的子代理会话都会以 `opencode attach <server> -s <session>` 实时窗格打开,在主 tmux 窗口右侧纵向堆叠(主窗格保持左侧份额——默认 40%,子代理列占右侧 60%)。窗口只会在主窗格(服务器启动时所在窗格,即启动时的 `TMUX_PANE`)上切分:你自己的侧边窗格与 tmux 状态栏绝不会被触碰;从其他窗格接入的 TUI 客户端同样能在那里看到这些子代理窗格。 - -![tmux 分屏镜像:主会话居左,子代理实时 pane 竖排居右](docs/assets/tmux-pane-mirroring.png) - -> 开箱即用,无需任何配置。唯一前提:在 tmux 会话中运行 opencode;tmux 之外该功能完全惰性、零副作用。 - -- **可见上限+FIFO**:子代理窗格最多同时可见 3 个(`tmux.maxPanes`,1..4);超出的并发派发在 FIFO 队列中等待,某个可见子代理结束后,排队者原地接管其窗格(原地重生,窗格数不变)。每次完成都会收缩右列并重新均分布局:3→2 均分 → 1 独占右列 → 0 = 只剩主窗格(全宽恢复)。 -- **卫生**:窗格通过 pane 标题标记为 `swm:<agent-name>`;上次崩溃残留的窗格会在插件启动时清扫(kill,按标题前缀或 attach 启动命令匹配)。每次布局操作后都会恢复窗口的活动窗格(焦点保持)。 -- **天生安全**:不在 tmux 中或 `tmux.enabled=false` 时完全惰性;所有 tmux 失败一律 fail-open——只写状态日志,绝不阻塞派发。 -- **观看须知**:该窗格是附加到子代理会话的真实交互式 TUI——不要在里面打字(按键会进入子代理会话)。退出观看窗格只是移除显示,子代理继续运行。 - -由 `opencode-switchman.jsonc` 的可选 `tmux` 段配置(`enabled` / `rightPct` / `maxPanes` / `mini`,默认 `true` / `60` / `3` / `false`)。 - -## 子代理上下文硬顶 - -主会话享有软/硬/压三档水位+自动交接;被委派的壳子代理会话此前完全没有上下文控制,一路跑过 18 万 token 也无人拦截。现在每个壳子代理会话只有一道硬顶(`context.subagentForceTokens`,默认 100,000 token,钳制 20k..1M,并在可知时额外以壳模型上下文窗口的 90% 封顶),实测口径与会话水位相同:最新 assistant 消息的 input + output + reasoning + cache.read。触顶后,插件拒绝该子代理会话内的所有后续工具调用并下达收尾指令;子代理随后给出的纯文本答复——一份详细的工作进度总结(已完成 / 关键发现含 file:line 证据 / 未完成 / 下一步)——即作为任务结果返回给委派方,会话随即永久终止(终止事件写入状态日志)。合规两侧预先约定:子代理系统提示的壳规则第 6 条(首次触顶拒绝即停止、交回总结),随包调度员规程第 2 节约定编排侧契约(绝不重试已终止的会话;重新派发、只注入所需上下文)。 - -终止是永久且有意的:此后任何通过 `task_id` 恢复该会话的 `task` 调用都会被永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响。理由:子代理是可复现的工人(其规格写在委派 prompt 里),「终止并交回」优于「压缩后续跑」。`context.subagentCap: false` 只阻止新的终止——已终止的会话不复活。 - -由 `opencode-switchman.jsonc` 的 `context.subagentForceTokens`(默认 `100000`)/ `context.subagentCap`(默认 `true`)配置(详见配置项表)。 - -## 核心思想 - -### 问题 - -多订阅并存的真实痛点: - -1. **认知错配**:让旗舰模型干扫描清点的杂活,token 花在不该花的地方;让轻量模型做架构设计,返工反而最贵 -2. **水位盲飞**:GLM 5 小时窗耗尽了还在硬撞、Copilot premium 积分月底作废没花完、DeepSeek 余额见底才发现 -3. **单点视角**:复审用同一个模型族自查,盲区相同,审不出问题 -4. **协议松弛**:「让 XX 帮我看看」式委派无结构、无校验,子代理拿到的是含糊任务 - -### 解法:调度员 + 壳矩阵 + 确定性拦截 - -opencode-switchman 把编排拆成三层,各司其职: - -| 层 | 载体 | 职责 | -|---|---|---| -| **认知层** | 主模型(调度员)+ 随包注入的调度员规程 | 任务四维画像(认知强度×机械度×上下文×紧急度)、决定自做还是委派、选档选壳、写 DELEGATION_V1 委派 prompt | -| **执行层** | 「模型×档位」空壳子代理(如 `glm-mx-53-high`) | 只绑定模型与思考档位,角色由委派 prompt 动态赋予(programmer/tester/reviewer 等 14 角色) | -| **确定性层** | 插件本体 | 六闸拦截、ROUTE_META 硬校验、加权模型评分、配额/成本感知选链、探针 / 熔断 / 实调隔离自愈、四行横幅实时注入 | - -**Token 经济学为第一性原则**:返工是最贵的 token。由此派生六档认知分层—— - -| 档位 | 典型角色 | 用什么 | -|---|---|---| -| economy | clerk / scouter 扫描清点 | 最便宜的轻量模型,low→medium→high 档 | -| mechanical | tester / ops 回归与脚本 | 轻量模型,medium→high→xhigh→max 档 | -| main | programmer / uiux / data-analyst | 主力模型,medium→high→xhigh→max 档 | -| hard | planner 架构核心 | 最强模型,high→xhigh→max 档 | -| vision | observer 看图 | 视觉模型,medium→high→xhigh→max 档 | -| review | reviewer / 专家席 审案 | **强制异模型族**(防同族盲区),high→xhigh→max 档 | - -思考档位偏好是独立的一层路由算法:每档按上表偏好序选思考档(首个被支持的档位即默认档);`off` 档只作 lane 级兜底——仅当该档没有思考档候选可用时(如只支持开/关的模型)才进链,绝不排到思考档候选之前。壳在排序前还按能力面划池:review 只从 `ro`(只读)壳池选,其余 lane 只从 `rw` 壳池选,仅当本池为空才跨池兜底。 - -水位只影响排序(用满不浪费),唯一硬拦是「调用必失败」(额度确定耗尽或硬门命中);按量计费(`billing: "api"`)provider 在自动路由中不会被 deny——它们经 0.85 系数在同能力档内沉底,未知 provider 模型经 0.75 惩罚沉底,无需任何厂商专属的链尾席位或 deny 规则。 +```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]` 横幅块。 -```mermaid -flowchart TD - A[opencode 启动] --> B[config 钩子<br/>注入全量壳矩阵到 cfg.agent<br/>+ 凭证收集] - B --> C[后台预热<br/>探针矩阵 / 三池配额 / 计价快照<br/>10min 周期自愈刷新] - C --> D[主模型工作<br/>按调度员规程决策] - D --> E{自做 or 委派?} - E -->|小任务| Z[主模型直接完成] - E -->|委派| F[选档选壳<br/>写 DELEGATION_V1 + ROUTE_META] - F --> G[task 派发<br/>tool.execute.before 拦截] - G --> H{六闸判定} - H -->|放行| I[壳子代理执行] - H -->|deny| J[报错附原因+改派候选<br/>主模型按链改派] - I --> K{执行结果} - K -->|成功| L[摘要回传主模型] - K -->|失败| M[event 钩子记账<br/>classifyFailure + 隔离<br/>600s 窗 ≥2 败 → 熔断 600s] - M --> D - J --> D - D -.每轮 LLM 请求.-> N[system.transform<br/>注入调度员规程 + 四行横幅<br/>路由/水位/限制 实时可见] +三个步骤全部通过才算完成;请汇报你做的改动并给出验证证据。 ``` -### 六闸拦截(顺序即优先级) - -主模型派发子代理时,插件在 task 工具执行前做确定性校验,任一命中即 deny 并附改派候选: - -| 闸 | 判定 | 语义 | -|---|---|---| -| 1 注册表 | 壳未启用/未探测 | 禁派未注册面 | -| 2 探针矩阵 | 组合实测 down / retired | 拦明确不可用;连续 404 下线消失模型 | -| 3 熔断 / 隔离 | 600s 窗内 ≥2 败或实调隔离中 | 「连续失败熔断中,约 10 分钟自动恢复」/「实调失败后隔离中」 | -| 4 池耗尽 | 配额判定必失败 | 附人读原因(GLM 100% / Copilot 确定耗尽 / DS 欠费) | -| 5 协议 | ROUTE_META 缺失/非法 | deny 附样例与合法值表 | -| 6 语义 | 同族复审 / rw→ro 壳 / 图像→非视觉壳 | 「复审须异族视角」等 | - -ROUTE_META 是嵌在委派 prompt 内的单行协议,六键六值,插件逐字段校验: - -``` -ROUTE_META {"lane":"main","role":"programmer","producer_family":"glm","capability":"rw","modality":"text","source":"auto"} -``` +</details> -### 数据面(全部自动、fail-open) +**前置条件**:[opencode](https://opencode.ai),推荐 CLI/TUI(弹窗、侧栏、横幅在 TUI 里最完整;桌面端共享同一份配置与状态)。任意供应商可用;Copilot / GLM / DeepSeek 额外享有配额感知路由。凭证从 opencode 自身鉴权层只读获取,插件不存密钥。 -- **探针**:对三大额度池发起真实请求探活(其余供应商 fail-open 放行),矩阵落盘(TTL 600s)。配置面变化立即全量刷新;平时由 10 分钟周期自愈。 -- **配额**:GLM monitor / DeepSeek balance / Copilot `copilot_internal/user` 直查,无代理、分层 TTL 缓存。 -- **失败分类**:厂商无关的 `classifyFailure` 归一为 `rate_limit / quota / auth / not_found / server / network / unknown`。探针 429 仅置 `strained`(降权留链);实调 429 不再误置 Copilot 池耗尽,只有 402 或 403 且含 quota 文案才置耗尽。1 小时窗内连续 3 次 404 会自动 retired:链路排除、闸 deny、横幅标注。 -- **实调失败隔离**:探针 ok 但实际委派失败时,combo 进入内存隔离 30 分钟(`rate_limit` 类 10 分钟),所有会话即时感知,重启即清;它与既有 600s 熔断双轨并行。 -- **成本与评分**:models.dev 计价与策展能力分共同进入加权评分;硬门命中的候选先出局再评分。 -- **决策日志**:每次横幅重建把候选链与因子分写入 `state/routing-decisions.jsonl`(环形 200 行)。 -- **横幅**:每轮系统提示注入 `[路由][水位][限制][更新]` 四行,调度员实时可见。[限制] 行包含下线模型数量与降级标注;[更新] 行在发现新版本时给出升级 / 忽略命令入口。 -- **自更新**:启动检查缓存 24 小时。prod 模式对比 npm registry,可执行 `/switchman-update` 静默升级,随后横幅显示「已升级待重启」并提醒重启;`/switchman-ignore` 仅忽略本会话,重启后恢复提示。local 模式对比 `origin/main`,只提示手动更新并仅注册 `/switchman-ignore`。 -- **fail-open 铁律**:任何钩子异常只写 stderr 绝不阻塞主流程;配额未知不硬拦,熔断、探针与实调隔离互为独立事实源。 +## 快速上手 -### 状态目录 +五步跑通。完整图文版:**[docs/quick-start.zh.md](./docs/quick-start.zh.md)** / [English](./docs/quick-start.md)。 -`~/.config/opencode/opencode-switchman/`:`shells.json`(可选自定义覆盖,缺省用插件内置矩阵)、`model-matrix.json`(探针)、`routing.json`(熔断)、`routing-decisions.jsonl`(200 行评分审计环形日志)、`failures.log`(记账)、`*-quota.json` / `ds-balance.json`(配额缓存)、`costs.json`(计价)、`delegation-template.md`(委派模板全文)。 +1. **连接 provider** —— TUI 里运行 `/connect`:Copilot 走 OAuth、DeepSeek 粘 API key;GLM Coding Plan 在 `opencode.json` 里加 `zhipuai-coding-plan` 自定义 provider。 +2. **挑选参与编排的模型** —— `/models` 后按 `ctrl+f` 收藏(桌面端:「管理模型」开关)。 +3. *(可选)***`/modelRank`** —— 固定你自己的能力排名,所有决策面压过系统评分。 +4. *(可选)***`/poolConfig`** —— 为六个任务池定制候选清单。 +5. **重启、验证** —— 确认 `[ROUTES]`/`[LIMITS]` 横幅与侧栏 `switchman` 面板,有不对劲就跑 `/switchman-doctor`。之后正常使用即可。 -## 模型矩阵维护 +## 核心功能 -默认(`matrix.mode=auto`)矩阵在运行期动态构建:desktop 可见模型与 TUI favorites 自动双向同步,会话模型兜底,任一配置面变化都会触发全量探针重算,无需任何维护;模型临时 down 由探针自愈(每 10 分钟后台刷新,自动进降级/熔断),连续 404 的消失模型会 retired,直到配置面再次变化。 +**核心** -超集保底=**opencode 自带免费模型**(OpenCode Zen:models.dev `opencode` provider 下 `-free` 后缀模型+`big-pickle` 特例,且剔除 `status=deprecated` 的已轮换旧模型=「今日可用」集,随目录每 24h 滚动、无需手工维护);目录不可用(无网冷启动)时 fail-open 回退内置静态清单。 +- **上下文水位控制** —— 会话上下文每轮实测(`[WATERMARK:SESSION]`),软/硬/压三档水位;逐轮自读预算闸自动约束越界读取;每个子代理一条硬顶(触顶交回总结、会话终止);压水位自动交接(完整分叉备份+压缩),任务不中断。 +- **自动化决策调度** —— 随包调度员规程让主模型学会派活;六个认知档位把任务交给合适的模型和思考档;六道确定性闸门逐条校验每次派发;失败自动熔断隔离、自愈恢复。 -内置静态矩阵仅作为 `legacy` 模式与离线兜底。如需自定义 legacy 静态面: +**辅助** -```bash -# 1. 同步权威启用面(opencode 模型管理中打开的模型,每行 provider/model-id) -$EDITOR scripts/visible-models.txt -# 2. 重生成内置矩阵(拉取 models.dev 档位声明) -bun run gen:shells -# 3. 重启 opencode(legacy 模式生效) -``` +- **多订阅编排** —— Copilot / GLM / DeepSeek 跨池配额感知路由(任意供应商均可参与)、高峰避让、计费加权、跨家族评审强制。 +- **手动覆盖** —— `/poolConfig`、`/modelRank`、`/expert`、`/handover`、`/switchman-doctor`、`/switchman-update`。 +- **看得见** —— 每轮系统提示注入实时四行横幅、TUI 侧栏状态面板、tmux 窗格镜像、按会话归档的工件工作区、路由决策审计日志。 -## 开发与验证 +完整配置项表、架构与内部机制:[docs/reference.zh.md](./docs/reference.zh.md)(English: [docs/reference.md](./docs/reference.md))。 -```bash -bun install -bun test # 174 项行为契约 fixture(META/六闸/选链/评分/熔断/配额/更新) -bunx tsc --noEmit # 类型检查 -bun run build # 重新生成矩阵并打包单文件 bundle -``` +## 文档 -本地调试与正式包可用幂等脚本一键切换,切换后重启 opencode 生效: +- 快速上手(图文):[中文](./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) -```bash -bun run mode:local # build + 三处配置切到 file:// 本仓库(仓库根自动推导) -bun run mode:prod # 拉 npm 最新版,切到精确版本条目 + 清旧插件缓存 + 升级横幅 -bun run mode:prod --version 0.2.0 # 指定版本回切(免联网) -``` +## 计划与展望 -两条命令都会同步三处配置(行级手术保留注释与第三方插件,幂等可重复执行): +近期计划接入更多供应商的配额支持——在 Copilot / GLM / DeepSeek 之外,覆盖更多订阅制与按量付费池。你的供应商还没被覆盖?欢迎[提 issue](https://github.com/mrzturn/opencode-switchman/issues),我会根据实际情况安排优化。功能建议与 bug 反馈同样欢迎。 -- `opencode.jsonc`/`opencode.json` 与 `tui.jsonc`/`tui.json` 的 `plugin` 数组(tui 缺失自动补建,侧边栏状态面板跟随 hook 插件一起切源) -- 主配置 `opencode-switchman.jsonc` 的 `$schema`(local 指向仓库内 schema,prod 指向 GitHub main) +## 为爱发电 -`prod` 与一键安装器共用同一套改写/缓存清理逻辑(`scripts/update-cli.mjs`);从源码切换后若要长期使用正式版,仍推荐 `npx -y opencode-switchman@latest`。 +本项目开源、免费,也会一直免费下去。但维护它并不免费:要支持和测试各家供应商对本插件的兼容适配,需要开通很多订阅、一个一个实地调试,每一轮都是真金白银的消耗。 -## 文档 +如果这个插件真的帮到了你,手头也宽裕,可以请作者喝杯咖啡。在此万分感谢。 -- [技术方案(契约/算法/实测记录)](./docs/2026-08-28-opencode-switchman-技术方案.md) -- 调度员规程:内置于 [`src/assets/agents-md.ts`](./src/assets/agents-md.ts),随包经系统提示自动注入(仅英文,无需手动安装;仓库根目录的 [AGENTS.md](./AGENTS.md) 仅为插件开发指南) -- 委派模板 DELEGATION_V1:安装后见状态目录 `delegation-template.md` +| 支付宝 | 微信支付 | 微信扫码为他点赞 | +|:---:|:---:|:---:| +| ![支付宝](docs/pay/alipay.png) | ![微信支付](docs/pay/wechat_pay.jpg) | ![微信支付](docs/pay/wechat_pay_2.jpg) | ## License diff --git a/docs/assets/hero.svg b/docs/assets/hero.svg new file mode 100644 index 0000000..12ca5d3 --- /dev/null +++ b/docs/assets/hero.svg @@ -0,0 +1,251 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 640" width="1600" height="640" font-family="ui-sans-serif, -apple-system, 'Segoe UI', sans-serif"> + <defs> + <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1"> + <stop offset="0" stop-color="#0b1220"/> + <stop offset="1" stop-color="#0e1a2e"/> + </linearGradient> + <linearGradient id="water" x1="0" y1="0" x2="0" y2="1"> + <stop offset="0" stop-color="#7dd3fc"/> + <stop offset="0.5" stop-color="#38bdf8"/> + <stop offset="1" stop-color="#0369a1"/> + </linearGradient> + <linearGradient id="steel" x1="0" y1="0" x2="0" y2="1"> + <stop offset="0" stop-color="#cbd5e1"/> + <stop offset="1" stop-color="#64748b"/> + </linearGradient> + <radialGradient id="glow" cx="0.5" cy="0.5" r="0.5"> + <stop offset="0" stop-color="#0ea5e9" stop-opacity="0.5"/> + <stop offset="1" stop-color="#0ea5e9" stop-opacity="0"/> + </radialGradient> + <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse"> + <path d="M40 0H0V40" fill="none" stroke="#1e293b" stroke-width="1" opacity="0.35"/> + </pattern> + <clipPath id="tankClip"> + <rect x="152" y="252" width="336" height="236" rx="24"/> + </clipPath> + <clipPath id="pipeClip"> + <rect x="492" y="461" width="306" height="18" rx="9"/> + </clipPath> + </defs> + + <!-- backdrop --> + <rect width="1600" height="640" fill="url(#bg)"/> + <rect width="1600" height="640" fill="url(#grid)"/> + <ellipse cx="850" cy="460" rx="700" ry="260" fill="url(#glow)" opacity="0.22"/> + + <!-- horizon ground --> + <ellipse cx="1150" cy="668" rx="660" ry="96" fill="#0d1929" opacity="0.9"/> + <!-- stars in the upper sky --> + <g fill="#e2e8f0"> + <circle cx="720" cy="84" r="2" opacity="0.3"/> + <circle cx="905" cy="132" r="1.6" opacity="0.22"/> + <circle cx="1120" cy="70" r="2.2" opacity="0.32"/> + <circle cx="1300" cy="118" r="1.5" opacity="0.2"/> + <circle cx="1470" cy="82" r="2" opacity="0.3"/> + <circle cx="1548" cy="176" r="1.6" opacity="0.22"/> + <circle cx="1210" cy="176" r="1.4" opacity="0.18"/> + <circle cx="880" cy="226" r="1.5" opacity="0.16"/> + <circle cx="1020" cy="182" r="1.3" opacity="0.15"/> + <circle cx="1400" cy="230" r="1.6" opacity="0.2"/> + </g> + + <!-- wordmark --> + <text x="84" y="132" font-size="46" font-weight="700"> + <tspan fill="#cbd5e1">opencode-</tspan><tspan fill="#7dd3fc">switchman</tspan> + </text> + <text x="84" y="176" font-size="21" fill="#8aa0b8">Context on a meter. Tasks dispatch themselves.</text> + + <!-- soft / hard watermark guides (left of tank) --> + <rect x="56" y="337" width="94" height="26" rx="13" fill="#fbbf2415" stroke="#fbbf24" stroke-width="1.5"/> + <text x="103" y="354" font-size="12" fill="#fbbf24" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">SOFT 60%</text> + <line x1="150" y1="350" x2="488" y2="350" stroke="#fbbf24" stroke-width="2" stroke-dasharray="8 6" opacity="0.9"/> + <rect x="56" y="292" width="94" height="26" rx="13" fill="#f8717115" stroke="#f87171" stroke-width="1.5"/> + <text x="103" y="309" font-size="12" fill="#f87171" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">HARD 80%</text> + <line x1="150" y1="305" x2="488" y2="305" stroke="#f87171" stroke-width="2" stroke-dasharray="8 6" opacity="0.9"/> + + <!-- context tank --> + <rect x="150" y="250" width="340" height="240" rx="26" fill="#94c5fd0d" stroke="#7dd3fc" stroke-opacity="0.35" stroke-width="2"/> + <g clip-path="url(#tankClip)"> + <rect x="150" y="345" width="340" height="145" fill="url(#water)"/> + <circle cx="220" cy="420" r="4" fill="#bae6fd" opacity="0.35"/> + <circle cx="300" cy="440" r="3" fill="#bae6fd" opacity="0.3"/> + <circle cx="380" cy="410" r="5" fill="#bae6fd" opacity="0.35"/> + <circle cx="260" cy="382" r="3" fill="#bae6fd" opacity="0.3"/> + <rect x="150" y="452" width="340" height="38" fill="#075985" opacity="0.35"/> + </g> + <ellipse cx="320" cy="345" rx="168" ry="12" fill="#7dd3fc" opacity="0.55"/> + <path d="M162 344 Q320 332 478 344" fill="none" stroke="#e0f2fe" stroke-width="3" opacity="0.45"/> + <ellipse cx="320" cy="250" rx="170" ry="26" fill="#0f2740" stroke="#7dd3fc" stroke-opacity="0.4" stroke-width="2"/> + <ellipse cx="320" cy="250" rx="148" ry="17" fill="#16233c" stroke="#38bdf8" stroke-opacity="0.25"/> + <!-- level scale on tank wall --> + <g stroke="#64748b" stroke-width="2" opacity="0.6"> + <line x1="470" y1="463" x2="484" y2="463"/> + <line x1="470" y1="440" x2="484" y2="440"/> + <line x1="470" y1="417" x2="484" y2="417"/> + <line x1="470" y1="395" x2="484" y2="395"/> + <line x1="464" y1="372" x2="484" y2="372"/> + <line x1="470" y1="327" x2="484" y2="327"/> + <line x1="470" y1="305" x2="484" y2="305"/> + <line x1="470" y1="282" x2="484" y2="282"/> + <line x1="470" y1="260" x2="484" y2="260"/> + </g> + + <!-- sight glass (water gauge) --> + <rect x="490" y="290" width="34" height="8" fill="url(#steel)"/> + <rect x="490" y="430" width="34" height="8" fill="url(#steel)"/> + <rect x="520" y="280" width="36" height="206" rx="10" fill="#7dd3fc0f" stroke="#7dd3fc" stroke-opacity="0.3" stroke-width="2"/> + <rect x="524" y="345" width="28" height="137" rx="6" fill="url(#water)" opacity="0.9"/> + <circle cx="538" cy="345" r="9" fill="#e0f2fe" stroke="#7dd3fc" stroke-width="2"/> + <rect x="524" y="272" width="28" height="10" rx="3" fill="#64748b"/> + <rect x="524" y="484" width="28" height="10" rx="3" fill="#64748b"/> + <!-- float linkage to valve --> + <line x1="538" y1="337" x2="556" y2="290" stroke="#94a3b8" stroke-width="3"/> + <line x1="556" y1="290" x2="644" y2="410" stroke="#94a3b8" stroke-width="3"/> + <circle cx="556" cy="290" r="5" fill="#94a3b8"/> + + <!-- outflow pipe with water inside --> + <rect x="490" y="458" width="310" height="24" rx="12" fill="url(#steel)" stroke="#475569" stroke-width="1.5"/> + <g clip-path="url(#pipeClip)"> + <rect x="490" y="463" width="310" height="14" fill="url(#water)" opacity="0.9"/> + </g> + <rect x="560" y="452" width="10" height="36" rx="3" fill="#64748b"/> + <rect x="700" y="452" width="10" height="36" rx="3" fill="#64748b"/> + <!-- valve wheel driven by the float --> + <rect x="648" y="428" width="8" height="30" fill="#64748b"/> + <circle cx="652" cy="414" r="26" fill="none" stroke="#ef4444" stroke-width="6"/> + <line x1="652" y1="388" x2="652" y2="440" stroke="#ef4444" stroke-width="4"/> + <line x1="626" y1="414" x2="678" y2="414" stroke="#ef4444" stroke-width="4"/> + <circle cx="652" cy="414" r="6" fill="#ef4444"/> + <!-- level gauge on the line --> + <rect x="764" y="440" width="8" height="18" fill="url(#steel)"/> + <circle cx="768" cy="410" r="30" fill="#0f172a" stroke="#7dd3fc" stroke-width="2.5"/> + <line x1="748" y1="398" x2="754" y2="402" stroke="#64748b" stroke-width="2"/> + <line x1="768" y1="384" x2="768" y2="391" stroke="#64748b" stroke-width="2"/> + <line x1="788" y1="398" x2="782" y2="402" stroke="#64748b" stroke-width="2"/> + <line x1="768" y1="410" x2="784" y2="392" stroke="#fbbf24" stroke-width="4" stroke-linecap="round"/> + <circle cx="768" cy="410" r="4" fill="#fbbf24"/> + + <!-- downpipe into the hydraulic actuator --> + <rect x="794" y="470" width="24" height="74" fill="url(#steel)" stroke="#475569" stroke-width="1.5"/> + <rect x="798" y="474" width="16" height="66" fill="url(#water)" opacity="0.9"/> + <rect x="782" y="546" width="96" height="28" rx="12" fill="#1e293b" stroke="#64748b" stroke-width="2"/> + <rect x="866" y="552" width="46" height="16" rx="8" fill="url(#steel)" stroke="#475569"/> + <line x1="912" y1="560" x2="992" y2="552" stroke="#94a3b8" stroke-width="5" stroke-linecap="round"/> + <rect x="776" y="574" width="20" height="8" rx="3" fill="#475569"/> + <rect x="866" y="574" width="20" height="8" rx="3" fill="#475569"/> + + <!-- the switchman at work, behind the main rail --> + <g> + <ellipse cx="1060" cy="558" rx="58" ry="9" fill="#16233c"/> + <!-- switch stand --> + <line x1="1010" y1="554" x2="1010" y2="500" stroke="#94a3b8" stroke-width="5"/> + <circle cx="1010" cy="492" r="5" fill="#22d3ee"/> + <circle cx="1010" cy="492" r="9" fill="none" stroke="#22d3ee" stroke-width="2" opacity="0.4"/> + <rect x="1004" y="500" width="12" height="10" rx="3" fill="#64748b"/> + <!-- legs --> + <line x1="1052" y1="514" x2="1046" y2="552" stroke="#334155" stroke-width="8" stroke-linecap="round"/> + <line x1="1066" y1="514" x2="1072" y2="552" stroke="#334155" stroke-width="8" stroke-linecap="round"/> + <rect x="1038" y="548" width="16" height="7" rx="3" fill="#1e293b"/> + <rect x="1066" y="548" width="16" height="7" rx="3" fill="#1e293b"/> + <!-- vest --> + <rect x="1040" y="470" width="36" height="50" rx="11" fill="#fb923c"/> + <line x1="1046" y1="486" x2="1070" y2="486" stroke="#fde68a" stroke-width="4" stroke-linecap="round"/> + <line x1="1046" y1="500" x2="1070" y2="500" stroke="#fde68a" stroke-width="4" stroke-linecap="round"/> + <!-- head + cap --> + <circle cx="1058" cy="452" r="12" fill="#fcd9b8"/> + <path d="M1044 450 a14 14 0 0 1 28 0 z" fill="#0ea5e9"/> + <rect x="1056" y="446" width="17" height="4" rx="2" fill="#0284c7"/> + <!-- arms pulling the stand lever --> + <line x1="1044" y1="482" x2="1016" y2="502" stroke="#fcd9b8" stroke-width="6" stroke-linecap="round"/> + <line x1="1074" y1="482" x2="1018" y2="506" stroke="#fcd9b8" stroke-width="6" stroke-linecap="round"/> + <circle cx="1016" cy="502" r="4" fill="#eab308"/> + </g> + + <!-- track junction --> + <polygon points="985,542 985,558 1010,550" fill="#475569"/> + <g stroke="#475569" stroke-width="5" opacity="0.9"> + <line x1="1030" y1="534" x2="1030" y2="566"/> + <line x1="1080" y1="534" x2="1080" y2="566"/> + <line x1="1130" y1="535" x2="1130" y2="565"/> + <line x1="1190" y1="537" x2="1190" y2="563"/> + <line x1="1260" y1="539" x2="1260" y2="561"/> + <line x1="1340" y1="541" x2="1340" y2="559"/> + <line x1="1430" y1="543" x2="1430" y2="557"/> + </g> + <g fill="none" stroke="#334155" stroke-width="14" stroke-linecap="round"> + <path d="M995 550 H1520"/> + <path d="M995 550 C1140 550 1230 380 1520 380"/> + <path d="M995 550 C1140 550 1230 612 1520 612"/> + </g> + <g fill="none" stroke="#64748b" stroke-width="2" stroke-dasharray="12 10"> + <path d="M995 550 H1520"/> + <path d="M995 550 C1140 550 1230 380 1520 380"/> + <path d="M995 550 C1140 550 1230 612 1520 612"/> + </g> + <!-- active blade pointing to main --> + <line x1="995" y1="550" x2="1120" y2="550" stroke="#22d3ee" stroke-width="6" stroke-linecap="round" opacity="0.9"/> + + <!-- ctx cart on the main line --> + <rect x="1272" y="514" width="56" height="30" rx="7" fill="#164e63" fill-opacity="0.85" stroke="#22d3ee" stroke-width="2"/> + <text x="1300" y="534" font-size="14" fill="#a5f3fc" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">ctx</text> + <circle cx="1286" cy="548" r="5" fill="#0f172a" stroke="#64748b" stroke-width="2"/> + <circle cx="1314" cy="548" r="5" fill="#0f172a" stroke="#64748b" stroke-width="2"/> + + <!-- destination pools --> + <g font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="15" text-anchor="middle"> + <rect x="1408" y="358" width="112" height="44" rx="10" fill="#0b1526" stroke="#a78bfa" stroke-width="2"/> + <text x="1464" y="385" fill="#ddd6fe">hard</text> + <rect x="1408" y="528" width="112" height="44" rx="10" fill="#0b1526" stroke="#22d3ee" stroke-width="2"/> + <text x="1464" y="555" fill="#a5f3fc">main</text> + <rect x="1408" y="590" width="112" height="44" rx="10" fill="#0b1526" stroke="#fbbf24" stroke-width="2"/> + <text x="1464" y="617" fill="#fde68a">economy</text> + </g> + + <!-- the "ox & horse" (hard-working programmers) watching from the hill --> + <g> + <ellipse cx="1330" cy="322" rx="150" ry="28" fill="#1c2c4a"/> + <path d="M1180 322 A150 28 0 0 1 1480 322" fill="none" stroke="#7dd3fc" stroke-width="3" opacity="0.22"/> + <g fill="none" stroke="#2dd4bf" stroke-width="2" stroke-linecap="round" opacity="0.55"> + <path d="M1230 310 q-2 -8 -5 -10 M1230 310 q0 -10 0 -13 M1230 310 q3 -8 6 -10"/> + <path d="M1340 302 q-2 -8 -5 -10 M1340 302 q0 -10 0 -13 M1340 302 q3 -8 6 -10"/> + <path d="M1440 308 q-2 -8 -5 -10 M1440 308 q0 -10 0 -13 M1440 308 q3 -8 6 -10"/> + </g> + <!-- ox (chubby, sitting with a slight forward tilt, facing left) --> + <g transform="rotate(-6 1268 286)"> + <ellipse cx="1268" cy="286" rx="44" ry="38" fill="#f1f5f9"/> + <circle cx="1282" cy="282" r="12" fill="#94a3b8" opacity="0.5"/> + <ellipse cx="1300" cy="314" rx="16" ry="9" fill="#dbe4ee"/> + <rect x="1240" y="316" width="12" height="14" rx="5" fill="#dbe4ee"/> + <rect x="1258" y="316" width="12" height="14" rx="5" fill="#dbe4ee"/> + <path d="M1308 272 q16 -2 12 18" fill="none" stroke="#dbe4ee" stroke-width="4" stroke-linecap="round"/> + <!-- ox head --> + <circle cx="1234" cy="248" r="17" fill="#f8fafc"/> + <ellipse cx="1223" cy="254" rx="11" ry="8" fill="#f3b6c0"/> + <circle cx="1221" cy="253" r="1.8" fill="#be6b78" opacity="0.8"/> + <circle cx="1230" cy="243" r="2.2" fill="#0f172a"/> + <path d="M1222 234 q-10 -12 -19 -5" fill="none" stroke="#e2e8f0" stroke-width="5" stroke-linecap="round"/> + <path d="M1243 231 q3 -14 15 -12" fill="none" stroke="#e2e8f0" stroke-width="5" stroke-linecap="round"/> + <ellipse cx="1218" cy="241" rx="5" ry="3" fill="#dbe4ee" transform="rotate(-25 1218 241)"/> + <ellipse cx="1248" cy="234" rx="5" ry="3" fill="#dbe4ee" transform="rotate(20 1248 234)"/> + </g> + <!-- horse (sitting like a dog, slim, facing left) --> + <circle cx="1428" cy="296" r="28" fill="#a16207"/> + <rect x="1391" y="242" width="38" height="78" rx="17" fill="#b45309"/> + <rect x="1396" y="312" width="8" height="14" rx="4" fill="#92400e"/> + <rect x="1408" y="312" width="8" height="14" rx="4" fill="#92400e"/> + <path d="M1454 288 q20 0 16 24" fill="none" stroke="#78350f" stroke-width="4" stroke-linecap="round"/> + <path d="M1468 308 q6 6 2 14" fill="none" stroke="#78350f" stroke-width="5" stroke-linecap="round"/> + <!-- horse neck + head --> + <path d="M1400 256 L1372 222" fill="none" stroke="#b45309" stroke-width="22" stroke-linecap="round"/> + <path d="M1400 250 Q1408 234 1396 220" fill="none" stroke="#78350f" stroke-width="5" stroke-linecap="round"/> + <ellipse cx="1366" cy="214" rx="14" ry="10" fill="#b45309"/> + <ellipse cx="1353" cy="218" rx="8" ry="6" fill="#d6b28a"/> + <circle cx="1363" cy="211" r="2" fill="#0f172a"/> + <path d="M1372 205 l4 -13 8 10 z" fill="#92400e"/> + <path d="M1380 208 l8 -11 4 12 z" fill="#92400e"/> + <!-- little "..." above their heads: just watching --> + <circle cx="1300" cy="234" r="2.5" fill="#94a3b8" opacity="0.8"/> + <circle cx="1312" cy="226" r="2.5" fill="#94a3b8" opacity="0.55"/> + <circle cx="1326" cy="220" r="2.5" fill="#94a3b8" opacity="0.3"/> + </g> +</svg> diff --git a/docs/pay/alipay.png b/docs/pay/alipay.png new file mode 100644 index 0000000..7a2801c Binary files /dev/null and b/docs/pay/alipay.png differ diff --git a/docs/pay/wechat_pay.jpg b/docs/pay/wechat_pay.jpg new file mode 100644 index 0000000..dd0db8e Binary files /dev/null and b/docs/pay/wechat_pay.jpg differ diff --git a/docs/pay/wechat_pay_2.jpg b/docs/pay/wechat_pay_2.jpg new file mode 100644 index 0000000..b544681 Binary files /dev/null and b/docs/pay/wechat_pay_2.jpg differ diff --git a/docs/quick-start.md b/docs/quick-start.md index 974180c..f73cffa 100644 --- a/docs/quick-start.md +++ b/docs/quick-start.md @@ -144,4 +144,4 @@ That's it — from here just use opencode normally. Your primary model is now a | `/switchman-doctor` | TUI & app | Local, credential-free diagnostics | Per call | — | | `/switchman-update` | TUI & app | Upgrade the plugin to the latest release | After restart | opencode plugin config | -> Deeper dives: [Manual overrides](../README.md#manual-overrides-poolconfig-and-modelrank-new-in-v025) · [Options (`opencode-switchman.jsonc`)](../README.md#options-opencode-switchmanjsonc) · [How it works](../README.md#how-it-works) +> Deeper dives: [Manual overrides](./reference.md#manual-overrides) · [Options (`opencode-switchman.jsonc`)](./reference.md#configuration-opencode-switchmanjsonc) · [How it works](./reference.md#how-it-works) diff --git a/docs/quick-start.zh.md b/docs/quick-start.zh.md index 5af0d99..3a2af4e 100644 --- a/docs/quick-start.zh.md +++ b/docs/quick-start.zh.md @@ -144,4 +144,4 @@ | `/switchman-doctor` | TUI & app | 本地、脱敏诊断 | 单次调用 | — | | `/switchman-update` | TUI & app | 升级插件到最新版 | 重启后生效 | opencode 插件配置 | -> 延伸阅读([README.zh.md](../README.zh.md)):手动覆盖层 · 配置项(opencode-switchman.jsonc) · 工作原理 +> 延伸阅读([reference.zh.md](./reference.zh.md)):手动覆盖层 · 配置项(opencode-switchman.jsonc) · 工作原理 diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..2fe9415 --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,430 @@ +# opencode-switchman — Full Manual + +[README](../README.md) · **Reference (EN)** · 中文 [参考手册](./reference.zh.md) + +The README is deliberately short. Everything else lives here: installation details, the complete options table, manual overrides, and how the plugin works inside. + +**Contents** + +- [Installation](#installation) +- [Configuration: opencode-switchman.jsonc](#configuration-opencode-switchmanjsonc) +- [Verify the installation](#verify-the-installation) +- [Sidebar status panel (TUI, optional)](#sidebar-status-panel-tui-optional) +- [Manual overrides](#manual-overrides) +- [Core ideas](#core-ideas) +- [How it works](#how-it-works) +- [Dynamic activation matrix](#dynamic-activation-matrix) +- [Model scoring engine](#model-scoring-engine) +- [Subagent context hard cap](#subagent-context-hard-cap) +- [Artifact workspace (.switchman)](#artifact-workspace-switchman) +- [tmux pane mirroring (optional)](#tmux-pane-mirroring-optional) +- [Maintaining the model matrix](#maintaining-the-model-matrix) +- [Development & verification](#development--verification) +- [Release highlights](#release-highlights) +- [Further documentation](#further-documentation) + +## Installation + +One-liner paths (recommended), covered in the [README](../README.md#install). This section is the long version. + +### Prerequisites + +- [opencode](https://opencode.ai) — **the CLI/TUI is the strongly recommended interface** (the plugin's operational surface — sidebar status panel, `/poolConfig` / `/modelRank` dialogs, live banners — is richest there): configure everything in the TUI first, then optionally switch to the desktop app for a GUI experience; both share the same config and state +- Any opencode provider works out of the box; the following three additionally get quota control (any combination, all optional): + - **GitHub Copilot**: just sign in via GitHub in opencode (`/connect`) + - **GLM**: custom provider (`zhipuai-coding-plan`, baseURL `https://open.bigmodel.cn/api/coding/paas/v4` + apiKey) + - **DeepSeek**: custom provider (`deepseek` + apiKey) +- Zero-config credentials: the plugin reads them **read-only** from opencode's auth layer (auth.json / provider options / env vars) — it never stores secrets or refreshes tokens itself + +### Let your AI install it + +In the AI era, we strongly recommend letting an AI perform the installation and configuration for you — it reads your real environment, writes the correct values, and verifies the result itself, which is far less error-prone than manual copy-pasting. Copy the prompt below to the AI you are currently using: + +```text +Please install and configure the opencode-switchman plugin for my opencode, strictly following its official instructions. + +Official sources (authoritative, do not guess from memory): +- GitHub repo: https://github.com/mrzturn/opencode-switchman +- npm package: https://www.npmjs.com/package/opencode-switchman +Read the repo README's "Installation & Usage" section and follow it exactly. + +Steps: +1. Install the latest version published on npm: run `npx -y opencode-switchman@latest` (or `bunx opencode-switchman@latest`) — it rewrites the `plugin` entry in my opencode config to the exact latest version (it also works in the project-level `opencode.json` if that is what I use). +2. Complete the functional configuration: all plugin settings live in the standalone `opencode-switchman.jsonc` in my opencode config directory, auto-generated with defaults and inline comments on first start; check it against my providers (e.g. `zhipuai-coding-plan` / `deepseek` / `github-copilot`) and adjust as needed. +3. Verify correctness so opencode loads, starts, and runs the plugin: run `/switchman-doctor` inside opencode for a local credential-free diagnostic report and fix every error it reports; then restart opencode and confirm the plugin actually loaded — the log should contain `[opencode-switchman] injected N model shells (agents)` and my primary model's system prompt should carry the live `[ROUTES]/[WATERMARK]/[LIMITS]` banner block. + +Do not declare success until all three steps pass; report what you changed and show the verification evidence. +``` + +### Install / update: what the one-liners actually do + +Both commands cover first install and later updates (idempotent, safe to re-run): they rewrite the `plugin` entry in your opencode config and `tui.jsonc` to the exact latest version `opencode-switchman@x.y.z` (JSONC comments preserved), prune stale plugin caches (`~/.cache/opencode/packages/opencode-switchman*`), and on upgrade flag the "upgraded, restart required" banner — **restart opencode to take effect**. + +The in-plugin `/switchman-update` command invokes the same updater (the old `npm install` approach never affected the path OpenCode actually loads). + +> **Why the entry is an exact version instead of a bare name / `@latest`**: OpenCode ≤1.18.x pins its plugin cache to a per-spec directory (e.g. `~/.cache/opencode/packages/opencode-switchman`) and never re-queries npm after the first install — bare names and `@latest` keep reusing the stale cache (observed pinned at 0.0.1). Exact versions get their own cache directory, so the updater rewrites the version instead. + +### Option: npm (manual) + +Add to your opencode config (`~/.config/opencode/opencode.json` or project `opencode.json`): + +```json +{ + "plugin": ["opencode-switchman"] +} +``` + +opencode installs and loads the npm package automatically via Bun at startup, no other steps needed. For later updates use the one-liner above or `/switchman-update` inside opencode. + +> **Nothing else goes into your opencode config**: all plugin configuration (water levels, billing, peaks, thresholds, banner, matrix, custom lanes, etc.) lives in the standalone `opencode-switchman.jsonc` file (see below) — auto-generated on first start with inline comments. The legacy tuple-options form (`["opencode-switchman", {...}]`) is deprecated and kept compatible for one release (explicit values still win; `/switchman-doctor` flags them as SWM044 and suggests migrating). + +### Option: from source + +```bash +git clone https://github.com/mrzturn/opencode-switchman.git +cd opencode-switchman +bun install +bun run build # produces dist/opencode-switchman.js +``` + +Then pick one of two loading methods: + +**a) Config reference (recommended, follows the repo)** — point the `plugin` array at the repo directory via `file://`: + +```json +{ + "plugin": ["file:///absolute/path/to/opencode-switchman"] +} +``` + +The plugin loads the repo's `dist` bundle directly; after `git pull`, re-run `bun run build` and restart opencode to upgrade. **Choose either this or the plugins-directory deployment** — using both double-loads the plugin. + +**b) Single-file deploy** — `bun run deploy` builds and copies into the global plugin directory `~/.config/opencode/plugins/opencode-switchman.js`, which is auto-loaded. The desktop app's embedded core runs on Node, which is exactly what the single-file `deploy` bundle targets. + +> **Note**: a `file://` entry in the `plugin` array and a plugins-directory deployment must not coexist (the same plugin loads twice). Once published to npm, replace the `file://...` entry with `"opencode-switchman"` to switch to npm installation. Restart opencode to take effect. + +> **Upgrading from the pre-rename plugin (switchman.js)**: delete the old `~/.config/opencode/plugins/switchman.js` to avoid double injection. The state directory has moved to `~/.config/opencode/opencode-switchman/` (the old one can be removed; all state self-heals). + +## Configuration: opencode-switchman.jsonc + +**Apart from the plugin registration itself (the `plugin` array in your opencode config), every plugin setting lives in the standalone `opencode-switchman.jsonc`** — auto-created on first startup in the OpenCode config directory (`OPENCODE_CONFIG_DIR`, then `$XDG_CONFIG_HOME/opencode`, then `~/.config/opencode`) with a `$schema` for editor hints and per-key comments; invalid values fail open to defaults. Edit the file and re-run config (or restart opencode) to apply; `/switchman-doctor` produces a local, credential-free diagnostic report. + +**providers — per-provider policy**: it ships with the stable provider keys `deepseek`, `zhipuai-coding-plan`, and `github-copilot` (matching OpenCode's own official provider IDs), but **any opencode official or custom provider key is legal** — unknown keys are treated as custom providers (routed with generic defaults; near-miss spellings of the built-in keys get a doctor warning). `observe` controls quota lookup/banner display; `enabled` independently opts a provider into routing water-level, peak, and exhaustion rules (both default to `true`/`false` respectively). `billing` declares the cost structure — `subscription` (score boost 1.0) or `api` (0.85, sinks within its capability tier); it is the only source of billing priority (never inferred from models.dev or auth). `peak` ranges use ISO weekdays (`1`–`7`) and `[start,end)` `HH:mm` ranges; defaults are GLM weekdays 14:00–18:00 and DeepSeek weekdays 09:00–12:00 plus 14:00–18:00. + +**Behavior sections** (`quota` / `cost` / `capability` / `matrix` / `banner` / `rules` / `lanes`): see the Options table below — same file, nowhere else. + +### Options (opencode-switchman.jsonc) + +| Key | Default | Description | +|---|---|---| +| `providers.<id>.enabled / observe / billing / peak` | `false / true / factory / factory` | Provider policy: routing participation, quota observation, cost structure (subscription=1.0 / api=0.85), peak windows (see above) | +| `quota.glmFiveHourReservePct` | `90` | GLM 5-hour window reserve water level (%): hard-block GLM shells once reached (avoid 429); weekly still only blocks at 100% | +| `quota.deepseekLowBalanceWarnCny` | `10` | DeepSeek balance warning threshold (CNY): the banner water-level line warns below it (warning only, no hard block, pay-as-you-go) | +| `cost.enabled` | `true` | models.dev pricing snapshot as one coefficient in weighted model scoring | +| `capability.enabled / source / apiKey / tierThresholds / lmarenaCheck` | `true / auto / – / built-in quantile / false` | Dynamic capability tiers: `auto` = Artificial Analysis first when apiKey present, otherwise OpenRouter; key may also come from `ARTIFICIAL_ANALYSIS_API_KEY` env | +| `matrix.mode / watch` | `auto / true` | Activation matrix: `auto` by host (desktop = visible models / CLI/TUI = favorites), `app`/`tui` force a mode, `legacy` restores the static matrix; `watch` recomputes and fully refreshes probes on surface changes (mode/watch are startup-level; restart to apply) | +| `banner.enabled` | `true` | Four-line banner injection | +| `rules.enabled / delegationFloor` | `true / 3000` | Bundled dispatcher rules (AGENTS.md) injection; `delegationFloor` is the self-do token floor interpolated into the rules (dispatch by default below it is a violation) | +| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 60000 / 80000 / 120000 / 1500 / true` | **Measured session watermark + self-read budget**: the plugin measures each main session's context from message token usage and injects a live `[WATERMARK:SESSION]` line every turn (with per-turn growth and remaining-turns-to-hard estimates). Every self-read is costed against `readBudgetTokens` from turn 1: over-budget reads are auto-bounded (a `limit` is auto-appended) or denied with exact bounded-retry params, and a per-turn 2× cap stops read chains; un-estimable tool outputs are charged post-hoc. Verification/delivery bash (git, test/lint, build) always passes; unbounded history dumps (`git log -p` without `-n`) are always denied with a scoping hint; past `hardTokens` read-class closes (wrap-up mode); past `forceTokens` the banner demands compaction and, with `autoHandover: true` (default), `/handover` fires automatically: full fork backup + compaction, the running task continues on the summarized context. Shell subagent sessions are exempt from this watermark and get their own single hard cap instead (see `context.subagentForceTokens` / `context.subagentCap` below); all three thresholds are additionally capped at 90% of the current session model's context window when known (models.dev) | +| `context.subagentForceTokens / subagentCap` | `100000 / true` | **Subagent context hard cap**: shell subagent sessions get a single hard cap (measured = input + output + reasoning + cache.read of the latest assistant message, same estimator as the session watermark), clamped 20k..1M and additionally capped at 90% of the shell model's context window. On crossing, every further tool call in that subagent session is denied with a wrap-up order; the subagent's next text-only answer (a detailed work-progress summary) becomes the task result returned to the delegating session and the session is permanently terminated. Later `task` calls resuming it via `task_id` are denied permanently (persistent registry `~/.config/opencode/opencode-switchman/subagent-cap.json`); fresh dispatches without `task_id` are unaffected; `subagentCap: false` prevents new terminations only — already-terminated sessions stay dead | +| `builtinAgents.mode` | `deny` | Built-in `explore`/`general` subagents compete with shell routing and were previously fail-open; `deny` blocks them with an economy/main re-dispatch hint (the task-tool description from opencode core actively advertises them), `allow` restores the old pass-through | +| `injection.mode` | `chain` | Shell injection face: `chain` = six lane chains ∪ favorites/visible models (saves ~6-10k tokens of task-tool description per session; naming an off-chain model gets a `denyUninjected` hint to enable it in model management), `all` = every usable model (old behavior). Startup-level: restart to apply | +| `dispatch.autoRedirect` | `true` | On a dispatch deny, rewrite `subagent_type` in-flight to the chain-head candidate the deny message already names (single hop, same-snapshot guard re-check) — the first dispatch lands on the best available shell instead of burning deny-and-retry rounds; `false` restores deny-and-retry | +| `relay.image` | `true` | Vision-less main models: user-attached images are decoded to disk and replaced with path text + reading guidance (delegate a vision-lane shell or an MCP vision tool); local paths / http URLs pass through; fully fail-open | +| `lang.enabled / ask / candidates` | `true / true / factory list` | Per-project language preference: per-turn `[LANG]` iron-rule line (conversation / comments & commits / docs), first-use ask re-surfaced every user turn until configured and enforced by a hard gate (write/edit/bash/task denied while unconfigured; decline waives per session), persisted to `.switchman/settings.json` (AGENTS.md marker as read-only fallback), `/switchman-lang` re-asks | +| `lanes` | built-in chains | Custom per-lane shell chains (override built-in preference order); keys = economy/mechanical/main/hard/vision/review | +| `workspace.enabled / dirname` | `true / ".switchman"` | Artifact workspace: per main session, a `<project-root>/.switchman/<yyyy-mm-dd>/<sessionId>-<title>/` folder whose path is injected into the dispatcher protocol every turn; holds `SESSION.md` / `dispatches.jsonl` / `media/`. Disabled = no folders created and the protocol section is neutralized | +| `tmux.enabled / rightPct / maxPanes / mini` | `true / 60 / 3 / false` | tmux pane mirroring (effective only when the opencode server itself runs inside tmux): every dispatched subagent opens as a live `opencode attach` pane in a right-hand column of the home tmux window; `rightPct` = right column width percent (10..90, main pane keeps the rest), `maxPanes` = max visible subagent panes (1..4; extra dispatches wait in a FIFO queue), `mini` = minimal attach interface instead of the full TUI | + +> **Migrating legacy tuple options**: `quota.*.enabled` → `providers.<id>.observe` (SWM042), `billingWindow.*` → `providers.<id>.peak` (SWM043), and the remaining behavior sections (`quota` thresholds / `cost` / `capability` / `matrix` / `banner` / `rules` / `lanes`) → same-named jsonc sections (SWM044); `providers.glm/deepseek` (credential-collection lists) never took effect and have been removed. Explicit tuple values stay honored for one compatibility release, then will be dropped. + +## Verify the installation + +After starting opencode, every system prompt of the primary model carries a live banner block (the dispatcher's ground truth): + +``` +[ROUTES] economy: glm-53f-low→glm-47-off→glm-5t-off | mechanical: glm-53f-high→glm-47-off | main: glm-53f-high | hard: glm-53-high | vision: glm-53f-high | review: glm-53-high-ro +[WATERMARK] GLM 5h 10% weekly 38% (refreshed 09-11 10:00) | Copilot credits 0% left (refreshes 2026-10-01) | DeepSeek balance exhausted | advice: ... +[WATERMARK:SESSION] measured session context ~37k (soft 60k/hard 80k/force 100k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 +[LIMITS] down: none | reviewer prefers cross-family (same-family self-review = DOWNGRADED, allowed only when no cross-family reviewer exists) | api-billed & unknown models sink by coefficient (explicit billing=subscription wins) | matrix: cli·watch/ok | manual capability rank: 9 models, task-pool selection: 6 pools active (/modelRank /poolConfig to adjust) +[TODO] 0/6 done · in_progress: draft the README section — keep todowrite current (update as each item starts/finishes) +[LANG] conversation=en comments=en docs=en (source: project settings) — reply and reason in the conversation language; code comments, commit messages, and generated docs follow their own settings +[UPDATE] new version available: /switchman-update or /switchman-ignore +``` + +The log also shows `[opencode-switchman] injected N model shells (agents)` — N varies dynamically with the model surface of credentialed providers. Lane candidates are generated algorithmically from capability score × effort affinity × billing/unknown coefficients, with vision/review structural gates and no vendor-specific seats; runtime health, quota, and cost rules then select the current first candidate. + +## Sidebar status panel (TUI, optional) + +v0.2.0 adds a live `switchman` panel at the bottom of the OpenCode TUI sidebar; v1.0.0 polishes it into a fully aligned, English-localized operational view. Observed provider water levels render as gradient bars on a globally aligned 8-column grid (labels, bars, and reset times line up across provider blocks; any non-zero quota paints at least one filled cell), with peak-period warnings, per-provider observe-only tags (collapsed when every provider observes), the current head candidate for each of the six lanes, restart-required badges for newly detected models/providers, a version line on the marquee row (the running version — local builds append the checked commit short SHA — plus a green `→ v<latest>` when the update check reports a newer release, `→ origin/main` for local builds; the blinking `[RESTART NEEDED]` tag also lights up while an installed upgrade awaits a restart), and the most recent status notice. The panel polls local state every 2 seconds; non-banner notices never flood `stderr` or cover the input box. It is a separate TUI Slot plugin (`src/tui.tsx`, exported at `opencode-switchman/tui`) and is independent of the server-side hook plugin above. + +> **Recommended workflow**: set the plugin up in the TUI first — pick model favorites, tune `/poolConfig` and `/modelRank`, and watch the sidebar while it routes. The desktop app is an optional alternative afterwards (it shares the same config and state); the TUI is simply where the operational surface — dialogs, sidebar, banners — is richest. + +![Switchman sidebar: quotas, peak periods, lane candidates, and status notice](assets/tui-sidebar-status.png) + +![OpenCode model picker alongside the Switchman TUI integration](assets/tui-model-picker.png) + +Since TUI plugins have no directory auto-discovery, add the same package spec to your **`tui.jsonc`/`tui.json`** `plugin` array (npm install and `opencode plugin <spec>` do this automatically; only needed manually if you hand-edit config or use `mode:local`/`mode:prod` from source): + +```json +{ + "plugin": ["opencode-switchman"] +} +``` + +## 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. + +### /poolConfig — per-lane model assignment (manual dialog; conversational: /poolConfig-chat) + +- **TUI (/poolConfig)**: a native select dialog (same interaction as the model/thinking-level pickers) — pick a task pool (economy / mechanical / main / hard / vision / review), then toggle models up and down the list: select to include, select again to exclude, with a capability tier shown per model. Shortcuts: "Select all" and "Uncheck all" (rebuild mode — check just the few to keep; exiting with none checked keeps the previous selection, the first check after a clear writes the new list). Changes are written through immediately with a toast receipt. +- **Non-TUI / in-session (/poolConfig-chat)**: a conversational flow — it injects a per-pool assignment overview (use a pool name to get the full `[x]/[ ]` list); reply "main: keep only 3 5" or "economy: add 1, drop 2" and the agent calls the bundled `switchman-config.js` CLI to persist. +- **Semantics**: assignment = making each task pool's candidate models **deliberately different** (e.g. lightweight models only for economy, heavy thinkers only for hard) — a pool's manual list **overrides the system default candidate set**, and models inside it are still recommended by capability level; **the same model may join multiple pools**; pools without a configured (or with an empty) list keep the system default. "Clear config" restores the system default for that pool. +- **Config file**: `~/.config/opencode/opencode-switchman/pool-config.json` (key = task pool name, value = array of participating modelIds). + +![/poolConfig step 1 — pick a task pool, each lane showing how many models participate](assets/tui-pool-config-pools.png) + +![/poolConfig step 2 — toggle models per pool with capability tiers and select-all / uncheck-all / clear shortcuts](assets/tui-pool-config-models.png) + +### /modelRank — model capability ranking (manual dialog; conversational: /modelRank-chat) + +- **TUI (/modelRank)**: a dialog listing models by effective capability — manual entries interleave with base-score models in one merged ordering; moving a model up/down anchors it a manual score between its new neighbors (one-spot nudges, no need to rank everything above), plus pin-to-top / remove; effective immediately. +- **Non-TUI / in-session (/modelRank-chat)**: a conversational flow — it injects the current ranking and a reference ordering; reply "pin glm-5.3 to top" or "clear the ranking" and the agent translates that into `rank` CLI calls to persist. +- **Semantics**: manual ranking **takes priority over the base capability score** (realtime index → bundled snapshot → curated table all yield) — matched models (including their prefix variants) get a rank-position score and S/A/B/C tier: rankings with ≤4 entries map positions to S/A/B/C in order; ≥5 entries use quantile buckets (top 20% S / next 20% A / next 20% B / rest C, same semantics as the OpenRouter rank source); within a tier, the linear rank position breaks ties. Unranked models are unaffected. The ranking feeds every decision surface: lane chains, effort affinity, capability-level gates, and deny hints. +- **Config file**: `~/.config/opencode/opencode-switchman/capability-rank.json` (`models` array order = strongest first). + +![/modelRank — capability ranking with manual-rank vs base-score provenance](assets/tui-model-rank.png) + +### /expert — expert consultation (conversational) + +- Usage: `/expert <your requirement or design question>` — the description is passed verbatim to the expert; with no description the agent asks first. +- 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"). + +## Core ideas + +### The problem + +Real pain points of juggling multiple subscriptions: + +1. **Cognitive mismatch**: flagship models doing scan-and-count chores (tokens wasted), or lightweight models doing architecture design (rework is the most expensive token of all) +2. **Flying blind on water levels**: hammering GLM after the 5-hour window is exhausted, letting Copilot premium credits expire unused at month's end, discovering an empty DeepSeek balance only at failure +3. **Single-family blind spots**: reviewing with the same model family that produced the code — same blind spots, nothing found +4. **Loose delegation**: "hey, take a look at this" prompts carry no structure and no validation + +### The solution: dispatcher + shell matrix + deterministic gating + +opencode-switchman splits orchestration into three layers: + +| Layer | Vehicle | Responsibility | +|---|---|---| +| **Cognitive** | Primary model (dispatcher) + bundled dispatcher rules | Four-dimension task profiling (cognitive intensity × mechanicalness × context size × urgency), self-do vs. delegate, lane & shell choice, writing DELEGATION_V1 prompts | +| **Execution** | "model × effort" bare shells (e.g. `glm-mx-53-high`) | Bind only model and reasoning effort; roles are assigned dynamically by the delegation prompt (14 roles: programmer/tester/reviewer/…) | +| **Deterministic** | The plugin | Six-gate interception, ROUTE_META hard validation, weighted model scoring, quota/cost-aware chain computation, probe / breaker / real-dispatch isolation, live four-line banner | + +**Token economics is the first principle**: rework is the most expensive token. Hence six cognitive lanes: + +| Lane | Typical roles | Uses | +|---|---|---| +| economy | clerk / scouter scanning | cheapest lightweight model, low→medium→high effort | +| 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 | +| vision | observer image reading | vision-capable models, medium→high→xhigh→max effort | +| review | reviewer / expert panel | **forced hetero-family** (against same-family blind spots), high→xhigh→max effort | + +Effort preference is a routing layer of its own: each lane prefers the thinking levels listed above (first supported level is the default), and `off`-effort shells serve only as lane-level fallback — they enter a chain only when no thinking-level candidate is available (e.g. models that only support on/off), never ahead of one. Shells are likewise partitioned by capability face before ranking: the review lane draws only from `ro` (read-only) shells, all other lanes only from `rw` shells, with cross-face fallback only when a lane's own pool is empty. + +Water levels only affect ordering (use it, don't waste it); the only hard block is "this call cannot possibly succeed" (quota definitively exhausted or hard gate hit). Pay-as-you-go (`billing: "api"`) providers are never denied for auto routing — they sink within their capability tier via the 0.85 coefficient, and unknown-provider models sink via the 0.75 penalty, so no vendor-specific tail-seat or deny rule is needed. + +## How it works + +### Lifecycle + +```mermaid +flowchart TD + A[opencode starts] --> B[config hook<br/>inject full shell matrix into cfg.agent<br/>+ credential collection] + B --> C[background warm-up<br/>probe matrix / pool quotas / pricing snapshot<br/>10-min self-healing refresh] + C --> D[primary model works<br/>guided by dispatcher rules] + D --> E{self-do or delegate?} + E -->|small task| Z[primary model does it directly] + E -->|delegate| F[pick lane & shell<br/>write DELEGATION_V1 + ROUTE_META] + F --> G[task dispatch<br/>intercepted at tool.execute.before] + G --> H{six-gate check} + H -->|pass| I[shell subagent executes] + H -->|deny| J[error with reason + reroute candidate<br/>dispatcher follows the chain] + I --> K{outcome} + K -->|success| L[summary returns to dispatcher] + K -->|failure| M[event hook accounting<br/>classifyFailure + isolation<br/>≥2 failures in 600s → breaker 600s] + M --> D + J --> D + D -.every LLM request.-> N[system.transform<br/>inject dispatcher rules + four-line banner<br/>live routing / quota / limits] +``` + +### The six gates (order = priority) + +On every subagent dispatch, the plugin runs deterministic checks before the task tool executes; any hit denies with a reroute candidate: + +| Gate | Check | Meaning | +|---|---|---| +| 1 Registry | shell not enabled / unprobed | unregistered surfaces cannot be dispatched | +| 2 Probe matrix | combo measured down / retired | block the clearly unavailable; consecutive 404 retires a vanished model | +| 3 Breaker / isolation | ≥2 failures within 600s or real-dispatch isolation active | "tripping, auto-recovers in ~10 min" / "isolated after real dispatch failure" | +| 4 Pool exhausted | quota says the call must fail | human-readable reason (GLM 100% / Copilot definitively out / DS overdrawn) | +| 5 Protocol | ROUTE_META missing / illegal | deny with sample & legal values | +| 6 Semantics | same-family review / rw→ro shell / image→non-vision | "review needs a hetero-family lens", etc. | + +ROUTE_META is a single-line protocol embedded in the delegation prompt, six keys, validated field by field: + +``` +ROUTE_META {"lane":"main","role":"programmer","producer_family":"glm","capability":"rw","modality":"text","source":"auto"} +``` + +### Data plane (fully automatic, fail-open) + +- **Probe**: fires real requests against the three quota pools (other providers fail open), persists a matrix (TTL 600s). A surface change triggers a full refresh immediately; otherwise the 10-minute cycle self-heals. +- **Quotas**: direct queries — GLM monitor / DeepSeek balance / Copilot `copilot_internal/user` — no proxy, tiered TTL caches. +- **Failure classification**: vendor-neutral `classifyFailure` normalizes `rate_limit / quota / auth / not_found / server / network / unknown`. Probe 429 becomes `strained` (score down, still in chain); real 429 no longer marks Copilot exhausted, while 402 or 403 with quota wording does. Three consecutive 404s in a 1-hour window retire the model: chain excluded, gate denied, and banner marked. +- **Real-dispatch isolation**: if a combo probes OK but actual delegation fails, it is isolated in memory for 30 minutes (10 minutes for `rate_limit`), immediately visible to all sessions and cleared on restart. This runs alongside the existing 600s breaker. +- **Costs and scoring**: models.dev pricing and curated capability grades feed the weighted score; hard-gated candidates are excluded before scoring. +- **Decision log**: each banner rebuild writes candidate chains plus factor scores to `state/routing-decisions.jsonl` (ring buffer, 200 lines). +- **Banner**: `[ROUTES][WATERMARK][LIMITS][UPDATE]` four lines injected into every system prompt, keeping the dispatcher informed. `[LIMITS]` includes retired-model counts and downgrade marks; `[UPDATE]` exposes upgrade / ignore commands when a new version is detected. +- **Self-update**: startup checks are cached for 24h. Production installs compare against npm registry and can run `/switchman-update` for silent upgrade, then show "upgraded, restart required"; `/switchman-ignore` suppresses the notice for the current session only. Local mode compares against `origin/main`, shows manual update guidance, and only registers `/switchman-ignore`. +- **Fail-open iron law**: any hook error only writes to stderr and never blocks the main flow; unknown quotas never hard-block — breaker, probe, and dispatch isolation are independent sources of truth. + +### State directory + +`~/.config/opencode/opencode-switchman/`: `shells.json` (optional custom override; the bundled matrix is the default), `model-matrix.json` (probe), `routing.json` (breaker), `routing-decisions.jsonl` (200-line scoring audit ring), `failures.log` (accounting), `*-quota.json` / `ds-balance.json` (quota caches), `costs.json` (pricing), `delegation-template.md` (full DELEGATION_V1 template). + +## Dynamic activation matrix + +The shell matrix is no longer a static list — it is built at runtime and updated in real time: + +- **Desktop app** visible models and **CLI/TUI** favorites are bidirectionally synchronized. `mtime` decides the fresher side; a same-millisecond tie does not write either side, and the default CLI path is used as fallback when needed. +- With neither surface configured, it falls back to "the models your live sessions are actually using"; concurrent sessions are unioned, and any model switch is followed in real time on the next request. +- Model-management / favorites changes are watched live (fs.watch + mtime polling fallback). Any surface change recomputes the active matrix and triggers a **full probe refresh immediately** instead of waiting for TTL; the 10-minute periodic refresh still keeps the matrix self-healing. +- Newly added providers are detected in real time with a banner notice (the agent registry is immutable at runtime, so their shells are **registered automatically after restarting opencode** — zero manual maintenance). +- A superset of shells (every conversation-capable model of credentialed providers × models.dev tiers) is injected at startup; `matrix.mode=legacy` fully restores the old static behavior. + +## Model scoring engine + +Routing is now an explicit, traceable score rather than a hidden preference list: + +- **Base capability dominates**: curated S/A/B/C capability grades are matched by exact model id → prefix → family → global fallback, and the match route is recorded for audit. Tier groups are irreversible: a lower tier can never outrank a higher tier. +- **Weighted coefficients**: final score multiplies `effortFit × health × water × costBias × peak × billingBoost × unknownPenalty`. Health is `ok=1.0` / `strained=0.6`; water uses the tighter of the two windows and can boost Copilot when surplus credits are near expiry; peak applies `×0.93` to any provider whose configured peak window is active, as a same-tier yield that never ejects a stronger model across capability tiers. `billingBoost` is driven solely by the explicit `billing` field in `opencode-switchman.jsonc` (`subscription=1.0`, `api=0.85`) — no vendor is hardcoded in the routing rules. `unknownPenalty=0.75` applies to models that miss the whole classification cascade (exact → prefix → family), sinking them behind known models within the same tier. +- **Hard gates do not score**: down, breaker-open, pool-exhausted, retired, and real-dispatch-isolated combos are removed before scoring. `immediate` urgency sorts by probe latency instead of economics. +- **Decision log**: every banner rebuild writes lane candidates and the six-factor score breakdown to `state/routing-decisions.jsonl` as a 200-line ring buffer. + +## Subagent context hard cap + +Main sessions get the three-tier watermark (soft / hard / force) plus auto-handover; dispatched shell subagent sessions previously had no context control at all and could run past 180k tokens. Now every shell subagent session gets a single hard cap (`context.subagentForceTokens`, default 100,000 tokens, clamped 20k..1M and additionally capped at 90% of the shell model's context window), measured with the same estimator as the session watermark: input + output + reasoning + cache.read of the latest assistant message. On crossing, the plugin denies every further tool call in that subagent session with a wrap-up order; the subagent's next text-only answer — a detailed work-progress summary (completed / key findings with file:line evidence / remaining work / next steps) — becomes the task result returned to the delegating session, and the session is permanently terminated (terminations are recorded in the status log). Compliance is pre-armed on both sides: shell rule 6 of the subagent system prompt (stop at the first cap deny, hand back the summary), and bundled dispatcher protocol section 2 on the orchestrator side (never retry a terminated session; start a fresh dispatch re-seeding only needed context). + +Termination is permanent by design: any later `task` call resuming that session via `task_id` is denied permanently (persistent registry `~/.config/opencode/opencode-switchman/subagent-cap.json`, survives restarts), while fresh dispatches without `task_id` are unaffected. Rationale: a subagent is a reproducible worker (its spec lives in the delegation prompt), so terminate-and-hand-back beats compaction-continuation. `context.subagentCap: false` prevents new terminations only — already-terminated sessions stay dead. + +Configured by `context.subagentForceTokens` (default `100000`) / `context.subagentCap` (default `true`) in `opencode-switchman.jsonc` (see the Options table). + +## Artifact workspace (.switchman) + +For every main session the plugin auto-creates a per-project folder `<project-root>/.switchman/<yyyy-mm-dd>/<sessionId>-<title>/` (date = session creation day; the title slug part renames itself when the session title is generated or edited). The injected dispatcher protocol gets this folder path interpolated every turn, so plans, implementation progress, process-control notes, design docs, and other intermediate artifacts default to the session folder instead of scattering across the repo or being dumped into chat. Plugin-maintained files inside the folder: + +- `SESSION.md` — session metadata (id / title / project / timestamps) +- `dispatches.jsonl` — one JSON line per allowed task delegation (ts / shell / lane / role / source / redirected) +- `media/` — images relayed for vision delegation (moved here from the old global state directory, fail-open fallback) + +Configured by `workspace.enabled` / `workspace.dirname` in `opencode-switchman.jsonc` (defaults `true` / `".switchman"`); when disabled, no folders are created and the protocol section is neutralized. + +## tmux pane mirroring (optional) + +When the opencode server itself runs inside tmux, every dispatched subagent session opens as a live `opencode attach <server> -s <session>` pane, stacked in a right-hand column of the home tmux window (main pane keeps the left share — default 40% — the subagent column takes the right 60%). The window is only ever split at the home pane (the pane the server was launched in, `TMUX_PANE` at startup): your own sidebar panes and the tmux status line are never touched, and TUI clients attached from other panes still see the subagent panes there. + +![tmux pane mirroring: main session left, live subagent panes stacked on the right](assets/tmux-pane-mirroring.png) + +> Works out of the box — no configuration needed. The only requirement: run opencode inside a tmux session; outside tmux the feature stays completely inert. + +- **Visibility cap + FIFO**: at most 3 subagent panes are visible (`tmux.maxPanes`, 1..4); extra concurrent dispatches wait in a FIFO queue, and when a visible subagent finishes, a queued one takes over its pane in place (in-place respawn, pane count unchanged). Each completion shrinks the column again and re-evens the layout: 3→2 even halves → 1 full right pane → 0 = main pane alone (full width restored). +- **Hygiene**: panes are labeled `swm:<agent-name>` via pane title; leftover panes from a crashed previous run are swept (killed) at plugin startup (matched by title prefix or the attach start command). The window's active pane is restored after every layout op (focus preservation). +- **Safe by construction**: inert outside tmux and when `tmux.enabled=false`; all tmux failures are fail-open — status log only, never blocks dispatch. +- **Viewer etiquette**: the pane is a real interactive TUI attached to the subagent session — don't type into it (keystrokes go to the subagent session). Quitting a viewer pane just removes the display; the subagent keeps running. + +Configured by the optional `tmux` section in `opencode-switchman.jsonc` (`enabled` / `rightPct` / `maxPanes` / `mini`, defaults `true` / `60` / `3` / `false`). + +## Maintaining the model matrix + +By default (`matrix.mode=auto`) the matrix is built at runtime: desktop visible models and TUI favorites synchronize automatically, session models fill the gap, and any surface change triggers a full probe recomputation — zero upkeep. Temporary model outages self-heal via probes (10-minute background refresh, automatic degradation/breaking), while repeated 404s retire vanished models until the surface changes again. + +The superset floor is **opencode's built-in free models** (OpenCode Zen: models under the models.dev `opencode` provider with the `-free` suffix plus the `big-pickle` exception, excluding those marked `status=deprecated` — i.e. the "available today" set), rolling with the catalog every 24h — no manual upkeep. If the catalog is unreachable (offline cold start), it fail-opens back to the bundled static list. + +The bundled static matrix serves only `legacy` mode and the offline fallback. To customize that legacy surface: + +```bash +# 1. Sync the authoritative enabled surface (models visible in opencode model management, one provider/model-id per line) +$EDITOR scripts/visible-models.txt +# 2. Regenerate the bundled matrix (fetches effort tiers from models.dev) +bun run gen:shells +# 3. Restart opencode (takes effect in legacy mode) +``` + +## Development & verification + +```bash +bun install +bun test # behavioral contract fixtures (META / gates / chains / scoring / breaker / quota / update) +bunx tsc --noEmit # type check +bun run build # regenerate matrix and bundle the single-file build +``` + +For local plugin development versus the published package, use the idempotent mode switchers and restart opencode after switching: + +```bash +bun run mode:local # build + switch all three configs to file:// this repo (root auto-detected) +bun run mode:prod # fetch npm latest, switch to a pinned version entry + prune old caches + upgrade banner +bun run mode:prod --version 0.2.0 # pin a specific version (no network needed) +``` + +Both commands sync three configs (line-level surgery that preserves comments and third-party plugins; idempotent): + +- the `plugin` arrays in `opencode.jsonc`/`opencode.json` and `tui.jsonc`/`tui.json` (tui is created if missing, so the sidebar status panel switches sources together with the hook plugin) +- the `$schema` in the main config `opencode-switchman.jsonc` (local points at the in-repo schema, prod at GitHub main) + +`prod` shares the rewrite/cache-prune logic with the one-shot installer (`scripts/update-cli.mjs`); for long-term production use prefer `npx -y opencode-switchman@latest`. + +## Release highlights + +User-facing summaries per release; the complete notes and migration guides live in [CHANGELOG.md](../CHANGELOG.md). + +### v1.x — deterministic context governance & richer overrides (post-1.0.0) + +- **Shell subagent context hard cap**: every shell subagent session now has a hard context cap (`context.subagentForceTokens`, default 100k tokens) — past the cap every tool call is denied with a wrap-up order, the subagent hands back a detailed progress summary as its task result, and the session can never be resumed via `task_id` (persistent registry). See [Subagent context hard cap](#subagent-context-hard-cap). +- **Always-on per-call read budget (core routing algorithm update)**: the old per-tool one-time nudge (a coupon models rationally burned via retry/probing) is replaced by a deterministic budget gate. Every read is costed against `context.readBudgetTokens` (default 1500) from turn 1 — over-budget reads are auto-bounded or denied with exact bounded-retry params; a per-turn 2× self-read cap (resetting on user turns) stops read chains; un-estimable tool outputs are charged post-hoc. Watermarks keep lifecycle duties only (soft = advice, hard = wrap-up deny, force = auto-handover). Delivery/verification bash (git, test/lint, build) passes at every tier; unbounded archaeology (`git log -p` without `-n`) is denied at every tier with a scoping hint. +- **Per-project language preference**: a per-turn `[LANG]` iron-rule line pins the conversation / comments & commits / docs languages, captured by a first-use ask (re-surfaced at the start of every user turn until configured, and enforced by a hard gate — write/edit/bash/task calls are denied with an ask-first error while the project is unconfigured; the user's decline waives the gate for that session), persisted per project, adjustable via `/switchman-lang`. +- **Todo discipline**: protocol §0.7 plus a per-turn `[TODO]` status line keeps the main session's todo list real-time current (delegated-shell results included). +- **/expert expert consultation** and **bundled agent skills**: dispatch requirements to the strongest cross-family expert; opinionated skills sync into the opencode global skills dir at startup (add/overwrite-only, marker-gated cleanup, fail-open). +- **Review-lane last resort**: with no cross-family read-only shell alive, the chain keeps the best ro shells and same-family review is allowed with a `DOWNGRADED` note instead of an empty chain. +- **Auto-handover robustness**: numbered `[backup]` sessions (survives restarts, never recycles numbers), compaction routed through the same channel as the manual `/compact`, and a detached compaction leg that can no longer deadlock the session. +- **Sidebar version line**: the marquee row shows the running version and, when the update check reports a newer release, the latest version; the blinking `[RESTART NEEDED]` tag now also covers installed-but-not-loaded upgrades. +- **tmux pane mirroring**: every dispatched subagent opens as a live `opencode attach` pane stacked in a right-hand column of the home tmux window — capped visible panes with a FIFO queue, in-place respawn, auto re-evening on completion, and full fail-open safety. See [tmux pane mirroring](#tmux-pane-mirroring-optional). + +### v1.0.0 — English-first stable release + +- English localization across protocol assets, runtime messages, code comments, and docs; banner anchors renamed to `[ROUTES]` / `[WATERMARK]` / `[WATERMARK:SESSION]` / `[LIMITS]` / `[UPDATE]`. +- TUI sidebar layout/color polish: 8-column aligned quota grid, gradient watermark fills over muted tracks, brightened 400-level lane/model palette, collapsed observe-only tags. + +### v0.2.0 — live, capability-aware orchestration + +v0.2.0 evolves switchman from a fixed multi-provider dispatcher into a live, capability-aware orchestration layer. + +- **TUI operations view**: optional sidebar panel for water levels, peak windows, the six lane leaders, restart-required state, and the latest runtime notice. +- **Dynamic activation matrix**: synchronizes desktop visible models and CLI/TUI favorites, falls back to active session models, and refreshes probes immediately when the model surface changes. +- **Capability-aware routing**: dynamically classifies models into capability tiers, keeps stronger tiers ahead of weaker tiers, then uses effort fit, health, water level, peak timing, explicit billing, and unknown-model confidence as transparent tie-breakers. +- **Provider-neutral policy**: any official or custom OpenCode provider can participate. Explicit `billing: "subscription" | "api"` replaces vendor-specific routing preferences. +- **Safer live operations**: real-dispatch isolation, retirement of repeatedly missing models, route-decision audit logs, and clearer restart/update guidance make routing failures observable and self-healing. +- **Simpler configuration and upgrades**: all plugin settings now live in generated `opencode-switchman.jsonc`; legacy tuple options are diagnosed and supported for one compatibility release. `/handover` runs directly (no AI round-trip): it forks the full current session into a `[backup]`-titled backup and compacts the current session in place, staying in the same session (unlike the built-in `/fork`, which switches to the forked session). Crossing the force watermark also fires it automatically (`context.autoHandover`, default on), letting an unfinished task continue on the compacted context. + +## Further documentation + +- [Technical spec (contracts / algorithms / field-test notes)](./2026-08-28-opencode-switchman-technical-design.md) +- Dispatcher rules: bundled in [`src/assets/agents-md.ts`](../src/assets/agents-md.ts) and injected via system prompt (English-only, no manual install needed; the repo's own [AGENTS.md](../AGENTS.md) is a dev-only contribution guide) +- DELEGATION_V1 template: see `delegation-template.md` in the state directory after installation diff --git a/docs/reference.zh.md b/docs/reference.zh.md new file mode 100644 index 0000000..a432398 --- /dev/null +++ b/docs/reference.zh.md @@ -0,0 +1,430 @@ +# opencode-switchman — 完整手册 + +[README](../README.zh.md) · **参考手册(中文)** · English [Reference](./reference.md) + +README 刻意保持简短,其余内容都在这里:安装细节、完整配置项表、手动覆盖命令,以及插件的内部工作原理。 + +**目录** + +- [安装](#安装) +- [配置:opencode-switchman.jsonc](#配置opencode-switchmanjsonc) +- [验证安装](#验证安装) +- [侧边栏状态面板(TUI 插件,可选)](#侧边栏状态面板tui-插件可选) +- [手动覆盖层](#手动覆盖层) +- [核心思想](#核心思想) +- [工作原理](#工作原理) +- [动态激活矩阵](#动态激活矩阵) +- [模型评分引擎](#模型评分引擎) +- [子代理上下文硬顶](#子代理上下文硬顶) +- [工件工作区(.switchman)](#工件工作区switchman) +- [tmux 窗格镜像(可选)](#tmux-窗格镜像可选) +- [模型矩阵维护](#模型矩阵维护) +- [开发与验证](#开发与验证) +- [版本亮点](#版本亮点) +- [延伸文档](#延伸文档) + +## 安装 + +一键安装/更新命令见 [README](../README.zh.md#安装),这里是完整版。 + +### 前置条件 + +- [opencode](https://opencode.ai)——**强烈推荐以 CLI/TUI 为主力界面**(插件的操作面——侧栏状态面板、`/poolConfig` / `/modelRank` 弹窗、实时横幅——在 TUI 里最完整):建议先用 TUI 完成全部配置,之后可自行选择是否换用桌面端体验;两端共享同一份配置与状态 +- 任意 opencode 供应商均可接入,以下三池额外享有额度控制(可任意组合,全部可选): + - **GitHub Copilot**:opencode 内 GitHub 登录(`/connect`)即可 + - **GLM**:自定义 provider(`zhipuai-coding-plan`,baseURL `https://open.bigmodel.cn/api/coding/paas/v4` + apiKey) + - **DeepSeek**:自定义 provider(`deepseek` + apiKey) +- 凭证零配置:插件从 opencode 鉴权层(auth.json / provider options / 环境变量)**只读**获取,不另存密钥、绝不自行刷新 token + +### 让 AI 替你安装 + +AI 时代强烈推荐由 AI 自主完成安装配置——AI 能读取你的真实环境、写入正确的值,并自行验证结果,比手动复制粘贴更不容易出错。把下面这段话直接复制给你当前使用的 AI: + +```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]` 横幅块。 + +三个步骤全部通过才算完成;请汇报你做的改动并给出验证证据。 +``` + +### 安装 / 更新:一键命令实际做了什么 + +两条命令均同时覆盖首次安装与后续更新(幂等,可重复执行):自动把 opencode 配置与 `tui.jsonc` 的 `plugin` 条目改写为最新精确版本 `opencode-switchman@x.y.z`(JSONC 注释原样保留)、清理旧插件缓存(`~/.cache/opencode/packages/opencode-switchman*`),升级场景在横幅标记「已升级待重启」——**重启 opencode 后生效**。 + +插件内升级入口 `/switchman-update` 调用的是同一更新器(旧版直接 `npm install` 的方式对 opencode 实际加载路径无效)。 + +> **为什么条目是精确版本,而不是裸包名 / `@latest`**:opencode ≤1.18.x 的插件缓存按 spec 名固定目录(如 `~/.cache/opencode/packages/opencode-switchman`),首次装入后不再向 npm 查询新版本——裸名与 `@latest` 会一直复用旧缓存(实测从 0.0.1 钉死不升级)。精确版本号每个版本一个独立缓存目录,所以更新器直接改写版本号。 + +### 方式:npm 安装(手动) + +在 opencode 配置(`~/.config/opencode/opencode.json` 或项目 `opencode.json`)中添加: + +```json +{ + "plugin": ["opencode-switchman"] +} +``` + +opencode 启动时会自动经 Bun 安装并加载该 npm 包,无需其他步骤。后续升级请用上面的「一键更新」,或在 opencode 内执行 `/switchman-update`。 + +> **除插件安装外无需改 opencode 配置**:全部插件配置(水位、计费、高峰、阈值、横幅、矩阵、自定义档链等)都在独立文件 `opencode-switchman.jsonc` 中(见下节),首启自动生成、带注释。旧的元组 options(`["opencode-switchman", {...}]` 第二项)已弃用,兼容保留一代(显式值仍优先,`/switchman-doctor` 会提示 SWM044 并建议迁移)。 + +### 方式:源码安装 + +```bash +git clone https://github.com/mrzturn/opencode-switchman.git +cd opencode-switchman +bun install +bun run build # 生成 dist/opencode-switchman.js +``` + +然后二选一: + +**a) 配置引用(推荐,随仓库更新)**——在 opencode 配置的 `plugin` 数组中用 `file://` 指向仓库目录: + +```json +{ + "plugin": ["file:///absolute/path/to/opencode-switchman"] +} +``` + +插件直接加载仓库内的 `dist` 产物;`git pull` 后重跑 `bun run build` 并重启 opencode 即完成升级。此方式与 plugins 目录部署**二选一**,同时使用会双重注入。 + +**b) 部署单文件**——`bun run deploy` 构建并复制到全局插件目录 `~/.config/opencode/plugins/opencode-switchman.js`,自动加载。桌面端内嵌核心跑 Node 运行时,`deploy` 产出的单文件 bundle 即为此设计。 + +> **注意**:`plugin` 数组中的 `file://` 引用与 plugins 目录部署不可并存(同名插件会加载两份);发布 npm 后,把 `file://...` 换成 `"opencode-switchman"` 即可切换为 npm 安装。重启 opencode 生效。 + +> **从旧版(switchman.js)升级**:请删除旧的 `~/.config/opencode/plugins/switchman.js`,避免新旧两份插件同时注入;状态目录已迁移至 `~/.config/opencode/opencode-switchman/`(旧目录可删,全部状态自动重建)。 + +## 配置:opencode-switchman.jsonc + +**除插件安装(opencode 配置的 `plugin` 数组)外,插件全部配置都在独立文件 `opencode-switchman.jsonc`**——首次启动在 OpenCode 配置目录自动生成(优先级:`OPENCODE_CONFIG_DIR`、`$XDG_CONFIG_HOME/opencode`、`~/.config/opencode`),带 `$schema` 编辑器提示与逐键注释,坏值 fail-open 回退缺省;改文件后在 opencode 内重跑一次配置(或重启)即生效,`/switchman-doctor` 可出本地、脱敏且不联网的诊断报告。 + +**providers——供应商策略段**:随包内置稳定键 `deepseek`、`zhipuai-coding-plan`、`github-copilot`(与 opencode 官方 provider ID 一致),且**任意 opencode 官方/自定义 provider 键均合法**——未知键按自定义 provider 处理(通用缺省参与编排;对内置键的近似拼写 doctor 会给 warn 建议)。`observe` 控制配额查询与横幅展示,`enabled` 独立控制水位、高峰和耗尽是否参与路由(默认分别为 `true`、`false`)。`billing` 显式声明计费结构——`subscription`(评分系数 1.0)或 `api`(0.85,同 tier 内沉底);这是计费优先级的唯一来源(不从 models.dev/auth 推断)。`peak` 高峰区间使用 ISO 周日 `1`–`7` 与 `[start,end)` 的 `HH:mm`;出厂缺省 GLM 工作日 14:00–18:00、DeepSeek 工作日 09:00–12:00 与 14:00–18:00。 + +**行为段**(`quota` / `cost` / `capability` / `matrix` / `banner` / `rules` / `lanes`):详见下方「配置项」表——同样只写这一个文件。 + +### 配置项(opencode-switchman.jsonc) + +| 键 | 默认 | 说明 | +|---|---|---| +| `providers.<id>.enabled / observe / billing / peak` | `false / true / 见出厂 / 见出厂` | 供应商策略:路由参与、配额观察、计费结构(subscription=1.0 / api=0.85)、高峰窗口(详见上节) | +| `quota.glmFiveHourReservePct` | `90` | GLM 5 小时窗预留水位(%):达到即硬拦 GLM 壳避免用满 429;周额度仍只认 100% | +| `quota.deepseekLowBalanceWarnCny` | `10` | DeepSeek 余额预警阈值(元):低于该值横幅 [WATERMARK] 提示(仅预警不硬拦,按量计费) | +| `cost.enabled` | `true` | models.dev 计价快照作为加权模型评分的一个系数 | +| `capability.enabled / source / apiKey / tierThresholds / lmarenaCheck` | `true / auto / – / 内置分位 / false` | 动态能力分级:`auto`=有 apiKey 先 Artificial Analysis、失败/无 key 转 OpenRouter;key 也可走环境变量 `ARTIFICIAL_ANALYSIS_API_KEY` | +| `matrix.mode / watch` | `auto / true` | 激活矩阵:`auto` 按宿主自动(desktop=可见模型 / CLI/TUI=favorites),`app`/`tui` 强制指定,`legacy` 旧静态矩阵;`watch`=配置面变化即重算并全量刷新探针(mode/watch 为启动级,重启生效) | +| `banner.enabled` | `true` | 四行横幅注入开关 | +| `rules.enabled / delegationFloor` | `true / 3000` | 调度员规程(AGENTS.md)随包注入开关;`delegationFloor`=自做底价(token),注入规程时插值 | +| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 60000 / 80000 / 120000 / 1500 / true` | **会话上下文水位实测+自读预算闸**:插件从消息 token usage 实测主会话上下文并每轮注入 `[WATERMARK:SESSION]` 行(附每轮增速与距硬水位剩余轮数估算)。自读从第 1 轮起按 `readBudgetTokens` 计费:预估超限的读取自动追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮另有 2× 上限阻断连续读取,无法预估的工具输出事后记账。验证/交付类 bash(git、测试/lint、构建)全水位放行;无界历史翻查(如不带 `-n` 的 `git log -p`)任何水位一律拦截并附收窄提示;超硬水位读取类关闭(收尾模式);超压水位横幅强制立即压缩,且 `autoHandover: true`(默认)时自动触发 `/handover`:完整分叉备份+压缩,未完成的任务在摘要上下文上继续。壳子代理会话不适用本水位,改走自身的单道硬顶(见 `context.subagentForceTokens` / `context.subagentCap`);三档水位在可知时额外以当前会话模型上下文窗口(models.dev)的 90% 封顶 | +| `context.subagentForceTokens / subagentCap` | `100000 / true` | **子代理上下文硬顶**:壳子代理会话只有一道硬顶(实测=最新 assistant 消息的 input + output + reasoning + cache.read,与会话水位同口径),钳制 20k..1M 并额外以壳模型上下文窗口的 90% 封顶。触顶即拒绝该会话所有后续工具调用并下达收尾指令,子代理的下一份纯文本答复(详细的工作进度总结)直接作为任务结果返回委派方,会话永久终止;此后带 `task_id` 恢复该会话的 `task` 调用一律永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响;`subagentCap: false` 只阻止新的终止——已终止的会话不复活 | +| `builtinAgents.mode` | `deny` | 内置 explore/general 与壳路由抢任务且此前放行;`deny`=拦截附 economy/main 改派建议,`allow`=恢复放行 | +| `injection.mode` | `chain` | 壳注入面:`chain`=六档链精选∪favorites/可见集(task 工具描述每会话省约 6-10k token,链外模型点名走 denyUninjected 提示);`all`=可用全集(旧行为)。启动级,重启生效 | +| `dispatch.autoRedirect` | `true` | 派发被拒时在途改写 `subagent_type` 到拒绝消息已点名的链首候选(单跳、同快照守卫复检)——首次派发直接落在最优可用壳上,不再烧「拒绝-重试」轮次;`false` 恢复拒绝-重试 | +| `relay.image` | `true` | 无视觉主模型:用户附带图片自动落盘并替换为路径文本+阅读指引(委托 vision 壳或交给 MCP 视觉工具);本地路径 / http URL 原样透传;全程 fail-open | +| `lang.enabled / ask / candidates` | `true / true / 出厂清单` | 项目级语言偏好:每轮 `[LANG]` 铁律行(会话 / 注释与提交 / 文档),首次询问未完成配置则每轮用户输入重新询问,未配置期间写入/编辑/bash/派发被硬闸门拒绝(拒绝问卷则本会话豁免),落盘 `.switchman/settings.json`(AGENTS.md 标记为只读回退),`/switchman-lang` 重新询问 | +| `lanes` | 内置六档链 | 自定义各档壳链(覆盖内置偏好序);键=economy/mechanical/main/hard/vision/review | +| `workspace.enabled / dirname` | `true / ".switchman"` | 工件工作区:每个主会话自动创建 `<project-root>/.switchman/<yyyy-mm-dd>/<sessionId>-<title>/` 目录,路径每轮注入调度员规程;目录内含 `SESSION.md` / `dispatches.jsonl` / `media/`。关闭后不再创建目录,规程段落同步失效 | +| `tmux.enabled / rightPct / maxPanes / mini` | `true / 60 / 3 / false` | tmux 窗格镜像(仅当 opencode 服务器自身运行在 tmux 中时生效):每条被委派的子代理在主 tmux 窗口右侧列实时打开一个 `opencode attach` 窗格;`rightPct`=右列宽度百分比(10..90,主窗格占其余),`maxPanes`=可见子代理窗格上限(1..4;超出的派发在 FIFO 队列等待),`mini`=用极简 attach 界面取代完整 TUI | + +> **旧元组 options 迁移**:`quota.*.enabled`→`providers.<id>.observe`(SWM042)、`billingWindow.*`→`providers.<id>.peak`(SWM043)、其余行为段(`quota` 阈值/`cost`/`capability`/`matrix`/`banner`/`rules`/`lanes`)→同名 jsonc 段(SWM044);`providers.glm/deepseek`(凭证收集清单)从未实际生效,已删除。元组显式配置兼容一代(值仍优先),下个大版本移除。 + +## 验证安装 + +启动 opencode 后,主模型每轮系统提示中会出现实时横幅(即调度依据): + +``` +[ROUTES] economy: glm-53f-low→glm-47-off→glm-5t-off | mechanical: glm-53f-high→glm-47-off | main: glm-53f-high | hard: glm-53-high | vision: glm-53f-high | review: glm-53-high-ro +[WATERMARK] GLM 5h 10% weekly 38% (refreshed 09-11 10:00) | Copilot credits 0% left (refreshes 2026-10-01) | DeepSeek balance exhausted | advice: ... +[WATERMARK:SESSION] measured session context ~37k (soft 60k/hard 80k/force 100k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 +[LIMITS] down: none | reviewer prefers cross-family (same-family self-review = DOWNGRADED, allowed only when no cross-family reviewer exists) | api-billed & unknown models sink by coefficient (explicit billing=subscription wins) | matrix: cli·watch/ok | manual capability rank: 9 models, task-pool selection: 6 pools active (/modelRank /poolConfig to adjust) +[TODO] 0/6 done · in_progress: 撰写 README 章节 — keep todowrite current (update as each item starts/finishes) +[LANG] conversation=zh-CN comments=en docs=en (source: project settings) — 用会话语言回复与推理;代码注释、提交信息与生成文档各随其设置 +[UPDATE] new version available: /switchman-update or /switchman-ignore +``` + +同时日志可见 `[opencode-switchman] injected N model shells (agents)`——N 随有凭证 provider 的模型面动态变化。六档候选由能力分×档位亲和×计费/未知组系数算法生成,并经 vision/review 结构门过滤,无任何厂商预留席位;运行期再按健康、水位与成本选出当前链首。 + +## 侧边栏状态面板(TUI 插件,可选) + +v0.2.0 在 OpenCode TUI 侧边栏底部新增实时 `switchman` 面板,v1.0.0 又做了全面的排版与配色打磨(并完成英文本地化):各家 provider 的水位以渐变条呈现、对齐到全局 8 列网格(标签、进度条与刷新时间跨块对齐,非零小额配额也保证至少一格填充),带高峰标记、observe-only 折叠标签、六个任务档位当前链首、新增模型/provider 的「需要重启」标记、走马灯行上的版本信息(当前运行版本——本地构建会附上所在提交短 SHA——更新检查发现新版本时以绿色显示 `→ v<最新版>`,本地构建显示 `→ origin/main`;已安装升级待重启时闪烁 `[RESTART NEEDED]` 标记),以及最新一条运行通知。面板每 2 秒轮询本地状态;非横幅 `stderr` 通知不会刷屏或遮挡输入框。这是一套独立的 TUI Slot 插件(`src/tui.tsx`,导出路径 `opencode-switchman/tui`),与 server 端 hook 插件互相独立。 + +> **推荐工作流**:先用 TUI 完成全部配置——选好模型收藏、调好 `/poolConfig` 与 `/modelRank`、盯着侧栏看它路由;之后可自行选择是否换用桌面端(两端共享同一份配置与状态,而弹窗、侧栏、横幅等操作面在 TUI 里最完整)。 + +![Switchman 侧边栏:水位、高峰、任务档位候选与状态通知](assets/tui-sidebar-status.png) + +![OpenCode 模型选择器与 Switchman TUI 集成](assets/tui-model-picker.png) + +TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** 的 `plugin` 数组里加入同一个包 spec(npm 安装或 `opencode plugin <spec>` 会自动完成;只有手改配置或从源码用 `mode:local`/`mode:prod` 时才需要手动确认): + +```json +{ + "plugin": ["opencode-switchman"] +} +``` + +## 手动覆盖层 + +两个手动配置命令让你用配置压过系统默认决策,全部状态落盘、可手改、保存即热加载(mtime 感知,即时生效,侧栏同步刷新)。会话式(AI 交互换算 CLI)版本为同名的 `-chat` 后缀命令。v0.2.5 新增。 + +### /poolConfig —— 任务池选配(手动弹窗;会话式用 /poolConfig-chat) + +- **TUI(/poolConfig)**:弹出选择框(与选模型/思考等级同款交互)——先选任务池(economy / mechanical / main / hard / vision / review),再对全部可用模型上下勾选:选中即参与该池、再选即移出,附能力档标注。快捷项:「全选」与「全部取消」(重建模式——只勾选想保留的几个;一个都没勾就退出则保持原选配不变,清空后第一次勾选即写入新清单)。改动实时落盘并 toast 回执。 +- **非 TUI / 会话内(/poolConfig-chat)**:会话式流程——注入各池选配总览(带池名可看 `[x]/[ ]` 完整清单),回复「main 只留 3 5」「economy 勾 1、取消 2」由 agent 调 `switchman-config.js` 落盘。 +- **语义**:选配=让各任务池的候选模型**体现差异化**(如 economy 只配轻量模型、hard 只配重思考模型)——某池的手动清单**优先于系统默认候选集**,清单内模型仍按能力等级排序推荐;**同一模型可重复参与多个池**;未配置/空清单的池走系统默认决策。「清除配置」=恢复该池系统默认。 +- **配置文件**:`~/.config/opencode/opencode-switchman/pool-config.json`(键=任务池名,值=参与该池的 modelId 数组)。 + +![/poolConfig 第一步——选择任务池,各池显示已参与模型数](assets/tui-pool-config-pools.png) + +![/poolConfig 第二步——按能力档逐个勾选模型,支持全选/全部取消/清除快捷项](assets/tui-pool-config-models.png) + +### /modelRank —— 模型能力排名(手动弹窗;会话式用 /modelRank-chat) + +- **TUI(/modelRank)**:弹窗按有效能力给出单一合并排序——手动条目与基础分模型交错排列;上移/下移会给模型锚定一个介于新上下邻居之间的手动分(一次挪一格,无需把上面的模型全排一遍),另有置顶/移出排名,即时生效。 +- **非 TUI / 会话内(/modelRank-chat)**:会话式流程——注入当前排名与参考排序,回复「把 glm-5.3 排到最前」「清空排名」由 agent 换算 `rank` 命令落盘。 +- **语义**:手动排名**优先于基础能力分**(实时第三方指数 → 内置快照 → 策展表全部让位)——命中模型(含其前缀变体)按排名序位取能力分与 S/A/B/C 档:排名 ≤4 项时依次 S/A/B/C;≥5 项按分位口径(top20% S / 次20% A / 次20% B / 其余 C,与 OpenRouter 序位派生同口径);同档内按序位线性分细排。未排名模型不受影响。排名参与所有决策面:六档链排序、档位亲和、能力等级闸与 deny 改派建议。 +- **配置文件**:`~/.config/opencode/opencode-switchman/capability-rank.json`(`models` 数组顺序=能力降序,#1 最强)。 + +![/modelRank——模型能力排名:手动命中优先于基础能力分](assets/tui-model-rank.png) + +### /expert —— 专家咨询(会话式) + +- 用法:`/expert <你的需求或设计问题>` — 描述会原样传给专家;不带描述时代理会先询问。 +- 行为:把需求派发给当前最强的可用专家——优先 **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」)。 + +## 核心思想 + +### 问题 + +多订阅并存的真实痛点: + +1. **认知错配**:让旗舰模型干扫描清点的杂活,token 花在不该花的地方;让轻量模型做架构设计,返工反而最贵 +2. **水位盲飞**:GLM 5 小时窗耗尽了还在硬撞、Copilot premium 积分月底作废没花完、DeepSeek 余额见底才发现 +3. **单点视角**:复审用同一个模型族自查,盲区相同,审不出问题 +4. **协议松弛**:「让 XX 帮我看看」式委派无结构、无校验,子代理拿到的是含糊任务 + +### 解法:调度员 + 壳矩阵 + 确定性拦截 + +opencode-switchman 把编排拆成三层,各司其职: + +| 层 | 载体 | 职责 | +|---|---|---| +| **认知层** | 主模型(调度员)+ 随包注入的调度员规程 | 任务四维画像(认知强度×机械度×上下文×紧急度)、决定自做还是委派、选档选壳、写 DELEGATION_V1 委派 prompt | +| **执行层** | 「模型×档位」空壳子代理(如 `glm-mx-53-high`) | 只绑定模型与思考档位,角色由委派 prompt 动态赋予(programmer/tester/reviewer 等 14 角色) | +| **确定性层** | 插件本体 | 六闸拦截、ROUTE_META 硬校验、加权模型评分、配额/成本感知选链、探针 / 熔断 / 实调隔离自愈、四行横幅实时注入 | + +**Token 经济学为第一性原则**:返工是最贵的 token。由此派生六档认知分层—— + +| 档位 | 典型角色 | 用什么 | +|---|---|---| +| economy | clerk / scouter 扫描清点 | 最便宜的轻量模型,low→medium→high 档 | +| mechanical | tester / ops 回归与脚本 | 轻量模型,medium→high→xhigh→max 档 | +| main | programmer / uiux / data-analyst | 主力模型,medium→high→xhigh→max 档 | +| hard | planner 架构核心 | 最强模型,high→xhigh→max 档 | +| vision | observer 看图 | 视觉模型,medium→high→xhigh→max 档 | +| review | reviewer / 专家席 审案 | **强制异模型族**(防同族盲区),high→xhigh→max 档 | + +思考档位偏好是独立的一层路由算法:每档按上表偏好序选思考档(首个被支持的档位即默认档);`off` 档只作 lane 级兜底——仅当该档没有思考档候选可用时(如只支持开/关的模型)才进链,绝不排到思考档候选之前。壳在排序前还按能力面划池:review 只从 `ro`(只读)壳池选,其余 lane 只从 `rw` 壳池选,仅当本池为空才跨池兜底。 + +水位只影响排序(用满不浪费),唯一硬拦是「调用必失败」(额度确定耗尽或硬门命中);按量计费(`billing: "api"`)provider 在自动路由中不会被 deny——它们经 0.85 系数在同能力档内沉底,未知 provider 模型经 0.75 惩罚沉底,无需任何厂商专属的链尾席位或 deny 规则。 + +## 工作原理 + +### 生命周期流程 + +```mermaid +flowchart TD + A[opencode 启动] --> B[config 钩子<br/>注入全量壳矩阵到 cfg.agent<br/>+ 凭证收集] + B --> C[后台预热<br/>探针矩阵 / 三池配额 / 计价快照<br/>10min 周期自愈刷新] + C --> D[主模型工作<br/>按调度员规程决策] + D --> E{自做 or 委派?} + E -->|小任务| Z[主模型直接完成] + E -->|委派| F[选档选壳<br/>写 DELEGATION_V1 + ROUTE_META] + F --> G[task 派发<br/>tool.execute.before 拦截] + G --> H{六闸判定} + H -->|放行| I[壳子代理执行] + H -->|deny| J[报错附原因+改派候选<br/>主模型按链改派] + I --> K{执行结果} + K -->|成功| L[摘要回传主模型] + K -->|失败| M[event 钩子记账<br/>classifyFailure + 隔离<br/>600s 窗 ≥2 败 → 熔断 600s] + M --> D + J --> D + D -.每轮 LLM 请求.-> N[system.transform<br/>注入调度员规程 + 四行横幅<br/>路由/水位/限制 实时可见] +``` + +### 六闸拦截(顺序即优先级) + +主模型派发子代理时,插件在 task 工具执行前做确定性校验,任一命中即 deny 并附改派候选: + +| 闸 | 判定 | 语义 | +|---|---|---| +| 1 注册表 | 壳未启用/未探测 | 禁派未注册面 | +| 2 探针矩阵 | 组合实测 down / retired | 拦明确不可用;连续 404 下线消失模型 | +| 3 熔断 / 隔离 | 600s 窗内 ≥2 败或实调隔离中 | 「连续失败熔断中,约 10 分钟自动恢复」/「实调失败后隔离中」 | +| 4 池耗尽 | 配额判定必失败 | 附人读原因(GLM 100% / Copilot 确定耗尽 / DS 欠费) | +| 5 协议 | ROUTE_META 缺失/非法 | deny 附样例与合法值表 | +| 6 语义 | 同族复审 / rw→ro 壳 / 图像→非视觉壳 | 「复审须异族视角」等 | + +ROUTE_META 是嵌在委派 prompt 内的单行协议,六键六值,插件逐字段校验: + +``` +ROUTE_META {"lane":"main","role":"programmer","producer_family":"glm","capability":"rw","modality":"text","source":"auto"} +``` + +### 数据面(全部自动、fail-open) + +- **探针**:对三大额度池发起真实请求探活(其余供应商 fail-open 放行),矩阵落盘(TTL 600s)。配置面变化立即全量刷新;平时由 10 分钟周期自愈。 +- **配额**:GLM monitor / DeepSeek balance / Copilot `copilot_internal/user` 直查,无代理、分层 TTL 缓存。 +- **失败分类**:厂商无关的 `classifyFailure` 归一为 `rate_limit / quota / auth / not_found / server / network / unknown`。探针 429 仅置 `strained`(降权留链);实调 429 不再误置 Copilot 池耗尽,只有 402 或 403 且含 quota 文案才置耗尽。1 小时窗内连续 3 次 404 会自动 retired:链路排除、闸 deny、横幅标注。 +- **实调失败隔离**:探针 ok 但实际委派失败时,combo 进入内存隔离 30 分钟(`rate_limit` 类 10 分钟),所有会话即时感知,重启即清;它与既有 600s 熔断双轨并行。 +- **成本与评分**:models.dev 计价与策展能力分共同进入加权评分;硬门命中的候选先出局再评分。 +- **决策日志**:每次横幅重建把候选链与因子分写入 `state/routing-decisions.jsonl`(环形 200 行)。 +- **横幅**:每轮系统提示注入 `[ROUTES][WATERMARK][LIMITS][UPDATE]` 四行,调度员实时可见。[LIMITS] 行包含下线模型数量与降级标注;[UPDATE] 行在发现新版本时给出升级 / 忽略命令入口。 +- **自更新**:启动检查缓存 24 小时。prod 模式对比 npm registry,可执行 `/switchman-update` 静默升级,随后横幅显示「已升级待重启」并提醒重启;`/switchman-ignore` 仅忽略本会话,重启后恢复提示。local 模式对比 `origin/main`,只提示手动更新并仅注册 `/switchman-ignore`。 +- **fail-open 铁律**:任何钩子异常只写 stderr 绝不阻塞主流程;配额未知不硬拦,熔断、探针与实调隔离互为独立事实源。 + +### 状态目录 + +`~/.config/opencode/opencode-switchman/`:`shells.json`(可选自定义覆盖,缺省用插件内置矩阵)、`model-matrix.json`(探针)、`routing.json`(熔断)、`routing-decisions.jsonl`(200 行评分审计环形日志)、`failures.log`(记账)、`*-quota.json` / `ds-balance.json`(配额缓存)、`costs.json`(计价)、`delegation-template.md`(委派模板全文)。 + +## 动态激活矩阵 + +壳矩阵不再是静态清单,而是运行期动态构建、实时更新: + +- **desktop app** 可见模型与 **CLI/TUI** favorites 双向同步。`mtime` 决定更新方向;同毫秒平局不写任一侧,必要时使用默认 CLI 路径兜底。 +- 两者皆未设置时,自动回退为「当前活跃会话正在使用的模型」;多会话并行取并集,任何会话切换模型,矩阵在下一请求实时跟进。 +- 模型管理 / favorites 变更实时监听(fs.watch + mtime 轮询兜底)。任一配置面变化都会立即重算激活矩阵并触发**全量探针刷新**,不等待 TTL;10 分钟周期刷新继续负责自愈。 +- 新增 provider 实时检测并横幅提示(agent 注册表运行期不可变,对应壳**重启 opencode 后自动纳入**,无需手动维护)。 +- 启动即注入超集壳(有凭证 provider 的全部可对话模型 × models.dev 档位),`matrix.mode=legacy` 可完整回退旧静态矩阵行为。 + +## 模型评分引擎 + +路由现在是显式、可追溯的评分,而不是隐藏偏好序: + +- **base 能力分主导**:策展的 S/A/B/C 能力分按 exact 模型 id → 前缀 → family → global fallback 四路匹配,并记录命中路径。tier 分组不可逆:低档永远压不过高档。 +- **加权系数**:最终分数乘以 `effortFit × health × water × costBias × peak × billingBoost × unknownPenalty`。health 为 `ok=1.0` / `strained=0.6`;water 取两个窗口中更吃紧者,并会在 Copilot 富余且临期时反向提权烧积分;peak 对任意 provider 的高峰窗口做同档 `×0.93` 让位,绝不跨能力级出局。`billingBoost` 只由 `opencode-switchman.jsonc` 显式 `billing` 字段驱动(`subscription=1.0`、`api=0.85`)——编排规则零厂商硬编码;`unknownPenalty=0.75` 施加给精确→前缀→family 全链未命中的未知组模型,同 tier 排已知模型之后。 +- **硬门不参与打分**:down、熔断、池耗尽、retired、实调隔离中的组合先出局再评分。`immediate` 紧急档改按探针延迟排序。 +- **决策日志**:每次横幅重建都会把各档候选与六因子评分写入 `state/routing-decisions.jsonl`,保留 200 行环形日志。 + +## 子代理上下文硬顶 + +主会话享有软/硬/压三档水位+自动交接;被委派的壳子代理会话此前完全没有上下文控制,一路跑过 18 万 token 也无人拦截。现在每个壳子代理会话只有一道硬顶(`context.subagentForceTokens`,默认 100,000 token,钳制 20k..1M,并在可知时额外以壳模型上下文窗口的 90% 封顶),实测口径与会话水位相同:最新 assistant 消息的 input + output + reasoning + cache.read。触顶后,插件拒绝该子代理会话内的所有后续工具调用并下达收尾指令;子代理随后给出的纯文本答复——一份详细的工作进度总结(已完成 / 关键发现含 file:line 证据 / 未完成 / 下一步)——即作为任务结果返回给委派方,会话随即永久终止(终止事件写入状态日志)。合规两侧预先约定:子代理系统提示的壳规则第 6 条(首次触顶拒绝即停止、交回总结),随包调度员规程第 2 节约定编排侧契约(绝不重试已终止的会话;重新派发、只注入所需上下文)。 + +终止是永久且有意的:此后任何通过 `task_id` 恢复该会话的 `task` 调用都会被永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响。理由:子代理是可复现的工人(其规格写在委派 prompt 里),「终止并交回」优于「压缩后续跑」。`context.subagentCap: false` 只阻止新的终止——已终止的会话不复活。 + +由 `opencode-switchman.jsonc` 的 `context.subagentForceTokens`(默认 `100000`)/ `context.subagentCap`(默认 `true`)配置(详见配置项表)。 + +## 工件工作区(.switchman) + +每个主会话(main)创建时,插件都会自动建立项目内目录 `<project-root>/.switchman/<yyyy-mm-dd>/<sessionId>-<title>/`(日期取会话创建当天;标题 slug 段会在会话标题生成或修改时自动重命名)。注入的调度员规程每轮插值该目录路径,方案、实现进度、过程管控笔记、设计文档等中间工件默认落到会话目录,不再散落仓库各处或堆进对话。插件同时在目录内维护以下文件: + +- `SESSION.md` — 会话元数据(id / 标题 / 项目 / 时间戳) +- `dispatches.jsonl` — 每条被放行的任务委派一行 JSON(ts / shell / lane / role / source / redirected) +- `media/` — 视觉委派中转的图片(已从旧全局状态目录迁来,fail-open 兜底) + +由 `opencode-switchman.jsonc` 的 `workspace.enabled` / `workspace.dirname` 配置(默认 `true` / `".switchman"`);关闭后不再创建任何目录,规程中的对应段落同步失效。 + +## tmux 窗格镜像(可选) + +opencode 服务器自身运行在 tmux 中时,每条被委派的子代理会话都会以 `opencode attach <server> -s <session>` 实时窗格打开,在主 tmux 窗口右侧纵向堆叠(主窗格保持左侧份额——默认 40%,子代理列占右侧 60%)。窗口只会在主窗格(服务器启动时所在窗格,即启动时的 `TMUX_PANE`)上切分:你自己的侧边窗格与 tmux 状态栏绝不会被触碰;从其他窗格接入的 TUI 客户端同样能在那里看到这些子代理窗格。 + +![tmux 分屏镜像:主会话居左,子代理实时 pane 竖排居右](assets/tmux-pane-mirroring.png) + +> 开箱即用,无需任何配置。唯一前提:在 tmux 会话中运行 opencode;tmux 之外该功能完全惰性、零副作用。 + +- **可见上限+FIFO**:子代理窗格最多同时可见 3 个(`tmux.maxPanes`,1..4);超出的并发派发在 FIFO 队列中等待,某个可见子代理结束后,排队者原地接管其窗格(原地重生,窗格数不变)。每次完成都会收缩右列并重新均分布局:3→2 均分 → 1 独占右列 → 0 = 只剩主窗格(全宽恢复)。 +- **卫生**:窗格通过 pane 标题标记为 `swm:<agent-name>`;上次崩溃残留的窗格会在插件启动时清扫(kill,按标题前缀或 attach 启动命令匹配)。每次布局操作后都会恢复窗口的活动窗格(焦点保持)。 +- **天生安全**:不在 tmux 中或 `tmux.enabled=false` 时完全惰性;所有 tmux 失败一律 fail-open——只写状态日志,绝不阻塞派发。 +- **观看须知**:该窗格是附加到子代理会话的真实交互式 TUI——不要在里面打字(按键会进入子代理会话)。退出观看窗格只是移除显示,子代理继续运行。 + +由 `opencode-switchman.jsonc` 的可选 `tmux` 段配置(`enabled` / `rightPct` / `maxPanes` / `mini`,默认 `true` / `60` / `3` / `false`)。 + +## 模型矩阵维护 + +默认(`matrix.mode=auto`)矩阵在运行期动态构建:desktop 可见模型与 TUI favorites 自动双向同步,会话模型兜底,任一配置面变化都会触发全量探针重算,无需任何维护;模型临时 down 由探针自愈(每 10 分钟后台刷新,自动进降级/熔断),连续 404 的消失模型会 retired,直到配置面再次变化。 + +超集保底=**opencode 自带免费模型**(OpenCode Zen:models.dev `opencode` provider 下 `-free` 后缀模型+`big-pickle` 特例,且剔除 `status=deprecated` 的已轮换旧模型=「今日可用」集,随目录每 24h 滚动、无需手工维护);目录不可用(无网冷启动)时 fail-open 回退内置静态清单。 + +内置静态矩阵仅作为 `legacy` 模式与离线兜底。如需自定义 legacy 静态面: + +```bash +# 1. 同步权威启用面(opencode 模型管理中打开的模型,每行 provider/model-id) +$EDITOR scripts/visible-models.txt +# 2. 重生成内置矩阵(拉取 models.dev 档位声明) +bun run gen:shells +# 3. 重启 opencode(legacy 模式生效) +``` + +## 开发与验证 + +```bash +bun install +bun test # 行为契约 fixture(META/六闸/选链/评分/熔断/配额/更新) +bunx tsc --noEmit # 类型检查 +bun run build # 重新生成矩阵并打包单文件 bundle +``` + +本地调试与正式包可用幂等脚本一键切换,切换后重启 opencode 生效: + +```bash +bun run mode:local # build + 三处配置切到 file:// 本仓库(仓库根自动推导) +bun run mode:prod # 拉 npm 最新版,切到精确版本条目 + 清旧插件缓存 + 升级横幅 +bun run mode:prod --version 0.2.0 # 指定版本回切(免联网) +``` + +两条命令都会同步三处配置(行级手术保留注释与第三方插件,幂等可重复执行): + +- `opencode.jsonc`/`opencode.json` 与 `tui.jsonc`/`tui.json` 的 `plugin` 数组(tui 缺失自动补建,侧边栏状态面板跟随 hook 插件一起切源) +- 主配置 `opencode-switchman.jsonc` 的 `$schema`(local 指向仓库内 schema,prod 指向 GitHub main) + +`prod` 与一键安装器共用同一套改写/缓存清理逻辑(`scripts/update-cli.mjs`);从源码切换后若要长期使用正式版,仍推荐 `npx -y opencode-switchman@latest`。 + +## 版本亮点 + +分版本的用户向摘要;完整发布说明与升级指南见 [CHANGELOG.md](../CHANGELOG.md)。 + +### v1.x——确定性上下文治理与更强的手动覆盖(1.0.0 之后) + +- **壳子代理上下文硬顶**:每条壳子代理会话现在都有硬性上下文上限(`context.subagentForceTokens`,默认 100k token)——越过上限后每次工具调用都会被拒绝并附收尾指令,子代理以一份详细的进度总结作为任务结果交回主会话,且该会话永远无法再经 `task_id` 续接(持久化注册表)。详见 [子代理上下文硬顶](#子代理上下文硬顶)。 +- **常开逐次调用读预算(核心算法更新)**:用确定性预算闸取代旧的「每工具一次性提醒」(那种优惠券式提醒会被模型用重试/试探理性烧掉)。自第 1 轮起,每次读取都按 `context.readBudgetTokens`(默认 1500)计费——预估超限的读取就地追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮 2× 自读上限(用户发言即重置)阻断连续读取链;无法预估的工具输出事后记账。水位只保留生命周期职责(软=建议、硬=收尾拒绝、压=自动交接)。交付/验证类 bash(git、测试/lint、构建)任何水位放行;无界翻史(不带 `-n` 的 `git log -p`)任何水位拦截并附收窄提示。 +- **项目级语言偏好**:每轮注入 `[LANG]` 铁律行(会话 / 注释与提交 / 文档三种语言),首次使用时询问并按项目落盘(未配置则每轮用户输入都会重新询问,且写入/编辑/bash/派发调用会被硬闸门拒绝并指回问卷;用户明确拒绝则本会话豁免),`/switchman-lang` 可随时修改。 +- **待办纪律**:规程 §0.7 + 每轮 `[TODO]` 状态行,主会话待办实时更新(含委派壳的结果)。 +- **/expert 专家咨询与随包 agent skills**:需求一键派给当前最强跨家族专家;开箱技能启动时同步进 opencode 全局技能目录(只增改不删、标记门控清理、fail-open)。 +- **review 档兜底**:跨家族只读壳全灭时保留最优 ro 壳、允许同族评审并标注 `DOWNGRADED`,不再出现空链。 +- **自动交接健壮性**:`[backup]` 备份自行编号(重启不乱、编号不回收)、压缩走与手动 `/compact` 相同通道、压缩腿异步化不再死锁会话。 +- **侧栏版本行**:走马灯行显示当前运行版本,更新检查发现新版本时同时显示最新版本;闪烁的 `[RESTART NEEDED]` 标记现在也覆盖「已安装升级但未生效」的场景。 +- **tmux 窗格镜像**:opencode 服务器自身跑在 tmux 里时,每条被委派的子代理都会在主 tmux 窗口右侧列以实时 `opencode attach` 窗格打开——可见窗格封顶+FIFO 队列、原地接管、完成即重新均分布局,全程 fail-open。详见 [tmux 窗格镜像](#tmux-窗格镜像可选)。 + +### v1.0.0——英文优先的稳定版 + +- 协议资产、运行期消息、代码注释与文档全面英文化;横幅锚点更名为 `[ROUTES]` / `[WATERMARK]` / `[WATERMARK:SESSION]` / `[LIMITS]` / `[UPDATE]`。 +- TUI 侧栏排版配色打磨:8 列对齐的配额网格、渐变水位条叠于暗色轨道、400 级亮色系、observe-only 折叠标签。 + +### v0.2.0——实时能力感知编排 + +v0.2.0 将 switchman 从固定多供应商调度器升级为实时、能力感知的编排层。 + +- **TUI 运行视图**:可选侧边栏面板集中展示水位、高峰窗口、六档链首、待重启状态和最新运行通知。 +- **动态激活矩阵**:双向同步 desktop 可见模型和 CLI/TUI favorites;未配置时以活跃会话模型兜底;模型面变化即刻重算并刷新探针。 +- **能力感知路由**:运行期动态分级,强模型优先于低级模型;再以档位亲和、健康、水位、高峰、显式计费和未知模型置信度做可追溯的同级排序。 +- **供应商中立策略**:任意 OpenCode 官方或自定义 provider 都可参与;由显式 `billing: "subscription" | "api"` 取代厂商专属路由偏好。 +- **更可靠的在线运行**:新增实调失败隔离、重复缺失模型下线、路由决策审计日志和更清晰的重启/更新提示,让失败可观察、可自愈。 +- **更简单的配置与升级**:全部插件配置统一到自动生成的 `opencode-switchman.jsonc`;旧元组 options 会被诊断,并再兼容一个版本。`/handover` 直接执行(无 AI 往返):把当前完整会话分叉为 `[backup]` 备份并就地压缩当前会话,留在同一会话内(不同于内置 `/fork` 会切到分叉会话)。越过压水位也会自动触发(`context.autoHandover`,默认开启),未完成的任务在压缩后的上下文上继续。 + +## 延伸文档 + +- [技术方案(契约/算法/实测记录)](./2026-08-28-opencode-switchman-technical-design.md) +- 调度员规程:内置于 [`src/assets/agents-md.ts`](../src/assets/agents-md.ts),随包经系统提示自动注入(仅英文,无需手动安装;仓库根目录的 [AGENTS.md](../AGENTS.md) 仅为插件开发指南) +- 委派模板 DELEGATION_V1:安装后见状态目录 `delegation-template.md`