diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d5e617..49429f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes describe user-visible behavior; implementation details remain in the technical specification and commit history. +## [Unreleased] + +### Added + +- **Subagent context hard cap (default 100k tokens)** — a shell subagent whose measured context crosses the cap gets every further tool call denied with a wrap-up order; its next text-only answer (a detailed progress summary) becomes the task result returned to the delegating session, and the session is then permanently terminated — any `task_id` resume is denied, and the registry is persisted in `subagent-cap.json` so termination survives restarts. Fresh dispatches without `task_id` are unaffected. +- **Config** — `context.subagentForceTokens` (default 100000, clamped 20k..1M, window-capped at 90%) and `context.subagentCap` (`true`/`false` master switch). +- **Shell rule 6 pre-arms compliance** — stop on the first cap deny and return the summary; dispatcher protocol §2 documents the orchestrator-side contract (never retry a terminated session). + +- **tmux pane mirroring (`tmux.*`)** — when the opencode server itself runs inside tmux, every dispatched subagent session now opens as a live `opencode attach -s ` pane, stacked in a right-hand column of the home tmux window (default split: main pane 40% / subagent column 60%). At most 3 subagent panes are visible (`tmux.maxPanes`, 1..4); extra concurrent dispatches wait in a FIFO queue and take over a finished pane in place; each completion shrinks the column and re-evens the layout back down to the main pane at full width. Panes are labeled `swm:` via pane title, leftovers from a crashed previous run are swept (killed) at plugin startup, the window's active pane is preserved across layout ops, and `tmux.mini` swaps the full TUI for a minimal attach interface. +- The mirroring only ever splits the pane the server was launched in (`TMUX_PANE` at startup) — user sidebar panes and the tmux status line are never touched — and is fully fail-open: inert outside tmux or when `tmux.enabled=false`, with tmux failures written to the status log only and never blocking dispatch. Note: 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. +- **/poolConfig "Uncheck all" shortcut** — besides "Select all", the per-pool model dialog now offers a one-shot "Uncheck all" (rebuild mode): instead of unchecking models one by one to keep just a few, clear everything in place and check only the ones to keep. While nothing is checked the previous config stays untouched on disk — exiting without any check keeps the pre-clear selection in effect, and the first check after the clear writes the new list. + +### Fixed + +- **Split-screen pane no longer missing when the main session re-invokes a previously used subagent** — a task call carrying `task_id` makes opencode reuse the previous child session instead of creating a new one, so no `session.created` event fires and the pane trigger (which relied entirely on that event) never ran — resume dispatches opened no pane. The plugin now detects the reuse at the allowed dispatch sites, verifies the reused session still exists (a stale `task_id` falls back to a fresh session, which the existing event path covers), and opens/maintains the pane directly; a viewer pane the user closed moments earlier no longer swallows the re-display either. + +- **Vision/review lanes no longer collapse to "all unavailable" when a whole provider dies** — lane base chains allocated their few candidate seats by capability tier only, so when every top-seated combo was genuinely down (e.g. Copilot answering `402 monthly quota exceeded` across the board and DeepSeek in arrears), healthy lower-tier shells (GLM) had been sliced out of the chain in advance and the lanes showed "all unavailable→terminal failure protocol" until quotas recovered, restarts included. Two layers fix it: matrix-down shells are now filtered out **before** seat allocation (health-aware seats, same combo-down verdict the registry uses to mark a shell disabled; unknown/missing verdicts still fail-open), and `computeLane` backfills an otherwise-empty chain once from candidates dropped only by health reasons (matrix-down / disabled / breaker) via a relaxed-gate ranking pass — structural and pool-level gates (modality, capability, pool-config, exhaustion, retirement) still reject, so illegitimate candidates are never resurrected; if nothing structurally valid remains, the lane keeps its `exhausted` status and the terminal failure protocol. +- **Proven-exhausted pools sink out of the chain heads under the observe-only contract** — the health-aware fix above keyed on per-combo matrix verdicts, so a Copilot shell whose combo probed "strained" (429 noise from a dead pool) or was unprobed still took the chain-head seat by tier while the pool itself was provably dead (live case: the mechanical lane headed `copilot-53codex-high` with Copilot's monthly quota exhausted — `has_quota:false`, remaining −2560 — and GLM healthy). Chain selection now consumes a snapshot-driven `poolUnavailable` resolver (the same `glmExhausted`/`copilotExhausted`/`deepseekExhausted` math, deliberately **not** the policy-gated routing flags): shells of a proven-exhausted pool are excluded from base-chain seats and dropped with `reason=pool-unavailable`, and may only re-enter as the chain **tail** via the backfill pass when nothing healthy exists (health-suspect candidates still rank ahead). This is selection only — the six dispatch gates never see the resolver, so observe-only (routing:false) pools keep their no-hard-denial contract; missing quota snapshots fail open. +- **Blinking `[RESTART NEEDED]` in the TUI sidebar** — the restart tag next to the rainbow "switchman" label used to render as static red text that was easy to stop seeing; it now blinks (~600ms on/off off the marquee heartbeat) in bold red while `active-matrix.json.restartRequired` is non-empty, and stays hidden otherwise (fail-open unchanged). + +- **New provider models surface without a restart** — the plugin used to trust its cross-restart provider cache blindly and only refreshed it in the background for the *next* startup, so models a provider added mid-cycle (e.g. a new flagship appearing on GitHub Copilot) stayed missing from the shell matrix, the /modelRank and /poolConfig lists, and kept triggering a false "favorites contain invalid models" banner until a second restart. Now: a cache older than 24h triggers a live provider.list probe before the superset build (cache stays the fail-open fallback), and the background watchdog detects model-list drift against the running superset and rebuilds it in place — manifest, lists, banner and activation view turn consistent immediately. Dispatching the brand-new shells still needs one opencode restart (cfg.agent is injected once — platform constraint), and the status log says so explicitly. + ## [1.0.0] - 2026-09-05 First stable release: the feature surface is complete and the English-first global surface (code, comments, bundled assets, docs, and UI copy) is done — ready for publication beyond the Chinese-language user base. diff --git a/README.md b/README.md index 52ecad7..a843cb7 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,28 @@ If you hold multiple model subscriptions (GitHub Copilot premium credits, Zhipu ## Installation & Usage +### Recommended: let your AI install it for you + +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. + +Just copy the prompt below and paste it to the AI you are currently using, and let it install opencode-switchman for you: + +```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 @@ -134,14 +156,14 @@ Two manual commands let your configuration beat system defaults. All state is pe ### /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. Changes are written through immediately with a toast receipt. +- **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 / clear shortcuts](docs/assets/tui-pool-config-models.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) @@ -164,12 +186,14 @@ Both commands can also be driven directly via the bundled CLI: `node /dist/ ### 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 (once per 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. +- **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 @@ -201,7 +225,8 @@ See the complete, user-facing release notes and migration guide in [CHANGELOG.md | `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; all three thresholds are additionally capped at 90% of the current session model's context window when known (models.dev) | +| `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 | @@ -209,6 +234,7 @@ See the complete, user-facing release notes and migration guide in [CHANGELOG.md | `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 once 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. @@ -241,6 +267,29 @@ For every main session the plugin auto-creates a per-project folder `<project-ro 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 diff --git a/README.zh.md b/README.zh.md index 171b485..2db9be6 100644 --- a/README.zh.md +++ b/README.zh.md @@ -14,6 +14,28 @@ OpenCode 六档壳矩阵编排插件——让主模型成为调度员,把任 ## 安装与使用 +### 推荐方式:让 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)`(注入 N 只模型空壳),且主模型的系统提示中应带有实时 `[ROUTES]/[WATERMARK]/[LIMITS]` 横幅块。 + +三个步骤全部通过才算完成;请汇报你做的改动并给出验证证据。 +``` + ### 前置条件 - [opencode](https://opencode.ai)——**强烈推荐以 CLI/TUI 为主力界面**(插件的操作面——侧栏状态面板、`/poolConfig` / `/modelRank` 弹窗、实时横幅——在 TUI 里最完整):建议先用 TUI 完成全部配置,之后可自行选择是否换用桌面端体验;两端共享同一份配置与状态 @@ -134,14 +156,14 @@ TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** ### /poolConfig —— 任务池选配(手动弹窗;会话式用 /poolConfig-chat) -- **TUI(/poolConfig)**:弹出选择框(与选模型/思考等级同款交互)——先选任务池(economy / mechanical / main / hard / vision / review),再对全部可用模型上下勾选:选中即参与该池、再选即移出,附能力档标注,改动实时落盘并 toast 回执。 +- **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) +![/poolConfig 第二步——按能力档逐个勾选模型,支持全选/全部取消/清除快捷项](docs/assets/tui-pool-config-models.png) ### /modelRank —— 模型能力排名(手动弹窗;会话式用 /modelRank-chat) @@ -164,12 +186,14 @@ TUI 插件没有目录自动发现机制,需要在 **`tui.jsonc`/`tui.json`** ### 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]` 铁律行(会话 / 注释与提交 / 文档三种语言),首次使用每会话询问一次并按项目落盘,`/switchman-lang` 可随时修改。 - **待办纪律**:规程 §0.7 + 每轮 `[TODO]` 状态行,主会话待办实时更新(含委派壳的结果)。 - **/expert 专家咨询与随包 agent skills**:需求一键派给当前最强跨家族专家;开箱技能启动时同步进 opencode 全局技能目录(只增改不删、标记门控清理、fail-open)。 - **review 档兜底**:跨家族只读壳全灭时保留最优 ro 壳、允许同族评审并标注 `DOWNGRADED`,不再出现空链。 - **自动交接健壮性**:`[backup]` 备份自行编号(重启不乱、编号不回收)、压缩走与手动 `/compact` 相同通道、压缩腿异步化不再死锁会话。 +- **tmux 窗格镜像**:opencode 服务器自身跑在 tmux 里时,每条被委派的子代理都会在主 tmux 窗口右侧列以实时 `opencode attach` 窗格打开——可见窗格封顶+FIFO 队列、原地接管、完成即重新均分布局,全程 fail-open(详见 [tmux 窗格镜像](#tmux-窗格镜像可选))。 ### v1.0.0——英文优先的稳定版 @@ -201,7 +225,8 @@ v0.2.0 将 switchman 从固定多供应商调度器升级为实时、能力感 | `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`)任何水位一律拦截并附收窄提示;超硬水位读取类关闭(收尾模式);超压水位横幅强制立即压缩。壳子代理会话豁免;三档水位在可知时额外以当前会话模型上下文窗口(models.dev)的 90% 封顶 | +| `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]` 铁律行(会话 / 注释与提交 / 文档),首次使用每会话询问一次,落盘 `.switchman/settings.json`(AGENTS.md 标记为只读回退),`/switchman-lang` 重新询问 | @@ -209,6 +234,7 @@ v0.2.0 将 switchman 从固定多供应商调度器升级为实时、能力感 | `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`(凭证收集清单)从未实际生效,已删除。元组显式配置兼容一代(值仍优先),下个大版本移除。 @@ -241,6 +267,29 @@ v0.2.0 将 switchman 从固定多供应商调度器升级为实时、能力感 由 `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`)配置(详见配置项表)。 + ## 核心思想 ### 问题 diff --git a/docs/assets/tmux-pane-mirroring.png b/docs/assets/tmux-pane-mirroring.png new file mode 100644 index 0000000..2ae8d97 Binary files /dev/null and b/docs/assets/tmux-pane-mirroring.png differ diff --git a/src/assets/agents-md.ts b/src/assets/agents-md.ts index a7421fe..6b0a9a3 100644 --- a/src/assets/agents-md.ts +++ b/src/assets/agents-md.ts @@ -57,6 +57,7 @@ Goal: <…>; known facts: <…>; relevant paths: <…>; output format: <conclusi 1. Self-contained prompt: goal, known facts and conclusions, file paths, output format; project-level constraints must be written into the prompt (subagents have no guarantee of global AGENTS.md injection). 2. Summaries only: conclusions + file:line, no large verbatim quotes; do not make subagents re-check what you have already verified. 3. Standard orchestration (scale to size): big features scouter (if needed) → planner → reviewer case review → programmer → tester → (core) reviewer re-review; hard-to-locate bugs start with scouter → programmer → tester; ops for operations, data-analyst for data, uiux for UI, clerk for docs (lanes in the table above). +4. Subagent hard cap: a shell subagent whose context reaches the cap is force-terminated — its final output is a detailed progress summary returned to you as the task result, and its session can never be resumed (task_id resume denials are permanent). On such a denial, start a fresh dispatch with a new self-contained prompt re-seeding only the needed context; never retry the dead session. ## 3. Artifact Workspace Task artifacts (plans, implementation progress, process-control notes, design docs, delegation records, intermediate outputs) default to this session's workspace folder: \`{{WORKSPACE_DIR}}/\` — auto-created and maintained by the plugin under the project root (\`.switchman/<yyyy-mm-dd>/<sessionId>-<title>/\`; SESSION.md = session metadata, media/ = relayed images, dispatches.jsonl = dispatch trace). Rules: only final deliverables go to their real project paths; never scatter process documents elsewhere in the repo; never dump long intermediate documents into chat — write a file and cite its relative path. Delegated executors write files only when the prompt names an exact target path inside this workspace, and return relative paths in their report. diff --git a/src/config.ts b/src/config.ts index 1fa9734..7b84b9c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,7 +5,7 @@ import { canonicalKeyOf, defaultProviderConfig, genericProviderDefaults, PROVIDE import type { PeakRange, ProviderKey, ProviderUserConfig } from "./provider-config" import type { CapabilityTierThresholds, Lane, Pool, RoutePolicy, SwitchmanOptions } from "./types" import { DEFAULT_LANG_CANDIDATES } from "./types" -import { DEFAULT_READ_BUDGET_TOKENS, MAX_READ_BUDGET_TOKENS, MIN_READ_BUDGET_TOKENS } from "./context-watch" +import { DEFAULT_READ_BUDGET_TOKENS, MAX_READ_BUDGET_TOKENS, MAX_SUBAGENT_CAP_TOKENS, MIN_READ_BUDGET_TOKENS, MIN_SUBAGENT_CAP_TOKENS } from "./context-watch" export interface ConfigDiagnostic { code: string; level: "error" | "warn" | "info"; path?: string; hint?: string } // [2026-09-04]-[English localization: translate CLI messages and comments; no logic change] @@ -16,7 +16,7 @@ export interface ConfigDiagnostic { code: string; level: "error" | "warn" | "inf export interface UserQuotaConfig { glmFiveHourReservePct: number; deepseekLowBalanceWarnCny: number } export interface UserCapabilityConfig { enabled: boolean; source: "auto" | "artificial-analysis" | "openrouter"; apiKey?: string; tierThresholds?: CapabilityTierThresholds | "quantile"; lmarenaCheck: boolean } export interface UserMatrixConfig { mode: "auto" | "app" | "tui" | "legacy"; watch: boolean } -export interface UserContextConfig { gates: boolean; softTokens: number; hardTokens: number; forceTokens: number; autoHandover: boolean; readBudgetTokens?: number } +export interface UserContextConfig { gates: boolean; softTokens: number; hardTokens: number; forceTokens: number; autoHandover: boolean; readBudgetTokens?: number; subagentForceTokens: number; subagentCap: boolean } export interface UserConfig { version: number providers: Record<string, ProviderUserConfig> @@ -36,16 +36,18 @@ export interface UserConfig { workspace: { enabled: boolean; dirname: string } // [2026-09-05]-[project language preference: conversation/comments/docs language — first-run ask + per-turn [LANG] iron-rule line] lang: { enabled: boolean; ask: boolean; candidates: string[] } + // [2026-09-06]-[tmux pane mirroring: live subagent attach panes in the home tmux window's right column] + tmux: { enabled: boolean; rightPct: number; maxPanes: number; mini: boolean } lanes: Partial<Record<Lane, string[]>> extensions: Record<string, unknown> } export interface LoadedUserConfig { path: string; config: UserConfig; diagnostics: ConfigDiagnostic[]; generated: boolean } -export const DEFAULT_CONTEXT_TOKENS = { soft: 60_000, hard: 80_000, force: 120_000 } as const +export const DEFAULT_CONTEXT_TOKENS = { soft: 60_000, hard: 80_000, force: 120_000, subagentForce: 100_000 } as const export const DEFAULT_DELEGATION_FLOOR = 3_000 /** Factory defaults for behavior sections (fillMissing baseline; only bad-typed values fall back and report SWM037) */ -export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "capability" | "matrix" | "banner" | "rules" | "context" | "builtinAgents" | "injection" | "dispatch" | "relay" | "workspace" | "lang" | "lanes"> { +export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "capability" | "matrix" | "banner" | "rules" | "context" | "builtinAgents" | "injection" | "dispatch" | "relay" | "workspace" | "lang" | "tmux" | "lanes"> { return { quota: { glmFiveHourReservePct: 90, deepseekLowBalanceWarnCny: 10 }, cost: { enabled: true }, @@ -53,13 +55,14 @@ export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "ca matrix: { mode: "auto", watch: true }, banner: { enabled: true }, rules: { enabled: true, delegationFloor: DEFAULT_DELEGATION_FLOOR }, - context: { gates: true, softTokens: DEFAULT_CONTEXT_TOKENS.soft, hardTokens: DEFAULT_CONTEXT_TOKENS.hard, forceTokens: DEFAULT_CONTEXT_TOKENS.force, autoHandover: true, readBudgetTokens: DEFAULT_READ_BUDGET_TOKENS }, + context: { gates: true, softTokens: DEFAULT_CONTEXT_TOKENS.soft, hardTokens: DEFAULT_CONTEXT_TOKENS.hard, forceTokens: DEFAULT_CONTEXT_TOKENS.force, autoHandover: true, readBudgetTokens: DEFAULT_READ_BUDGET_TOKENS, subagentForceTokens: DEFAULT_CONTEXT_TOKENS.subagentForce, subagentCap: true }, builtinAgents: { mode: "deny" }, injection: { mode: "chain" }, dispatch: { autoRedirect: true }, relay: { image: true }, workspace: { enabled: true, dirname: ".switchman" }, lang: { enabled: true, ask: true, candidates: [...DEFAULT_LANG_CANDIDATES] }, + tmux: { enabled: true, rightPct: 60, maxPanes: 3, mini: false }, lanes: {}, } } @@ -179,6 +182,9 @@ export function validateUserConfig(value: unknown): { config: UserConfig; diagno if (typeof tk.autoHandover !== "boolean") bad("context.autoHandover", () => { filled.context.autoHandover = defaults.context.autoHandover }) // [2026-09-05]-[v1 read budget: finite token number clamped to [MIN_READ_BUDGET_TOKENS, MAX_READ_BUDGET_TOKENS]; bad values fall back to the factory default (SWM037)] if (typeof tk.readBudgetTokens !== "number" || !Number.isFinite(tk.readBudgetTokens) || tk.readBudgetTokens < MIN_READ_BUDGET_TOKENS || tk.readBudgetTokens > MAX_READ_BUDGET_TOKENS) bad("context.readBudgetTokens", () => { filled.context.readBudgetTokens = defaults.context.readBudgetTokens }) + // [2026-09-06]-[subagent hard cap: finite token number clamped to [MIN_SUBAGENT_CAP_TOKENS, MAX_SUBAGENT_CAP_TOKENS] + on/off switch; bad values fall back (SWM037)] + if (typeof tk.subagentCap !== "boolean") bad("context.subagentCap", () => { filled.context.subagentCap = defaults.context.subagentCap }) + if (typeof tk.subagentForceTokens !== "number" || !Number.isFinite(tk.subagentForceTokens) || tk.subagentForceTokens < MIN_SUBAGENT_CAP_TOKENS || tk.subagentForceTokens > MAX_SUBAGENT_CAP_TOKENS) bad("context.subagentForceTokens", () => { filled.context.subagentForceTokens = defaults.context.subagentForceTokens }) if (filled.builtinAgents.mode !== "deny" && filled.builtinAgents.mode !== "allow") bad("builtinAgents.mode", () => { filled.builtinAgents.mode = defaults.builtinAgents.mode }) if (filled.injection.mode !== "chain" && filled.injection.mode !== "all") bad("injection.mode", () => { filled.injection.mode = defaults.injection.mode }) // [2026-09-05]-[artifact workspace: enabled boolean + flat directory name (path separators/".."/absolute values rejected, fallback ".switchman")] @@ -191,6 +197,11 @@ export function validateUserConfig(value: unknown): { config: UserConfig; diagno if (typeof filled.lang.enabled !== "boolean") bad("lang.enabled", () => { filled.lang.enabled = defaults.lang.enabled }) if (typeof filled.lang.ask !== "boolean") bad("lang.ask", () => { filled.lang.ask = defaults.lang.ask }) if (!Array.isArray(filled.lang.candidates) || filled.lang.candidates.length === 0 || !filled.lang.candidates.every((c: unknown) => typeof c === "string" && c.trim() === c && !!c.trim() && c.length <= 48)) bad("lang.candidates", () => { filled.lang.candidates = structuredClone(defaults.lang.candidates) }) + // [2026-09-06]-[tmux pane mirroring: enabled/mini booleans; rightPct integer 10..90; maxPanes integer 1..4] + if (typeof filled.tmux.enabled !== "boolean") bad("tmux.enabled", () => { filled.tmux.enabled = defaults.tmux.enabled }) + if (!Number.isInteger(filled.tmux.rightPct) || filled.tmux.rightPct < 10 || filled.tmux.rightPct > 90) bad("tmux.rightPct", () => { filled.tmux.rightPct = defaults.tmux.rightPct }) + if (!Number.isInteger(filled.tmux.maxPanes) || filled.tmux.maxPanes < 1 || filled.tmux.maxPanes > 4) bad("tmux.maxPanes", () => { filled.tmux.maxPanes = defaults.tmux.maxPanes }) + if (typeof filled.tmux.mini !== "boolean") bad("tmux.mini", () => { filled.tmux.mini = defaults.tmux.mini }) if (!["auto", "artificial-analysis", "openrouter"].includes(filled.capability.source)) bad("capability.source", () => { filled.capability.source = defaults.capability.source }) if (filled.capability.apiKey !== undefined && typeof filled.capability.apiKey !== "string") bad("capability.apiKey", () => { filled.capability.apiKey = undefined }) // lanes: each value must be string[]; a single bad value only falls back that lane (rest kept) @@ -259,6 +270,8 @@ export function resolveEffectiveOptions(raw: unknown, cfg: UserConfig): { option workspace: has(o, "workspace") ? { ...cfg.workspace, ...o.workspace } : cfg.workspace, // [2026-09-05]-[project language preference switch: same merge pattern (jsonc baseline, tuple explicit keys override)] lang: has(o, "lang") ? { ...cfg.lang, ...o.lang } : cfg.lang, + // [2026-09-06]-[tmux pane mirroring switches: same merge pattern] + tmux: has(o, "tmux") ? { ...cfg.tmux, ...o.tmux } : cfg.tmux, lanes: has(o, "lanes") ? o.lanes : cfg.lanes, matrix: { mode: has(o.matrix, "mode") ? o.matrix!.mode! : cfg.matrix.mode, @@ -272,7 +285,7 @@ export function resolveEffectiveOptions(raw: unknown, cfg: UserConfig): { option lmarenaCheck: has(o.capability, "lmarenaCheck") ? o.capability!.lmarenaCheck! : cfg.capability.lmarenaCheck, }, } - for (const section of ["cost", "banner", "rules", "lanes", "matrix", "capability", "context", "builtinAgents", "injection", "dispatch", "relay", "workspace", "lang"] as const) if (has(o, section)) legacySections.push(section) + for (const section of ["cost", "banner", "rules", "lanes", "matrix", "capability", "context", "builtinAgents", "injection", "dispatch", "relay", "workspace", "lang", "tmux"] as const) if (has(o, section)) legacySections.push(section) return { options, legacySections } } export function routePolicy(config: UserConfig, legacy?: Partial<Record<Pool, boolean>>): RoutePolicy { diff --git a/src/context-watch.ts b/src/context-watch.ts index dc83eb2..4f0b18d 100644 --- a/src/context-watch.ts +++ b/src/context-watch.ts @@ -132,6 +132,43 @@ export function turnBudgetOf(readBudget: number): number { return readBudget * 2 } +// [2026-09-06]-[subagent hard cap: shell subagent sessions previously had no context control (they could run past 180k +// tokens indefinitely); unlike the main session's three-tier watermark + auto-handover, a subagent is a reproducible +// worker (its spec lives in the delegation prompt), so the correct lifecycle is terminate-and-hand-back: past ONE hard +// cap every tool call in that session is denied with a wrap-up instruction, the model's next text-only answer (the +// detailed progress summary) becomes the task result returned to the delegator, and the session is permanently +// terminated (no task_id resume; fresh dispatches unaffected)] +export const DEFAULT_SUBAGENT_CAP_TOKENS = 100_000 +export const MIN_SUBAGENT_CAP_TOKENS = 20_000 +export const MAX_SUBAGENT_CAP_TOKENS = 1_000_000 + +/** Effective subagent hard cap in tokens (defensive defaults — config validation already guarantees sane values, but + * the plugin-tuple compat shim can bypass it); null = mechanism disabled */ +export function subagentCapOf(context: { subagentCap?: boolean; subagentForceTokens?: number } | undefined): number | null { + if (context?.subagentCap === false) return null + const raw = context?.subagentForceTokens + if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return DEFAULT_SUBAGENT_CAP_TOKENS + return Math.min(MAX_SUBAGENT_CAP_TOKENS, Math.max(MIN_SUBAGENT_CAP_TOKENS, Math.round(raw))) +} + +/** Window clamp shared with the main-session thresholds: never force past 90% of the model's context window */ +export function capByWindow(cap: number, windowTokens?: number): number { + if (typeof windowTokens !== "number" || !Number.isFinite(windowTokens) || windowTokens <= 0) return cap + return Math.min(cap, Math.floor(windowTokens * 0.9)) +} + +const fmtK = (n: number): string => `${Math.round(n / 1000)}k` + +/** Deny text injected as the tool error inside a capped subagent session — doubles as the wrap-up order */ +export function subagentCapDenyMessage(tokens: number, cap: number): string { + return `[opencode-switchman] SUBAGENT CONTEXT CAP REACHED (~${fmtK(tokens)}/${fmtK(cap)} tokens): this session is terminated and all tools are denied. Immediately output your detailed work-progress summary as your final text answer — what was completed, key findings with file:line evidence, what remains, concrete next steps — it is returned to the delegating session as the task result. Do NOT call any more tools: repeated attempts cannot resume you and only waste the return trip.` +} + +/** Deny text for any task call trying to resume a terminated session (task_id = child sessionID) */ +export function subagentResumeDenyMessage(sessionId: string): string { + return `[opencode-switchman] session ${sessionId} was force-terminated at the subagent context cap and can never be resumed (permanent). Start a FRESH dispatch (task call without task_id) with a new self-contained prompt re-seeding only the context the new subagent needs; the terminated session's final progress summary was already returned to you as its task result.` +} + /** Post-hoc charging for tool outputs we could not pre-estimate (bash, glob/grep/list): ~3.5 bytes/token */ export function estimateOutputTokens(outputLength: number): number { return Math.ceil(outputLength / 3.5) diff --git a/src/index.ts b/src/index.ts index 7e61f13..6850369 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,12 +14,14 @@ import { basename, join } from "node:path" import { AGENTS_MD } from "./assets/agents-md" import { DELEGATION_TEMPLATE } from "./assets/delegation-template" import { - loadContext, buildRegistry, loadManifest, laneShells, paths, + loadContext, buildRegistry, loadManifest, laneShells, paths, loadMatrix, cleanExpired, ensureStateDir, stateDir, loadSupersetShells, writeJsonAtomic, appendStatusLog, writeRouteSnapshot, writeQuotaBrief, loadProviderCache, saveProviderCache, nowIso, + providerCacheStale, providerModelsDelta, + loadSubagentCapRegistry, saveSubagentCapRegistry, withPathLock, } from "./state" import { checkShell, noteUnknownAgent, shellLikeName, denyUninjected, builtinAgentDeny, BUILTIN_SUBAGENTS } from "./gates" import { @@ -29,7 +31,8 @@ import { import { READ_CLASS_TOOLS, estimateContextTokens, thresholdsOf, watermarkLevel, budgetGateDecision, estimateReadRange, estimateOutputTokens, readBudgetOf, turnBudgetOf, - capThresholdsByWindow, + capThresholdsByWindow, subagentCapOf, capByWindow, + subagentCapDenyMessage, subagentResumeDenyMessage, } from "./context-watch" import type { ReadEstimate, FileSample, ContextThresholds } from "./context-watch" import { backupSession, compactSession, v1HandoverPort, type HandoverResult } from "./handover-core" @@ -56,6 +59,7 @@ import { classifyFailure } from "./failclass" import { LANE_ORDER, DEFAULT_LANG_CANDIDATES } from "./types" import type { SwitchmanOptions, Lane, LaneResult, Pool, ShellRegEntry, ModelKey } from "./types" import { WorkspaceTracker, DEFAULT_WORKSPACE_DIRNAME, type EnsuredWorkspace } from "./workspace" +import { TmuxPaneManager, serverOriginOf } from "./tmux" import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion } from "./lang-config" import { detectMode, readConfigured, normalizeProviderListResponse } from "./activation" import type { MatrixModeOption } from "./activation" @@ -66,7 +70,7 @@ import { parseRouteMeta } from "./meta" import { relayImageParts } from "./relay" import { syncBundledSkills } from "./skill-sync" import { MatrixManager } from "./matrix-manager" -import { laneBaseChain } from "./lane-policy" +import { laneBaseChain, filterMatrixDownShells, filterPoolUnavailableShells } from "./lane-policy" import { buildShells, loadCatalog, bundledModelIndex, isConversational, toManifestEntry, freeFloorModels, contextWindowOf, @@ -147,9 +151,18 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const conflictNames = new Set<string>() let supersetDefs: ShellDefinition[] = [] let degradedModelCount = 0 + // [2026-09-06]-[model list the current superset was built from: the provider.list watchdog diffs fresh probe results + // against it to detect mid-session model drift (provider added/dropped models) and rebuild the superset manifest] + let lastSupersetModels: string[] = [] // [2026-09-04]-[measured session context watermark: message.updated token usage → main-session (non-shell/non-internal) watermark; // past the line, read-class tools get the tiered gate (nudge first, then hard deny) — turns rules self-reporting into mechanism enforcement] const sessionWatermark = new Map<string, { tokens: number; at: number }>() + // [2026-09-06]-[subagent hard cap: parallel watermark map for DISPATCHED SHELL sessions (the main-session map above + // explicitly excludes them) + the in-process mirror of the persistent termination registry. Past the cap every tool + // call in that session is denied with a wrap-up order (the next text-only answer = progress summary = task result) + // and the session can never be resumed via task_id; fresh dispatches are unaffected] + const shellWatermark = new Map<string, { tokens: number; at: number }>() + const terminatedSessions = new Set<string>() // [2026-09-05]-[v1 read budget: per-turn self-read spend (resets each user turn), watermark sample history for // pace estimation, and last-seen user message id for turn-boundary detection (assistant parentID comparison)] const turnReadUsage = new Map<string, { used: number; at: number }>() @@ -180,6 +193,18 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-05]-[project language preference: per-session first-ask latch (released on capture/session delete); // the config itself is re-read from disk EVERY turn, so "configured = never ask again" holds across restarts] const langAsked = new Set<string>() + // [2026-09-06]-[tmux pane mirroring: dispatched subagent sessions open as live `opencode attach` panes in the home + // tmux window — main pane left / subagent column right (max 3 visible, FIFO replacement on completion); inert + // outside tmux, fail-open everywhere. pendingTask = dispatch intents recorded per main session, consumed by the + // matching child session.created (parentID + agent name) so internal sessions (title/summary) never open panes] + const tmuxPanes = new TmuxPaneManager({ + options: () => options.tmux, + serverOrigin: serverOriginOf((input as any).serverUrl, process.env.OPENCODE_PORT) ?? "", + dir: pluginDirectory, + log: (m) => appendStatusLog(m), + }) + void tmuxPanes.init() + const pendingTask = new Map<string, Array<{ agent: string; at: number }>>() function isShellOrInternalSession(sessionID: string | undefined): boolean { if (!sessionID) return false @@ -188,6 +213,14 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { return /-mx-/.test(agent) || agent === "title" || agent === "compaction" || agent === "summary" } + // [2026-09-06]-[subagent cap scope: true only for DISPATCHED SHELL sessions — skipSystemInjection unions internal + // sessions (title/compaction/summary), which are short-lived and must never be terminated by the cap] + function isShellAgentSession(sessionID: string | undefined): boolean { + if (!sessionID) return false + if (dynamic) return manager?.isShellSession(sessionID) === true + return /-mx-/.test(sessionAgent.get(sessionID) ?? "") + } + function kk(n: number): string { return `${Math.round(n / 1000)}k` } // [2026-09-05]-[v1 read budget helpers: file head sampling for read-cost estimation, per-turn spend bookkeeping, @@ -246,6 +279,41 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } } + // [2026-09-06]-[subagent hard cap: configured cap window-capped at 90% of the shell model's context window (same + // clamp as sessionThresholds; shell sessions record their model key in sessionMsgModel too); null = disabled] + function effectiveSubagentCap(sessionId: string | undefined): number | null { + const base = subagentCapOf(options.context) + if (base === null) return null + try { + const key = sessionId ? sessionMsgModel.get(sessionId) : undefined + const win = key ? contextWindowOf(metaIndexRuntime ?? bundledModelIndex(), key) : undefined + return capByWindow(base, win) + } catch { + return base + } + } + + // [2026-09-06]-[termination persistence: read-merge-write under the state file's path lock so parallel terminations + // (several capped subagents in flight) never clobber each other; bounded at 500 entries, oldest dropped first] + function persistTerminatedSession(sessionId: string, tokens: number, agent: string | undefined): void { + void (async () => { + try { + await withPathLock(paths().subagentCap, async () => { + const reg = loadSubagentCapRegistry() + reg[sessionId] = { at: Date.now(), tokens, ...(agent ? { agent } : {}) } + const ids = Object.keys(reg) + if (ids.length > 500) { + for (const id of ids.sort((a, b) => (reg[a].at ?? 0) - (reg[b].at ?? 0)).slice(0, ids.length - 500)) delete reg[id] + } + saveSubagentCapRegistry(reg) + }) + } catch { /* fail-open: the in-process Set still enforces the cap for this session */ } + })() + } + try { + for (const id of Object.keys(loadSubagentCapRegistry())) terminatedSessions.add(id) + } catch { /* fail-open */ } + /** Mean per-turn context growth from recent watermark samples (positive deltas only, mean of last 5 of last 9) */ function watermarkPace(sessionId: string): { delta: number; turnsToHard: number } | null { const h = wmHistory.get(sessionId) @@ -349,6 +417,13 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { function traceDispatch(sessionID: string | undefined, shellName: string, prompt: unknown, redirected: boolean): void { try { if (!sessionID || isShellOrInternalSession(sessionID)) return + // [2026-09-06]-[tmux pane mirroring: record the dispatch intent; the matching child session.created consumes it] + { + const q = (pendingTask.get(sessionID) ?? []).filter((e) => Date.now() - e.at < 10 * 60_000) + q.push({ agent: shellName, at: Date.now() }) + if (q.length > 8) q.splice(0, q.length - 8) + pendingTask.set(sessionID, q) + } const [meta] = parseRouteMeta(prompt) workspace.traceDispatch(sessionID, { ts: nowIso(), session: sessionID, shell: shellName, @@ -360,6 +435,35 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } catch { /* fail-open */ } } + /** + * [2026-09-06 fix]-[tmux pane mirroring resume: a task call carrying task_id REUSES the previous child session + * (opencode task tool skips sessions.create) — no session.created event fires, so the intent-matching trigger + * never runs and the pane would never (re)open. Verify the reused session exists first: on a stale/unknown + * task_id opencode silently falls back to a FRESH session whose pane still arrives via session.created, and a + * blind pane here would attach to nothing. A lookup error fails open (pane opened anyway — house style; the + * session clearly existed or the model would have no task_id). Called right after every allowed-dispatch + * traceDispatch — never on deny paths] + */ + function noteResumedChild(sessionID: string | undefined, shellName: string, args: unknown): void { + try { + const tid = (args as any)?.task_id + if (!sessionID || isShellOrInternalSession(sessionID) || typeof tid !== "string" || !tid) return + void withTimeout(Promise.resolve( + (pluginClient as any)?.session?.get?.({ path: { id: tid }, query: { directory: pluginDirectory } }), + ), 3_000) + .then((res) => { + // verified missing → opencode will create a fresh session; the session.created path covers that pane + if (res && !(res as any)?.data?.id) return + void tmuxPanes.noteChild(sessionID, tid, shellName) + appendStatusLog(`tmux pane mirroring: resume dispatch ses_${tid.slice(-6)} (${shellName}) — task_id reuse, pane opened directly (no session.created will fire)`) + }) + .catch(() => { + void tmuxPanes.noteChild(sessionID, tid, shellName) + appendStatusLog(`tmux pane mirroring: resume dispatch ses_${tid.slice(-6)} (${shellName}) — session lookup failed, fail-open pane`) + }) + } catch { /* fail-open */ } + } + function clearBannerCache(): void { bannerCache = null } @@ -461,6 +565,69 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } } + /** [2026-09-06]-[superset face build extracted from the config hook: one shared body for startup and the provider.list + * watchdog's model-drift rebuild. Persists shell-superset.json (the /modelRank //poolConfig candidate source) and refreshes + * the closure views (supersetDefs / metaIndexRuntime / degradedModelCount / lastSupersetModels). Deliberately does NOT touch + * cfg.agent — that surface is one-shot (opencode plugin API constraint); the startup path injects shells right after, while + * the watchdog path relies on updateSuperset + a restart hint for dispatch]-[new provider models visible without restart] */ + async function computeSupersetFace( + stateRoot: string, + providerModels: { models: string[]; providers: string[] }, + ): Promise<{ + defs: ShellDefinition[] + supersetModels: string[] + knownProviders: Set<string> + fullShells: number + configured: ReturnType<typeof readConfiguredSafe> + }> { + // [2026-09-06]-[extracted to plugin level, TS aliased narrowing (dynamic) no longer applies; both call sites are dynamic-path + // only (config hook after the !dynamic early return / watchdog scheduled there), so legacy never reaches here] + const configured = readConfiguredSafe(stateRoot, runMode as "desktop" | "cli") + const catalog = await loadCatalog().catch(() => ({ index: {}, status: "none" as const, etag: null })) + const freeFloor = freeFloorModels(catalog.index) + const floorModels = freeFloor.length > 0 + ? freeFloor + : [...new Set(loadManifest().shells.map((s) => `${s.provider}/${s.modelId}`))] + if (freeFloor.length > 0) appendStatusLog(`floor = ${freeFloor.length} OpenCode Zen free models (catalog ${catalog.status})`) + else appendStatusLog(`floor fell back to the static manifest (catalog ${catalog.status}, 0 free models)`) + const realKnownProviders = new Set(providerModels.providers) + const invalidFavoriteModels = configured.models.filter((m) => !realKnownProviders.has(m.slice(0, m.indexOf("/")))) + if (invalidFavoriteModels.length > 0) { + appendStatusLog(`visible set/favorites contain invalid models with unknown provider (provider not connected; ignored, no shells built): ${invalidFavoriteModels.join(", ")}`) + } + const validConfiguredModels = configured.models.filter((m) => realKnownProviders.has(m.slice(0, m.indexOf("/")))) + const supersetModels = [...new Set([...validConfiguredModels, ...providerModels.models, ...floorModels])] + .filter((full) => isConversational(full.slice(full.indexOf("/") + 1))) + .sort() + const metaIndex: Record<string, EffortInfo> = { ...bundledModelIndex(), ...catalog.index } + metaIndexRuntime = metaIndex + let defs = buildShells(supersetModels, metaIndex, { + roAliases: true, degradedFamilyByProvider: true, markDegraded: true, + }) + const fullShells = defs.length + defs = selectInjectableDefs(defs, { + customLanes: (options.lanes as Record<string, readonly string[]> | null) ?? null, + keepModels: options.injection!.mode === "all" ? new Set(supersetModels) : new Set(validConfiguredModels), + preferredModels: new Set(validConfiguredModels.map((m) => m.slice(m.indexOf("/") + 1))), + capabilityOf: (modelId) => baseScoreDynamic(modelId), + billingBoostOf, unknownOf: unknownOfModel, + costOf: (modelId) => costOf(modelId), + }) + degradedModelCount = new Set(defs.filter((d) => d.degraded).map((d) => `${d.provider}/${d.modelId}`)).size + supersetDefs = defs + lastSupersetModels = supersetModels + try { + writeJsonAtomic(paths().shellSuperset, { + generated_at: new Date().toISOString(), + counts: { superset_models: supersetModels.length, shells: defs.length, full_shells: fullShells, degraded: degradedModelCount }, + mode: runMode, + shells: defs.map(toManifestEntry), + }) + } catch { /* fail-open */ } + const knownProviders = new Set<string>([...supersetModels.map((m) => m.slice(0, m.indexOf("/"))), ...providerModels.providers]) + return { defs, supersetModels, knownProviders, fullShells, configured } + } + /** [2026-09-01]-[P3 startup race fix: single attempt with a short timeout (blocks briefly); failure/not-ready throws for the caller's backoff retry]- * single provider.list probe (no retry logic here; retries belong to collectProviderModels's backoff scheduling) */ async function attemptProviderList( @@ -532,6 +699,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { function scheduleProviderListWatchdog( input: { client?: { provider?: { list?: () => Promise<unknown> } } }, knownProviders: ReadonlySet<string>, + stateRoot: string, ): void { const delays = [15_000, 30_000, 60_000] // 3 background rounds, increasing gaps, 105s more in total; process exit ends it naturally, no explicit cancel const run = async () => { @@ -546,6 +714,26 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { appendStatusLog(`provider.list background probe: new provider(s) connected (${fresh.join(", ")}) — restart opencode to complete shell registration`) clearBannerCache() } + // [2026-09-06]-[model-drift heal: when the fresh list differs from the one the current superset was built from + // (a provider added/dropped models mid-session — e.g. a new flagship appearing on Copilot), rebuild the superset + // manifest and the activation view so /modelRank and /poolConfig list the new models without a restart; dispatch of + // the brand-new shells still needs one restart (cfg.agent is one-shot), which the log states explicitly]-[fail-open] + const delta = providerModelsDelta(lastSupersetModels, result.models) + if (delta.added.length > 0 || delta.removed.length > 0) { + try { + const face = await computeSupersetFace(stateRoot, { models: result.models, providers: result.providers }) + manager?.updateSuperset(face.defs, face.knownProviders) + clearBannerCache() + refreshSidebarState() + const drift = [ + delta.added.length > 0 ? `added: ${delta.added.join(", ")}` : null, + delta.removed.length > 0 ? `removed: ${delta.removed.join(", ")}` : null, + ].filter(Boolean).join("; ") + appendStatusLog(`provider.list background probe: model list drifted (${drift}) — superset manifest rebuilt, /modelRank //poolConfig lists updated${delta.added.length > 0 ? "; new shells dispatch after the next opencode restart" : ""}`) + } catch (exc) { + appendStatusLog(`provider.list background probe: superset rebuild failed (kept previous manifest): ${exc}`) + } + } return } catch { /* keep backing off to the next round, fail-open */ } } @@ -633,6 +821,32 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } } + // [2026-09-06]-[pool-exhaustion-aware seats: snapshot-driven "pool is PROVEN exhausted" resolver for chain SELECTION + // (base-chain seat filter + computeLane pool-unavailable drop/backfill-tail). Same exhaustion math as + // quotaExhaustedFlags (glmExhausted/copilotExhausted/deepseekExhausted over the live quota snapshot) but deliberately + // NOT gated by policy.<pool>.routing: under observe-only (routing:false, factory default) pools keep their + // no-hard-denial contract, yet a proven-exhausted pool (e.g. Copilot has_quota=false / remaining<0) must not take + // chain-head seats by tier ahead of live pools. Missing snapshot (observe off) or any error reads false = fail-open + // (no proof, no sinking). SELECTION only — the six dispatch gates never receive this resolver, so no denial path + // changes] + function poolUnavailableOf(): (pool: string) => boolean { + try { + const qv = quotaView(creds as any, { observe: { + glm: policy.glm.observe, + deepseek: policy.deepseek.observe, + copilot: policy.copilot.observe, + } }) + const flags = { + glm: glmExhausted(qv.glm, options.quota!.glm!.fiveHourReservePct)[0], + copilot: copilotExhausted(qv.copilot)[0], + deepseek: deepseekExhausted(qv.deepseek)[0], + } + return (pool: string) => flags[pool as Pool] === true + } catch { + return () => false + } + } + function currentContext() { warmup() const ctx = loadContext(options, creds as any, dynamic ? dynamicManifest() : undefined) @@ -671,8 +885,20 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (!dynamic || !manager) return laneShells(loadContext(options, creds as any), lane) const m = loadManifest() const attrs = new Map<string, { effort: string; capability: string; vision: boolean; pool: string; provider: string; modelId: string; cost: number | null }>() + // [2026-09-06]-[health-aware seats: matrix-down shells are removed BEFORE seat allocation (same "combo down" + // verdict the registry uses to mark a shell disabled), so the capability-tier-only top-4/top-2 seat caps can no + // longer spend every seat on dead combos while healthy lower-tier shells get sliced out — vision/review went + // fully empty when a whole provider answered 402 and the seated shells all probed down. Unknown/missing combos + // fail-open (kept). [pool-exhaustion-aware seats: shells of a PROVEN-exhausted pool (snapshot-driven, observe-only + // safe) are excluded from seats the same way — a "strained" 429 combo inside a dead pool must not outrank live + // pools by tier (live mechanical head was copilot-53codex-high while Copilot monthly quota was exhausted)]] + // -[impact: dynamic lane base chains; static/custom lanes untouched] + const comboStatusOf = (matrixKey: string): string | null => { + const st = loadMatrix()?.combos?.[matrixKey]?.status + return typeof st === "string" ? st : null + } // [2026-08-29]-[failure classification: dynamic filters retired-model shells first, so models 404ing continuously never re-enter redirect candidates] - for (const s of filterRetiredShells((dynamicManifest() ?? m).shells)) { + for (const s of filterPoolUnavailableShells(filterMatrixDownShells(filterRetiredShells((dynamicManifest() ?? m).shells), comboStatusOf), poolUnavailableOf())) { attrs.set(s.name, { effort: s.effort, capability: s.capability, vision: s.vision, pool: String(s.pool), provider: s.provider, modelId: s.modelId, cost: costOf(s.modelId) }) } return laneBaseChain(lane, { @@ -732,6 +958,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { preferredModels: preferredModelIds(), // [2026-09-03]-[task-pool selection: banner recommendation matches each lane's selection list] poolConfig: loadPoolConfig(), + // [2026-09-06]-[pool-exhaustion-aware seats: banner heads with live pools even under observe-only policy] + poolUnavailable: poolUnavailableOf(), }) } catch { /* one lane failing never affects the others */ } } @@ -861,6 +1089,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { glmPeak: extras.glmPeak, states: extras.states as any, poolConfig: loadPoolConfig(), + // [2026-09-06]-[pool-exhaustion-aware seats: lane-head hints point at live pools, same source as the banner] + poolUnavailable: poolUnavailableOf(), } as any, undefined) } catch { return null } } @@ -970,6 +1200,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { states: extras?.states as any, // [2026-09-03]-[deny-postscript candidates never recommend models outside the task-pool selection list (same source as gate 5.5/banner)] poolConfig: loadPoolConfig(), + // [2026-09-06]-[pool-exhaustion-aware seats: redirect hints point at live pools, same source as the banner] + poolUnavailable: poolUnavailableOf(), } as any, agent) } catch { return null @@ -1033,7 +1265,6 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-08-29]-[superset injection: config once (cfg.agent is immutable at runtime) → runtime activation gating] // superset = config surface ∪ all conversational models of credentialed providers ∪ floor models; embedding classes excluded const stateRoot = resolveOpencodeStateRoot() - const configured = readConfiguredSafe(stateRoot, runMode) // [2026-09-01]-[instant startup across restarts: after the first successful provider.list probe, providers/models are cached (written only on // real success, see scheduleProviderListWatchdog/the success branch below); non-first startups build shells straight from the cache, // no longer blocking on the provider.list network race at every restart (the old backoff took up to ~30s) — the cache may lag the @@ -1042,80 +1273,45 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const providerCache = loadProviderCache() let providerModels: { models: string[]; providers: string[]; fellBack: boolean } let usedProviderCache = false - if (providerCache) { + if (providerCache && !providerCacheStale(providerCache)) { providerModels = { models: providerCache.models, providers: providerCache.providers, fellBack: false } usedProviderCache = true appendStatusLog(`provider.list using cross-restart cache (${providerCache.providers.length} providers, cached at ${providerCache.at}); verifying additions in background`) + } else if (providerCache) { + // [2026-09-06]-[stale cache no longer trusted blindly: provider model lists grow over time (new flagship models), and + // the old "cache first, heal next restart" flow locked brand-new models out of the injected surface until a second + // restart. A cache past TTL (or with an unparseable timestamp) now triggers a live probe (full backoff budget) before + // the superset build; on probe failure the stale cache is still used (fail-open) and the background watchdog keeps + // retrying]-[new provider models surface in the same restart] + appendStatusLog(`provider.list cache stale (cached at ${providerCache.at}), probing live before the superset build`) + const live = await collectProviderModels(input, cfg) + if (!live.fellBack) { + providerModels = live + saveProviderCache({ at: nowIso(), models: live.models, providers: live.providers }) + } else { + providerModels = { models: providerCache.models, providers: providerCache.providers, fellBack: false } + usedProviderCache = true + } } else { providerModels = await collectProviderModels(input, cfg) if (!providerModels.fellBack) saveProviderCache({ at: nowIso(), models: providerModels.models, providers: providerModels.providers }) } - const catalog = await loadCatalog().catch(() => ({ index: {}, status: "none" as const, etag: null })) - // [2026-09-01]-[floor source change: opencode's bundled free models (OpenCode Zen, models.dev opencode provider - // -free ∪ big-pickle special case, 24h rolling) take priority; catalog unavailable (offline cold start) fail-open falls back to the static manifest] - const freeFloor = freeFloorModels(catalog.index) - const floorModels = freeFloor.length > 0 - ? freeFloor - : [...new Set(loadManifest().shells.map((s) => `${s.provider}/${s.modelId}`))] - if (freeFloor.length > 0) appendStatusLog(`floor = ${freeFloor.length} OpenCode Zen free models (catalog ${catalog.status})`) - else appendStatusLog(`floor fell back to the static manifest (catalog ${catalog.status}, 0 free models)`) - // [2026-09-01]-[hardening: configured (visible set/favorites) used to be merged into supersetModels blindly; dirty favorites (e.g. accidentally - // favoriting "provider/not-a-model" whose provider is not in the real connected set) would be built by buildShells as real, - // dispatchable-but-doomed shells, and would pollute knownProviders below, distorting computeActivation's "provider known" - // verdict so the dirty data was never detected. Now filter by the real connected provider set first, logging filtered entries - // separately instead of passively promoting them into "seemingly legal" shells] - const realKnownProviders = new Set(providerModels.providers) - const invalidFavoriteModels = configured.models.filter((m) => !realKnownProviders.has(m.slice(0, m.indexOf("/")))) - if (invalidFavoriteModels.length > 0) { - appendStatusLog(`visible set/favorites contain invalid models with unknown provider (provider not connected; ignored, no shells built): ${invalidFavoriteModels.join(", ")}`) - } - const validConfiguredModels = configured.models.filter((m) => realKnownProviders.has(m.slice(0, m.indexOf("/")))) - const supersetModels = [...new Set([...validConfiguredModels, ...providerModels.models, ...floorModels])] - .filter((full) => isConversational(full.slice(full.indexOf("/") + 1))) - .sort() - const metaIndex: Record<string, EffortInfo> = { ...bundledModelIndex(), ...catalog.index } - // [2026-09-04]-[image relay: the same metadata index serves messages.transform runtime vision queries (same source as shell injection)] - metaIndexRuntime = metaIndex - supersetDefs = buildShells(supersetModels, metaIndex, { - roAliases: true, degradedFamilyByProvider: true, markDegraded: true, - }) - // [2026-09-04]-[injection surface mode configurable: chain (default) = six-lane chain curation ∪ favorites/visible set (saves 6-10k - // tokens/session on the task tool description; out-of-chain models called by name go through denyUninjected hinting to enable them - // in model management); all = the full usable set (old behavior, any available model callable). cfg.agent takes effect once; - // changing the config needs a restart] - const injectKeepModels = options.injection!.mode === "all" - ? new Set(supersetModels) - : new Set(validConfiguredModels) - const fullSupersetCount = supersetDefs.length - supersetDefs = selectInjectableDefs(supersetDefs, { - customLanes: (options.lanes as Record<string, readonly string[]> | null) ?? null, - keepModels: injectKeepModels, - preferredModels: new Set(validConfiguredModels.map((m) => m.slice(m.indexOf("/") + 1))), - capabilityOf: (modelId) => baseScoreDynamic(modelId), - billingBoostOf, unknownOf: unknownOfModel, - costOf: (modelId) => costOf(modelId), - }) - degradedModelCount = new Set(supersetDefs.filter((d) => d.degraded).map((d) => `${d.provider}/${d.modelId}`)).size - const { injected, conflicts } = injectShellDefs(cfg, supersetDefs) + // [2026-09-06]-[superset build moved into computeSupersetFace (shared with the watchdog's model-drift rebuild); + // the hook keeps only the one-shot cfg.agent injection]-[single source of truth for the superset build] + const face = await computeSupersetFace(stateRoot, providerModels) + const fullSupersetCount = face.fullShells + const { injected, conflicts } = injectShellDefs(cfg, face.defs) injectedNames.clear() for (const n of injected) injectedNames.add(n) conflictNames.clear() for (const n of conflicts) conflictNames.add(n) - try { - writeJsonAtomic(paths().shellSuperset, { - generated_at: new Date().toISOString(), - counts: { superset_models: supersetModels.length, shells: supersetDefs.length, full_shells: fullSupersetCount, degraded: degradedModelCount }, - mode: runMode, - shells: supersetDefs.map(toManifestEntry), - }) - } catch { /* fail-open */ } - const knownProviders = new Set<string>([...supersetModels.map((m) => m.slice(0, m.indexOf("/"))), ...providerModels.providers]) - // [2026-09-01]-[async fallback: when the in-hook backoff still falls back entirely, or this startup used the cross-restart cache (no live probe), + const knownProviders = face.knownProviders + // [2026-08-29]-[async fallback: when the in-hook backoff still falls back entirely, or this startup used the cross-restart cache (no live probe), // the background keeps probing — a newly seen provider can only be hinted as restart-required (hard cfg.agent one-shot constraint, see // the scheduleProviderListWatchdog comment), but at least "would a restart take effect now" becomes a live, explicit status hint] - if (providerModels.fellBack || usedProviderCache) scheduleProviderListWatchdog(input, knownProviders) + if (providerModels.fellBack || usedProviderCache) scheduleProviderListWatchdog(input, knownProviders, stateRoot) manager = new MatrixManager({ - stateRoot, mode: runMode, superset: supersetDefs, + stateRoot, mode: runMode, superset: face.defs, injectedNames, knownProviders, watchEnabled: options.matrix!.watch === true, onRecompute: (state, newTargets, source) => { @@ -1140,9 +1336,9 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { appendStatusLog(`activation matrix recomputed (gen=${state.generation}, active shells ${state.activeShells.length}, probes ${source}×${targets.length})`) }, }) - manager.recompute(configured) + manager.recompute(face.configured) manager.start() - appendStatusLog(`injected ${injected.size} shells (mode=${runMode}, injection surface=${options.injection!.mode}=${fullSupersetCount}→${supersetDefs.length} after curation, conflicts ${conflicts.size}; activation gating active)`) + appendStatusLog(`injected ${injected.size} shells (mode=${runMode}, injection surface=${options.injection!.mode}=${fullSupersetCount}→${face.defs.length} after curation, conflicts ${conflicts.size}; activation gating active)`) // [2026-08-29]-[config hook triggers the self-update check]-[async check; failure never blocks startup] refreshSelfUpdate().then((state) => { if (state?.outdated) clearBannerCache() }).catch(() => {}) } catch (exc) { @@ -1300,6 +1496,31 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { }, "tool.execute.before": async (input, output) => { + // [2026-09-06]-[subagent hard cap gate, runs before every other gate: (a) any tool inside a terminated shell + // subagent session is denied with a wrap-up order — the model's next text-only answer (detailed progress + // summary) becomes the task result returned to the delegator; (b) any task call resuming a terminated session + // via task_id is rejected permanently (fresh dispatches without task_id are unaffected). subagentCap: false + // prevents NEW terminations only — already-terminated sessions stay dead] + try { + const capSid = (input as any).sessionID as string | undefined + if (capSid && terminatedSessions.has(capSid)) { + denySkip.add(input.callID) + const cap = effectiveSubagentCap(capSid) ?? subagentCapOf(options.context) ?? 0 + appendStatusLog(`subagent context cap: tool '${input.tool}' denied in terminated session ${capSid}`) + throw new Error(subagentCapDenyMessage(shellWatermark.get(capSid)?.tokens ?? cap, cap)) + } + if (input.tool === "task") { + const tid = (output.args as any)?.task_id + if (typeof tid === "string" && tid && terminatedSessions.has(tid)) { + denySkip.add(input.callID) + appendStatusLog(`subagent context cap: resume of terminated session ses_${tid.slice(-6)} denied (permanent)`) + throw new Error(subagentResumeDenyMessage(tid)) + } + } + } catch (e) { + if (denySkip.has(input.callID)) throw e + // internal error on our side (never one of our own denies) → fail-open, do not break the tool path + } // [2026-09-04]-[read watermark gate: read-class/bash tools other than task are intercepted by tier per the measured session watermark] if (input.tool !== "task") { // [2026-09-05]-[no-vision image read guard runs first: image files are skipped by the read budget gate (BINARY_EXT), @@ -1375,6 +1596,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (cand && tryRedirect(cand, output.args?.prompt)) { appendStatusLog(`auto-redirect ${agent} → ${cand} (uninjected shell; redirected to the chain-head candidate)`) traceDispatch(input.sessionID, cand, output.args?.prompt, true) + noteResumedChild(input.sessionID, cand, output.args) return } } @@ -1399,6 +1621,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { output.args.prompt = newPrompt appendStatusLog(`auto-redirect ${agent} → ${cand} (built-in agent blocked; appended a synthetic ROUTE_META)`) traceDispatch(input.sessionID, cand, newPrompt, true) + noteResumedChild(input.sessionID, cand, output.args) return } } @@ -1408,16 +1631,21 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } appendStatusLog(noteUnknownAgent(agent)) traceDispatch(input.sessionID, agent, output.args?.prompt, false) + noteResumedChild(input.sessionID, agent, output.args) return } const r = checkShell(agent, shell, output.args?.prompt, gateSnap) if (r.note) appendStatusLog(r.note) - if (!r.deny) traceDispatch(input.sessionID, agent, output.args?.prompt, false) + if (!r.deny) { + traceDispatch(input.sessionID, agent, output.args?.prompt, false) + noteResumedChild(input.sessionID, agent, output.args) + } if (r.deny) { // [2026-09-04]-[autoRedirect: denied and a hint candidate is already computed → one-hop silent redirect (guard re-check), zero retries] if (tryRedirect(r.redirect, output.args?.prompt)) { appendStatusLog(`auto-redirect ${agent} → ${r.redirect} (${r.deny.slice(0, 60)})`) traceDispatch(input.sessionID, r.redirect ?? agent, output.args?.prompt, true) + noteResumedChild(input.sessionID, r.redirect ?? agent, output.args) return } // [2026-09-04]-[autoRedirect: gate 6 META invalid — synthesize a ROUTE_META at the prompt tail for non-review lanes and re-check the same @@ -1434,6 +1662,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { output.args.prompt = newPrompt appendStatusLog(`auto-redirect ${agent} (added ROUTE_META, ${lane} lane)`) traceDispatch(input.sessionID, agent, newPrompt, true) + noteResumedChild(input.sessionID, agent, output.args) return } } @@ -1544,9 +1773,29 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { else sessionAgent.set(info.id, info.agent) // [2026-09-05]-[artifact workspace: registered AFTER the agent classification above (shell/internal sessions excluded)] noteWorkspaceSession((event as any).properties?.info) + // [2026-09-06]-[tmux pane mirroring: a child session (parentID set) whose agent matches a recorded dispatch + // intent opens as a live attach pane; internal sessions (title/summary/compaction) never match and are ignored. + // task_id RESUME dispatches reuse the child session and never fire session.created — noteResumedChild at the + // allowed dispatch sites covers them] + const childParent = (event as any).properties?.info?.parentID + if (typeof childParent === "string" && childParent) { + const q = pendingTask.get(childParent) + const idx = q ? q.findIndex((e) => e.agent === info.agent) : -1 + if (q && idx >= 0) { + q.splice(idx, 1) + if (!q.length) pendingTask.delete(childParent) + void tmuxPanes.noteChild(childParent, info.id, info.agent) + } + } } return } + // [2026-09-06]-[tmux pane mirroring: child session loop finished → promote a queued child or shrink the column] + if (event.type === "session.idle") { + const sid = (event as any).properties?.sessionID + if (typeof sid === "string" && tmuxPanes.tracking(sid)) void tmuxPanes.noteChildEnd(sid) + return + } // [2026-09-05]-[artifact workspace: session.updated carries the generated/edited title → record + ensure // (title rename guarded inside the tracker; steady-state updates do no IO)] if (event.type === "session.updated") { @@ -1585,6 +1834,26 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { turnReadUsage.delete(sid) } } + } else if (typeof sid === "string" && isShellAgentSession(sid) && info?.role === "assistant") { + // [2026-09-06]-[subagent hard cap: shell sessions get a parallel watermark; on first crossing of the + // window-capped cap the session is terminated — every later tool call is denied with a wrap-up order + // (the next text-only answer = detailed progress summary = task result) and task_id resumes are + // permanently rejected via the persistent registry. Internal sessions (title/summary) never land here.] + const am = info as { modelID?: unknown; providerID?: unknown } + if (typeof am.modelID === "string" && typeof am.providerID === "string") { + sessionMsgModel.set(sid, `${am.providerID}/${am.modelID}`) + } + const est = estimateContextTokens(info) + if (est !== null) { + shellWatermark.set(sid, { tokens: est, at: Date.now() }) + const cap = effectiveSubagentCap(sid) + if (cap !== null && est >= cap && !terminatedSessions.has(sid)) { + terminatedSessions.add(sid) + const agentName = dynamic ? manager?.sessionAgentName(sid) : sessionAgent.get(sid) + persistTerminatedSession(sid, est, agentName) + appendStatusLog(`subagent context cap: session ${sid}${agentName ? ` (${agentName})` : ""} reached ~${Math.round(est / 1000)}k tokens (cap ${Math.round(cap / 1000)}k) — tools denied, progress summary demanded, session terminated (no task_id resume)`) + } + } } return } @@ -1594,6 +1863,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const sid = sessionDeletedId((event as any).properties) if (sid) { sessionWatermark.delete(sid) + shellWatermark.delete(sid) // [2026-09-06]-[subagent cap watermark follows the same cleanup; terminatedSessions is intentionally NOT cleaned — termination is permanent] turnReadUsage.delete(sid) wmHistory.delete(sid) lastUserMsg.delete(sid) @@ -1601,6 +1871,9 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { sessionTodos.delete(sid) workspace.forget(sid) langAsked.delete(sid) + // [2026-09-06]-[tmux pane mirroring: deleted child frees its pane; deleted main drops its dispatch intents] + if (tmuxPanes.tracking(sid)) void tmuxPanes.noteChildEnd(sid) + pendingTask.delete(sid) if (dynamic && manager?.noteSessionDeleted(sid)) manager.scheduleRecompute(50, "session") } return diff --git a/src/lane-policy.ts b/src/lane-policy.ts index aaeb108..87dd093 100644 --- a/src/lane-policy.ts +++ b/src/lane-policy.ts @@ -235,3 +235,38 @@ export function laneBaseChains(input: Omit<LanePolicyInput, "builtin">, builtinL } return out } + +/** + * [2026-09-06]-[health-aware seats: filter shells whose probe combo verdict is "down" BEFORE lane seat allocation. + * The seat caps in computeLaneChain (primary.slice(0,4) + fallbacks.slice(0,2)) are capability-tier-only, so without + * this pre-filter every seat can land on a dead combo (e.g. a whole provider answering 402) while healthy lower-tier + * shells are sliced out in advance and the lane ends empty at runtime ("all unavailable→terminal failure protocol"). + * Pure: the verdict lookup is injected by the caller, no state-file IO here (same "matrix down" predicate the registry + * uses to mark a shell disabled in state.ts buildRegistry). Unknown/missing verdicts fail-open (kept); "strained" is + * not "down" and stays.]-[impact: dynamic base chains (index.ts baseChainFor) allocate seats to live shells only] + */ +export function filterMatrixDownShells<T extends { matrixKey: string }>( + shells: readonly T[], + comboStatusOf?: (matrixKey: string) => string | null | undefined, +): T[] { + if (!comboStatusOf) return [...shells] + return shells.filter((s) => String(comboStatusOf(s.matrixKey) ?? "").toLowerCase() !== "down") +} + +/** + * [2026-09-06]-[pool-exhaustion-aware seats (sibling of filterMatrixDownShells, same call site): exclude shells whose + * provider pool is PROVEN exhausted (snapshot-driven glmExhausted/copilotExhausted/deepseekExhausted verdict, NOT the + * policy-gated quotaExhaustedFlags) from base-chain SEATS. Without it, combos that probed "strained" (429 noise from a + * dead pool) or "unknown/missing" fail open, outrank healthy pools by tier, and take the lane head — the live + * mechanical chain headed with a Copilot shell while every Copilot call was doomed (monthly quota exhausted). This is + * SELECTION only, not dispatch denial: observe-only (routing:false) pools keep their no-hard-denial contract; the + * shells can still re-enter the chain via the computeLane health-aware backfill tail. Pure: resolver injected, no + * state-file IO here.]-[impact: dynamic base chains never seat a proven-exhausted pool ahead of live pools] + */ +export function filterPoolUnavailableShells<T extends { pool: string }>( + shells: readonly T[], + poolUnavailable?: (pool: string) => boolean, +): T[] { + if (!poolUnavailable) return [...shells] + return shells.filter((s) => !poolUnavailable(String(s.pool))) +} diff --git a/src/lane.ts b/src/lane.ts index 42d0da6..b041f67 100644 --- a/src/lane.ts +++ b/src/lane.ts @@ -255,6 +255,12 @@ export interface ComputeLaneParams { * lane → normalized modelId set participating in that task pool (the same model may join several lanes); a non-empty * list takes effect, missing key/empty = fail-open all models; unselected models after configuration get reason=pool-config] */ poolConfig?: Partial<Record<string, ReadonlySet<string>>> | null + /** [2026-09-06]-[pool-exhaustion-aware seats: snapshot-driven "pool is PROVEN exhausted" resolver (same math as + * glmExhausted/copilotExhausted/deepseekExhausted, NOT the policy-gated quotaExhaustedFlags) — proven-exhausted + * pools sink out of the seats (reason=pool-unavailable) even under observe-only (routing:false) policy, and their + * candidates become tail-backfill-eligible. Absent/throwing = fail-open (no pool sunk). SELECTION only: no dispatch + * denial is derived from this resolver, the six gates stay untouched] */ + poolUnavailable?: (pool: string) => boolean } /** agentDown reference (implemented here to avoid a circular dependency: purely reads the passed-in routing) */ @@ -312,6 +318,11 @@ export function computeLane(lane: Lane, base: string[], p: ComputeLaneParams): L // match, filter only when the list exists and is non-empty, missing key = fail-open all models] const allow = p.poolConfig?.[lane] if (allow && allow.size > 0 && !allow.has(normalizeModelKey(shell.modelId))) reason = "pool-config" + // [2026-09-06]-[pool-exhaustion-aware seats: AFTER pool-config so an explicitly excluded shell keeps its + // non-resurrectable pool-config reason; proven-exhausted-pool shells sink with reason=pool-unavailable and + // become tail-backfill-eligible (unlike the policy-gated pool-exhausted class, which dispatch gates deny and + // which therefore stays non-backfillable)] + else if (p.poolUnavailable?.(String(shell.pool))) reason = "pool-unavailable" } } if (reason) { @@ -384,6 +395,90 @@ export function computeLane(lane: Lane, base: string[], p: ComputeLaneParams): L legacySort(chain, p, glmPeak, immediate) } + // [2026-09-06]-[health-aware backfill: the seat-limited base chain can be wiped out entirely by runtime health gates + // (registry disabled mark from a matrix "down" combo / breaker) while structurally valid candidates exist — the lane + // then reported "all unavailable→terminal failure protocol" even though routing targets were merely unhealthy, and + // deny-redirects had no candidate to name. When the ranked chain is empty, re-rank the candidates that were dropped + // ONLY by health reasons (status-disabled / matrix-down / breaker) once with relaxHealthGates so the lane backfills + // instead of starving; healthy candidates always rank ahead (here the chain was empty, so everything appended is + // backfill by definition). Structural and pool-level gates (modality / capability / pool-config / exhaustion / + // retirement) stay active in the relaxed pass — pool-config-excluded, modality-mismatched, exhausted or retired + // candidates are never resurrected. Still empty → the "exhausted" status and terminal failure protocol are kept as + // today.]-[impact: computeLane never returns an empty chain while a structurally-valid health-dropped candidate + // exists; firstCandidate / deny-redirect postscripts share this same source] + // [2026-09-06 extension]-[pool-unavailable tail: proven-exhausted-pool candidates (reason=pool-unavailable, + // observe-only SELECTION drop) may backfill the chain TAIL when nothing healthy exists — a dead Copilot model as + // last resort is still better than an empty lane. They rank strictly AFTER health-dropped candidates (class order, + // rank order within a class): a merely-suspect shell beats a proven-dead pool. The policy-gated pool-exhausted + // class stays non-backfillable (dispatch gates deny those; backfilling them would only produce guaranteed denies)] + if (chain.length === 0 && regOk && mcombos) { + const healthDrops = new Set(["status-disabled", "matrix-down", "breaker"]) + const classOf = (reason: string): 0 | 1 | null => healthDrops.has(reason) ? 0 : reason === "pool-unavailable" ? 1 : null + const backfillNames = dropped + .map((d) => ({ shell: d.shell, cls: classOf(d.reason) })) + .filter((d): d is { shell: string; cls: 0 | 1 } => d.cls !== null && Boolean(registry![d.shell])) + if (backfillNames.length > 0) try { + const rankables = backfillNames.map(({ shell: name }) => { + const sh = registry![name]! + const entry = mcombos![sh.matrixKey] + return { + key: name, + modelId: sh.modelId, + effort: sh.effort, + pool: sh.pool, + family: sh.family, + capability: sh.capability, + vision: sh.vision, + matrixStatus: String(entry?.status ?? "").toLowerCase() || "missing", + latencyMs: typeof entry?.latency_ms === "number" ? entry.latency_ms : null, + } + }) + const { ranked, breakdowns } = rankCandidates(rankables, { + lane, + immediate, + glmPeak, + water: p.water ?? {}, + routing, + registry, + quotaExhausted: exhausted, + routePolicy: p.routePolicy, + retiredModels: p.retiredModels, + realFailedCombos: p.realFailedCombos, + producerFamily: p.producerFamily, + modality: p.modality, + capability: p.capability, + costs: p.costs, + billingBoostOf: p.billingBoostOf, + peakOf: p.peakOf, + preferredModels: p.preferredModels, + relaxHealthGates: true, + }) + const order = new Map(ranked.map((r, i) => [r.key, i])) + const cls = new Map(backfillNames.map((d) => [d.shell, d.cls])) + // class 0 (health-suspect) ranks ahead of class 1 (proven-exhausted pool); rank order within a class + const appended = [...order.keys()].sort((a, b) => (cls.get(a) ?? 1) - (cls.get(b) ?? 1) || (order.get(a) ?? 0) - (order.get(b) ?? 0)) + for (const name of appended) { + const sh = registry![name]! + const lat = mcombos![sh.matrixKey]?.latency_ms + chain.push({ + shell: name, + pool: sh.pool, + family: sh.family, + effort: sh.effort, + capability: sh.capability, + vision: sh.vision, + latency_ms: typeof lat === "number" ? lat : null, + }) + } + for (const c of chain) { + const bd = breakdowns.get(c.shell) + if (bd) c.score = bd + } + } catch (exc) { + appendStatusLog(`backfill ranking failed (lane stays empty): ${exc}`) + } + } + // [2026-08-31]-[de-vendorization: removed the auto_ok/DS-only gating — api-billed models with source=auto are no // longer hard-blocked, soft-sorted instead by the billingBoost factor; status only distinguishes ok/exhausted (+ fail-open * mark)] let status: string diff --git a/src/matrix-manager.ts b/src/matrix-manager.ts index 262bea6..f85bd17 100644 --- a/src/matrix-manager.ts +++ b/src/matrix-manager.ts @@ -122,6 +122,11 @@ export class MatrixManager { return this.sessions.get(sessionID)?.isShell ?? false } + /** [2026-09-06]-[agent name recorded at session.created/chat.params (subagent-cap termination logs / registry entries)] */ + sessionAgentName(sessionID: string): string | undefined { + return this.sessions.get(sessionID)?.agent + } + /** transform-phase system-injection skip check: shell sessions union internal agents (title/compaction/summary) -- * classified by the agent name in pre-registration/registry, effective from the first turn (session.created pre-registration) */ skipSystemInjection(sessionID: string): boolean { @@ -143,6 +148,26 @@ export class MatrixManager { return [...out].sort() } + /** [2026-09-06]-[watchdog superset rebuild: replace the superset view after a background provider.list refresh detects + * model drift (provider added/dropped models mid-session). shellsByModel/defByName are rebuilt, knownProviders refreshed, + * activation recomputed (sameActivation short-circuits no-op rebuilds). cfg.agent is deliberately untouched — that surface + * is one-shot (opencode plugin API constraint), so newly added shells stay undispatchable until restart; the config + * surfaces (shell-superset.json consumers: /modelRank, /poolConfig, denies, banner) turn consistent immediately]- */ + updateSuperset(defs: readonly ShellDefinition[], knownProviders: ReadonlySet<string>): ActivationState { + this.opts.superset = defs + this.opts.knownProviders = knownProviders + this.shellsByModel.clear() + this.defByName.clear() + for (const d of defs) { + const mk = `${d.provider}/${d.modelId}` as ModelKey + const list = this.shellsByModel.get(mk) ?? [] + list.push(d) + this.shellsByModel.set(mk, list) + this.defByName.set(d.name, d) + } + return this.recompute(undefined, "startup") + } + /** Synchronous recompute: read config surface -> union -> persist; state-equivalence short-circuit (no generation bump/no cache clear) * [2026-08-29]-[fix review-P1 write race: this method is fully synchronous (read-compute-write without await) -> naturally * atomic in-process; the model-matrix.json read-modify-write completes synchronously (in-process atomic); async probe writes diff --git a/src/provider-config.ts b/src/provider-config.ts index ac3ea03..509c3fc 100644 --- a/src/provider-config.ts +++ b/src/provider-config.ts @@ -140,6 +140,14 @@ export function renderDefaultConfigJsonc(): string { // Directory name under the project root (flat name, no path separators). "dirname": ".switchman" }, + // Tmux pane mirroring: dispatched subagent sessions open as live "opencode attach" panes in a right-hand + // column of the home tmux window (main pane left / subagents right; status line untouched). Inert outside tmux. + // "tmux": { + // "enabled": true, // master switch (effective only when the server runs inside tmux) + // "rightPct": 60, // right column width percent (10..90; default 60 = main 40 / right 60) + // "maxPanes": 3, // max visible subagent panes (1..4; extra dispatches wait in a FIFO queue and take over freed panes) + // "mini": false // true = minimal attach interface instead of the full TUI + // }, // Third-party/future extension data goes under namespace keys, not into providers. "extensions": {} } diff --git a/src/scoring.ts b/src/scoring.ts index 6ad5363..804905a 100644 --- a/src/scoring.ts +++ b/src/scoring.ts @@ -181,22 +181,36 @@ export interface RankContext { billingBoostOf?: (provider: string) => number /** [2026-08-31]-[de-vendorization: provider → billing-peak active (any provider's peak config evaluated)] */ peakOf?: (provider: string) => boolean - /** [2026-09-02]-[favorites first: favorite models (by modelId) sort first within the same tier; tiers never invert; + /** [2026-08-31]-[favorites first: favorite models (by modelId) sort first within the same tier; tiers never invert; * no effect under immediate (latency-only ordering)] */ preferredModels?: ReadonlySet<string> | null + /** [2026-09-06]-[pool-exhaustion-aware seats: snapshot-driven "pool is PROVEN exhausted" resolver (same source as + * computeLane's poolUnavailable param) — proven-exhausted-pool shells are gated out of the ranking like other hard + * drops, but are skipped by the relaxHealthGates backfill pass so they can serve as chain-tail last resorts] */ + poolUnavailable?: (pool: string) => boolean + /** [2026-09-06]-[health-aware backfill: when true, the health gates (matrix down / disabled status / breaker / + * real-fail isolation / proven-exhausted pool) are skipped for that single ranking pass, so computeLane can backfill + * a lane whose seated candidates all died at runtime. Structural gates (modality / capability) and the policy-gated + * quota-exhaustion / retirement gates stay active — illegitimate candidates are never resurrected.]-[impact: isGated only] */ + relaxHealthGates?: boolean } /** Hard gates: matrix down (strained is not down) / breaker / exhaustion / retirement / real-call isolation / semantic gates (same source as computeLane) */ function isGated(s: Rankable, ctx: RankContext): boolean { - if (s.matrixStatus === "down") return true + // [2026-09-06]-[health-aware backfill: relaxHealthGates skips only the health-class gates below (matrix down / + // disabled / breaker / real-fail isolation / pool-unavailable); quotaExhausted / retiredModels / modality / + // capability gating is deliberately kept active in the relaxed pass] + const relax = ctx.relaxHealthGates === true + if (!relax && s.matrixStatus === "down") return true const registry = ctx.registry const shell = registry?.[s.key] - if (shell && shell.status !== "enabled") return true + if (!relax && shell && shell.status !== "enabled") return true const down = ctx.routing?.down_agents - if (down && (s.key in down || (shell?.comboKey && shell.comboKey in down))) return true + if (!relax && down && (s.key in down || (shell?.comboKey && shell.comboKey in down))) return true if (shell && ctx.retiredModels?.has(`${shell.provider}/${shell.modelId}`)) return true - if (shell?.comboKey && ctx.realFailedCombos?.has(shell.comboKey)) return true + if (!relax && shell?.comboKey && ctx.realFailedCombos?.has(shell.comboKey)) return true if (shell && ctx.quotaExhausted?.[shell.pool as Pool] && ctx.routePolicy?.[shell.pool as Pool]?.routing !== false) return true + if (!relax && shell && ctx.poolUnavailable?.(String(shell.pool))) return true // [2026-09-05]-[review same-family hard drop removed: family moved from elimination to ordering — cross-family // candidates rank ahead via famClassOf below and a same-family shell is a last-resort DOWNGRADED self-review seat // (denied at the dispatch gate only while a cross-family reviewer exists on the chain)] diff --git a/src/shells.json b/src/shells.json index 69f1602..8fd5df2 100644 --- a/src/shells.json +++ b/src/shells.json @@ -1,6 +1,6 @@ { "_note": "opencode-switchman full matrix: authoritative enabled surface (models enabled in model management, scripts/visible-models.txt) × all declared thinking efforts (models.dev reasoning_options, toggle→off). Generated by scripts/gen-shells.ts — do not edit by hand; after model on/off changes, sync the pin file and re-run bun run gen:shells. The six lane chains are computed from capability score × lane affinity × structural gate × billing factor (api billing 0.85, unknown group 0.75, sunk by coefficient; no vendor-reserved seats).", - "generated_at": "2026-09-05T15:10:02.416Z", + "generated_at": "2026-09-06T14:55:56.419Z", "counts": { "shells": 104, "visible_models": 13 diff --git a/src/shells.ts b/src/shells.ts index 6ac6616..2a31140 100644 --- a/src/shells.ts +++ b/src/shells.ts @@ -51,6 +51,10 @@ export const SHELL_BODY = [ "3. Only do work within the target scope; record out-of-scope issues under \"Remaining Issues\" instead of fixing them opportunistically.", "4. Report truthfully: call a failure a failure, a skip a skip, mark uncertainty as uncertain; write \"verified\" only for what has been verified.", "5. Project AGENTS.md and the delegator's explicit constraints take priority over personal preferences; never output secrets, credentials, or configuration contents under any circumstances.", + // [2026-09-06]-[subagent hard cap pre-arm: the cap itself is enforced by the plugin (every tool call denied past the + // line, session permanently terminated); this rule makes the first deny land immediately instead of after retries. + // Static text — the deny message carries the exact numbers] + "6. Context cap: your shell session is hard-capped (~100k tokens). If a tool call is rejected with a context-cap error, stop calling tools immediately and output your detailed work-progress summary (completed work, key findings with file:line evidence, remaining work, next steps) as your final text answer — it is returned to the delegating session as the task result. Never repeat a denied call.", ].join("\n") /** Single shell → opencode AgentConfig (for config-hook injection) */ diff --git a/src/state.ts b/src/state.ts index fdde570..734bd1d 100644 --- a/src/state.ts +++ b/src/state.ts @@ -38,6 +38,9 @@ export const paths = () => { // replaces the fixed thinking-parameter table probe.ts/shells.ts previously guessed by modelId prefix] copilotThinking: join(dir, "copilot-thinking.json"), shellSuperset: join(dir, "shell-superset.json"), + // [2026-09-06]-[subagent hard cap: persistent registry of force-terminated shell subagent sessions (sessionID → + // {at, tokens, agent}); survives restarts so a terminated session can never be resumed via task_id] + subagentCap: join(dir, "subagent-cap.json"), // [2026-09-01]-[provider.list result cached across restarts: written only on real probe success (not fallback), so next // startup builds shells straight from cache and no longer waits out the provider.list network race on every restart — // new providers are discovered by the background probe, only then is a restart hinted] @@ -271,6 +274,43 @@ export function saveProviderCache(cache: ProviderCache): void { writeJsonAtomic(paths().providerCache, cache) } +// [2026-09-06]-[subagent hard cap registry: sessionID → termination record; broken/missing file = empty registry +// (fail-open — a lost registry only means an already-dead session could be resumed into a fresh cap denial)] +export interface SubagentCapEntry { at: number; tokens: number; agent?: string } +export type SubagentCapRegistry = Record<string, SubagentCapEntry> +export function loadSubagentCapRegistry(): SubagentCapRegistry { + const data = readJson<SubagentCapRegistry>(paths().subagentCap) + if (!data || typeof data !== "object" || Array.isArray(data)) return {} + return data +} +export function saveSubagentCapRegistry(registry: SubagentCapRegistry): void { + writeJsonAtomic(paths().subagentCap, registry) +} + +// [2026-09-06]-[provider cache freshness + model-set delta: the startup stale-cache live probe and the watchdog superset +// rebuild share these pure predicates; provider model lists grow over time (new flagship models), so a cache past TTL (or +// with an unparseable timestamp) must not be trusted blindly]-[pure layer for testability] +export const PROVIDER_CACHE_MAX_AGE_MS = 24 * 3_600_000 +/** Cache age in ms; null when the timestamp is missing/unparseable (callers should treat null as stale) */ +export function providerCacheAgeMs(cache: ProviderCache, now = Date.now()): number | null { + const t = Date.parse(cache.at ?? "") + return Number.isFinite(t) ? now - t : null +} +/** True = do not trust this cache for the superset build (stale past TTL, or timestamp unparseable/missing) */ +export function providerCacheStale(cache: ProviderCache, now = Date.now(), maxAgeMs = PROVIDER_CACHE_MAX_AGE_MS): boolean { + const age = providerCacheAgeMs(cache, now) + return age === null || age > maxAgeMs +} +/** Order-insensitive diff between the model list the current superset was built from and a fresh provider.list result */ +export function providerModelsDelta(builtFrom: readonly string[], fresh: readonly string[]): { added: string[]; removed: string[] } { + const prev = new Set(builtFrom) + const next = new Set(fresh) + return { + added: [...next].filter((m) => !prev.has(m)).sort(), + removed: [...prev].filter((m) => !next.has(m)).sort(), + } +} + export function ensureStateDir(): void { try { mkdirSync(stateDir(), { recursive: true }) diff --git a/src/tmux.ts b/src/tmux.ts new file mode 100644 index 0000000..88fea35 --- /dev/null +++ b/src/tmux.ts @@ -0,0 +1,362 @@ +// [2026-09-06]-[tmux pane mirroring: dispatched subagent sessions become live `opencode attach` panes stacked in +// a right-hand column of the home tmux window. Layout: main pane left (100-rightPct), subagent column right, +// up to maxPanes visible (default 3, evenly stacked); extra dispatches wait in a FIFO queue and take over the +// first freed pane; each completion shrinks the column back (3→2 even halves → 1 full → 0 = main pane alone). +// The window is only ever split at the HOME PANE (never the whole window), so user sidebars and the status line +// stay untouched. Everything is fail-open: any tmux/IO error only logs and never blocks dispatch.] +import { execFile } from "node:child_process" +import type { TmuxOptions } from "./types" + +export interface TmuxResolvedOptions { + enabled: boolean + rightPct: number + maxPanes: number + mini: boolean +} + +/** Pane title marker prefix + start-command sniff used to find our leftovers (restart sweep) */ +export const TMUX_PANE_MARKER = "swm:" + +function shq(s: string): string { + return `'${s.replace(/'/g, "'\\''")}'` +} + +/** Resolve the attach origin from the plugin serverUrl, falling back to the OPENCODE_PORT env; null = not a local http server */ +export function serverOriginOf(serverUrl: unknown, envPort?: string): string | null { + try { + const raw = typeof serverUrl === "string" ? serverUrl : serverUrl instanceof URL ? serverUrl.toString() : "" + if (raw.startsWith("http://127.0.0.1") || raw.startsWith("http://localhost")) { + const u = new URL(raw) + return u.origin + } + } catch { /* fall through */ } + const port = typeof envPort === "string" && /^\d+$/.test(envPort) ? envPort : "" + return port ? `http://127.0.0.1:${port}` : null +} + +/** Pure argv builders (unit-tested without tmux; executed via execFile, no shell on our side) */ +export function splitPaneArgs(o: { target: string; dir: string; axis: "h" | "v"; size: string; before?: boolean }): string[] { + return ["split-window", "-d", "-P", "-F", "#{pane_id}", ...(o.before ? ["-b"] : []), ...(o.axis === "h" ? ["-h"] : ["-v"]), "-l", o.size, "-c", o.dir, "-t", o.target] +} + +export function respawnPaneArgs(o: { target: string; dir: string; command: string }): string[] { + return ["respawn-pane", "-k", "-c", o.dir, "-t", o.target, o.command] +} + +export function killPaneArgs(target: string): string[] { + return ["kill-pane", "-t", target] +} + +export function resizePaneArgs(o: { target: string; height: number }): string[] { + return ["resize-pane", "-t", o.target, "-y", String(Math.max(1, Math.floor(o.height)))] +} + +export function selectPaneArgs(target: string): string[] { + return ["select-pane", "-t", target] +} + +export function setPaneTitleArgs(o: { target: string; title: string }): string[] { + return ["select-pane", "-T", o.title, "-t", o.target] +} + +export function displayFormatArgs(o: { target: string; format: string }): string[] { + return ["display-message", "-p", "-t", o.target, o.format] +} + +export function listPanesArgs(target: string): string[] { + return ["list-panes", "-t", target, "-F", "#{pane_id}\t#{pane_title}\t#{pane_start_command}"] +} + +/** The command each subagent pane runs: a live TUI attached to the running server, opened on the child session */ +export function viewerCommand(o: { origin: string; sessionId: string; dir: string; mini: boolean; bin?: string }): string { + const bin = o.bin && o.bin.trim() ? o.bin.trim() : "opencode" + return `${bin} attach ${o.origin} -s ${o.sessionId}${o.mini ? " --mini" : ""} --dir ${shq(o.dir)}` +} + +export function defaultsOf(o: TmuxOptions | undefined): TmuxResolvedOptions { + return { + enabled: o?.enabled !== false, + rightPct: typeof o?.rightPct === "number" && Number.isInteger(o.rightPct) && o.rightPct >= 10 && o.rightPct <= 90 ? o.rightPct : 60, + maxPanes: typeof o?.maxPanes === "number" && Number.isInteger(o.maxPanes) && o.maxPanes >= 1 && o.maxPanes <= 4 ? o.maxPanes : 3, + mini: o?.mini === true, + } +} + +export interface TmuxPaneManagerDeps { + env?: Record<string, string | undefined> + options: () => TmuxOptions | undefined + serverOrigin: string + dir: string + bin?: string + exec?: (args: string[]) => Promise<string> + log?: (message: string) => void +} + +interface Child { id: string; agent: string; main: string } +interface Slot { pane: string; child: Child } + +/** + * Serialized (promise-chained) tmux pane manager. One instance per plugin process; all mutators enqueue jobs so + * concurrent session events never interleave tmux operations. Inert until init() proves the home pane exists. + */ +export class TmuxPaneManager { + private env: Record<string, string | undefined> + private optionsOf: () => TmuxResolvedOptions + private origin: string + private dir: string + private bin?: string + private exec: (args: string[]) => Promise<string> + private log: (message: string) => void + + private home = "" + private win = "" + private ready = false + private slots: Slot[] = [] + private queue: Child[] = [] + private children = new Map<string, Child>() + private chain: Promise<unknown> = Promise.resolve() + private pollTimer: ReturnType<typeof setInterval> | null = null + + constructor(deps: TmuxPaneManagerDeps) { + this.env = deps.env ?? process.env + this.optionsOf = () => defaultsOf(deps.options()) + this.origin = deps.serverOrigin + this.dir = deps.dir + this.bin = deps.bin + this.exec = + deps.exec ?? + ((args) => + new Promise<string>((resolve, reject) => { + execFile("tmux", args, { timeout: 5_000 }, (err, stdout) => (err ? reject(err) : resolve(String(stdout)))) + })) + this.log = deps.log ?? (() => {}) + } + + /** Probe the home pane + window, sweep leftovers from a previous run; never throws */ + async init(): Promise<void> { + try { + const opts = this.optionsOf() + if (!opts.enabled) return + if (!this.origin) return + if (!this.env.TMUX || !this.env.TMUX_PANE) return + this.home = this.env.TMUX_PANE + this.win = (await this.exec(displayFormatArgs({ target: this.home, format: "#{window_id}" }))).trim() + if (!this.win.startsWith("@")) return + await this.sweepLeftovers() + this.ready = true + } catch (exc) { + this.ready = false + this.log(`tmux pane mirroring disabled (init failed): ${exc instanceof Error ? exc.message : exc}`) + } + } + + /** Kill panes this plugin left behind before a restart (title marker or attach start-command in the home window) */ + private async sweepLeftovers(): Promise<void> { + try { + const out = await this.exec(listPanesArgs(this.home)) + for (const line of out.split("\n")) { + const [pane, title, startCommand] = line.split("\t") + if (!pane || pane === this.home) continue + const ours = (title ?? "").startsWith(TMUX_PANE_MARKER) || /opencode attach -s ses_/.test(startCommand ?? "") + if (ours) await this.exec(killPaneArgs(pane)).catch(() => {}) + } + } catch { /* best effort */ } + } + + tracking(childSessionId: string): boolean { + return this.children.has(childSessionId) + } + + /** A subagent session started (event-driven; job chained so ordering is deterministic) */ + noteChild(mainSessionId: string, childSessionId: string, agent: string): void { + this.children.set(childSessionId, { id: childSessionId, agent, main: mainSessionId }) + this.enqueue(async () => { + if (!this.ready || !this.optionsOf().enabled) return + // [2026-09-06 fix]-[resume re-display: sweep dead panes BEFORE the duplicate check — a user-closed viewer of + // this same child lingers in slots up to one poll period (4s) and would otherwise swallow the re-display] + await this.dropDeadSlots() + if (this.queue.some((c) => c.id === childSessionId) || this.slots.some((s) => s.child.id === childSessionId)) return + await this.displayChild({ id: childSessionId, agent, main: mainSessionId }) + }) + } + + /** A subagent session finished its loop (or was deleted): promote a queued child or shrink the column */ + noteChildEnd(childSessionId: string): void { + this.children.delete(childSessionId) + this.enqueue(async () => { + if (!this.ready) return + const qi = this.queue.findIndex((c) => c.id === childSessionId) + if (qi >= 0) { + this.queue.splice(qi, 1) + return + } + const si = this.slots.findIndex((s) => s.child.id === childSessionId) + if (si < 0) return + const slot = this.slots[si] + const next = this.queue.shift() + if (next) { + // pane count stays at max: the freed pane is respawned with the next queued child + await this.spawnViewer(slot.pane, next) + slot.child = next + } else { + // the ended child's own pane leaves the layout (never kill a pane showing a still-running child) + await this.withFocus(() => this.removeSlot(si)) + } + }) + } + + /** Test/diagnostic snapshot */ + stats(): { ready: boolean; panes: number; queued: number; tracked: number } { + return { ready: this.ready, panes: this.slots.length, queued: this.queue.length, tracked: this.children.size } + } + + /** Awaitable for tests: resolves after every enqueued job so far has settled */ + flush(): Promise<unknown> { + return this.chain + } + + private enqueue(job: () => Promise<void>): void { + this.chain = this.chain + .then(job) + .catch((exc) => this.log(`tmux pane mirroring op failed (continuing): ${exc instanceof Error ? exc.message : exc}`)) + } + + /** Show a child in a new right-column pane (grow by one) or queue it when the column is full */ + private async displayChild(child: Child): Promise<void> { + await this.dropDeadSlots() + const max = this.optionsOf().maxPanes + if (this.slots.length >= max) { + this.queue.push(child) + this.log(`tmux pane mirroring: column full (${this.slots.length} panes), queued ses_${child.id.slice(-6)} (${child.agent})`) + return + } + await this.withFocus(async () => { + const pane = await this.growByOne() + if (!pane) return + this.slots.push({ pane, child }) + await this.spawnViewer(pane, child) + }) + this.syncPoll() + } + + private async growByOne(): Promise<string> { + const opts = this.optionsOf() + if (this.slots.length === 0) { + const out = await this.exec(splitPaneArgs({ target: this.home, dir: this.dir, axis: "h", size: `${opts.rightPct}%` })) + return out.trim() + } + const last = this.slots[this.slots.length - 1].pane + const out = await this.exec(splitPaneArgs({ target: last, dir: this.dir, axis: "v", size: "50%" })) + const pane = out.trim() + // keep the column visually even: after the split, pull the top pane down to 1/N of the column height + const n = this.slots.length + 1 + if (n >= 3) { + // [2026-09-06]-[live-test fix: the new pane is not in this.slots yet (pushed by the caller after this returns), + // so measure it explicitly — without it total under-counts and the top pane resize lands on a wrong height] + const heights = await this.measureAll() + const newH = Number((await this.exec(displayFormatArgs({ target: pane, format: "#{pane_height}" }))).trim()) + const total = heights.reduce((a, b) => a + b, 0) + (Number.isFinite(newH) && newH > 0 ? newH : 0) + if (total > 0 && this.slots.length > 0) { + await this.exec(resizePaneArgs({ target: this.slots[0].pane, height: Math.floor(total / n) })).catch(() => {}) + } + } + return pane + } + + /** + * Remove one slot from the layout: kill its pane (space merges into the sibling), then re-even the survivors + * (3→2 halves, 4→3 thirds, ...). 1 or 0 remaining panes need no geometry. Called inside withFocus. + */ + private async removeSlot(si: number): Promise<void> { + const slot = this.slots[si] + this.slots.splice(si, 1) + if (await this.paneExists(slot.pane)) await this.exec(killPaneArgs(slot.pane)).catch(() => {}) + if (this.slots.length >= 2) { + const total = (await this.measureAll()).reduce((a, b) => a + b, 0) + if (total > 0) { + await this.exec(resizePaneArgs({ target: this.slots[0].pane, height: Math.floor(total / this.slots.length) })).catch(() => {}) + } + } + if (this.slots.length === 0) this.log("tmux pane mirroring: all subagent panes closed, main pane restored") + this.syncPoll() + } + + /** Spawn the attach viewer into a pane and label it */ + private async spawnViewer(pane: string, child: Child): Promise<void> { + const opts = this.optionsOf() + const cmd = viewerCommand({ origin: this.origin, sessionId: child.id, dir: this.dir, mini: opts.mini, bin: this.bin }) + await this.exec(respawnPaneArgs({ target: pane, dir: this.dir, command: cmd })) + await this.exec(setPaneTitleArgs({ target: pane, title: `${TMUX_PANE_MARKER}${child.agent}` })).catch(() => {}) + this.log(`tmux pane mirroring: ses_${child.id.slice(-6)} (${child.agent}) displayed in pane ${pane}`) + } + + /** Drop slots whose pane vanished (viewer exited / user killed the pane); queued children then backfill */ + private async dropDeadSlots(): Promise<void> { + let dropped = false + for (const slot of [...this.slots]) { + if (!(await this.paneExists(slot.pane))) { + this.slots = this.slots.filter((s) => s !== slot) + dropped = true + } + } + if (dropped) { + this.log("tmux pane mirroring: detected closed pane(s), reconciling layout") + while (this.slots.length < this.optionsOf().maxPanes && this.queue.length > 0) { + const next = this.queue.shift() + if (next) await this.displayChild(next) + } + if (this.slots.length === 0) this.log("tmux pane mirroring: all subagent panes closed, main pane restored") + } + } + + private async paneExists(pane: string): Promise<boolean> { + try { + const out = await this.exec(displayFormatArgs({ target: pane, format: "#{pane_id}" })) + return out.trim() === pane + } catch { + return false + } + } + + private async measureAll(): Promise<number[]> { + const heights: number[] = [] + for (const slot of this.slots) { + try { + const h = Number((await this.exec(displayFormatArgs({ target: slot.pane, format: "#{pane_height}" }))).trim()) + heights.push(Number.isFinite(h) && h > 0 ? h : 0) + } catch { + heights.push(0) + } + } + return heights + } + + /** Preserve the window's active pane across structural ops (splits/kills move focus) */ + private async withFocus(job: () => Promise<void>): Promise<void> { + if (!this.win) return job() + const saved = await this.exec(displayFormatArgs({ target: this.win, format: "#{pane_id}" })).catch(() => "") + await job() + const now = await this.exec(displayFormatArgs({ target: this.win, format: "#{pane_id}" })).catch(() => "") + if (saved && now && saved !== now) await this.exec(selectPaneArgs(saved)).catch(() => {}) + } + + /** Poll while panes are open: a viewer can exit on its own (user quit / server switch) — self-heal the layout */ + private syncPoll(): void { + const need = this.slots.length > 0 || this.queue.length > 0 + if (need && !this.pollTimer) { + this.pollTimer = setInterval(() => { + this.enqueue(async () => { + if (!this.ready) return + await this.dropDeadSlots() + if (this.slots.length === 0 && this.queue.length === 0) this.syncPoll() + }) + }, 4_000) + // never hold the process open just for polling + const t = this.pollTimer as unknown as { unref?: () => void } + t.unref?.() + } else if (!need && this.pollTimer) { + clearInterval(this.pollTimer) + this.pollTimer = null + } + } +} diff --git a/src/tui.tsx b/src/tui.tsx index fdbbeae..3b9124f 100644 --- a/src/tui.tsx +++ b/src/tui.tsx @@ -21,7 +21,7 @@ import { join, relative, isAbsolute, sep } from "node:path" // [2026-09-03]-[/poolConfig //modelRank interactive dialogs: task-pool pick lists and capability ranking read/write the // user override layer (pool-config.json / capability-rank.json) directly, taking effect in sync with the plugin main // process mtime hot reload] -import { loadPoolConfig, writePoolConfig, resetPoolConfig, loadCapabilityRank, writeCapabilityRank } from "./user-overrides" +import { loadPoolConfig, writePoolConfig, resetPoolConfig, loadCapabilityRank, writeCapabilityRank, applyRankMove } from "./user-overrides" import { allModelRows, rankViewRows } from "./config-cli" import { LANE_ORDER, type Lane } from "./types" import { runHandover, type HandoverPort } from "./handover-core" @@ -314,8 +314,11 @@ function ViewInner(props: { api: TuiPluginApi; sessionID: string }) { {(ch, i) => <span style={{ fg: hsvToHex(i() * 28 + tick() * 3, 0.65, 1) }}>{ch}</span>} </For> </b> - {restartRequired().length > 0 && ( - <span style={{ fg: theme().error }}> [RESTART REQUIRED]</span> + {/* [2026-09-06]-[blinking restart tag: ~600ms on/off via the 150ms marquee heartbeat (tick/4 parity), bold + red — a pending shell-registration restart used to render as a static tag that was easy to stop seeing; + fail-open unchanged: empty restartRequired list renders nothing]-[impacts the sidebar title row only] */} + {restartRequired().length > 0 && Math.floor(tick() / 4) % 2 === 0 && ( + <span style={{ fg: theme().error }}><b> [RESTART NEEDED]</b></span> )} </text> <For each={routes()}> @@ -456,10 +459,20 @@ function PoolModelsDialog(props: { api: TuiPluginApi; lane: Lane }) { setSelected(new Set(rows().map((r) => r.key))) props.api.ui.toast({ variant: "success", message: `${props.lane} pool config cleared (system default candidate set restored)` }) } + // [2026-09-06]-[Uncheck-all shortcut: clears the checkbox state in place (no disk write) so a short list can be + // built by checking a few models instead of unchecking the rest one by one; while nothing is checked the previous + // config stays untouched on disk — exiting without any check keeps the pre-clear selection in effect, and the + // first check after the clear materializes the new explicit list]-[impacts PoolModelsDialog only] + const uncheckAll = () => { + if (selected().size === 0) return + setSelected(new Set<string>()) + props.api.ui.toast({ variant: "info", message: `${props.lane} pool: all unchecked — check the models to keep; exiting with none checked keeps the previous selection` }) + } const nSel = () => selected().size const options = createMemo(() => [ { title: "← Back to pool list", value: "__back", onSelect: () => props.api.ui.dialog.replace(() => <PoolPickerDialog api={props.api} />) }, { title: "☑ Select all", value: "__all", onSelect: () => bulk() }, + { title: "☐ Uncheck all (then check the few to keep; exit with none checked keeps the old list)", value: "__uncheckAll", onSelect: uncheckAll }, { title: "✕ Clear config (system default: all available models participate)", value: "__reset", onSelect: reset }, ...rows().map((r) => ({ title: `${selected().has(r.key) ? "[x]" : "[ ]"} ${r.modelId}`, @@ -481,17 +494,75 @@ function openModelRankDialog(api: TuiPluginApi): void { api.ui.dialog.replace(() => <RankPickerDialog api={api} />) } +// ---- [2026-09-06]-[/modelRank list hotkeys: ctrl+up / ctrl+down (alt+up / alt+down mirrored for terminals that swallow +// ctrl+arrows) move the highlighted model within the manual ranking without opening the per-model action dialog. +// The host DialogSelect has no per-dialog key API exposed to plugins, so the binding lives in the global keymap layer +// (registered in tui() below; ctrl/alt+arrows are unbound by the host) and the open dialog claims the module-level +// context: with no claimant the commands are silent no-ops, so global key real estate stays clean]---- +type RankHotkeyClaim = { move: (delta: -1 | 1) => void } +let rankHotkeyClaim: RankHotkeyClaim | null = null + function RankPickerDialog(props: { api: TuiPluginApi }) { - const rows = createMemo(() => rankViewRows()) + // rev bumps on every hotkey write so rows() re-reads the rank file and re-sorts the list in place (enter-action + // flows keep using dialog.replace instead, which rebuilds the component from scratch) + const [rev, setRev] = createSignal(0) + const rows = createMemo(() => { + rev() + return rankViewRows() + }) + // Highlight tracking: onMove covers filter/navigate; before the first onMove the host selects row 0 + const [highlight, setHighlight] = createSignal<string | null>(null) + const highlighted = () => highlight() ?? rows()[0]?.key ?? null + const claim: RankHotkeyClaim = { + move: (delta) => { + const key = highlighted() + if (!key) return + const row = rows().find((r) => r.key === key) + const name = row?.modelId ?? key + const cur = [...(loadCapabilityRank()?.models ?? [])] + const i = cur.indexOf(key) + const res = applyRankMove(cur, key, delta) + const skip = (message: string) => props.api.ui.toast({ variant: "info", message }) + if (!res) { + // Boundary no-ops must stay audible, otherwise mashing the key feels broken + if (i < 0) skip(`${name} is not in the manual ranking (ctrl+up adds it at the end; enter = per-model actions)`) + else skip(`${name} is already at the ${delta === -1 ? "top" : "bottom"} of the manual ranking`) + return + } + try { + writeCapabilityRank(res.models) + } catch (exc) { + props.api.ui.toast({ variant: "error", message: `write failed: ${exc instanceof Error ? exc.message : exc}` }) + return + } + props.api.ui.toast({ + variant: "success", + message: i < 0 + ? `Added ${name} to the ranking (manual rank #${res.index + 1}, effective immediately, sidebar refreshes)` + : `Moved ${name} to rank #${res.index + 1} (effective immediately, sidebar refreshes)`, + }) + // Cursor follows the moved model: `current` is the only cursor control the plugin DialogSelect exposes + // (side effect: the ● marker stays on the last-moved model until the dialog closes) + setHighlight(key) + setRev((v) => v + 1) + }, + } + rankHotkeyClaim = claim + onCleanup(() => { + if (rankHotkeyClaim === claim) rankHotkeyClaim = null + }) return ( <props.api.ui.DialogSelect - title="Model capability ranking (#1 strongest; manual hits take precedence over base scores; pick a model to adjust)" + title="Model capability ranking (#1 strongest; ctrl+up/ctrl+down move the highlighted model; enter = per-model actions)" + placeholder="Search · alt+up/alt+down mirror ctrl+up/ctrl+down (also work)" options={rows().map((r, i) => ({ title: `#${String(i + 1).padStart(2, "0")} ${r.modelId}`, value: r.key, description: `${r.tier}-tier · ${r.source === "manual" ? "manual rank" : "base capability score"}`, onSelect: () => props.api.ui.dialog.replace(() => <RankActionsDialog api={props.api} model={r.modelId} modelKey={r.key} />), }))} + current={highlighted() ?? undefined} + onMove={(opt) => setHighlight(String(opt.value))} flat /> ) @@ -500,25 +571,20 @@ function RankPickerDialog(props: { api: TuiPluginApi }) { function RankActionsDialog(props: { api: TuiPluginApi; model: string; modelKey: string }) { const rank = () => [...(loadCapabilityRank()?.models ?? [])] const at = () => rank().indexOf(props.modelKey) + // [2026-09-06]-[reorder rules now come from the shared applyRankMove helper (same semantics as the list hotkeys); + // only the boundary feedback is dialog-specific]- const apply = (next: string[], message: string) => { writeCapabilityRank(next) props.api.ui.toast({ variant: "success", message: `${message} (effective immediately, sidebar refreshes)` }) props.api.ui.dialog.replace(() => <RankPickerDialog api={props.api} />) } const move = (delta: -1 | 0 | 1) => { - // delta 0 = pin to top; ±1 = swap with the neighbor (moving an unranked model up/down = insert at the target - // position) - const cur = rank() - const i = cur.indexOf(props.modelKey) - if (delta === 0) { - if (i >= 0) cur.splice(i, 1) - cur.unshift(props.modelKey) - } else { - const target = i >= 0 ? Math.min(Math.max(i + delta, 0), cur.length - 1) : cur.length - if (i >= 0) cur.splice(i, 1) - cur.splice(target, 0, props.modelKey) + const res = applyRankMove(rank(), props.modelKey, delta) + if (!res) { + props.api.ui.toast({ variant: "info", message: `${props.model} is already at the ${delta === 1 ? "bottom" : "top"} of the manual ranking` }) + return } - apply(cur, delta === 0 ? `Pinned ${props.model} to top` : `Moved ${props.model} to rank #${cur.indexOf(props.modelKey) + 1}`) + apply(res.models, delta === 0 ? `Pinned ${props.model} to top` : `Moved ${props.model} to rank #${res.index + 1}`) } const ranked = () => at() >= 0 const options = createMemo(() => { @@ -658,6 +724,37 @@ const tui: TuiPlugin = async (api) => { bindings: [], }) } catch { /* fail-open */ } + // [2026-09-06]-[/modelRank list hotkeys: separate fail-open block so a keymap that rejects these bindings cannot take + // down the palette commands above; only active while the ranking dialog is open (claims rankHotkeyClaim), alt + // variants mirror ctrl for terminals that swallow ctrl+arrows; hidden keeps them out of the palettes]- + try { + api.keymap.registerLayer({ + commands: [ + { + name: "switchman.rank.move-up", + title: "Move the highlighted model up in /modelRank", + desc: "In the /modelRank dialog, move the highlighted model up one spot in the manual ranking", + category: "switchman", + hidden: true, + run: () => rankHotkeyClaim?.move(-1), + }, + { + name: "switchman.rank.move-down", + title: "Move the highlighted model down in /modelRank", + desc: "In the /modelRank dialog, move the highlighted model down one spot in the manual ranking", + category: "switchman", + hidden: true, + run: () => rankHotkeyClaim?.move(1), + }, + ], + bindings: [ + { key: "ctrl+up", cmd: "switchman.rank.move-up", desc: "Move the highlighted model up in /modelRank" }, + { key: "ctrl+down", cmd: "switchman.rank.move-down", desc: "Move the highlighted model down in /modelRank" }, + { key: "alt+up", cmd: "switchman.rank.move-up", desc: "Move the highlighted model up in /modelRank" }, + { key: "alt+down", cmd: "switchman.rank.move-down", desc: "Move the highlighted model down in /modelRank" }, + ], + }) + } catch { /* fail-open: hosts without binding-layer support keep the enter-only flow */ } } const plugin: TuiPluginModule & { id: string } = { diff --git a/src/types.ts b/src/types.ts index c9c65ac..26f22aa 100644 --- a/src/types.ts +++ b/src/types.ts @@ -294,6 +294,12 @@ export interface ContextOptions { autoHandover?: boolean /** Per-call self-read budget R* in tokens: reads estimated above this are auto-bounded or denied with bounded-retry params; default 1500 (clamped 200..20000) */ readBudgetTokens?: number + /** [2026-09-06]-[subagent hard cap (tokens): when a shell subagent's measured context reaches it, every further tool + * call in that session is denied with a wrap-up order (the next text-only answer = detailed progress summary = task + * result) and the session is permanently terminated (no task_id resume); default 100_000, clamped 20k..1M, window-capped + * at 90%; subagentCap: false disables the mechanism entirely] */ + subagentForceTokens?: number + subagentCap?: boolean } // [2026-09-04]-[Builtin subagent block: explore/general compete with shell routing and were previously fail-open allowed; // default deny with economy/main redirect suggestions; allow restores the old behavior] @@ -331,6 +337,19 @@ export interface LangOptions { /** Candidate language labels offered in the ask (custom free input always allowed besides these) */ candidates?: string[] } +// [2026-09-06]-[tmux pane mirroring: dispatched subagent sessions open as live `opencode attach` panes in a +// right-hand column of the home tmux window (main pane left, subagent panes right; status line untouched); +// inert outside tmux — see src/tmux.ts] +export interface TmuxOptions { + /** Master switch (default true); effective only when the server itself runs inside tmux */ + enabled?: boolean + /** Width share of the right subagent column in percent (default 60 = main 40 / right 60) */ + rightPct?: number + /** Max simultaneously visible subagent panes in the right column (default 3; extras wait in a FIFO queue) */ + maxPanes?: number + /** Use the minimal attach interface instead of the full TUI (default false) */ + mini?: boolean +} /** Factory default ask candidates (labels; users may configure their own via jsonc lang.candidates) */ export const DEFAULT_LANG_CANDIDATES: readonly string[] = ["English", "简体中文", "日本語", "Español", "Français", "Deutsch"] // [2026-09-01]-[Config surface consolidated into opencode-switchman.jsonc: tuple options demoted to a compatibility shim @@ -352,4 +371,5 @@ export interface SwitchmanOptions { relay?: RelayOptions workspace?: WorkspaceOptions lang?: LangOptions + tmux?: TmuxOptions } diff --git a/src/user-overrides.ts b/src/user-overrides.ts index 28d7177..c15e38f 100644 --- a/src/user-overrides.ts +++ b/src/user-overrides.ts @@ -132,6 +132,29 @@ export function overrideSummary(): { rankModels: number; poolLanes: number } { return { rankModels: rank?.models.length ?? 0, poolLanes: Object.keys(loadPoolConfig()).length } } +// ---- Pure manual-ranking move (shared semantics for the TUI /modelRank dialog: enter actions and ctrl+up/ctrl+down hotkeys) ---- + +/** [2026-09-06]-[/modelRank hotkeys: extract the reorder rules shared by the RankActions dialog and the new list-level + * ctrl+up/ctrl+down hotkeys into one pure helper so both surfaces stay in lockstep]- + * [delta 0 = pin to top; ±1 = move one spot toward the front/back (unranked + down is a no-op, unranked + up/pin + * materializes an entry: pin → front, up → appended at the end, mirroring the dialog's "Add to ranking (at the end)"). + * Boundary-hit ranked moves return null (no write). Pure: returns the next list + the model's new index, no I/O] */ +export function applyRankMove(models: readonly string[], key: string, delta: -1 | 0 | 1): { models: string[]; index: number } | null { + const cur = [...models] + const i = cur.indexOf(key) + if (delta === 0) { + if (i >= 0) cur.splice(i, 1) + cur.unshift(key) + return { models: cur, index: 0 } + } + if (i < 0) return delta === 1 ? { models: [...cur, key], index: cur.length } : null + const target = i + delta + if (target < 0 || target >= cur.length) return null + cur.splice(i, 1) + cur.splice(target, 0, key) + return { models: cur, index: target } +} + // ---- Writes (shared by CLI/TUI; atomic replacement + cache invalidation; empty list = delete key/file back to default) ---- export function writeCapabilityRank(models: string[]): CapabilityRankFile { diff --git a/test/dispatch-gates.test.ts b/test/dispatch-gates.test.ts index e6bdd88..a11b17f 100644 --- a/test/dispatch-gates.test.ts +++ b/test/dispatch-gates.test.ts @@ -179,7 +179,7 @@ describe("config: new behavior-section validation", () => { test("defaults: context 60/80/100k, gates on, builtinAgents deny, injection chain, floor 3000", () => { const { config, diagnostics } = validateUserConfig(base) expect(diagnostics.filter((d) => d.level === "error")).toEqual([]) - expect(config.context).toEqual({ gates: true, softTokens: 60_000, hardTokens: 80_000, forceTokens: 120_000, readBudgetTokens: 1_500, autoHandover: true }) + expect(config.context).toEqual({ gates: true, softTokens: 60_000, hardTokens: 80_000, forceTokens: 120_000, readBudgetTokens: 1_500, autoHandover: true, subagentForceTokens: 100_000, subagentCap: true }) expect(config.builtinAgents.mode).toBe("deny") expect(config.injection.mode).toBe("chain") expect(config.rules.delegationFloor).toBe(3_000) diff --git a/test/lane-policy.test.ts b/test/lane-policy.test.ts index 3986b2a..7d8e2ef 100644 --- a/test/lane-policy.test.ts +++ b/test/lane-policy.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { computeLaneChain } from "../src/lane-policy" +import { computeLaneChain, filterMatrixDownShells, filterPoolUnavailableShells } from "../src/lane-policy" import { loadManifest } from "../src/state" import { baseScoreFromCapabilityIndex, loadBundledCapability } from "../src/capability" import { baseScore } from "../src/model-ranks" @@ -212,4 +212,51 @@ describe("candidate-chain algorithm", () => { } expect(manifest.lanes.review.every((name) => manifest.shells.find((shell) => shell.name === name)!.capability === "ro")).toBe(true) }) + // [2026-09-06]-[health-aware seats contract: seat caps are capability-tier-only, so matrix-down shells must be + // filtered BEFORE seat allocation (pure filterMatrixDownShells, verdict lookup injected — same predicate as the + // registry's disabled mark); otherwise a whole provider answering 402 slices healthy lower-tier shells out and the + // lane ends empty (live incident: vision/review went fully empty on 2026-09-06)] + test("[2026-09-06] health-aware seats: matrix-down shells are filtered before seat allocation; unknown/missing verdicts and strained fail-open", () => { + const cand = [ + { name: "s-dead", modelId: "s", pool: "copilot", effort: "high", capability: "rw", vision: false, matrixKey: "p|s|high" }, + { name: "b-alive", modelId: "b", pool: "glm", effort: "high", capability: "rw", vision: false, matrixKey: "p|b|high" }, + { name: "c-unprobed", modelId: "c", pool: "glm", effort: "high", capability: "rw", vision: false, matrixKey: "p|c|high" }, + ] + const statusOf = (key: string) => ({ "p|s|high": "down", "p|b|high": "ok", "p|c|high": null }[key] ?? null) + expect(filterMatrixDownShells(cand, statusOf).map((s) => s.name)).toEqual(["b-alive", "c-unprobed"]) + // no lookup injected = identity (fail-open) + expect(filterMatrixDownShells(cand)).toHaveLength(3) + // strained is not down: stays; verdict lookup is case-tolerant ("DOWN" filters too) + expect(filterMatrixDownShells(cand, (k) => (k === "p|s|high" ? "strained" : "ok"))).toHaveLength(3) + expect(filterMatrixDownShells(cand, (k) => (k === "p|s|high" ? "DOWN" : "ok")).map((s) => s.name)).toEqual(["b-alive", "c-unprobed"]) + }) + test("[2026-09-06] health-aware seats: tier-only seat caps fill with dead S/A shells — after the pre-filter the healthy lower-tier shell takes the seat", () => { + const five = [ + { name: "s1", modelId: "s1", pool: "copilot", effort: "high", capability: "rw", vision: true }, + { name: "s2", modelId: "s2", pool: "copilot", effort: "high", capability: "rw", vision: true }, + { name: "a3", modelId: "a3", pool: "copilot", effort: "high", capability: "rw", vision: true }, + { name: "a4", modelId: "a4", pool: "copilot", effort: "high", capability: "rw", vision: true }, + { name: "b5", modelId: "b5", pool: "glm", effort: "high", capability: "rw", vision: true }, + ] + const cap = (id: string) => ({ s1: 1, s2: 1, a3: 0.85, a4: 0.85, b5: 0.7 }[id]!) + const capTier = (id: string) => ({ s1: "S", s2: "S", a3: "A", a4: "A", b5: "B" }[id] as "S" | "A" | "B") + const capOf = (id: string) => ({ score: cap(id), tier: capTier(id) }) + // tier-only world: the four S/A shells occupy all four primary seats, the healthy B shell is sliced out + expect(computeLaneChain(five, capOf, "vision")).toEqual(["s1", "s2", "a3", "a4"]) + // with the dead S/A shells pre-filtered (baseChainFor health-aware seats), the live B shell heads the chain + const dead = new Set(["s1", "s2", "a3", "a4"]) + expect(computeLaneChain(five.filter((s) => !dead.has(s.name)), capOf, "vision")).toEqual(["b5"]) + }) + test("[2026-09-06] pool-exhaustion-aware seats: proven-exhausted pools are filtered before seat allocation; resolver absent = identity (fail-open)", () => { + const cand = [ + { name: "cp-dead-pool", modelId: "cp", pool: "copilot", effort: "high", capability: "rw", vision: true, matrixKey: "p|cp|high" }, + { name: "glm-alive", modelId: "glm", pool: "glm", effort: "high", capability: "rw", vision: true, matrixKey: "p|glm|high" }, + ] + const sunk = filterPoolUnavailableShells(cand, (pool) => pool === "copilot") + expect(sunk.map((s) => s.name)).toEqual(["glm-alive"]) + // no resolver = identity (fail-open, e.g. quota data unavailable) + expect(filterPoolUnavailableShells(cand)).toHaveLength(2) + // a healthy pool is never sunk + expect(filterPoolUnavailableShells(cand, () => false)).toHaveLength(2) + }) }) diff --git a/test/pane-resume.test.ts b/test/pane-resume.test.ts new file mode 100644 index 0000000..b105ced --- /dev/null +++ b/test/pane-resume.test.ts @@ -0,0 +1,131 @@ +// [2026-09-06 fix]-[tmux pane mirroring resume wiring: a task call carrying task_id REUSES the previous child +// session (opencode task tool skips sessions.create → no session.created event), so the pane must be opened +// directly from the allowed dispatch sites (noteResumedChild). Contract: allowed dispatch + task_id + verified +// session → resume pane triggered (status-log line); verified-missing session → skipped (the fallback fresh +// session is covered by session.created); fresh dispatch (no task_id) and deny paths never trigger it] +import { describe, expect, test, afterAll } from "bun:test" +import { existsSync, mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const prevState = process.env.SWITCHMAN_STATE +const prevConfigDir = process.env.OPENCODE_CONFIG_DIR +process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-pane-resume-state-")) +process.env.OPENCODE_CONFIG_DIR = mkdtempSync(join(tmpdir(), "switchman-pane-resume-cfg-")) +mkdirSync(process.env.SWITCHMAN_STATE, { recursive: true }) +// hermetic state (same trick as routing.test.ts / auto-redirect.test.ts): pre-seed every TTL cache so the six gates +// never hit the network; the empty catalog pins the curated table +writeFileSync( + join(process.env.SWITCHMAN_STATE, "capability.json"), + JSON.stringify({ source: "artificial-analysis", version: "fixed-empty", fetched_at: Date.now() / 1000, thresholds: { S: 62, A: 55, B: 45 }, models: {} }), +) +writeFileSync(join(process.env.SWITCHMAN_STATE, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +for (const [file, body] of Object.entries({ + "model-matrix.json": { + generated_at: new Date().toISOString(), + combos: Object.fromEntries(loadManifest().shells.map((s) => [s.matrixKey, { status: "ok", latency_ms: 100, checked_at: new Date().toISOString() }])), + }, + "costs.json": { scores: {}, fetched_at: Date.now() / 1000 }, + "selfupdate.json": { checked_at: new Date().toISOString(), mode: "prod", current: "0.0.0-test", latest: "0.0.0-test", outdated: false }, + "glm-quota.json": { status: "ok", fetched_at: Date.now() / 1000 }, + "copilot-quota.json": { status: "ok", fetched_at: Date.now() / 1000 }, + "ds-balance.json": { status: "ok", fetched_at: Date.now() / 1000 }, +} as Record<string, unknown>)) { + writeFileSync(join(process.env.SWITCHMAN_STATE, file), JSON.stringify(body)) +} +afterAll(() => { + if (prevState === undefined) delete process.env.SWITCHMAN_STATE + else process.env.SWITCHMAN_STATE = prevState + if (prevConfigDir === undefined) delete process.env.OPENCODE_CONFIG_DIR + else process.env.OPENCODE_CONFIG_DIR = prevConfigDir +}) + +import { SwitchmanPlugin } from "../src/index" +import { loadManifest, stateDir } from "../src/state" +import { rmSync } from "node:fs" + +type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> + +type GetBehavior = "present" | "missing" | "throws" | "absent" + +function pluginInput(behavior: GetBehavior, seen: string[]): any { + return { + client: { + provider: { list: async () => [] }, + session: behavior === "absent" + ? undefined + : { + get: async ({ path }: { path: { id: string } }) => { + seen.push(path.id) + if (behavior === "throws") throw new Error("server hiccup") + return behavior === "present" ? { data: { id: path.id } } : {} + }, + }, + }, + } +} + +async function makeHooks(behavior: GetBehavior, seen: string[]): Promise<Hooks> { + const hooks = await SwitchmanPlugin(pluginInput(behavior, seen), { matrix: { mode: "legacy" } } as any) + const cfg: Record<string, unknown> = {} + await hooks.config!(cfg) + return { ...hooks, _cfg: cfg } as any +} + +/** Legacy mode + an unknown non-builtin agent = fail-open allowed dispatch (site fires deterministically, no gates) */ +async function runTask(hooks: Hooks, callID: string, args: Record<string, unknown>): Promise<void> { + const output: any = { args } + await hooks["tool.execute.before"]!({ tool: "task", sessionID: "s-test", callID } as any, output) + // noteResumedChild verifies asynchronously (void then-chain) — give the microtask/timer a moment + await new Promise((r) => setTimeout(r, 20)) +} + +function statusLogText(): string { + const p = join(stateDir(), "status-log.json") + if (!existsSync(p)) return "" + const data = JSON.parse(readFileSync(p, "utf8")) + return (Array.isArray(data) ? data : []).map((e: { text?: string }) => String(e?.text ?? "")).join("\n") +} + +/** status-log persists across tests in the shared state dir — truncate for per-test isolation */ +function resetLog(): void { + rmSync(join(stateDir(), "status-log.json"), { force: true }) +} + +// opencode-style id: the log line suffixes ses_${id.slice(-6)} (house convention), so keep the last 6 chars intact +const TASK_ID = "ses_ab12cd" +const RESUME_MARK = `resume dispatch ses_ab12cd` + +describe("tmux pane resume wiring (task_id reuse, no session.created)", () => { + test("fresh dispatch (no task_id): no resume trigger", async () => { + resetLog() + const hooks = await makeHooks("present", []) + await runTask(hooks, "c-fresh", { subagent_type: "mystery-agent", prompt: "hello" }) + expect(statusLogText()).not.toContain(RESUME_MARK) + }, 20_000) + + test("resume with a verified session: pane trigger fires directly", async () => { + resetLog() + const seen: string[] = [] + const hooks = await makeHooks("present", seen) + await runTask(hooks, "c-resume", { subagent_type: "mystery-agent", prompt: "hello", task_id: TASK_ID }) + expect(seen).toContain(TASK_ID) + expect(statusLogText()).toContain(RESUME_MARK) + }, 20_000) + + test("resume with a verified-missing session: skipped (opencode falls back to a fresh session covered by session.created)", async () => { + resetLog() + const seen: string[] = [] + const hooks = await makeHooks("missing", seen) + await runTask(hooks, "c-missing", { subagent_type: "mystery-agent", prompt: "hello", task_id: TASK_ID }) + expect(seen).toContain(TASK_ID) + expect(statusLogText()).not.toContain(RESUME_MARK) + }, 20_000) + + test("resume when the session lookup errors: fail-open, trigger still fires", async () => { + resetLog() + const hooks = await makeHooks("throws", []) + await runTask(hooks, "c-throw", { subagent_type: "mystery-agent", prompt: "hello", task_id: TASK_ID }) + expect(statusLogText()).toContain(RESUME_MARK) + }, 20_000) +}) diff --git a/test/provider-refresh.test.ts b/test/provider-refresh.test.ts new file mode 100644 index 0000000..85a6f39 --- /dev/null +++ b/test/provider-refresh.test.ts @@ -0,0 +1,142 @@ +// Provider-refresh behavior contract (v1.3; bun test) +// Covers: provider cache freshness gate (stale-cache live probe predicate), model-list delta detection, +// and the watchdog's in-place superset rebuild via MatrixManager.updateSuperset. +// [2026-09-06]-[new suite for the provider-refresh feature: startup stale-cache probe + background drift rebuild] +import { describe, test, expect } from "bun:test" +import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-prefresh-")) + +import { providerCacheStale, providerCacheAgeMs, providerModelsDelta, PROVIDER_CACHE_MAX_AGE_MS } from "../src/state" +import type { ProviderCache } from "../src/state" +import { buildShells } from "../src/catalog" +import { MatrixManager } from "../src/matrix-manager" +import { paths } from "../src/state" + +// ---- Sandbox (pattern of test/activation.test.ts: stateHome=userData root, stateRoot=stateHome/opencode) ---- +const stateHome = mkdtempSync(join(tmpdir(), "opencode-state-")) +const stateRoot = join(stateHome, "opencode") +mkdirSync(stateRoot, { recursive: true }) +mkdirSync(paths().dir, { recursive: true }) + +// ================= 1. providerCacheStale / providerCacheAgeMs ================= +describe("provider cache freshness gate", () => { + // Fixed epoch so the boundary math is deterministic (no wall-clock flakiness) + const NOW = 1_800_000_000_000 + const cacheOf = (at: string): ProviderCache => ({ at, models: ["glm/glm-5.3"], providers: ["glm"] }) + const isoAgo = (ageMs: number) => new Date(NOW - ageMs).toISOString() + + test("cache written now → age ~0, not stale", () => { + const c = cacheOf(new Date(NOW).toISOString()) + expect(providerCacheAgeMs(c, NOW)).toBe(0) + expect(providerCacheStale(c, NOW)).toBe(false) + }) + test("cache 25h old → stale (past the 24h TTL)", () => { + const c = cacheOf(isoAgo(25 * 3_600_000)) + expect(providerCacheAgeMs(c, NOW)).toBe(25 * 3_600_000) + expect(providerCacheStale(c, NOW)).toBe(true) + }) + test("unparseable timestamp → age null, stale (never trust blindly)", () => { + const c = cacheOf("not-a-date") + expect(providerCacheAgeMs(c, NOW)).toBeNull() + expect(providerCacheStale(c, NOW)).toBe(true) + }) + test("missing timestamp (partial object) → age null, stale (cache.at ?? \"\" fallback)", () => { + const c = { models: [], providers: ["glm"] } as unknown as ProviderCache + expect(providerCacheAgeMs(c, NOW)).toBeNull() + expect(providerCacheStale(c, NOW)).toBe(true) + }) + test("TTL boundary: exactly PROVIDER_CACHE_MAX_AGE_MS old → NOT stale (strict >); one ms more → stale", () => { + expect(providerCacheStale(cacheOf(isoAgo(PROVIDER_CACHE_MAX_AGE_MS)), NOW)).toBe(false) + expect(providerCacheStale(cacheOf(isoAgo(PROVIDER_CACHE_MAX_AGE_MS + 1)), NOW)).toBe(true) + }) +}) + +// ================= 2. providerModelsDelta ================= +describe("provider model-list delta", () => { + test("detects added, removed, and both directions", () => { + expect(providerModelsDelta(["glm/glm-5.3"], ["glm/glm-5.3", "glm/glm-5.4"])).toEqual({ added: ["glm/glm-5.4"], removed: [] }) + expect(providerModelsDelta(["glm/glm-5.3", "deepseek/deepseek-v4-pro"], ["glm/glm-5.3"])).toEqual({ added: [], removed: ["deepseek/deepseek-v4-pro"] }) + expect(providerModelsDelta(["a/m1", "b/m2"], ["b/m2", "c/m3"])).toEqual({ added: ["c/m3"], removed: ["a/m1"] }) + }) + test("identical sets (any order, duplicates in input) → both sides empty (Set semantics, no leak)", () => { + expect(providerModelsDelta(["a/m1", "b/m2"], ["b/m2", "a/m1"])).toEqual({ added: [], removed: [] }) + expect(providerModelsDelta(["a/m1", "a/m1", "b/m2"], ["b/m2", "b/m2", "a/m1"])).toEqual({ added: [], removed: [] }) + }) + test("outputs are sorted regardless of input order", () => { + const d = providerModelsDelta(["z/9", "a/1"], ["z/8", "b/3", "a/2"]) + expect(d.added).toEqual(["a/2", "b/3", "z/8"]) + expect(d.removed).toEqual(["a/1", "z/9"]) + }) +}) + +// ================= 3. MatrixManager.updateSuperset (watchdog superset rebuild) ================= +describe("MatrixManager.updateSuperset: in-place superset rebuild on model drift", () => { + const META = { + "glm/glm-5.3": { efforts: ["high"], toggle: true, vision: false }, + "github-copilot/gpt-5.6-terra": { efforts: ["high"], toggle: true, vision: true }, + } + // Startup face: provider.list saw only glm/glm-5.3 (terra not yet in the provider's list) + const initial = buildShells(["glm/glm-5.3"], META as any, { roAliases: true }) + // Watchdog drift face: provider.list now also returns terra → rebuilt superset + const rebuilt = buildShells(["glm/glm-5.3", "github-copilot/gpt-5.6-terra"], META as any, { roAliases: true }) + + test("favorite of a known provider with no shell → invalidConfigured, no shell of that model active", () => { + writeFileSync(join(stateRoot, "model.json"), JSON.stringify({ + recent: [], + favorite: [{ providerID: "github-copilot", modelID: "gpt-5.6-terra", visibility: "show", favorite: true }], + variant: null, + })) + const m = new MatrixManager({ + stateRoot, mode: "cli", superset: initial, + injectedNames: new Set(initial.map((d) => d.name)), + knownProviders: new Set(["glm", "github-copilot"]), + watchEnabled: false, + }) + const st = m.recompute() + expect(st.invalidConfigured).toContain("github-copilot/gpt-5.6-terra") + // [2026-09-06]-[adjusted per activation.ts computeActivation: invalid-only favorites do NOT narrow — the initial + // superset stays fully dispatchable (activation.ts:143-148, precedent test/activation.test.ts "only invalid favorites"); + // the pre-rebuild symptom is "no terra shell exists", not an empty active set] + expect(st.activeShells.some((n) => n.startsWith("copilot-mx-terra"))).toBe(false) + expect(st.activeShells).toContain("glm-mx-53-high") + }) + + test("updateSuperset: rebuilt defs make the favorite valid and active, generation bumps, matrix keys refresh", () => { + writeFileSync(join(stateRoot, "model.json"), JSON.stringify({ + recent: [], + favorite: [{ providerID: "github-copilot", modelID: "gpt-5.6-terra", visibility: "show", favorite: true }], + variant: null, + })) + const m = new MatrixManager({ + stateRoot, mode: "cli", superset: initial, + injectedNames: new Set(initial.map((d) => d.name)), + knownProviders: new Set(["glm", "github-copilot"]), + watchEnabled: false, + }) + m.recompute() + const prevGen = m.snapshot().generation + const next = m.updateSuperset(rebuilt, new Set(["glm", "github-copilot"])) + // The favorite is no longer dirty: its model now has shells in the superset + expect(next.invalidConfigured).not.toContain("github-copilot/gpt-5.6-terra") + expect(next.activeShells.length).toBeGreaterThan(0) + expect(next.activeShells).toContain("copilot-mx-terra-high") + // Configured-shells narrowing now applies (the favorite is the active surface; glm-only startup face drops out) + expect(next.activeShells.every((n) => n.startsWith("copilot-mx-terra"))).toBe(true) + expect(next.generation).toBeGreaterThan(prevGen) + // Probe targets refresh in place: terra combos are active matrix keys + expect(m.activeMatrixKeys().length).toBeGreaterThan(0) + expect(m.activeMatrixKeys().some((k) => k.startsWith("github-copilot|"))).toBe(true) + // [2026-09-06]-[adjusted per matrix-manager.ts noteChatParams: a null modelKey registers the session but returns + // false (matrix unaffected); the "main-session model change → true" contract needs a real modelKey. Either way the + // rebuilt-but-not-injected shell name stays a non-shell agent: injectedNames is untouched by updateSuperset + // (cfg.agent is one-shot — the platform restart constraint)] + expect(m.noteChatParams("s1", "copilot-mx-terra-high", null)).toBe(false) + expect(m.isShellSession("s1")).toBe(false) + expect(m.skipSystemInjection("s1")).toBe(false) + expect(m.noteChatParams("s1", "copilot-mx-terra-high", "github-copilot/gpt-5.6-terra")).toBe(true) + expect(m.isShellSession("s1")).toBe(false) // still a main session: the new shell is not dispatchable until restart + }) +}) diff --git a/test/rank-move.test.ts b/test/rank-move.test.ts new file mode 100644 index 0000000..891ca53 --- /dev/null +++ b/test/rank-move.test.ts @@ -0,0 +1,40 @@ +// [2026-09-06]-[applyRankMove unit contract: shared reorder semantics for the /modelRank dialog (enter actions + +// ctrl+up/ctrl+down hotkeys). Pure function — no filesystem, but the module chain expects a state dir to exist] +// Sandbox: SWITCHMAN_STATE points to a temp dir (same fixture pattern as user-overrides.test.ts) +import { describe, test, expect, beforeAll } from "bun:test" +import { mkdtempSync, mkdirSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-rm-")) +mkdirSync(process.env.SWITCHMAN_STATE, { recursive: true }) + +import { applyRankMove } from "../src/user-overrides" + +describe("applyRankMove (manual ranking reorder shared by dialog actions and hotkeys)", () => { + const list = ["a", "b", "c"] + + test("±1 swaps with the neighbor and reports the new index", () => { + expect(applyRankMove(list, "b", -1)).toEqual({ models: ["b", "a", "c"], index: 0 }) + expect(applyRankMove(list, "b", 1)).toEqual({ models: ["a", "c", "b"], index: 2 }) + }) + + test("boundary hits are null no-ops (no write)", () => { + expect(applyRankMove(list, "a", -1)).toBeNull() + expect(applyRankMove(list, "c", 1)).toBeNull() + }) + + test("pin to top: ranked and unranked both land at index 0", () => { + expect(applyRankMove(list, "c", 0)).toEqual({ models: ["c", "a", "b"], index: 0 }) + expect(applyRankMove(list, "z", 0)).toEqual({ models: ["z", "a", "b", "c"], index: 0 }) + }) + + test("unranked: up appends at the end, down is a no-op (hotkey hint path)", () => { + expect(applyRankMove(list, "z", 1)).toEqual({ models: ["a", "b", "c", "z"], index: 3 }) + expect(applyRankMove(list, "z", -1)).toBeNull() + }) + + test("input list is not mutated", () => { + expect(list).toEqual(["a", "b", "c"]) + }) +}) diff --git a/test/routing.test.ts b/test/routing.test.ts index fdab211..dcd45d7 100644 --- a/test/routing.test.ts +++ b/test/routing.test.ts @@ -307,6 +307,114 @@ describe("compute_lane", () => { expect(firstCross).toBeGreaterThanOrEqual(0) expect(firstCross).toBeLessThan(firstSame) }) + // [2026-09-06]-[health-aware backfill contract: a seat-limited base whose every candidate dies to runtime health + // gates (matrix-down / breaker) must backfill from the health-dropped set instead of reporting + // "all unavailable→terminal failure protocol"; structural drops (pool-config / modality) are never resurrected] + test("26a [2026-09-06] health-aware backfill: every seated candidate matrix-down → chain re-ranked from the health-dropped set (non-empty, status ok)", () => { + const base = ["glm-mx-53f-high", "ds-mx-v4fv-high"] + const matrix = matrixOk() + for (const name of base) matrix[manifest.shells.find((s) => s.name === name)!.matrixKey] = { status: "down" } + const r = computeLane("vision", base, { registry: fullRegistry(), matrix, routing: { down_agents: {}, down_expiry: {} } } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["matrix-down", "matrix-down"]) + expect([...r.chain.map((c) => c.shell)].sort()).toEqual([...base].sort()) + expect(r.status).toBe("ok") + }) + test("26b breaker-dropped candidate backfills the same way (health-class drop, single relaxed ranking pass)", () => { + const r = computeLane("main", ["glm-mx-53-high"], { + registry: fullRegistry(), + matrix: matrixOk(), + routing: { down_agents: { "glm-mx-53-high": "consecutive failures" }, down_expiry: {} }, + } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["breaker"]) + expect(r.chain.map((c) => c.shell)).toEqual(["glm-mx-53-high"]) + expect(r.status).toBe("ok") + }) + test("26c backfill must NOT resurrect pool-config-excluded candidates (lane stays exhausted)", () => { + const r = computeLane("vision", ["glm-mx-53f-high"], { + registry: fullRegistry(), + matrix: matrixOk(), + routing: { down_agents: {}, down_expiry: {} }, + poolConfig: { vision: new Set(["deepseek-v4-flash-vision-exp"]) }, + } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["pool-config"]) + expect(r.chain).toEqual([]) + expect(r.status).toBe("exhausted") + }) + test("26d backfill must NOT resurrect modality-mismatched candidates (lane stays exhausted)", () => { + const r = computeLane("vision", ["glm-mx-53-high"], { + registry: fullRegistry(), + matrix: matrixOk(), + routing: { down_agents: {}, down_expiry: {} }, + modality: "vision", + } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["modality"]) + expect(r.chain).toEqual([]) + expect(r.status).toBe("exhausted") + }) + test("26e mixed drops: the matrix-down candidate backfills, the pool-config-excluded one does not", () => { + const matrix = matrixOk() + matrix[manifest.shells.find((s) => s.name === "glm-mx-53f-high")!.matrixKey] = { status: "down" } + const r = computeLane("vision", ["glm-mx-53f-high", "glm-mx-53-high"], { + registry: fullRegistry(), + matrix, + routing: { down_agents: {}, down_expiry: {} }, + poolConfig: { vision: new Set(["glm-5.3-flash"]) }, // allows glm-5.3-flash, excludes glm-5.3 + } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["matrix-down", "pool-config"]) + expect(r.chain.map((c) => c.shell)).toEqual(["glm-mx-53f-high"]) + }) + test("26f no backfill while the chain is non-empty (healthy head stays; the down tail is not appended)", () => { + const matrix = matrixOk() + matrix[manifest.shells.find((s) => s.name === "ds-mx-v4fv-high")!.matrixKey] = { status: "down" } + const r = computeLane("vision", ["glm-mx-53f-high", "ds-mx-v4fv-high"], { registry: fullRegistry(), matrix, routing: { down_agents: {}, down_expiry: {} } } as any) + expect(r.chain.map((c) => c.shell)).toEqual(["glm-mx-53f-high"]) + }) + // [2026-09-06 pool-exhaustion-aware seats]-[observe-only SELECTION contract: a PROVEN-exhausted pool (snapshot-driven + // poolUnavailable resolver, same math as copilotExhausted but NOT policy-gated) must not take the head seat by tier + // (live incident: mechanical headed copilot-53codex-high — a strained 429 combo inside a 402-dead pool — while GLM + // was healthy); its candidates may only re-enter as the chain TAIL via the relaxed backfill pass when nothing + // healthy exists. No dispatch-denial semantics change] + test("26g proven-exhausted pool's tier-better shell loses the head seat to a healthy lower-tier shell (reason=pool-unavailable)", () => { + const r = computeLane("vision", ["copilot-mx-sol-high", "glm-mx-53f-high"], { + registry: fullRegistry(), + matrix: matrixOk(), + routing: { down_agents: {}, down_expiry: {} }, + poolUnavailable: (pool: string) => pool === "copilot", + } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["pool-unavailable"]) + expect(r.chain.map((c) => c.shell)).toEqual(["glm-mx-53f-high"]) + expect(r.status).toBe("ok") + }) + test("26h exhausted-pool shell backfills the chain TAIL when the lane would otherwise be empty (never ahead of healthy candidates)", () => { + const r = computeLane("vision", ["copilot-mx-sol-high"], { + registry: fullRegistry(), + matrix: matrixOk(), + routing: { down_agents: {}, down_expiry: {} }, + poolUnavailable: (pool: string) => pool === "copilot", + } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["pool-unavailable"]) + expect(r.chain.map((c) => c.shell)).toEqual(["copilot-mx-sol-high"]) + expect(r.status).toBe("ok") + }) + test("26i backfill class order: health-dropped candidates rank ahead of proven-exhausted-pool candidates", () => { + const r = computeLane("vision", ["glm-mx-53-high", "copilot-mx-sol-high"], { + registry: fullRegistry(), + matrix: matrixOk(), + routing: { down_agents: { "glm-mx-53-high": "consecutive failures" }, down_expiry: {} }, + poolUnavailable: (pool: string) => pool === "copilot", + } as any) + expect(r.dropped.map((d) => d.reason)).toEqual(["breaker", "pool-unavailable"]) + expect(r.chain.map((c) => c.shell)).toEqual(["glm-mx-53-high", "copilot-mx-sol-high"]) + }) + test("26j resolver absent or pool healthy → today's tier ordering unchanged (fail-open identity)", () => { + const p = { registry: fullRegistry(), matrix: matrixOk(), routing: { down_agents: {}, down_expiry: {} } } as any + // absent resolver: the tier-better exhausted-pool shell still heads, exactly as before the fix + const noResolver = computeLane("vision", ["copilot-mx-sol-high", "glm-mx-53f-high"], p) + expect(noResolver.chain.map((c) => c.shell)).toEqual(["copilot-mx-sol-high", "glm-mx-53f-high"]) + // resolver present but the pool not exhausted: unchanged + const healthy = computeLane("vision", ["copilot-mx-sol-high", "glm-mx-53f-high"], { ...p, poolUnavailable: () => false }) + expect(healthy.chain.map((c) => c.shell)).toEqual(["copilot-mx-sol-high", "glm-mx-53f-high"]) + }) }) // ================= 4. Breaker (3)================= diff --git a/test/scoring.test.ts b/test/scoring.test.ts index ff11396..a930318 100644 --- a/test/scoring.test.ts +++ b/test/scoring.test.ts @@ -245,6 +245,37 @@ describe("rankCandidates", () => { expect(r.ranked.map((s) => s.key)).toEqual(["strained"]) expect(r.breakdowns.get("strained")!.health).toBe(0.6) }) + test("[2026-09-06] relaxHealthGates: health gates (down/disabled/breaker/isolation) skip for the backfill pass; exhausted/retired gating stays active", () => { + const shells = [ + rankable({ key: "down", matrixStatus: "down" }), + rankable({ key: "breaker" }), + rankable({ key: "exhausted", pool: "copilot", family: "gpt", modelId: "gpt-5.6" }), + rankable({ key: "retired" }), + ] + const registry = { + down: shellReg({ name: "down" }), + breaker: shellReg({ name: "breaker" }), + exhausted: shellReg({ name: "exhausted", pool: "copilot", modelId: "gpt-5.6", family: "gpt" }), + retired: shellReg({ name: "retired", provider: "p", modelId: "m" }), + } + const r = rankCandidates(shells, ctx({ + routing: { down_agents: { breaker: "x" }, down_expiry: {} }, + registry, + quotaExhausted: { copilot: true }, + retiredModels: new Set(["p/m"]), + relaxHealthGates: true, + })) + // health-class candidates come back for the backfill; pool-exhausted and retired stay out + expect([...r.ranked.map((s) => s.key)].sort()).toEqual(["breaker", "down"]) + // without the flag the same input keeps today's hard-gate semantics + const strict = rankCandidates(shells, ctx({ + routing: { down_agents: { breaker: "x" }, down_expiry: {} }, + registry, + quotaExhausted: { copilot: true }, + retiredModels: new Set(["p/m"]), + })) + expect(strict.ranked).toEqual([]) + }) test("end-to-end mini sample: when main has no same-level B, fall back to the adjacent A rather than the farther S", () => { const shells = [ rankable({ key: "ds-s", modelId: "deepseek-v4-pro", pool: "deepseek", family: "deepseek", latencyMs: 5 }), diff --git a/test/subagent-cap.test.ts b/test/subagent-cap.test.ts new file mode 100644 index 0000000..1118571 --- /dev/null +++ b/test/subagent-cap.test.ts @@ -0,0 +1,140 @@ +// [2026-09-06]-[subagent hard cap behavioral contract: a shell subagent crossing the context cap is force-terminated — +// every further tool call in that session is denied with a wrap-up order, the session can never be resumed via task_id +// (persistent registry, survives plugin re-instantiation), internal sessions and sub-cap sessions are untouched, and +// fresh dispatches without task_id are unaffected] +import { describe, expect, test } from "bun:test" +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const configDir = mkdtempSync(join(tmpdir(), "switchman-subcap-config-")) +const stateDir = mkdtempSync(join(tmpdir(), "switchman-subcap-state-")) +process.env.OPENCODE_CONFIG_DIR = configDir +process.env.SWITCHMAN_STATE = stateDir +// [2026-09-06]-[model catalog stub: message.updated model-key recording consults the runtime index for the window cap] +writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) + +import { SwitchmanPlugin } from "../src/index" +import { + DEFAULT_SUBAGENT_CAP_TOKENS, MAX_SUBAGENT_CAP_TOKENS, MIN_SUBAGENT_CAP_TOKENS, + subagentCapOf, capByWindow, subagentCapDenyMessage, subagentResumeDenyMessage, +} from "../src/context-watch" + +type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> + +function readStatusLog(): string { + const p = join(stateDir, "status-log.json") + return existsSync(p) ? readFileSync(p, "utf8") : "" +} + +function assistantTokens(input: number): { role: "assistant"; tokens: { input: number; output: number; reasoning: number; cache: { read: number } } } { + // estimateContextTokens = input + output + reasoning + cache.read → +4_000 per event + return { role: "assistant", tokens: { input, output: 1_000, reasoning: 1_000, cache: { read: 2_000 } } } +} + +async function bootPlugin(): Promise<Hooks> { + const fakeClient = { + provider: { list: async () => [] }, + session: { + async get(opts: any) { return { data: { id: opts?.path?.id } } }, + }, + } + // [2026-09-06]-[legacy mode forced (same pattern as todo-nudge/pane-resume tests): the classification under test is + // sessionAgent-based; dynamic mode would need a probed superset for isShellSession] + return SwitchmanPlugin({ client: fakeClient, directory: "/w" } as any, { matrix: { mode: "legacy" } } as any) +} + +async function mark(hooks: Hooks, sessionId: string, input: number): Promise<void> { + await hooks.event!({ event: { type: "message.updated", properties: { sessionID: sessionId, info: assistantTokens(input) } } } as any) +} + +/** Register a shell child session (legacy mode classification: agent name matching /-mx-/) */ +async function seedShellSession(hooks: Hooks, sessionId: string, agent = "glm-mx-53f-low"): Promise<void> { + await hooks.event!({ event: { type: "session.created", properties: { info: { id: sessionId, agent } } } } as any) +} + +describe("subagent cap: pure decision layer", () => { + test("subagentCapOf: default 100k, clamped, disabled → null", () => { + expect(subagentCapOf(undefined)).toBe(DEFAULT_SUBAGENT_CAP_TOKENS) + expect(subagentCapOf({})).toBe(DEFAULT_SUBAGENT_CAP_TOKENS) + expect(subagentCapOf({ subagentForceTokens: 250_000 })).toBe(250_000) + expect(subagentCapOf({ subagentForceTokens: 1 })).toBe(MIN_SUBAGENT_CAP_TOKENS) + expect(subagentCapOf({ subagentForceTokens: 99_999_999 })).toBe(MAX_SUBAGENT_CAP_TOKENS) + expect(subagentCapOf({ subagentCap: false })).toBeNull() + expect(subagentCapOf({ subagentCap: false, subagentForceTokens: 50_000 })).toBeNull() + }) + test("capByWindow: never past 90% of the model window; unknown window keeps the base cap", () => { + expect(capByWindow(100_000, 200_000)).toBe(100_000) + expect(capByWindow(100_000, 100_000)).toBe(90_000) + expect(capByWindow(100_000, undefined)).toBe(100_000) + expect(capByWindow(100_000, -5)).toBe(100_000) + }) + test("deny messages carry the wrap-up order / permanent-termination guidance", () => { + const cap = subagentCapDenyMessage(101_000, 100_000) + expect(cap).toContain("SUBAGENT CONTEXT CAP REACHED") + expect(cap).toContain("101k/100k") + expect(cap).toContain("work-progress summary") + const resume = subagentResumeDenyMessage("ses_child1") + expect(resume).toContain("ses_child1") + expect(resume).toContain("can never be resumed") + expect(resume).toContain("without task_id") + }) +}) + +describe("subagent cap: plugin wiring", () => { + test("shell session crossing 100k → tools denied, task_id resume denied, registry persisted", async () => { + const hooks = await bootPlugin() + await seedShellSession(hooks, "ses_shell_cap") + // sub-cap watermark (94k measured): tools still allowed + await mark(hooks, "ses_shell_cap", 90_000) + await hooks["tool.execute.before"]!({ tool: "read", sessionID: "ses_shell_cap", callID: "call_pre" } as any, { args: {} } as any) + // crossing: measured context = 105_000 + 4_000 = 109k ≥ cap + await mark(hooks, "ses_shell_cap", 105_000) + expect(readStatusLog()).toContain("subagent context cap: session ses_shell_cap (glm-mx-53f-low)") + expect(readStatusLog()).toContain("session terminated") + await expect(hooks["tool.execute.before"]!({ tool: "read", sessionID: "ses_shell_cap", callID: "call_1" } as any, { args: {} } as any)).rejects.toThrow("SUBAGENT CONTEXT CAP REACHED") + await expect(hooks["tool.execute.before"]!({ tool: "bash", sessionID: "ses_shell_cap", callID: "call_2" } as any, { args: { command: "ls" } } as any)).rejects.toThrow("SUBAGENT CONTEXT CAP REACHED") + // resume from the main session via task_id → permanent denial + await expect(hooks["tool.execute.before"]!({ tool: "task", sessionID: "ses_main", callID: "call_3" } as any, { args: { subagent_type: "glm-mx-53f-low", task_id: "ses_shell_cap", prompt: "continue" } } as any)).rejects.toThrow("can never be resumed") + // fresh dispatch (no task_id) must NOT hit the resume deny (later gates may still speak, but never this one) + let freshErr: unknown = null + try { + await hooks["tool.execute.before"]!({ tool: "task", sessionID: "ses_main", callID: "call_4" } as any, { args: { subagent_type: "glm-mx-53f-low", prompt: "fresh" } } as any) + } catch (e) { freshErr = e } + expect(String(freshErr)).not.toContain("can never be resumed") + // let the fire-and-forget registry write land, then assert persistence + await new Promise((r) => setTimeout(r, 150)) + const reg = JSON.parse(readFileSync(join(stateDir, "subagent-cap.json"), "utf8")) + expect(reg.ses_shell_cap.tokens).toBe(109_000) + expect(reg.ses_shell_cap.agent).toBe("glm-mx-53f-low") + }, 30_000) + + test("internal sessions and main sessions are never terminated by the cap", async () => { + const hooks = await bootPlugin() + await seedShellSession(hooks, "ses_internal_title", "title") + await mark(hooks, "ses_internal_title", 180_000) + await mark(hooks, "ses_main_big", 180_000) + // the internal session's read passes the cap gate (the main-session read gate also exempts it); + // the main session at 180k is deliberately NOT read here — its own hard watermark gate owns that behavior + await hooks["tool.execute.before"]!({ tool: "read", sessionID: "ses_internal_title", callID: "call_i1" } as any, { args: {} } as any) + expect(readStatusLog()).not.toContain("ses_internal_title") + expect(readStatusLog()).not.toContain("termination") + // and its resume deny never fires (not a shell session) + let err: unknown = null + try { + await hooks["tool.execute.before"]!({ tool: "task", sessionID: "ses_main_big", callID: "call_i2" } as any, { args: { subagent_type: "glm-mx-53f-low", task_id: "ses_main_big" } } as any) + } catch (e) { err = e } + expect(String(err)).not.toContain("can never be resumed") + }, 30_000) + + test("termination survives plugin re-instantiation (persistent registry, no fresh message.updated needed)", async () => { + const hooks = await bootPlugin() // fresh instance, same SWITCHMAN_STATE → registry eager-loaded + await expect(hooks["tool.execute.before"]!({ tool: "task", sessionID: "ses_main", callID: "call_r1" } as any, { args: { subagent_type: "glm-mx-53f-low", task_id: "ses_shell_cap" } } as any)).rejects.toThrow("can never be resumed") + await expect(hooks["tool.execute.before"]!({ tool: "read", sessionID: "ses_shell_cap", callID: "call_r2" } as any, { args: {} } as any)).rejects.toThrow("SUBAGENT CONTEXT CAP REACHED") + }, 30_000) + + test("nested task inside a capped subagent session is denied by the same gate (a-branch, any tool class)", async () => { + const hooks = await bootPlugin() + await expect(hooks["tool.execute.before"]!({ tool: "task", sessionID: "ses_shell_cap", callID: "call_n1" } as any, { args: { subagent_type: "glm-mx-53f-low", prompt: "delegate onward" } } as any)).rejects.toThrow("SUBAGENT CONTEXT CAP REACHED") + }, 30_000) +}) diff --git a/test/tmux.test.ts b/test/tmux.test.ts new file mode 100644 index 0000000..65a1419 --- /dev/null +++ b/test/tmux.test.ts @@ -0,0 +1,327 @@ +// [2026-09-06]-[tmux pane mirroring behavioral contract: argv builders + TmuxPaneManager layout state machine +// (grow 1→2→3, FIFO queue beyond max, slot refill on completion, shrink 3→2→1→0, focus preservation, inert +// outside tmux, dead-pane self-heal). All tmux IO faked; no real tmux needed] +import { describe, expect, test } from "bun:test" +import { + TmuxPaneManager, + TMUX_PANE_MARKER, + defaultsOf, + killPaneArgs, + listPanesArgs, + resizePaneArgs, + respawnPaneArgs, + serverOriginOf, + setPaneTitleArgs, + splitPaneArgs, + viewerCommand, +} from "../src/tmux" +import type { TmuxOptions } from "../src/types" + +describe("tmux argv builders", () => { + test("splitPaneArgs: horizontal first split takes rightPct, keeps focus, prints pane id", () => { + expect(splitPaneArgs({ target: "%0", dir: "/p", axis: "h", size: "60%" })).toEqual([ + "split-window", "-d", "-P", "-F", "#{pane_id}", "-h", "-l", "60%", "-c", "/p", "-t", "%0", + ]) + }) + test("splitPaneArgs: vertical stack split + optional -b", () => { + expect(splitPaneArgs({ target: "%2", dir: "/p", axis: "v", size: "50%" })).toEqual([ + "split-window", "-d", "-P", "-F", "#{pane_id}", "-v", "-l", "50%", "-c", "/p", "-t", "%2", + ]) + expect(splitPaneArgs({ target: "%2", dir: "/p", axis: "v", size: "50%", before: true }).includes("-b")).toBe(true) + }) + test("viewerCommand: attach + session + quoted dir; mini flag", () => { + expect(viewerCommand({ origin: "http://127.0.0.1:50307", sessionId: "ses_a", dir: "/my proj", mini: false, bin: "opencode" })) + .toBe("opencode attach http://127.0.0.1:50307 -s ses_a --dir '/my proj'") + expect(viewerCommand({ origin: "http://127.0.0.1:1", sessionId: "ses_a", dir: "/p", mini: true }).includes(" --mini")).toBe(true) + }) + test("misc argv builders", () => { + expect(killPaneArgs("%3")).toEqual(["kill-pane", "-t", "%3"]) + expect(respawnPaneArgs({ target: "%3", dir: "/p", command: "opencode attach http://x -s ses_a" })).toEqual([ + "respawn-pane", "-k", "-c", "/p", "-t", "%3", "opencode attach http://x -s ses_a", + ]) + expect(resizePaneArgs({ target: "%3", height: 12.7 })).toEqual(["resize-pane", "-t", "%3", "-y", "12"]) + expect(setPaneTitleArgs({ target: "%3", title: "swm:tester" })).toEqual(["select-pane", "-T", "swm:tester", "-t", "%3"]) + expect(listPanesArgs("%0")).toEqual(["list-panes", "-t", "%0", "-F", "#{pane_id}\t#{pane_title}\t#{pane_start_command}"]) + }) + test("serverOriginOf: local http origins pass, OPENCODE_PORT fallback, remote/missing rejected", () => { + expect(serverOriginOf("http://127.0.0.1:50307/foo")).toBe("http://127.0.0.1:50307") + expect(serverOriginOf(new URL("http://localhost:4096"))).toBe("http://localhost:4096") + expect(serverOriginOf("https://remote.example.com", "50307")).toBe("http://127.0.0.1:50307") + expect(serverOriginOf(undefined)).toBeNull() + expect(serverOriginOf("https://remote.example.com")).toBeNull() + }) + test("defaultsOf clamps bad values", () => { + expect(defaultsOf(undefined)).toEqual({ enabled: true, rightPct: 60, maxPanes: 3, mini: false }) + expect(defaultsOf({ rightPct: 5, maxPanes: 99 } as TmuxOptions)).toEqual({ enabled: true, rightPct: 60, maxPanes: 3, mini: false }) + expect(defaultsOf({ rightPct: 70, maxPanes: 2, mini: true, enabled: false } as TmuxOptions)).toEqual({ enabled: false, rightPct: 70, maxPanes: 2, mini: true }) + }) +}) + +type Deps = ConstructorParameters<typeof TmuxPaneManager>[0] + +/** Fake tmux: records argv; split-window mints %N ids; display-message echoes the target (pane exists) */ +function fakeExec(log: string[][], o: { heights?: number[]; deadPanes?: Set<string>; activeSeq?: string[] } = {}) { + let next = 1 + let activeQuery = 0 + return async (args: string[]) => { + log.push(args) + const cmd = args[0] + if (cmd === "display-message") { + const fmt = args[args.length - 1] + const target = args[args.indexOf("-t") + 1] ?? "" + if (o.deadPanes?.has(target)) throw new Error(`can't find pane: ${target}`) + if (fmt === "#{window_id}") return "@1" + if (fmt === "#{pane_height}") return String(o.heights?.[0] ?? 30) + if (fmt === "#{pane_id}" && target === "@1") return o.activeSeq ? o.activeSeq[Math.min(activeQuery++, o.activeSeq.length - 1)] : target + return target + } + if (cmd === "list-panes") return "%0\tmain\t" + if (cmd === "split-window") return `%${next++}` + return "" + } +} + +function manager(log: string[][], opts: Partial<TmuxOptions> = {}, execOpts: Parameters<typeof fakeExec>[1] = {}): TmuxPaneManager { + const full: TmuxOptions = { enabled: true, rightPct: 60, maxPanes: 3, mini: false, ...opts } + return new TmuxPaneManager({ + env: { TMUX: "/tmp/sock,1,0", TMUX_PANE: "%0" }, + options: () => full, + serverOrigin: "http://127.0.0.1:50307", + dir: "/proj", + exec: fakeExec(log, execOpts), + log: () => {}, + }) +} + +const calls = (log: string[][], cmd: string) => log.filter((a) => a[0] === cmd) + +async function inited(m: TmuxPaneManager, log: string[][]): Promise<TmuxPaneManager> { + await m.init() + log.length = 0 + return m +} + +describe("TmuxPaneManager lifecycle", () => { + test("inert outside tmux (no TMUX env): init not ready, dispatches are no-ops", async () => { + const log: string[][] = [] + const m = new TmuxPaneManager({ + env: {}, + options: () => ({ enabled: true, rightPct: 60, maxPanes: 3, mini: false }), + serverOrigin: "http://127.0.0.1:1", + dir: "/p", + exec: fakeExec(log), + log: () => {}, + }) + await m.init() + m.noteChild("main", "ses_a", "glm-mx-53f-low") + await m.flush() + expect(m.stats().ready).toBe(false) + expect(log).toEqual([]) + }) + + test("disabled via options: inert even inside tmux", async () => { + const log: string[][] = [] + const m = await inited(manager(log, { enabled: false }), log) + m.noteChild("main", "ses_a", "glm-mx-53f-low") + await m.flush() + expect(m.stats().panes).toBe(0) + expect(log).toEqual([]) + }) + + test("first dispatch: split home pane -h 60%, spawn attach viewer, label the pane", async () => { + const log: string[][] = [] + const m = await inited(manager(log), log) + m.noteChild("main", "ses_abc", "glm-mx-53f-low") + await m.flush() + expect(m.stats().panes).toBe(1) + const splits = calls(log, "split-window") + expect(splits.length).toBe(1) + expect(splits[0]).toEqual(splitPaneArgs({ target: "%0", dir: "/proj", axis: "h", size: "60%" })) + const resawns = calls(log, "respawn-pane") + expect(resawns.length).toBe(1) + expect(resawns[0][resawns[0].length - 1]).toContain("opencode attach http://127.0.0.1:50307 -s ses_abc") + expect(calls(log, "select-pane").some((a) => a.includes(`${TMUX_PANE_MARKER}glm-mx-53f-low`))).toBe(true) + }) + + test("second dispatch: vertical 50% split of the first right pane, first pane not respawned", async () => { + const log: string[][] = [] + const m = await inited(manager(log), log) + m.noteChild("main", "ses_a", "agent-a") + await m.flush() + log.length = 0 + m.noteChild("main", "ses_b", "agent-b") + await m.flush() + expect(m.stats().panes).toBe(2) + const splits = calls(log, "split-window") + expect(splits.length).toBe(1) + expect(splits[0]).toEqual(splitPaneArgs({ target: "%1", dir: "/proj", axis: "v", size: "50%" })) + expect(calls(log, "respawn-pane").length).toBe(1) + expect(calls(log, "kill-pane").length).toBe(0) + }) + + test("third dispatch: split + re-even resize of the top pane (thirds)", async () => { + const log: string[][] = [] + const m = await inited(manager(log, {}, { heights: [40] }), log) + m.noteChild("main", "ses_a", "agent-a") + await m.flush() + m.noteChild("main", "ses_b", "agent-b") + await m.flush() + log.length = 0 + m.noteChild("main", "ses_c", "agent-c") + await m.flush() + expect(m.stats().panes).toBe(3) + // full column = 40+40+40=120 lines (the new pane is measured explicitly — live-test regression) → floor(120/3)=40 + const resizes = calls(log, "resize-pane") + expect(resizes.length).toBe(1) + expect(resizes[0]).toEqual(resizePaneArgs({ target: "%1", height: 40 })) + }) + + test("fourth dispatch beyond maxPanes: queued, no tmux ops; finishing a visible child swaps in the queued one on the freed pane", async () => { + const log: string[][] = [] + const m = await inited(manager(log), log) + for (const [id, agent] of [["ses_a", "a"], ["ses_b", "b"], ["ses_c", "c"], ["ses_d", "d"]] as const) m.noteChild("main", id, agent) + await m.flush() + expect(m.stats().panes).toBe(3) + expect(m.stats().queued).toBe(1) + expect(calls(log, "split-window").length).toBe(3) + log.length = 0 + m.noteChildEnd("ses_a") // displayed → ses_d takes over the pane, column stays at 3 + await m.flush() + expect(m.stats().panes).toBe(3) + expect(m.stats().queued).toBe(0) + expect(calls(log, "kill-pane").length).toBe(0) + expect(calls(log, "respawn-pane").length).toBe(1) + expect(calls(log, "respawn-pane")[0][calls(log, "respawn-pane")[0].length - 1]).toContain("-s ses_d") + }) + + test("completions shrink the column: 3→2 (kill + re-even), 2→1 (kill), 1→0 (last kill restores the main pane)", async () => { + const log: string[][] = [] + const m = await inited(manager(log, {}, { heights: [30] }), log) + for (const id of ["ses_a", "ses_b", "ses_c"]) m.noteChild("main", id, "agent") + await m.flush() + log.length = 0 + m.noteChildEnd("ses_a") + await m.flush() + expect(m.stats().panes).toBe(2) + expect(calls(log, "kill-pane").length).toBe(1) + // survivors (%2/%3) measured 30+30=60 lines → top pane pulled to 30 (even halves) + expect(calls(log, "resize-pane")[0]).toEqual(resizePaneArgs({ target: "%2", height: 30 })) + log.length = 0 + m.noteChildEnd("ses_b") + await m.flush() + expect(m.stats().panes).toBe(1) + expect(calls(log, "kill-pane").length).toBe(1) + expect(calls(log, "resize-pane").length).toBe(0) + log.length = 0 + m.noteChildEnd("ses_c") + await m.flush() + expect(m.stats()).toMatchObject({ panes: 0, queued: 0, tracked: 0 }) + expect(calls(log, "kill-pane").length).toBe(1) + }) + + test("unknown/queued child end is a no-op on layout; duplicate noteChild is idempotent", async () => { + const log: string[][] = [] + const m = await inited(manager(log), log) + m.noteChild("main", "ses_a", "a") + m.noteChild("main", "ses_a", "a") // duplicate + await m.flush() + expect(m.stats().panes).toBe(1) + log.length = 0 + m.noteChildEnd("ses_unknown") + await m.flush() + expect(log).toEqual([]) + }) + + // [2026-09-06 fix]-[resume contract: "repeat-call a previously used subagent" is a task_id REUSE of the same child + // session (no session.created fires) — noteChild must (re)display it in both stale-slot and completed states] + test("resume of the same child re-displays after its viewer pane was user-closed (stale slot swept before the duplicate check)", async () => { + const log: string[][] = [] + const dead = new Set<string>() + const m = await inited(manager(log, {}, { deadPanes: dead }), log) + m.noteChild("main", "ses_a", "agent-a") + await m.flush() + expect(m.stats().panes).toBe(1) + dead.add("%1") // user quit the viewer pane while the child still runs (slot lingers up to one 4s poll period) + log.length = 0 + m.noteChild("main", "ses_a", "agent-a") // main session resumes the same subagent (task_id reuse) + await m.flush() + expect(m.stats().panes).toBe(1) + const resawns = calls(log, "respawn-pane") + expect(resawns.length).toBe(1) + expect(resawns[0][resawns[0].length - 1]).toContain("-s ses_a") + expect(m.tracking("ses_a")).toBe(true) + }) + + test("resume of a finished child (slot already closed by completion) opens a fresh pane", async () => { + const log: string[][] = [] + const m = await inited(manager(log), log) + m.noteChild("main", "ses_a", "agent-a") + await m.flush() + m.noteChildEnd("ses_a") + await m.flush() + expect(m.stats().panes).toBe(0) + log.length = 0 + m.noteChild("main", "ses_a", "agent-a") // task_id reuse of the finished session + await m.flush() + expect(m.stats().panes).toBe(1) + expect(calls(log, "split-window").length).toBe(1) + const resawns = calls(log, "respawn-pane") + expect(resawns[0][resawns[0].length - 1]).toContain("-s ses_a") + }) + + test("focus preservation: if the window's active pane moved during ops, select-pane restores it", async () => { + const log: string[][] = [] + // active-pane query sequence: %0 before ops, %1 after (split moved focus) → restore to %0 + const m = await inited(manager(log, {}, { activeSeq: ["%0", "%1"] }), log) + m.noteChild("main", "ses_a", "a") + await m.flush() + const selects = calls(log, "select-pane").filter((a) => a[1] === "-t") + expect(selects[selects.length - 1]).toEqual(["select-pane", "-t", "%0"]) + }) + + test("dead pane self-heal: a vanished slot pane is dropped, layout reconciled, queued child promoted", async () => { + const log: string[][] = [] + const dead = new Set<string>() + const m = await inited(manager(log, {}, { deadPanes: dead }), log) + m.noteChild("main", "ses_a", "a") + await m.flush() + m.noteChild("main", "ses_b", "b") + await m.flush() + expect(m.stats().panes).toBe(2) + dead.add("%1") // user closed the first subagent pane + m.noteChild("main", "ses_c", "c") // any new event triggers reconcile + await m.flush() + expect(m.stats().panes).toBe(2) + // ses_a's pane gone → dropped; ses_c fills the freed slot; ses_b keeps its pane + const resawns = calls(log, "respawn-pane") + expect(resawns.some((a) => String(a[a.length - 1]).includes("-s ses_c"))).toBe(true) + expect(m.tracking("ses_a")).toBe(true) // still running server-side, just not displayed + m.noteChildEnd("ses_a") + await m.flush() + expect(m.tracking("ses_a")).toBe(false) + }) + + test("init sweeps leftover panes from a previous run (title marker or attach start command)", async () => { + const log: string[][] = [] + const exec = async (args: string[]) => { + log.push(args) + if (args[0] === "display-message") return args[args.length - 1] === "#{window_id}" ? "@1" : args[args.indexOf("-t") + 1] ?? "" + if (args[0] === "list-panes") { + return ["%0\tmain\t", "%2\tswm:old-agent\topencode attach http://x -s ses_old", "%3\tuser-pane\t"].join("\n") + } + return "" + } + const m = new TmuxPaneManager({ + env: { TMUX: "s", TMUX_PANE: "%0" }, + options: () => ({ enabled: true, rightPct: 60, maxPanes: 3, mini: false }), + serverOrigin: "http://127.0.0.1:1", + dir: "/p", + exec, + log: () => {}, + }) + await m.init() + const kills = calls(log, "kill-pane") + expect(kills).toEqual([killPaneArgs("%2")]) + expect(m.stats().ready).toBe(true) + }) +})