From 833641869b8fca584c5b4b570570efde5e5f2d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B1=B3=E6=96=AF=E7=89=B9=E6=8A=98=E8=85=BE?= <814442321@qq.com> Date: Tue, 15 Sep 2026 09:26:22 +0800 Subject: [PATCH 1/4] feat: shell soft-tier advisories, per-turn [ROUTE] line, dispatch opt-out, and META synthesis gates 1. Shell advisories reuse the main session's absolute soft/hard thresholds (conserve 60k / hand-off 80k / shared 120k cap, window-clamped pull-down); subagentForceTokens is now an optional override defaulting to forceTokens 2. Per-turn [ROUTE] token-economy line plus a project-level dispatch:"off" opt-out that stands down all task-call governance (cap/lang gates stay on) 3. Gate 6 synthesizes missing/malformed ROUTE_META with an observe note instead of denying; the three plugin-side META-rewrite retry paths in index.ts collapse into the single gate-side synthesis 4. Locale-following first-run language ask (env LC_ALL -> LANG -> en, byte-stable capture anchor) and injection mode "configured" narrowing the injected shell face to the configured set --- CHANGELOG.md | 14 +++ docs/reference.md | 15 +-- docs/reference.zh.md | 15 +-- src/assets/agents-md.ts | 6 +- src/assets/delegation-template.ts | 2 +- src/config.ts | 21 ++-- src/context-watch.ts | 62 ++++++++++- src/dispatch-mode.ts | 72 ++++++++++++ src/gates.ts | 55 ++++++++- src/index.ts | 158 ++++++++++++++++++-------- src/lang-config.ts | 113 ++++++++++++++++++- src/route-line.ts | 18 +++ src/shells.json | 2 +- src/shells.ts | 31 ++++-- src/types.ts | 12 +- test/auto-redirect.test.ts | 43 ++++--- test/dispatch-gates.test.ts | 167 +++++++++++++++++++++++++++- test/dispatch-mode.test.ts | 93 ++++++++++++++++ test/index-options.test.ts | 27 +++++ test/lang-config.test.ts | 78 ++++++++++++- test/route-line.test.ts | 62 +++++++++++ test/routing.test.ts | 16 ++- test/shell-context-advisory.test.ts | 115 +++++++++++++++++++ test/shells-select.test.ts | 32 ++++++ test/subagent-cap.test.ts | 105 +++++++++++++++-- 25 files changed, 1203 insertions(+), 131 deletions(-) create mode 100644 src/dispatch-mode.ts create mode 100644 src/route-line.ts create mode 100644 test/dispatch-mode.test.ts create mode 100644 test/route-line.test.ts create mode 100644 test/shell-context-advisory.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c2dc50..6fd5c41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes describe user-visible behavior; implementation details remain in the technical specification and commit history. +## [Unreleased] + +### Added + +- **Injection face mode `configured` (`injection.mode`)** — a third shell-injection mode that narrows the per-request task-tool description to exactly what can actually dispatch: when a favorites/visible set is configured, runtime dispatch is already gated by activation (configured ∪ session models) ∩ pool selection, so off-configured chain picks are dead context. `configured` skips the six-lane chain picks and injects only the configured models' shells, plus custom-lane and pool-config force-keeps (both stay dispatch-capable). With no favorites/visible set configured it behaves identically to `chain` (fail-open). Startup-level: restart to apply. +- **Shell subagent soft tiers with inline HANDOFF relay (shared absolute thresholds)** — shell subagents previously jumped straight from "no signal" to the hard-cap termination. Two graceful advisories now precede it, reusing the MAIN session's absolute soft/hard thresholds (soft 60k conserve / hard 80k hand-off by default — subagent context is equally token-expensive as main-session context), so there are no user-facing fraction coefficients: a conserve advisory (stop batch reads and long pastes, switch to targeted grep, keep outputs compact) and a hand-off advisory (finish the current unit, then end the final message with a compact handover block followed by the marker line `HANDOFF: inline · progress: n/m · next: `; that final message returns to the delegating session as the task result). The window-clamped effective cap still pulls the tiers down proportionally, so a tier can never exceed the real termination line and small-window shells keep headroom before it. Both report the measured numbers in absolute k, fire at most once per tier per shell session (in-memory dedup, cleared on session deletion; a restart re-arms), and ride the same per-turn system-prompt surface as the session watermark — the hard cap stays the termination backstop, and `subagentCap: false` disables the advisories together with it. The dispatcher side ships in the same release: the bundled protocol §2 gains the shell-handoff-relay rule (treat the handover block as the authoritative remaining-work state; start a fresh re-seeded dispatch, never resume the spent session). Config surface: the tiers follow the session's `softTokens`/`hardTokens`; the shell's termination line follows `forceTokens` by default, overridable via the now-optional `context.subagentForceTokens` (validated 20k..1M; invalid → deleted, falling back to `forceTokens`, fail-open). Restart to apply. +- **Per-turn `[ROUTE]` routing-discipline line** — main sessions now get one `[ROUTE]` line per turn, pushed after `[WATERMARK:SESSION]`/`[TODO]` under the same rules/banner visibility switch (both off = no line, respecting the zero-injection wish). It carries only what the injected lines lack today: the token cost model (hands-on spends and grows this session's context on every later turn; a dispatch spends a fresh shell context and returns a summary) and the declaration discipline, which protocol §6 widens from "before a major action" to "before each substantive action (the enumeration below is the minimum set, not the ceiling)". The line renders from a single pure module, so the text can never drift between surfaces. Restart to apply. +- **Language-preference ask follows the UI locale** — the first-run ask's three question texts are now localized into all 11 candidate tags (en, zh-CN, zh-TW, ja, ko, es, fr, de, it, pt, ru), detected at ask time from the environment (`LC_ALL` → `LANG`, env-style values like `zh_CN.UTF-8` normalized — `zh-HK` maps to `zh-TW` — with an English fallback when nothing matches) and surfaced once per ask activation in the status log (`lang ask locale=…`). Only the question texts localize: the `switchman-lang n/3:` marker prefix, the directive body and the gate's deny copy stay byte-stable English, so the plugin-side answer capture works identically in every locale. Restart to apply. +- **`dispatch: "off"` project opt-out** — a project can now stand down all dispatch governance by setting the top-level `"dispatch": "off"` in `.switchman/settings.json` (the same file the lang config lives in; read per call, so toggling takes effect on the next task call without a restart). Only the exact string `"off"` opts out — anything else (or an absent field) keeps fleet behavior, and a present-but-different value gets a one-time status-log note. When off, task calls are allowed ungoverned: the whole task path stands down (uninjected-shell and built-in-agent denies with their auto-redirects, all six gates including the breaker deny and the ROUTE_META/semantics checks). Deliberately still on: the subagent hard cap and its resume deny, the language gate, read/watermark gates, auto-handover, breaker failure recording, and the banner/watermark/TODO/`[LANG]` lines — the per-turn `[ROUTE]` line is the only prompt surface that hides. A `.switchman/settings.json` that is not valid JSON at all now warns once per process in the status log (`… is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)`); the "exists but no valid lang block" case stays silent as before. Restart to apply. + +### Changed + +- **ROUTE_META gate downgraded from deny to synthesize-and-observe** — a delegation prompt with a missing or unparseable ROUTE_META line is no longer hard-denied: the gate synthesizes a lane-default META (lane from the shell's lane, the lane's default role, matching capability/modality, `source: auto`) and lets the dispatch through to the semantic checks with a status-log note. This also removes the three inconsistent corners where the old deny still bit (auto-redirect off, the review lane, synthesis failure) and collapses the prompt-rewriting synthesis retries into the gate itself — redirected dispatches now carry the prompt as-is. Behavior change on upgrade: projects that relied on the missing-META deny as a discipline prod lose it (the `[ROUTE]` line's declaration discipline is the replacement surface); a **present-but-wrong** META (an illegal field value, or a parseable line missing required fields) still denies with the sample attached — only absence is synthesized. Declaring META remains the contract that unlocks cross-family review ranking and `source: user` pinning. Restart to apply. + ## [1.0.4] - 2026-09-11 ### Added diff --git a/docs/reference.md b/docs/reference.md index 2fe9415..c72d3a8 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -126,12 +126,13 @@ The plugin loads the repo's `dist` bundle directly; after `git pull`, re-run `bu | `banner.enabled` | `true` | Four-line banner injection | | `rules.enabled / delegationFloor` | `true / 3000` | Bundled dispatcher rules (AGENTS.md) injection; `delegationFloor` is the self-do token floor interpolated into the rules (dispatch by default below it is a violation) | | `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 60000 / 80000 / 120000 / 1500 / true` | **Measured session watermark + self-read budget**: the plugin measures each main session's context from message token usage and injects a live `[WATERMARK:SESSION]` line every turn (with per-turn growth and remaining-turns-to-hard estimates). Every self-read is costed against `readBudgetTokens` from turn 1: over-budget reads are auto-bounded (a `limit` is auto-appended) or denied with exact bounded-retry params, and a per-turn 2× cap stops read chains; un-estimable tool outputs are charged post-hoc. Verification/delivery bash (git, test/lint, build) always passes; unbounded history dumps (`git log -p` without `-n`) are always denied with a scoping hint; past `hardTokens` read-class closes (wrap-up mode); past `forceTokens` the banner demands compaction and, with `autoHandover: true` (default), `/handover` fires automatically: full fork backup + compaction, the running task continues on the summarized context. Shell subagent sessions are exempt from this watermark and get their own single hard cap instead (see `context.subagentForceTokens` / `context.subagentCap` below); all three thresholds are additionally capped at 90% of the current session model's context window when known (models.dev) | -| `context.subagentForceTokens / subagentCap` | `100000 / true` | **Subagent context hard cap**: shell subagent sessions get a single hard cap (measured = input + output + reasoning + cache.read of the latest assistant message, same estimator as the session watermark), clamped 20k..1M and additionally capped at 90% of the shell model's context window. On crossing, every further tool call in that subagent session is denied with a wrap-up order; the subagent's next text-only answer (a detailed work-progress summary) becomes the task result returned to the delegating session and the session is permanently terminated. Later `task` calls resuming it via `task_id` are denied permanently (persistent registry `~/.config/opencode/opencode-switchman/subagent-cap.json`); fresh dispatches without `task_id` are unaffected; `subagentCap: false` prevents new terminations only — already-terminated sessions stay dead | +| `context.subagentForceTokens / subagentCap` | `follows forceTokens (120000) / true` | **Subagent context hard cap + soft-tier advisories**: 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 when overridden and additionally capped at 90% of the shell model's context window; absent → follows the main session's `forceTokens`, one absolute termination line shared by default. Two graceful advisories precede the termination, reusing the main session's absolute soft/hard thresholds (`softTokens` = conserve, `hardTokens` = hand-off — subagent context is equally token-expensive); the window-clamped effective cap pulls them down proportionally, so a tier never exceeds the real termination line. On crossing the cap, 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. Each advisory tier fires at most once per shell session (in-memory dedup, cleared on session deletion; a restart re-arms); the dispatcher protocol's relay rule treats that handover as the authoritative remaining-work state (fresh re-seeded dispatch, never resume the spent session). Later `task` calls resuming a terminated session 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 and disables the advisories. A present-but-invalid `subagentForceTokens` override (non-finite / outside 20k..1M) is deleted with an SWM037 diagnostic, falling back to `forceTokens` (fail-open) | | `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 | +| `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), `configured` = [2026-09-11] when a favorites/visible set is configured, only those models' shells are injected (custom-lane/pool-config force-keeps stay) — off-configured chain picks can never pass the runtime activation gate anyway, so this removes dead per-request context; with nothing configured it behaves like `chain`. 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 | +| `dispatch: "off"` (in `.switchman/settings.json`) | absent (fleet) | Project-level dispatch opt-out: the top-level `"dispatch": "off"` in `.switchman/settings.json` stands down all dispatch governance for task calls — the whole task path is skipped (uninjected/built-in denies with their auto-redirects, all six gates including the breaker deny) and calls are allowed ungoverned. Only the exact string `"off"` opts out; anything else keeps fleet behavior (a present-but-different value gets a one-time status-log note). Deliberately still on: the subagent hard cap, the language gate, read/watermark gates, auto-handover, breaker failure recording, and the banner/watermark/TODO/`[LANG]` lines — the per-turn `[ROUTE]` line is the only prompt surface that hides. Read per call, so toggling takes effect without a restart; a settings.json that is not valid JSON at all warns once per process in the status log | | `relay.image` | `true` | Vision-less main models: user-attached images are decoded to disk and replaced with path text + reading guidance (delegate a vision-lane shell or an MCP vision tool); local paths / http URLs pass through; fully fail-open | -| `lang.enabled / ask / candidates` | `true / true / factory list` | Per-project language preference: per-turn `[LANG]` iron-rule line (conversation / comments & commits / docs), first-use ask re-surfaced every user turn until configured and enforced by a hard gate (write/edit/bash/task denied while unconfigured; decline waives per session), persisted to `.switchman/settings.json` (AGENTS.md marker as read-only fallback), `/switchman-lang` re-asks | +| `lang.enabled / ask / candidates` | `true / true / factory list` | Per-project language preference: per-turn `[LANG]` iron-rule line (conversation / comments & commits / docs), first-use ask re-surfaced every user turn until configured and enforced by a hard gate (write/edit/bash/task denied while unconfigured; decline waives per session), persisted to `.switchman/settings.json` (AGENTS.md marker as read-only fallback), `/switchman-lang` re-asks. The ask's question texts follow the detected UI locale (env `LC_ALL` → `LANG`, normalized — `zh_CN.UTF-8` → `zh-CN` — with an English fallback; only the questions localize, the marker prefix and directive body stay stable English) | | `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 | @@ -223,7 +224,7 @@ opencode-switchman splits orchestration into three layers: |---|---|---| | **Cognitive** | Primary model (dispatcher) + bundled dispatcher rules | Four-dimension task profiling (cognitive intensity × mechanicalness × context size × urgency), self-do vs. delegate, lane & shell choice, writing DELEGATION_V1 prompts | | **Execution** | "model × effort" bare shells (e.g. `glm-mx-53-high`) | Bind only model and reasoning effort; roles are assigned dynamically by the delegation prompt (14 roles: programmer/tester/reviewer/…) | -| **Deterministic** | The plugin | Six-gate interception, ROUTE_META hard validation, weighted model scoring, quota/cost-aware chain computation, probe / breaker / real-dispatch isolation, live four-line banner | +| **Deterministic** | The plugin | Six-gate interception, ROUTE_META validation (missing → lane-synthesized, illegal → deny), weighted model scoring, quota/cost-aware chain computation, probe / breaker / real-dispatch isolation, live four-line banner | **Token economics is the first principle**: rework is the most expensive token. Hence six cognitive lanes: @@ -274,7 +275,7 @@ On every subagent dispatch, the plugin runs deterministic checks before the task | 2 Probe matrix | combo measured down / retired | block the clearly unavailable; consecutive 404 retires a vanished model | | 3 Breaker / isolation | ≥2 failures within 600s or real-dispatch isolation active | "tripping, auto-recovers in ~10 min" / "isolated after real dispatch failure" | | 4 Pool exhausted | quota says the call must fail | human-readable reason (GLM 100% / Copilot definitively out / DS overdrawn) | -| 5 Protocol | ROUTE_META missing / illegal | deny with sample & legal values | +| 5 Protocol | ROUTE_META missing / illegal | missing or unparseable line → synthesized from the shell's lane and allowed with a status-log note; a present-but-wrong line (illegal value / missing required field) denies with sample & legal values | | 6 Semantics | same-family review / rw→ro shell / image→non-vision | "review needs a hetero-family lens", etc. | ROUTE_META is a single-line protocol embedded in the delegation prompt, six keys, validated field by field: @@ -320,11 +321,11 @@ Routing is now an explicit, traceable score rather than a hidden preference list ## 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). +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`, optional — absent follows the main session's `forceTokens`, i.e. 120,000 tokens by default, so one absolute termination line is shared; clamped 20k..1M when present, 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. Two graceful advisories precede the termination, reusing the main session's absolute soft/hard thresholds (`softTokens` conserve / `hardTokens` hand-off — subagent context is equally token-expensive as main-session context), with the window-clamped effective cap pulling them down proportionally. On crossing the cap, 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). +Configured by `context.subagentForceTokens` (optional — default follows `forceTokens`) / `context.subagentCap` (default `true`) in `opencode-switchman.jsonc` (see the Options table). ## Artifact workspace (.switchman) diff --git a/docs/reference.zh.md b/docs/reference.zh.md index a432398..fb4fdd6 100644 --- a/docs/reference.zh.md +++ b/docs/reference.zh.md @@ -126,12 +126,13 @@ bun run build # 生成 dist/opencode-switchman.js | `banner.enabled` | `true` | 四行横幅注入开关 | | `rules.enabled / delegationFloor` | `true / 3000` | 调度员规程(AGENTS.md)随包注入开关;`delegationFloor`=自做底价(token),注入规程时插值 | | `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 60000 / 80000 / 120000 / 1500 / true` | **会话上下文水位实测+自读预算闸**:插件从消息 token usage 实测主会话上下文并每轮注入 `[WATERMARK:SESSION]` 行(附每轮增速与距硬水位剩余轮数估算)。自读从第 1 轮起按 `readBudgetTokens` 计费:预估超限的读取自动追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮另有 2× 上限阻断连续读取,无法预估的工具输出事后记账。验证/交付类 bash(git、测试/lint、构建)全水位放行;无界历史翻查(如不带 `-n` 的 `git log -p`)任何水位一律拦截并附收窄提示;超硬水位读取类关闭(收尾模式);超压水位横幅强制立即压缩,且 `autoHandover: true`(默认)时自动触发 `/handover`:完整分叉备份+压缩,未完成的任务在摘要上下文上继续。壳子代理会话不适用本水位,改走自身的单道硬顶(见 `context.subagentForceTokens` / `context.subagentCap`);三档水位在可知时额外以当前会话模型上下文窗口(models.dev)的 90% 封顶 | -| `context.subagentForceTokens / subagentCap` | `100000 / true` | **子代理上下文硬顶**:壳子代理会话只有一道硬顶(实测=最新 assistant 消息的 input + output + reasoning + cache.read,与会话水位同口径),钳制 20k..1M 并额外以壳模型上下文窗口的 90% 封顶。触顶即拒绝该会话所有后续工具调用并下达收尾指令,子代理的下一份纯文本答复(详细的工作进度总结)直接作为任务结果返回委派方,会话永久终止;此后带 `task_id` 恢复该会话的 `task` 调用一律永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响;`subagentCap: false` 只阻止新的终止——已终止的会话不复活 | +| `context.subagentForceTokens / subagentCap` | `跟随 forceTokens(120000)/ true` | **子代理上下文硬顶+软档提醒**:壳子代理会话只有一道硬顶(实测=最新 assistant 消息的 input + output + reasoning + cache.read,与会话水位同口径),显式覆盖时钳制 20k..1M,并额外以壳模型上下文窗口的 90% 封顶;缺省跟随主会话 `forceTokens`,默认共享同一条绝对终止线。硬顶终止之前有两档柔性提醒,直接复用主会话的绝对软/硬阈值(`softTokens`=省着用,`hardTokens`=收尾交接——子代理上下文与主会话上下文同等昂贵);有效上限(含窗口封顶)按比例下拉两档,档位永不超过真实终止线。触顶即拒绝该会话所有后续工具调用并下达收尾指令,子代理的下一份纯文本答复(详细的工作进度总结)直接作为任务结果返回委派方,会话永久终止。每档每次会话最多触发一次(进程内去重,会话删除即清除;重启后重新武装);调度规程的交接转发规则把该交接块视为剩余工作的权威状态(全新派发、只注入所需上下文,绝不续接已耗尽的会话)。此后带 `task_id` 恢复该会话的 `task` 调用一律永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响;`subagentCap: false` 既阻止新的终止也一并关闭提醒。`subagentForceTokens` 覆盖值非法(非有限数 / 超出 20k..1M)时删除该覆盖并报 SWM037 诊断,回退跟随 `forceTokens`(fail-open) | | `builtinAgents.mode` | `deny` | 内置 explore/general 与壳路由抢任务且此前放行;`deny`=拦截附 economy/main 改派建议,`allow`=恢复放行 | -| `injection.mode` | `chain` | 壳注入面:`chain`=六档链精选∪favorites/可见集(task 工具描述每会话省约 6-10k token,链外模型点名走 denyUninjected 提示);`all`=可用全集(旧行为)。启动级,重启生效 | +| `injection.mode` | `chain` | 壳注入面:`chain`=六档链精选∪favorites/可见集(task 工具描述每会话省约 6-10k token,链外模型点名走 denyUninjected 提示);`all`=可用全集(旧行为);`configured`=[2026-09-11] 配置了 favorites/可见集时仅注入这些模型的壳(自定义泳道/pool-config 强制保留照旧)——链外精选本就过不了运行时 activation 门,删掉纯死的每请求上下文;未配置时与 `chain` 行为一致。启动级,重启生效 | | `dispatch.autoRedirect` | `true` | 派发被拒时在途改写 `subagent_type` 到拒绝消息已点名的链首候选(单跳、同快照守卫复检)——首次派发直接落在最优可用壳上,不再烧「拒绝-重试」轮次;`false` 恢复拒绝-重试 | +| `dispatch: "off"`(`.switchman/settings.json`) | 缺省(fleet) | 项目级派发退出:`.switchman/settings.json` 顶层 `"dispatch": "off"` 让所有派发治理对该项目的 task 调用停摆——整条 task 路径跳过(未注入/内置代理拒绝及其自动改写、全部六闸含熔断拒绝),调用不受治理直接放行。只有精确的字符串 `"off"` 生效,其他任何值保持 fleet 行为(存在但不同的值会记一条一次性状态日志)。刻意不停摆:子代理硬上限、语言闸、读取/水位闸、自动交接、熔断失败记账,以及横幅/水位/TODO/`[LANG]` 行——每轮 `[ROUTE]` 行是唯一隐藏的 prompt 表面。逐调用读取,切换无需重启;settings.json 完全不是合法 JSON 时按进程一次性写入状态日志警告 | | `relay.image` | `true` | 无视觉主模型:用户附带图片自动落盘并替换为路径文本+阅读指引(委托 vision 壳或交给 MCP 视觉工具);本地路径 / http URL 原样透传;全程 fail-open | -| `lang.enabled / ask / candidates` | `true / true / 出厂清单` | 项目级语言偏好:每轮 `[LANG]` 铁律行(会话 / 注释与提交 / 文档),首次询问未完成配置则每轮用户输入重新询问,未配置期间写入/编辑/bash/派发被硬闸门拒绝(拒绝问卷则本会话豁免),落盘 `.switchman/settings.json`(AGENTS.md 标记为只读回退),`/switchman-lang` 重新询问 | +| `lang.enabled / ask / candidates` | `true / true / 出厂清单` | 项目级语言偏好:每轮 `[LANG]` 铁律行(会话 / 注释与提交 / 文档),首次询问未完成配置则每轮用户输入重新询问,未配置期间写入/编辑/bash/派发被硬闸门拒绝(拒绝问卷则本会话豁免),落盘 `.switchman/settings.json`(AGENTS.md 标记为只读回退),`/switchman-lang` 重新询问。问卷题文跟随检测到的界面语言(env `LC_ALL` → `LANG`,归一化——`zh_CN.UTF-8` → `zh-CN`——无匹配回退英文;仅题文本地化,标记前缀与指令正文保持稳定英文) | | `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 | @@ -223,7 +224,7 @@ opencode-switchman 把编排拆成三层,各司其职: |---|---|---| | **认知层** | 主模型(调度员)+ 随包注入的调度员规程 | 任务四维画像(认知强度×机械度×上下文×紧急度)、决定自做还是委派、选档选壳、写 DELEGATION_V1 委派 prompt | | **执行层** | 「模型×档位」空壳子代理(如 `glm-mx-53-high`) | 只绑定模型与思考档位,角色由委派 prompt 动态赋予(programmer/tester/reviewer 等 14 角色) | -| **确定性层** | 插件本体 | 六闸拦截、ROUTE_META 硬校验、加权模型评分、配额/成本感知选链、探针 / 熔断 / 实调隔离自愈、四行横幅实时注入 | +| **确定性层** | 插件本体 | 六闸拦截、ROUTE_META 校验(缺失→按 lane 合成、非法→拒绝)、加权模型评分、配额/成本感知选链、探针 / 熔断 / 实调隔离自愈、四行横幅实时注入 | **Token 经济学为第一性原则**:返工是最贵的 token。由此派生六档认知分层—— @@ -274,7 +275,7 @@ flowchart TD | 2 探针矩阵 | 组合实测 down / retired | 拦明确不可用;连续 404 下线消失模型 | | 3 熔断 / 隔离 | 600s 窗内 ≥2 败或实调隔离中 | 「连续失败熔断中,约 10 分钟自动恢复」/「实调失败后隔离中」 | | 4 池耗尽 | 配额判定必失败 | 附人读原因(GLM 100% / Copilot 确定耗尽 / DS 欠费) | -| 5 协议 | ROUTE_META 缺失/非法 | deny 附样例与合法值表 | +| 5 协议 | ROUTE_META 缺失/非法 | 缺失或无法解析的行 → 按壳所在 lane 合成 META 后放行并记状态日志;存在但错误(非法值 / 缺必填字段)→ deny 附样例与合法值表 | | 6 语义 | 同族复审 / rw→ro 壳 / 图像→非视觉壳 | 「复审须异族视角」等 | ROUTE_META 是嵌在委派 prompt 内的单行协议,六键六值,插件逐字段校验: @@ -320,11 +321,11 @@ ROUTE_META {"lane":"main","role":"programmer","producer_family":"glm","capabilit ## 子代理上下文硬顶 -主会话享有软/硬/压三档水位+自动交接;被委派的壳子代理会话此前完全没有上下文控制,一路跑过 18 万 token 也无人拦截。现在每个壳子代理会话只有一道硬顶(`context.subagentForceTokens`,默认 100,000 token,钳制 20k..1M,并在可知时额外以壳模型上下文窗口的 90% 封顶),实测口径与会话水位相同:最新 assistant 消息的 input + output + reasoning + cache.read。触顶后,插件拒绝该子代理会话内的所有后续工具调用并下达收尾指令;子代理随后给出的纯文本答复——一份详细的工作进度总结(已完成 / 关键发现含 file:line 证据 / 未完成 / 下一步)——即作为任务结果返回给委派方,会话随即永久终止(终止事件写入状态日志)。合规两侧预先约定:子代理系统提示的壳规则第 6 条(首次触顶拒绝即停止、交回总结),随包调度员规程第 2 节约定编排侧契约(绝不重试已终止的会话;重新派发、只注入所需上下文)。 +主会话享有软/硬/压三档水位+自动交接;被委派的壳子代理会话此前完全没有上下文控制,一路跑过 18 万 token 也无人拦截。现在每个壳子代理会话只有一道硬顶(`context.subagentForceTokens`,可选——缺省跟随主会话 `forceTokens`,即默认 120,000 token,与主会话共享同一条绝对终止线;显式覆盖时钳制 20k..1M,并在可知时额外以壳模型上下文窗口的 90% 封顶),实测口径与会话水位相同:最新 assistant 消息的 input + output + reasoning + cache.read。硬顶终止之前有两档柔性提醒,直接复用主会话的绝对软/硬阈值(`softTokens` 省着用 / `hardTokens` 收尾交接——子代理上下文与主会话上下文同等昂贵),有效上限按比例下拉两档。触顶后,插件拒绝该子代理会话内的所有后续工具调用并下达收尾指令;子代理随后给出的纯文本答复——一份详细的工作进度总结(已完成 / 关键发现含 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`)配置(详见配置项表)。 +由 `opencode-switchman.jsonc` 的 `context.subagentForceTokens`(可选——缺省跟随 `forceTokens`)/ `context.subagentCap`(默认 `true`)配置(详见配置项表)。 ## 工件工作区(.switchman) diff --git a/src/assets/agents-md.ts b/src/assets/agents-md.ts index 6b0a9a3..dcb8fa0 100644 --- a/src/assets/agents-md.ts +++ b/src/assets/agents-md.ts @@ -13,6 +13,9 @@ // opencode's default system prompt and nothing re-surfaced the list, so it was written once and never updated; pairs with the // plugin-injected [TODO] per-turn status line (index.ts sessionTodoLine)] // [2026-09-05]-[v1 read budget: §5 rewritten from one-time nudge semantics to always-on per-call budget; placeholders preserved] +// [2026-09-14]-[shell handoff relay §2 item 5 + §6 declaration widening: D1's soft tiers end with the inline HANDOFF marker the +// dispatcher must treat as the authoritative remaining-work state; §6's declaration duty moves from a major-action list to +// every substantive action, matching the per-turn [ROUTE] line (src/route-line.ts)] export const AGENTS_MD = `# Global Protocol (master dispatcher rules; opencode-switchman subagent rules are embedded in the shell definitions) > This protocol ships with the opencode-switchman plugin and is injected into the system prompt automatically by default (bundled with the package, updated with versions); scope: opencode with the opencode-switchman plugin installed. @@ -58,6 +61,7 @@ Goal: <…>; known facts: <…>; relevant paths: <…>; output format: <conclusi 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. +5. Shell handoff relay: a shell nearing its context cap is warned by the plugin (conserve → hand off) and instructed to end with \`HANDOFF: inline · progress: n/m · next: <one sentence>\`. Treat that final handover block (completed / key evidence / remaining / next steps) as the authoritative remaining-work state: start a FRESH dispatch whose prompt re-seeds only what the next unit needs (never resume the spent session — its cap termination is permanent, task_id resumes are denied), or, when progress is m/m, fold the results into your own report. Never re-dispatch the same long context back into a fresh shell. ## 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. @@ -69,7 +73,7 @@ Task artifacts (plans, implementation progress, process-control notes, design do Each self-read is costed against a per-call injection budget (default ~1500 tokens; the live cap rides the \`[WATERMARK:SESSION]\` banner line). Reads over the cap are auto-bounded or rejected with exact bounded-retry params (\`read <file> limit=N offset=M\`); once the per-turn self-read cap is spent, delegate the turn's remaining reads to an economy shell. Watermarks are lifecycle advice only: past {{SOFT}} prefer delegating new scans; past {{HARD}} wrap up (verification/delivery bash stays open; state-changing git is delivery — run it yourself, never delegate it); at {{FORCE}} compact immediately. Unbounded history dumps (e.g. \`git log -p\` without \`-n\`) are rejected at any context size — scope them or delegate. ## 6. Major-Action Reporting and the Expert Panel -- [MANDATORY] Before a major action (self-reading >3 files or a single file >1000 lines, self-editing >100 lines or across files, commands expected to produce large output, any delegation), declare in one sentence: \`[DISPATCH] self: <one-line reason>\` / \`[DISPATCH] delegate <shell-name>: <one-line reason>\`; acting without declaration is forbidden. +- [MANDATORY] Before each substantive action (the enumeration below is the minimum set, not the ceiling; self-reading >3 files or a single file >1000 lines, self-editing >100 lines or across files, commands expected to produce large output, any delegation), declare in one sentence: \`[DISPATCH] self: <one-line reason>\` / \`[DISPATCH] delegate <shell-name>: <one-line reason>\`; acting without declaration is forbidden. - [MANDATORY] When a protocol-required behavior (review re-review, tester verification, delegation, watermark wrap-up, etc.) is not performed, declare: \`[DISPATCH] skip <action>: <specific verifiable reason>\` — a bare skip is a violation. - Expert panel triggers: core/security/data logic, deadlocks, or explicit user request; confirm via multiple-choice + cost estimate before triggering (three seats ≈ 150k–500k tokens). Expert seats = cross-family shells on the review chain (a same-family seat is a last-resort DOWNGRADED self-review, used only when no cross-family shell is available): α correctness & safety / β engineering feasibility / γ premise challenge. diff --git a/src/assets/delegation-template.ts b/src/assets/delegation-template.ts index 36f77f1..1d66b3c 100644 --- a/src/assets/delegation-template.ts +++ b/src/assets/delegation-template.ts @@ -4,7 +4,7 @@ export const DELEGATION_TEMPLATE = `# DELEGATION_V1 Delegation Prompt Template > Fixed-order template for the main model delegating tasks to empty shells (\`*-mx-*\`). > Fixed sections first, variable sections last — API-billed shells (pay-as-you-go) benefit from prefix caching; a byte-stable template head saves 1/30 of the input cost. -> The opencode-switchman plugin intercepts before task dispatch: a shell-name dispatch missing META or with a broken format will be denied (task tool error) with this sample attached. +> The opencode-switchman plugin intercepts before task dispatch: ROUTE_META is optional — a dispatch with a missing or unparseable line is allowed with a lane-synthesized META (source=auto) — but declaring it unlocks cross-family review ranking on the review lane and source=user pinning; a PRESENT line with an illegal value or a missing required field is still denied (task tool error) with this sample attached. ## Template Body (copy and use) diff --git a/src/config.ts b/src/config.ts index 7b84b9c..180e0c1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -16,7 +16,9 @@ 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; subagentForceTokens: number; subagentCap: boolean } +// [2026-09-14]-[subagentSoftTiers gains two advisory fractions of the effective cap (0 < f0 < f1 < 1, fail-open default)] +// [2026-09-15]-[subagentSoftTiers retired: shell advisories reuse the main session's absolute soft/hard thresholds; subagentForceTokens now optional — absent follows forceTokens] +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> @@ -28,7 +30,8 @@ export interface UserConfig { rules: { enabled: boolean; delegationFloor: number } context: UserContextConfig builtinAgents: { mode: "deny" | "allow" } - injection: { mode: "chain" | "all" } + // [2026-09-11]-[injection mode gains "configured": narrow the face to favorites/visible-set shells when configured (see types.ts)] + injection: { mode: "chain" | "all" | "configured" } // [2026-09-04]-[autoRedirect: silent-redirect-on-deny switch (default true); relay.image: image relay switch (default true)] dispatch: { autoRedirect: boolean } relay: { image: boolean } @@ -43,7 +46,8 @@ export interface UserConfig { } 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, subagentForce: 100_000 } as const +// [2026-09-15]-[subagentForce entry dropped: the shell hard line follows forceTokens by default (subagentForceTokens optional override)] +export const DEFAULT_CONTEXT_TOKENS = { soft: 60_000, hard: 80_000, force: 120_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) */ @@ -55,7 +59,8 @@ 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, subagentForceTokens: DEFAULT_CONTEXT_TOKENS.subagentForce, subagentCap: true }, + // [2026-09-15]-[subagentForceTokens/subagentSoftTiers omitted from defaults: the shell cap follows forceTokens and the advisories reuse the shared soft/hard thresholds] + 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, subagentCap: true }, builtinAgents: { mode: "deny" }, injection: { mode: "chain" }, dispatch: { autoRedirect: true }, @@ -182,11 +187,13 @@ 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)] + // [2026-09-06]-[subagent hard cap: on/off switch; the optional token override is clamped to [MIN_SUBAGENT_CAP_TOKENS, MAX_SUBAGENT_CAP_TOKENS] (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 }) + // [2026-09-15]-[subagentForceTokens optional: absent follows forceTokens (shared hard line); present-but-invalid + // (non-finite / outside 20k..1M) → the override is deleted (SWM037) so the cap falls back to forceTokens] + if (tk.subagentForceTokens !== undefined && (typeof tk.subagentForceTokens !== "number" || !Number.isFinite(tk.subagentForceTokens) || tk.subagentForceTokens < MIN_SUBAGENT_CAP_TOKENS || tk.subagentForceTokens > MAX_SUBAGENT_CAP_TOKENS)) bad("context.subagentForceTokens", () => { delete filled.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 }) + if (filled.injection.mode !== "chain" && filled.injection.mode !== "all" && filled.injection.mode !== "configured") 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")] if (typeof filled.workspace.enabled !== "boolean") bad("workspace.enabled", () => { filled.workspace.enabled = defaults.workspace.enabled }) { diff --git a/src/context-watch.ts b/src/context-watch.ts index 85da39d..8144f65 100644 --- a/src/context-watch.ts +++ b/src/context-watch.ts @@ -169,16 +169,18 @@ export function turnBudgetOf(readBudget: number): number { // 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 +// [2026-09-15]-[subagentForceTokens becomes optional, shared by default: subagent context is equally token-expensive as +// main-session context, so an absent/invalid override now follows forceTokens (one absolute termination line for both; +// the standalone 100k DEFAULT_SUBAGENT_CAP_TOKENS is retired) — present values keep the 20k..1M defensive clamp] /** 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 { +export function subagentCapOf(context: { subagentCap?: boolean; subagentForceTokens?: number; forceTokens?: 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 + if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return thresholdsOf(context).force return Math.min(MAX_SUBAGENT_CAP_TOKENS, Math.max(MIN_SUBAGENT_CAP_TOKENS, Math.round(raw))) } @@ -190,6 +192,60 @@ export function capByWindow(cap: number, windowTokens?: number): number { const fmtK = (n: number): string => `${Math.round(n / 1000)}k` +// [2026-09-15]-[subagent soft tiers switch from fraction coefficients to the MAIN session's ABSOLUTE soft/hard +// thresholds: subagent context is equally token-expensive as main-session context, so the two graceful advisories +// (conserve → hand-off) reuse softTokens/hardTokens (defaults 60k/80k) with no user-facing coefficients, expressed +// against the force anchor (subagentForceTokens when a valid finite number, else forceTokens). The window-clamped +// effective cap (capByWindow, already applied at the call site) still pulls the tiers down proportionally, so a tier +// never exceeds the real termination line and small-window shells keep headroom before termination; misconfigured +// thresholds violating 0 < f0 < f1 < 1 fall back to the pure-defaults derivation (fail-open)] +export function subagentSoftTiersOf( + context: { softTokens?: number; hardTokens?: number; forceTokens?: number; subagentForceTokens?: number } | undefined, +): [number, number] { + const t = thresholdsOf(context) + const raw = context?.subagentForceTokens + const anchor = typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? raw : t.force + const f0 = t.soft / anchor + const f1 = t.hard / anchor + if (!(f0 > 0 && f0 < f1 && f1 < 1)) return [60_000 / 120_000, 80_000 / 120_000] + return [f0, f1] +} + +/** Highest advisory tier for measured tokens vs the effective cap: 0 = none, 1 = conserve, 2 = hand off */ +export function shellSoftTier(tokens: number, cap: number, tiers: readonly [number, number]): 0 | 1 | 2 { + if (!(cap > 0)) return 0 + if (tokens >= Math.floor(tiers[1] * cap)) return 2 + if (tokens >= Math.floor(tiers[0] * cap)) return 1 + return 0 +} + +/** Advisory copy for a fired tier (tier texts pinned by test/subagent-cap.test.ts; k rendered from the live numbers) */ +export function shellSoftTierMessage(tier: 1 | 2, tokens: number, cap: number): string { + if (tier === 1) { + return `[SHELL-CONTEXT] measured shell context ≈ ${fmtK(tokens)}/${fmtK(cap)} (conserve): stop batch reads and long pastes — switch to targeted grep and cite only the needed excerpts; finish the current work unit before starting anything new; keep outputs compact.` + } + return `[SHELL-CONTEXT] measured shell context ≈ ${fmtK(tokens)}/${fmtK(cap)} (hand-off): open no new files or edits; finish the current unit, then end your FINAL message with a compact handover block (completed; key findings with file:line; remaining; next steps) followed by the marker line \`HANDOFF: inline · progress: n/m · next: <one sentence>\` (m = the delegation's work units, n = completed). Your final message is returned to the delegating session as the task result.` +} + +export interface ShellSoftTierInput { + terminated: boolean + tokens: number | undefined + /** effective (window-clamped) cap; null = subagentCap disabled → advisories off */ + cap: number | null + tiers: readonly [number, number] + /** highest tier already delivered for this session (0 = none) */ + delivered: 0 | 1 | 2 +} + +/** Pure advisory decision: at most one line per tier, delivered only when the computed tier exceeds the highest + * already delivered; terminated sessions and the disabled cap stay silent (the deny message governs) */ +export function shellSoftTierDecision(input: ShellSoftTierInput): { line: string | null; delivered: 0 | 1 | 2 } { + if (input.terminated || input.cap === null || input.tokens === undefined) return { line: null, delivered: input.delivered } + const tier = shellSoftTier(input.tokens, input.cap, input.tiers) + if (tier === 0 || tier <= input.delivered) return { line: null, delivered: input.delivered } + return { line: shellSoftTierMessage(tier, input.tokens, input.cap), delivered: tier } +} + /** 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.` diff --git a/src/dispatch-mode.ts b/src/dispatch-mode.ts new file mode 100644 index 0000000..67a9c0f --- /dev/null +++ b/src/dispatch-mode.ts @@ -0,0 +1,72 @@ +// [2026-09-14]-[D3 dispatch opt-out: top-level "dispatch": "off" in <workspace-dirname>/settings.json — the same file +// the lang config lives in (parseLangSettings ignores extra top-level fields, so the two coexist). Exactly the string +// "off" opts out; the field absent / non-string / any other value → fleet (fail-open). Read per call (cheap +// small-file JSON.parse, same pattern as loadLangConfig) so toggling the setting takes effect on the next task call / +// next request without a restart; never throws] +import { existsSync, readFileSync } from "node:fs" +import { join } from "node:path" +import { appendStatusLog } from "./state" +import { LANG_SETTINGS_FILE } from "./lang-config" + +export type DispatchMode = "fleet" | "off" + +export interface ParsedDispatchMode { + mode: DispatchMode + /** file exists but JSON.parse fails entirely (broken-settings warning case) */ + broken: boolean + /** a "dispatch" field is present but not the exact string "off" (visibility note; fleet behavior) */ + invalidValue: boolean + /** the raw present value for the note copy (undefined when absent) */ + rawValue?: string +} + +/** Pure parse of the settings.json text: exactly "off" → off; anything else → fleet (fail-open) */ +export function parseDispatchMode(text: string): ParsedDispatchMode { + let v: unknown + try { + v = JSON.parse(text) + } catch { + return { mode: "fleet", broken: true, invalidValue: false } + } + if (v && typeof v === "object" && !Array.isArray(v)) { + const d = (v as Record<string, unknown>).dispatch + if (d === undefined) return { mode: "fleet", broken: false, invalidValue: false } + if (d === "off") return { mode: "off", broken: false, invalidValue: false } + return { mode: "fleet", broken: false, invalidValue: true, rawValue: typeof d === "string" ? d : JSON.stringify(d) } + } + // valid JSON but not an object → no dispatch field exists; fleet, no note (same class as a missing file) + return { mode: "fleet", broken: false, invalidValue: false } +} + +// once-per-process-per-path guards: loadDispatchMode is read per call (task calls AND every system.transform request +// via the [ROUTE] gate), so un-gated notes would spam the status log on every request +const brokenWarned = new Set<string>() +const invalidNoted = new Set<string>() + +/** Read the project dispatch mode (sync, cheap, fail-open, never throws). Logs the broken-settings warning and the + * present-but-invalid note once per process per path via the injected log callback (defaults to appendStatusLog). */ +export function loadDispatchMode( + projectDir: string, + workspaceDirname: string, + log: (text: string) => void = appendStatusLog, +): DispatchMode { + const abs = join(projectDir, workspaceDirname, LANG_SETTINGS_FILE) + try { + if (!existsSync(abs)) return "fleet" + const parsed = parseDispatchMode(readFileSync(abs, "utf8")) + if (parsed.broken) { + if (!brokenWarned.has(abs)) { + brokenWarned.add(abs) + log(`[opencode-switchman] ${workspaceDirname}/${LANG_SETTINGS_FILE} is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)`) + } + return "fleet" + } + if (parsed.invalidValue && !invalidNoted.has(abs)) { + invalidNoted.add(abs) + log(`[opencode-switchman] ${workspaceDirname}/${LANG_SETTINGS_FILE} "dispatch" present but not exactly "off" (got: ${parsed.rawValue}) — ignored, fleet behavior`) + } + return parsed.mode + } catch { + return "fleet" + } +} diff --git a/src/gates.ts b/src/gates.ts index 9041a90..7b0d8cd 100644 --- a/src/gates.ts +++ b/src/gates.ts @@ -33,13 +33,52 @@ function laneForCheck(shellName: string, meta: Meta | null, lanes: Record<string return ROLE_LANE[meta?.role ?? ""] ?? laneOfShell(shellName, lanes) ?? "main" } +// [2026-09-14]-[D5: lane-default role table for the gate-6 synthesizer — the five non-review entries are exactly the +// table hardcoded at index.ts's former synthesis sites; review → reviewer (the review lane's own role, so gate 7's +// reviewer branch runs with producer_family absent = the cross-family preference is unenforced)] +const LANE_DEFAULT_ROLE: Record<string, string> = { + hard: "planner", main: "programmer", mechanical: "tester", economy: "scouter", vision: "observer", review: "reviewer", +} + +// [2026-09-14]-[D5: the gate-6 ROUTE_META disposition — MISSING (no parseable line) / MALFORMED (line present but +// unparseable) no longer deny: gate 6 synthesizes the lane-default META (the former index.ts synthesis table) and +// continues into gate 7 with an observe note. Only ABSENCE is synthesized: a PRESENT-but-wrong META (invalid field +// value, or a parseable line missing required fields) stays a producer-error deny with the sample hint. Gate 7 +// semantics on the synthesized meta: producer_family absent → review cross-family preference unenforced (the +// same-family DOWNGRADED note path still applies); source "auto" → fallback-eligibility checks apply unchanged. +// Review lane synthesizes capability "ro" (review is an ro lane) so the synthesized meta does not structurally +// deny every ro review shell at the rw/ro check — that would contradict the downgrade for the exact corner +// (autoRedirect off / review lane) that motivated it]- +function synthesizeMeta(agent: string, lanes: Record<string, string[]>): Meta { + const lane = (laneOfShell(agent, lanes) ?? "main") as import("./types").Lane + return { + lane, + role: LANE_DEFAULT_ROLE[lane] ?? "programmer", + capability: lane === "economy" || lane === "review" ? "ro" : "rw", + modality: lane === "vision" ? "image" : "text", + source: "auto", + } +} + +const ROUTE_META_SYNTH_NOTE = "[opencode-switchman] ROUTE_META missing/malformed — synthesized from lane; declare it to enable review cross-family / source=user semantics" + export function checkShell( agent: string, shell: ShellRegEntry, prompt: unknown, snap: GateSnapshot & { lanes: Record<string, string[]> }, ): GateResult { - const [meta, metaErr] = parseRouteMeta(prompt) + const [parsedMeta, metaErr] = parseRouteMeta(prompt) + let meta = parsedMeta + let metaSynthNote: string | null = null + // [2026-09-14]-[D5 downgrade-to-observe: a MISSING (no parseable line) or MALFORMED (line present but unparseable) + // META no longer denies — gate 6 synthesizes the lane-default META and continues into gate 7 with an observe note + // (see synthesizeMeta). Only ABSENCE is synthesized; a PRESENT-but-wrong META (invalid field value / missing + // required field on a parseable line) keeps the gate-6 deny below — a producer error the delegator must fix]- + if (metaErr === "missing" || metaErr === "malformed") { + meta = synthesizeMeta(agent, snap.lanes) + metaSynthNote = ROUTE_META_SYNTH_NOTE + } const lane = laneForCheck(agent, meta, snap.lanes) const base = snap.lanes[lane] ?? [] const regOk = snap.registry !== null @@ -172,8 +211,10 @@ export function checkShell( } } - // Gate 6 ROUTE_META hard gate: missing line / malformed / invalid field / missing required field all deny with a sample + live candidate - if (metaErr !== null) { + // Gate 6 ROUTE_META hard gate [2026-09-14]-[D5: only PRESENT-but-wrong META denies now — an invalid field value, or + // a parseable line missing required fields (a producer error worth surfacing with the sample + live candidate); + // missing/malformed was already synthesized above and never reaches this branch] + if (metaErr !== null && metaErr !== "missing" && metaErr !== "malformed") { const fallbackLane = laneForCheck(agent, null, snap.lanes) let fallback: string try { @@ -185,7 +226,7 @@ export function checkShell( return { deny: `${agent} dispatched to a shell name, invalid ROUTE_META: ${metaErrorHint(metaErr)}${fallback}`, note: null, - // redirection happens in index.ts (the prompt must be rewritten to synthesize META); stays null here + // a present-but-wrong META must be corrected by the delegator (rewriting it plugin-side would mask the error); stays null here redirect: null, } } @@ -248,7 +289,8 @@ export function checkShell( const rc = reviewChainOf() const onChain = Boolean(rc?.chain.some((c) => c.shell === agent)) const noPrimary = Boolean(rc && !rc.chain.some((c) => isPrimaryCandidate("review" as import("./types").Lane, baseScoreDynamic(snap.registry?.[c.shell]?.modelId ?? "")))) - if (onChain && noPrimary) return { deny: null, note: REVIEW_SELF_REVIEW_NOTE, redirect: null } + // [2026-09-14]-[D5: the gate-6 synth note rides along when the META was synthesized for this dispatch] + if (onChain && noPrimary) return { deny: null, note: [metaSynthNote, REVIEW_SELF_REVIEW_NOTE].filter(Boolean).join(" ") || null, redirect: null } } return { deny: `${agent} capability level too low to take ${lane} tasks${hint()}`, note: null, redirect: candidateOf() } } @@ -272,7 +314,8 @@ export function checkShell( // candidate exists on the review chain)] // [2026-09-05]-[review same-family self-review: the last-resort exemption note (no cross-family reviewer on the chain) // is emitted here after every structural gate passed] - return { deny: null, note: reviewSelfReviewNote, redirect: null } + // [2026-09-14]-[D5: a synthesized META rides as an observe note (a deny always supersedes it); both notes joined when they co-occur] + return { deny: null, note: [metaSynthNote, reviewSelfReviewNote].filter(Boolean).join(" ") || null, redirect: null } } /** Unregistered / non-shell name → fail-open (unknown built-in agents are not governed by routing) */ diff --git a/src/index.ts b/src/index.ts index e7b4843..a9e4d56 100644 --- a/src/index.ts +++ b/src/index.ts @@ -33,6 +33,7 @@ import { budgetGateDecision, estimateReadRange, estimateOutputTokens, readBudgetOf, turnBudgetOf, capThresholdsByWindow, subagentCapOf, capByWindow, subagentCapDenyMessage, subagentResumeDenyMessage, ctxControlMarkerOf, pausedWindowWarning, + subagentSoftTiersOf, shellSoftTierDecision, } from "./context-watch" import type { CtxControlAction, ReadEstimate, FileSample, ContextThresholds } from "./context-watch" import { backupSession, compactSession, v1HandoverPort, type HandoverResult } from "./handover-core" @@ -60,7 +61,9 @@ import { LANE_ORDER, DEFAULT_LANG_CANDIDATES } from "./types" import type { SwitchmanOptions, Lane, LaneResult, Pool, ShellRegEntry, ModelKey } from "./types" import { WorkspaceTracker, DEFAULT_WORKSPACE_DIRNAME, type EnsuredWorkspace } from "./workspace" import { TmuxPaneManager, serverOriginOf } from "./tmux" -import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion, langGateDecision, LANG_GATE_TOOLS, hasLangMarkerQuestions } from "./lang-config" +import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion, langGateDecision, LANG_GATE_TOOLS, hasLangMarkerQuestions, detectUiLocale } from "./lang-config" +import { renderRouteLine, routeLineEnabled } from "./route-line" +import { loadDispatchMode } from "./dispatch-mode" import { detectMode, readConfigured, normalizeProviderListResponse } from "./activation" import type { MatrixModeOption } from "./activation" // [2026-08-29]-[event/parameter shape-extraction pure functions moved to helpers.ts: the entry must not export non-plugin functions, otherwise @@ -163,6 +166,10 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // 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-14]-[subagent soft tiers: per-session highest advisory tier delivered (conserve=1 / hand-off=2); dedup is + // in-memory only — one long-lived plugin process, no state file — cleared on session.deleted; an opencode restart + // re-arms the advisories once per shell session (idempotent reminders; the hard cap keeps its persistent registry)] + const shellSoftTierDelivered = new Map<string, 0 | 1 | 2>() // [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 }>() @@ -414,6 +421,29 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } catch { return null } } + /** + * [SHELL-CONTEXT] advisory line for the system.transform shell branch: tracks the live shellWatermark measurement + * (exactly how [WATERMARK:SESSION] tracks main sessions), fires at most once per soft tier; terminated sessions and + * subagentCap:false stay silent (the deny message governs) + * [2026-09-14]-[D1: the graceful path before the hard cap termination backstop; HANDOFF relay contract = agents-md §2 item 5] + * [2026-09-15]-[tiers now derive from the MAIN session's absolute soft/hard thresholds (shared with the main session, + * no user-facing fraction coefficients), still pulled down proportionally by the effective window-clamped cap] + */ + function shellSoftTierLine(sessionID: string | undefined): string | null { + if (!sessionID) return null + try { + const d = shellSoftTierDecision({ + terminated: terminatedSessions.has(sessionID), + tokens: shellWatermark.get(sessionID)?.tokens, + cap: effectiveSubagentCap(sessionID), + tiers: subagentSoftTiersOf(options.context), + delivered: shellSoftTierDelivered.get(sessionID) ?? 0, + }) + shellSoftTierDelivered.set(sessionID, d.delivered) + return d.line + } catch { return null } + } + /** [2026-09-05]-[artifact workspace event path: record + ensure a main session's folder; shell/internal sessions filtered * (call AFTER the agent classification so isShellOrInternalSession sees the registration); logs only on create/rename] */ function noteWorkspaceSession(info: { id?: unknown; title?: unknown; directory?: unknown; created?: unknown } | null | undefined): void { @@ -449,8 +479,11 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { } catch { return null } } - /** [2026-09-05]-[artifact workspace dispatch trace: one JSONL line per allowed delegation (lane/role from ROUTE_META); fail-open no-op] */ - function traceDispatch(sessionID: string | undefined, shellName: string, prompt: unknown, redirected: boolean): void { + /** [2026-09-05]-[artifact workspace dispatch trace: one JSONL line per allowed delegation (lane/role from ROUTE_META); fail-open no-op] + * [2026-09-14]-[D5: when the META was missing/malformed it was synthesized by gate 6 — the trace falls back to + * laneOfShell inference over the caller's lane map and logs source:"synthesized" so dispatches.jsonl keeps lane + * attribution without inventing producer data] */ + function traceDispatch(sessionID: string | undefined, shellName: string, prompt: unknown, redirected: boolean, lanes?: Record<string, string[]>): void { try { if (!sessionID || isShellOrInternalSession(sessionID)) return // [2026-09-06]-[tmux pane mirroring: record the dispatch intent; the matching child session.created consumes it] @@ -460,12 +493,15 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (q.length > 8) q.splice(0, q.length - 8) pendingTask.set(sessionID, q) } - const [meta] = parseRouteMeta(prompt) + const [meta, metaErr] = parseRouteMeta(prompt) + const synthesized = metaErr === "missing" || metaErr === "malformed" workspace.traceDispatch(sessionID, { ts: nowIso(), session: sessionID, shell: shellName, - lane: typeof meta?.lane === "string" ? meta.lane : undefined, + lane: typeof meta?.lane === "string" + ? meta.lane + : synthesized && lanes ? laneOfShell(shellName, lanes) ?? undefined : undefined, role: typeof meta?.role === "string" ? meta.role : undefined, - source: typeof meta?.source === "string" ? meta.source : undefined, + source: synthesized ? "synthesized" : typeof meta?.source === "string" ? meta.source : undefined, redirected: redirected || undefined, }) } catch { /* fail-open */ } @@ -646,8 +682,14 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // model missed favorites/visible set (runtime chains still narrow to pool selection ∩ activation, gate 5.5 unchanged)]- const poolConfiguredIds = new Set<string>() for (const ids of Object.values(loadPoolConfig())) for (const id of ids) poolConfiguredIds.add(id) + // [2026-09-11]-[injection mode "configured": favorites/visible set non-empty → skip chain picks, the face is exactly the + // configured models' shells ∪ custom-lane/pool-config force-keeps (runtime dispatch is already gated by activation (configured ∪ + // session models) ∩ pool selection, so off-configured chain picks are dead per-request task-tool-description context); an + // empty configured set behaves identically to "chain" (fail-open)] + const configuredNarrowing = options.injection!.mode === "configured" && validConfiguredModels.length > 0 defs = selectInjectableDefs(defs, { customLanes: (options.lanes as Record<string, readonly string[]> | null) ?? null, + skipChainPicks: configuredNarrowing, keepModels: options.injection!.mode === "all" ? new Set(supersetModels) : new Set(validConfiguredModels), keepModelIds: poolConfiguredIds, preferredModels: new Set(validConfiguredModels.map((m) => m.slice(m.indexOf("/") + 1))), @@ -1423,7 +1465,16 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // shell subagents/internal agents get no dispatcher rules or banner (their role is already the executor; saves tokens and prevents role confusion); // [2026-08-29]-[re-review P1 fix — first-turn timing: transform runs before chat.params — rely on the agent-name classification pre-registered // by session.created (dynamic = skipSystemInjection; legacy = sessionAgent ∪ internal agent names), not on chat.params arriving first] + // [2026-09-14]-[the bare early-return becomes a shell branch: dispatched shell sessions (never internal + // title/compaction/summary) get at most one [SHELL-CONTEXT] soft-tier advisory pushed before returning — + // the transform re-runs on every model request, so the advisory tracks the live shellWatermark measurement; + // internal sessions and the zero-injection path keep returning with nothing injected]- if (input.sessionID) { + if (isShellAgentSession(input.sessionID)) { + const advisory = shellSoftTierLine(input.sessionID) + if (advisory) output.system.push(advisory) + return + } if (dynamic) { if (manager?.skipSystemInjection(input.sessionID)) return } else { @@ -1445,7 +1496,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (loaded) output.system.push(renderLangLine(loaded.cfg, loaded.source)) else if (options.lang!.ask !== false && input.sessionID && !langAsked.has(input.sessionID) && !langGateWaived.has(input.sessionID)) { langAsked.add(input.sessionID) - output.system.push(renderAskDirective(options.lang!.candidates ?? DEFAULT_LANG_CANDIDATES)) + // [2026-09-14]-[D4 locale-following ask: question texts follow the detected UI locale (env LC_ALL → LANG, + // normalized, fail-open "en"); the `switchman-lang n/3: ` marker prefix stays byte-stable so the plugin-side + // capture anchor is locale-independent; the directive body/deny copy stay English (model-facing)] + const ui = detectUiLocale() + appendStatusLog(`lang ask locale=${ui.locale} (${ui.via === "default" ? "default" : `env ${ui.via}`})`) + output.system.push(renderAskDirective(options.lang!.candidates ?? DEFAULT_LANG_CANDIDATES, ui.locale)) } } // [2026-08-29]-[fail-open visibility: explicit warning when injection crashes — don't dispatch; do it yourself or tell the user]- @@ -1491,6 +1547,19 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-05]-[todo nudge line: same gate as the watermark line — re-surfaces the unfinished todo list every turn] const todoLine = sessionTodoLine(input.sessionID) if (todoLine) output.system.push(todoLine) + // [2026-09-14]-[D2 per-turn [ROUTE] line: facts first, rule last — pushed after the watermark/TODO lines inside + // the same rules||banner block (zero-injection wish respected); carries the token cost-model sentence + the + // every-substantive-action declaration discipline] + // [2026-09-14]-[D3: the [ROUTE] line is the only prompt surface that hides under dispatch:"off" (per-request + // disk re-read, same stickiness as the lang line); watermark/TODO/banner stay on (information, not governance)]- + if (routeLineEnabled( + Boolean(options.rules!.enabled), + Boolean(options.banner!.enabled), + loadDispatchMode(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) === "off", + )) { + const routeLine = renderRouteLine() + if (routeLine) output.system.push(routeLine) + } } } catch (exc) { appendStatusLog(`rules/banner fail-open: ${exc}`) @@ -1624,6 +1693,22 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { 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-14]-[D3 dispatch:"off" opt-out: a project that set the top-level "dispatch":"off" in + // <workspace-dirname>/settings.json stands down ALL dispatch governance for task calls — the entire task path + // below is skipped (uninjected-shell deny + its autoRedirect, built-in agent deny + its autoRedirect, + // checkShell gates 1-7 including the breaker deny and gate 6/7) and the call is allowed ungoverned (a project + // that opted out must not be denied by governance it turned off; nothing left to redirect from either). + // Not dispatch governance, therefore still on: the cap gate and lang gate above, read/watermark gates, + // auto-handover, breaker RECORDING in message.part.updated, banner/watermark/TODO/[LANG] lines. Settings are + // re-read per call → toggling takes effect on the next task call without a restart; fail-open on errors]- + if (input.tool === "task") { + try { + if (loadDispatchMode(pluginDirectory, options.workspace?.dirname || DEFAULT_WORKSPACE_DIRNAME) === "off") { + appendStatusLog(`dispatch off: task call allowed ungoverned (subagent_type='${String(output.args?.subagent_type ?? "")}')`) + return + } + } catch { /* fail-open */ } + } // [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), @@ -1692,13 +1777,14 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { if (!shell) { if (dynamic && shellLikeName(agent)) { const hint = firstCandidateHint(agent, ctx, gateExtras) - // [2026-09-04]-[autoRedirect: uninjected-shell deny — when the META is valid and the chain-head candidate passes the guard, silently redirect and allow] + // [2026-09-04]-[autoRedirect: uninjected-shell deny — when the chain-head candidate passes the guard, silently redirect and allow] + // [2026-09-14]-[D5: dropped the META-validity precondition — a missing/malformed META is synthesized by + // gate 6 itself during the redirect guard's re-check, so the candidate is tried regardless of the prompt's META]- if (autoRedirectOn) { - const [meta, metaErr] = parseRouteMeta(output.args?.prompt) - const cand = meta !== null && metaErr === null ? firstCandidateShell(agent, ctx, gateExtras) : null + const cand = firstCandidateShell(agent, ctx, gateExtras) if (cand && tryRedirect(cand, output.args?.prompt)) { appendStatusLog(`auto-redirect ${agent} → ${cand} (uninjected shell; redirected to the chain-head candidate)`) - traceDispatch(input.sessionID, cand, output.args?.prompt, true) + traceDispatch(input.sessionID, cand, output.args?.prompt, true, gateSnap.lanes) noteResumedChild(input.sessionID, cand, output.args) return } @@ -1711,65 +1797,44 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { // [2026-09-04]-[built-in subagent blocking: explore/general compete with shell routing; default deny with a redirect suggestion] const builtinDeny = builtinAgentDeny(agent, options.builtinAgents!.mode ?? "deny", (lane) => laneHeadCandidate(lane, ctx)) if (builtinDeny) { - // [2026-09-04]-[autoRedirect: built-in agent blocking — append a synthetic ROUTE_META to the prompt tail and redirect to the corresponding lane's chain head] + // [2026-09-04]-[autoRedirect: built-in agent blocking — redirect to the corresponding lane's chain head] + // [2026-09-14]-[D5: the synthetic ROUTE_META append is gone — gate 6 synthesizes the missing META itself + // during the redirect guard's re-check, so the prompt is carried as-is (no rewriting at this site)]- if (autoRedirectOn) { const lane = BUILTIN_SUBAGENTS[agent] const cand = lane ? laneHeadCandidate(lane, ctx) : null - if (cand) { - const role = lane === "economy" ? "scouter" : "generic" - const metaLine = `ROUTE_META {"lane":"${lane}","role":"${role}","modality":"text","capability":"ro","source":"auto"}` - const basePrompt = typeof output.args?.prompt === "string" ? output.args.prompt : "" - const newPrompt = `${basePrompt}${basePrompt.endsWith("\n") ? "" : "\n"}${metaLine}` - if (tryRedirect(cand, newPrompt)) { - 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 - } + if (cand && tryRedirect(cand, output.args?.prompt)) { + appendStatusLog(`auto-redirect ${agent} → ${cand} (built-in agent blocked)`) + traceDispatch(input.sessionID, cand, output.args?.prompt, true, gateSnap.lanes) + noteResumedChild(input.sessionID, cand, output.args) + return } } denySkip.add(input.callID) throw new Error(builtinDeny) } appendStatusLog(noteUnknownAgent(agent)) - traceDispatch(input.sessionID, agent, output.args?.prompt, false) + traceDispatch(input.sessionID, agent, output.args?.prompt, false, gateSnap.lanes) noteResumedChild(input.sessionID, agent, output.args) return } const r = checkShell(agent, shell, output.args?.prompt, gateSnap) if (r.note) appendStatusLog(r.note) if (!r.deny) { - traceDispatch(input.sessionID, agent, output.args?.prompt, false) + traceDispatch(input.sessionID, agent, output.args?.prompt, false, gateSnap.lanes) 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) + traceDispatch(input.sessionID, r.redirect ?? agent, output.args?.prompt, true, gateSnap.lanes) 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 - // shell for pass (review requires a real cross-family producer_family, cannot be synthesized; deny stands)] - if (autoRedirectOn && !r.redirect && r.deny.includes("invalid ROUTE_META")) { - const lane = laneOfShell(agent, gateSnap.lanes) ?? "main" - if (lane !== "review") { - const role = ({ hard: "planner", main: "programmer", mechanical: "tester", economy: "scouter", vision: "observer" } as Record<string, string>)[lane] ?? "programmer" - const metaLine = `ROUTE_META {"lane":"${lane}","role":"${role}","modality":"${lane === "vision" ? "image" : "text"}","capability":"${lane === "economy" ? "ro" : "rw"}","source":"auto"}` - const basePrompt = typeof output.args?.prompt === "string" ? output.args.prompt : "" - const newPrompt = `${basePrompt}${basePrompt.endsWith("\n") ? "" : "\n"}${metaLine}` - const g = checkShell(agent, shell, newPrompt, gateSnap) - if (!g.deny && !(g.redirect && g.redirect !== agent)) { - 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 - } - } - } + // [2026-09-14]-[D5: the former gate-6 META-synthesis retry is gone — missing/malformed META no longer denies + // (gate 6 synthesizes + observes before gate 7), and a present-but-wrong META is a producer error that must + // be corrected by the delegator, not masked by a plugin-side rewrite]- denySkip.add(input.callID) throw new Error(r.deny) } @@ -1983,6 +2048,7 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { 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] + shellSoftTierDelivered.delete(sid) // [2026-09-14]-[subagent soft-tier dedup follows the session out (re-arm on a fresh same-id session is impossible; keeps the map bounded)] turnReadUsage.delete(sid) wmHistory.delete(sid) lastUserMsg.delete(sid) diff --git a/src/lang-config.ts b/src/lang-config.ts index 0be7e4a..4039d1f 100644 --- a/src/lang-config.ts +++ b/src/lang-config.ts @@ -91,16 +91,119 @@ export function saveLangConfig(projectDir: string, workspaceDirname: string, cfg const askTag = (n: 1 | 2 | 3) => `${LANG_ASK_MARKER} ${n}/3` -/** First-run ask directive: one question-tool call, three marker questions, plugin-side capture */ -export function renderAskDirective(candidates: readonly string[]): string { +// [2026-09-14]-[D4 locale-following ask: opencode exposes no locale surface to plugins, so the chain is env LC_ALL → +// LANG → "en" (normalized, unknown values fall through). Only the user-facing question texts localize — the directive +// body, the [LANG] line, the deny copy and the `switchman-lang n/3: ` prefix (the capture anchor for +// parseQuestionAnswers) stay byte-stable across all locales, so capture never depends on the locale] +/** Locale tags the ask questions are translated into (translation-table keys; matches the LANG_TAGS candidate set) */ +const UI_LOCALE_TAGS = ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de", "it", "pt", "ru"] + +/** + * Map a raw locale (BCP-47 or env style, e.g. "zh_CN.UTF-8") to one of UI_LOCALE_TAGS: exact case-insensitive match + * wins; zh-TW / zh-Hant / zh-HK / zh-MO prefixes map to zh-TW, any other zh* to zh-CN; otherwise the primary subtag + * must itself be a known tag; null when nothing matches (caller falls through / defaults to en). + */ +export function normalizeUiLocale(raw: unknown): string | null { + if (typeof raw !== "string") return null + const cleaned = raw.trim().split(".")[0]!.split("@")[0]!.replace(/_/g, "-") + if (!cleaned) return null + const lower = cleaned.toLowerCase() + const exact = UI_LOCALE_TAGS.find((t) => t.toLowerCase() === lower) + if (exact) return exact + if (lower.startsWith("zh")) return /^zh-(tw|hant|hk|mo)/.test(lower) ? "zh-TW" : "zh-CN" + const primary = lower.split("-")[0]! + return UI_LOCALE_TAGS.find((t) => t.toLowerCase() === primary) ?? null +} + +export interface UiLocaleDetection { locale: string; via: "LC_ALL" | "LANG" | "default" } + +/** Detect the UI locale for localizing the ask questions (sync, cheap, fail-open; never throws; unknown → "en"). + * Chain: env LC_ALL → env LANG (env-style "zh_CN.UTF-8" normalized) → "en"; an unrecognized value at any step + * falls through to the next one. Locale is read at ask time — no config. */ +export function detectUiLocale(env: Record<string, string | undefined> = process.env): UiLocaleDetection { + try { + for (const key of ["LC_ALL", "LANG"] as const) { + const tag = normalizeUiLocale(env[key]) + if (tag) return { locale: tag, via: key } + } + } catch { /* fail-open */ } + return { locale: "en", via: "default" } +} + +/** Builds a table entry so the `switchman-lang n/3: ` prefix is byte-stable across every locale (capture anchor) */ +const askQ = (n: 1 | 2 | 3, text: string) => `${askTag(n)}: ${text}` + +/** Localized question texts per UI locale tag (the only user-visible strings of the ask; options stay the native labels) */ +export const UI_LOCALE_ASK_TEXT: Readonly<Record<string, readonly [string, string, string]>> = Object.freeze({ + en: [ + askQ(1, "Conversation language for this project (your replies and reasoning)?"), + askQ(2, "Language for code comments and commit messages?"), + askQ(3, "Language for generated documents (plans, PRD, design docs, reports)?"), + ], + "zh-CN": [ + askQ(1, "本项目的对话语言(你的回复与推理)?"), + askQ(2, "代码注释与提交信息用什么语言?"), + askQ(3, "生成的文档(计划、PRD、设计文档、报告)用什么语言?"), + ], + "zh-TW": [ + askQ(1, "本專案的對話語言(回覆與推理)?"), + askQ(2, "程式碼註解與提交訊息使用什麼語言?"), + askQ(3, "產生的文件(計畫、PRD、設計文件、報告)使用什麼語言?"), + ], + ja: [ + askQ(1, "このプロジェクトの会話言語(返答と推論)は?"), + askQ(2, "コードコメントとコミットメッセージの言語は?"), + askQ(3, "生成されるドキュメント(計画、PRD、設計書、レポート)の言語は?"), + ], + ko: [ + askQ(1, "이 프로젝트의 대화 언어(응답과 추론)는 무엇인가요?"), + askQ(2, "코드 주석과 커밋 메시지에 사용할 언어는 무엇인가요?"), + askQ(3, "생성되는 문서(계획, PRD, 설계 문서, 보고서)의 언어는 무엇인가요?"), + ], + es: [ + askQ(1, "¿Idioma de conversación para este proyecto (tus respuestas y razonamiento)?"), + askQ(2, "¿Idioma para los comentarios de código y los mensajes de commit?"), + askQ(3, "¿Idioma para los documentos generados (planes, PRD, documentos de diseño, informes)?"), + ], + fr: [ + askQ(1, "Langue de conversation pour ce projet (réponses et raisonnement) ?"), + askQ(2, "Langue des commentaires de code et des messages de commit ?"), + askQ(3, "Langue des documents générés (plans, PRD, documents de conception, rapports) ?"), + ], + de: [ + askQ(1, "Gesprächssprache für dieses Projekt (deine Antworten und Gedankengänge)?"), + askQ(2, "Sprache für Codekommentare und Commit-Meldungen?"), + askQ(3, "Sprache für generierte Dokumente (Pläne, PRD, Design-Dokumente, Berichte)?"), + ], + it: [ + askQ(1, "Lingua di conversazione per questo progetto (le tue risposte e il tuo ragionamento)?"), + askQ(2, "Lingua per i commenti al codice e i messaggi di commit?"), + askQ(3, "Lingua per i documenti generati (piani, PRD, documenti di progettazione, report)?"), + ], + pt: [ + askQ(1, "Idioma de conversa para este projeto (suas respostas e raciocínio)?"), + askQ(2, "Idioma para comentários de código e mensagens de commit?"), + askQ(3, "Idioma para documentos gerados (planos, PRD, documentos de design, relatórios)?"), + ], + ru: [ + askQ(1, "Язык общения для этого проекта (ваши ответы и рассуждения)?"), + askQ(2, "Язык комментариев к коду и сообщений коммитов?"), + askQ(3, "Язык создаваемых документов (планы, PRD, проектные документы, отчёты)?"), + ], +}) + +/** First-run ask directive: one question-tool call, three marker questions, plugin-side capture. Question texts follow + * the detected UI locale (normalized, English fallback); the directive body stays English (model-facing). */ +export function renderAskDirective(candidates: readonly string[], locale = "en"): string { + const asks = UI_LOCALE_ASK_TEXT[normalizeUiLocale(locale) ?? "en"] ?? UI_LOCALE_ASK_TEXT.en! const opts = candidates.join(" / ") return [ `[opencode-switchman] Project language preference is not yet configured for this project. Before starting`, `the user's task, call the question tool ONCE with exactly these three questions (question texts verbatim, marker`, `included — the plugin captures the answers itself and persists the config; never write the settings file yourself):`, - `1. question "${askTag(1)}: Conversation language for this project (your replies and reasoning)?", single-choice, options: ${opts}`, - `2. question "${askTag(2)}: Language for code comments and commit messages?", single-choice, options: ${opts}`, - `3. question "${askTag(3)}: Language for generated documents (plans, PRD, design docs, reports)?", single-choice, options: ${opts}`, + `1. question "${asks[0]}", single-choice, options: ${opts}`, + `2. question "${asks[1]}", single-choice, options: ${opts}`, + `3. question "${asks[2]}", single-choice, options: ${opts}`, `The user may also type any other language (custom answer) — relay it verbatim as the option text.`, `HARD GATE: the plugin denies every write / edit / bash / task call in this project until the answers are captured`, `and the config is saved — asking first is not optional. After the tool returns: confirm the saved preferences in`, diff --git a/src/route-line.ts b/src/route-line.ts new file mode 100644 index 0000000..08ff0ac --- /dev/null +++ b/src/route-line.ts @@ -0,0 +1,18 @@ +// [2026-09-14]-[D2 per-turn [ROUTE] line: single pure renderer for the routing-discipline surface — ops has exactly one +// per-request injection surface (experimental.chat.system.transform), so one module keeps the line from ever drifting +// between "surfaces". It carries only what the injected lines lack today: the token cost-model sentence and the §6 +// declaration discipline elevated to every substantive action (the watermark line keeps the numbers/tier directives). +// The caller-side gate lives in index.ts (rules||banner block; the dispatch-mode opt-out gate lands with dispatch: "off")] +// [English-only repo iron rule applies to this line — it is model-facing protocol copy] + +/** The per-turn routing line: one sentence of declaration discipline + the hands-on vs dispatch token cost model */ +export function renderRouteLine(): string { + return "[ROUTE] token economy (IRON RULE): before each substantive action, declare in one sentence — [DISPATCH] self or delegate (§6) — weighing the measured context ([WATERMARK:SESSION]): hands-on spends and grows this session's context on every later turn, a dispatch spends a fresh shell context and returns a summary; long or heavy context favors dispatch, trivia (below the delegation floor, known-path reads, workspace bookkeeping, fleet coordination) stays hands-on." +} + +/** Pure gate rule: the line rides the same rules||banner visibility wish as the watermark/TODO lines (zero-injection + * respected); [2026-09-14]-[D3: dispatch:"off" hides it too — the single opt-out switch for the whole routing- + * discipline surface (zcode semantics), while the watermark/TODO/banner lines stay on (information, not governance)] */ +export function routeLineEnabled(rulesEnabled: boolean, bannerEnabled: boolean, dispatchOff: boolean): boolean { + return (rulesEnabled || bannerEnabled) && !dispatchOff +} diff --git a/src/shells.json b/src/shells.json index e1ccff3..ae827a4 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-10T03:30:20.019Z", + "generated_at": "2026-09-15T00:17:25.943Z", "counts": { "shells": 104, "visible_models": 13 diff --git a/src/shells.ts b/src/shells.ts index 9e0a544..f9e6629 100644 --- a/src/shells.ts +++ b/src/shells.ts @@ -110,6 +110,10 @@ export function injectShellDefs( export interface InjectableSelectOpts { /** User-defined lane overrides (baseChainFor returns their array directly); referenced shells are force-kept in the injection face */ customLanes?: Record<string, readonly string[]> | null + /** [2026-09-11]-[injection mode "configured": skip the six-lane laneBaseChain picks — the face becomes keepModels ∪ keepModelIds ∪ + * custom-lane references only (custom lanes stay force-kept: explicit user routing config, same spirit as the pool-config + * force-keep; dispatch is still gated at runtime by activation ∩ pool selection) */ + skipChainPicks?: boolean /** [2026-09-02]-[available models force-kept (provider/modelId key): injection face = available superset ∪ six-lane * chain selection ∪ custom lanes. When the caller passes all currently available models (provider connected and * chat-capable), no capability-competition pruning happens — favorites / named models never lose their seat to chain @@ -158,17 +162,22 @@ export function selectInjectableDefs( const keep = new Set<string>() for (const lane of LANE_ORDER as readonly Lane[]) { const custom = opts.customLanes?.[lane] - const chain = Array.isArray(custom) && custom.length > 0 - ? custom - : laneBaseChain(lane, { - builtin: [], - activeShells: new Set(attrs.keys()), - shells: attrs, - capabilityOf: opts.capabilityOf, - billingBoostOf: opts.billingBoostOf, - unknownOf: opts.unknownOf, - preferredModels: opts.preferredModels, - }) + if (Array.isArray(custom) && custom.length > 0) { + for (const name of custom) if (byName.has(name)) keep.add(name) + continue + } + // [2026-09-11]-[skipChainPicks: "configured" injection mode drops algorithmic chain picks (off-configured picks can never + // dispatch past the activation gate and only bloat the per-request task tool description); custom lanes above stay force-kept] + if (opts.skipChainPicks) continue + const chain = laneBaseChain(lane, { + builtin: [], + activeShells: new Set(attrs.keys()), + shells: attrs, + capabilityOf: opts.capabilityOf, + billingBoostOf: opts.billingBoostOf, + unknownOf: opts.unknownOf, + preferredModels: opts.preferredModels, + }) for (const name of chain) if (byName.has(name)) keep.add(name) } // [2026-09-02]-[available models force-kept: available models that lost chain competition (favorites / named targets / vision shells) are not pruned]- diff --git a/src/types.ts b/src/types.ts index 26f22aa..a3c058a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -296,8 +296,11 @@ export interface ContextOptions { 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] */ + * result) and the session is permanently terminated (no task_id resume); clamped 20k..1M when present, window-capped + * at 90%; subagentCap: false disables the mechanism entirely] + * [2026-09-15]-[now optional: absent follows forceTokens — the shell shares the main session's absolute termination + * line by default; the fraction-coefficient subagentSoftTiers option is retired, the two soft-tier advisories derive + * from the same shared soft/hard thresholds instead] */ subagentForceTokens?: number subagentCap?: boolean } @@ -306,7 +309,10 @@ export interface ContextOptions { export interface BuiltinAgentsOptions { mode?: "deny" | "allow" } // [2026-09-04]-[Injection surface mode: chain = six-lane chain picks ∪ favorites ∪ visible set (saves 6-10k/session; off-chain models // explicitly named get the denyUninjected hint); all = full available set (old behavior, any available model can be explicitly named)] -export interface InjectionOptions { mode?: "chain" | "all" } +// [2026-09-11]-[mode "configured": favorites/visible set non-empty → the injection face narrows to exactly those models' shells +// (custom-lane/pool-config force-keeps stay); runtime dispatch is already gated by activation ∩ pool selection, so off-configured +// chain picks are dead per-request context in the task tool description; empty configured set = identical to chain (fail-open)] +export interface InjectionOptions { mode?: "chain" | "all" | "configured" } // [2026-09-04]-[deny auto-redirect: wrong landing spots are silently rewritten inside tool.execute.before to the chain-head candidate (one hop + same-snapshot // guard re-check), sparing the main model repeated deny-and-retry token waste; default true] export interface DispatchOptions { autoRedirect?: boolean } diff --git a/test/auto-redirect.test.ts b/test/auto-redirect.test.ts index e9f4233..5d57fb6 100644 --- a/test/auto-redirect.test.ts +++ b/test/auto-redirect.test.ts @@ -90,16 +90,13 @@ describe("autoRedirect: legacy hooks (on by default)", () => { hooks = await makeHooks({ matrix: { mode: "legacy" } }) }, 20_000) - test("gate 6 META invalid → synthesize ROUTE_META at the prompt tail per the shell's lane and allow (same shell, no reshaping)", async () => { + // [2026-09-14]-[D5 gate-6 downgrade-to-observe: missing META no longer triggers a prompt-rewriting retry — gate 6 + // synthesizes internally and allows; the prompt is carried as-is (the observe note goes to the status log, not the prompt)]- + test("gate 6 META missing → allowed on the same shell, prompt untouched (synthesis lives inside the gate)", async () => { const before = "do one thing for me" const r = await runTask(hooks, "c1", "copilot-mx-luna-medium", before) expect(r.subagentType).toBe("copilot-mx-luna-medium") - expect(r.prompt.startsWith(before)).toBe(true) - // laneOfShell takes the first hit in LANE_ORDER order (the static manifest lists luna-medium under mechanical/main; mechanical hits first) - const lanesStatic = loadManifest().lanes as Record<string, string[]> - const lane = (["economy", "mechanical", "main", "hard", "vision", "review"] as const).find((l) => lanesStatic[l]?.includes("copilot-mx-luna-medium"))! - const roleOf: Record<string, string> = { economy: "scouter", mechanical: "tester", main: "programmer", hard: "planner", vision: "observer" } - expect(r.prompt).toContain(`ROUTE_META {"lane":"${lane}","role":"${roleOf[lane]}","modality":"text","capability":"${lane === "economy" ? "ro" : "rw"}","source":"auto"}`) + expect(r.prompt).toBe(before) }) test("gate 7 non-vision shell taking an image task → silently redirected to the vision chain-head shell (no throw)", async () => { @@ -112,9 +109,13 @@ describe("autoRedirect: legacy hooks (on by default)", () => { expect(def?.vision).toBe(true) }) - test("review lane META invalid → still throws the original deny (cross-family re-review cannot synthesize a META)", async () => { - const msg = await expectDeny(hooks, "c3", "copilot-mx-opus5-high-ro", "no META") - expect(msg).toContain("invalid ROUTE_META") + // [2026-09-14]-[D5: the review-lane corner is downgraded too — a missing META on an ro review shell is synthesized + // (lane=review → role=reviewer, capability=ro) and allowed; gate 7 runs with producer_family absent = cross-family + // preference unenforced (the old "review cannot synthesize" deny is gone)]- + test("review lane META missing → allowed with the gate-6 synthesis (no throw)", async () => { + const r = await runTask(hooks, "c3", "copilot-mx-opus5-high-ro", "no META") + expect(r.subagentType).toBe("copilot-mx-opus5-high-ro") + expect(r.prompt).toBe("no META") }) test("target guard still refuses (rw meta landing on a ro cross-family shell) → throws the original deny, no redirect", async () => { @@ -123,13 +124,19 @@ describe("autoRedirect: legacy hooks (on by default)", () => { expect(msg).toContain("requires a cross-family perspective") }) - test("explore built-in blocking → appends a synthetic ROUTE_META and rewrites subagent_type (no throw)", async () => { + // [2026-09-14]-[D5: the built-in-agent redirect no longer appends a synthetic ROUTE_META — the gate-6 synthesizer + // covers the re-check, so subagent_type is rewritten and the prompt is carried as-is]- + test("explore built-in blocking → rewrites subagent_type to an economy shell, prompt untouched (no throw)", async () => { const cfgAny = (hooks as any)._cfg as Record<string, any> - const r = await runTask(hooks, "c5", "explore", "scan the whole repo structure") + const before = "scan the whole repo structure" + const r = await runTask(hooks, "c5", "explore", before) expect(r.subagentType).not.toBe("explore") expect(r.subagentType).not.toBe("general") expect(cfgAny.agent![r.subagentType]).toBeTruthy() - expect(r.prompt).toContain('"lane":"economy","role":"scouter","modality":"text","capability":"ro","source":"auto"') + expect(r.prompt).toBe(before) + const laneOfTarget = (["economy", "mechanical", "main", "hard", "vision", "review"] as const) + .find((l) => (loadManifest().lanes as Record<string, string[]>)[l]?.includes(r.subagentType)) + expect(laneOfTarget).toBe("economy") }) }) @@ -139,8 +146,14 @@ describe("autoRedirect=false: keep throwing the deny", () => { hooks = await makeHooks({ matrix: { mode: "legacy" }, dispatch: { autoRedirect: false } }) }, 20_000) - test("gate 6 META invalid → throws (no META synthesized)", async () => { - const msg = await expectDeny(hooks, "d1", "copilot-mx-luna-medium", "no META") + // [2026-09-14]-[D5: gate 6 synthesizes a missing META regardless of autoRedirect (it is a gate disposition, not a + // redirect) — the old "deny bites when autoRedirect:false" corner is gone; a present-but-wrong META still throws]- + test("gate 6 META missing → allowed even with autoRedirect off (synthesis is a gate disposition, not a redirect)", async () => { + const r = await runTask(hooks, "d1", "copilot-mx-luna-medium", "no META") + expect(r.subagentType).toBe("copilot-mx-luna-medium") + }) + test("gate 6 META present-but-wrong → still throws with autoRedirect off (producer error, no redirect)", async () => { + const msg = await expectDeny(hooks, "d1b", "copilot-mx-luna-medium", 'ROUTE_META {"lane":"mechanical","role":"programmer","capability":"bogus","source":"auto"}\n任务') expect(msg).toContain("invalid ROUTE_META") }) test("explore → throws the built-in blocking deny", async () => { diff --git a/test/dispatch-gates.test.ts b/test/dispatch-gates.test.ts index a11b17f..c4237fc 100644 --- a/test/dispatch-gates.test.ts +++ b/test/dispatch-gates.test.ts @@ -176,10 +176,11 @@ describe("gates: built-in subagent blocking", () => { describe("config: new behavior-section validation", () => { const base = { version: 1, providers: {}, extensions: {} } - test("defaults: context 60/80/100k, gates on, builtinAgents deny, injection chain, floor 3000", () => { + test("defaults: context 60/80/120k, 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, subagentForceTokens: 100_000, subagentCap: true }) + // [2026-09-15]-[subagentForceTokens omitted (absent follows forceTokens); the subagentSoftTiers field is retired] + expect(config.context).toEqual({ gates: true, softTokens: 60_000, hardTokens: 80_000, forceTokens: 120_000, readBudgetTokens: 1_500, autoHandover: true, subagentCap: true }) expect(config.builtinAgents.mode).toBe("deny") expect(config.injection.mode).toBe("chain") expect(config.rules.delegationFloor).toBe(3_000) @@ -265,10 +266,16 @@ describe("gates: GateResult.redirect (autoRedirect)", () => { expect(r.redirect).toBeNull() }) - test("gate 6 invalid META deny → redirect=null (index layer synthesizes META for redirection)", () => { - const r = checkShell(glmShell.name, glmShell, "没有 META 的 prompt", snap()) // fixture: prompt without META - expect(r.deny).toContain("invalid ROUTE_META") - expect(r.redirect).toBeNull() + // [2026-09-14]-[D5 gate-6 downgrade-to-observe: a missing META no longer denies — the gate synthesizes from lane + // and allows with a note; only a PRESENT-but-wrong META (invalid field value / missing required field) still + // denies, with redirect=null (the producer must fix the line, the plugin does not rewrite it)]- + test("gate 6 META missing → allowed with the synthesized-from-lane note; present-but-wrong still denies (redirect=null)", () => { + const rMissing = checkShell(glmShell.name, glmShell, "没有 META 的 prompt", snap()) // fixture: prompt without META + expect(rMissing.deny).toBeNull() + expect(rMissing.note).toContain("synthesized from lane") + const rBad = checkShell(glmShell.name, glmShell, 'ROUTE_META {"lane":"main","role":"programmer","capability":"bogus","source":"auto"}\n任务', snap()) + expect(rBad.deny).toContain("invalid ROUTE_META") + expect(rBad.redirect).toBeNull() }) test("allow path has deny=null and redirect=null", () => { @@ -277,3 +284,151 @@ describe("gates: GateResult.redirect (autoRedirect)", () => { expect(r.redirect).toBeNull() }) }) + +// [2026-09-14]-[D3 dispatch:"off" stand-down fixtures: a project that set the top-level "dispatch":"off" in +// .switchman/settings.json gets its task calls allowed UNGOVERNED — every task deny class (breaker, gate 7 rw/ro, +// built-in blocking, dynamic uninjected deny) stands down, while the non-dispatch surfaces stay on: the subagent cap +// gate and the lang gate still deny (they run BEFORE the stand-down), breaker RECORDING in message.part.updated +// keeps feeding routing state, and the [ROUTE] line is the only prompt surface that hides. Fixture project A carries +// dispatch:"off" with NO lang block in settings.json + the AGENTS.md marker for the lang config — proving the +// "settings exists but no valid lang block" case stays silent and falls back; project B has dispatch:"off" and no +// lang config at all, proving the lang gate outranks the opt-out (specified gate order)]- +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const d3State = mkdtempSync(join(tmpdir(), "switchman-d3-state-")) +const d3Config = mkdtempSync(join(tmpdir(), "switchman-d3-config-")) +const prevD3State = process.env.SWITCHMAN_STATE +const prevD3Config = process.env.OPENCODE_CONFIG_DIR +process.env.SWITCHMAN_STATE = d3State +process.env.OPENCODE_CONFIG_DIR = d3Config +mkdirSync(d3State, { recursive: true }) +writeFileSync(join(d3State, "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(d3State, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) +// hermetic TTL pre-seeds (same trick as auto-redirect.test.ts: zero networking, gates reach gate 4/7 deterministically) +// + a pre-seeded breaker entry: project A's task calls to this shell must pass under dispatch:"off" (fleet denies) +const breakerShell = "glm-mx-53-high" +writeFileSync( + join(d3State, "model-matrix.json"), + JSON.stringify({ + generated_at: new Date().toISOString(), + combos: Object.fromEntries(loadManifest().shells.map((s) => [s.matrixKey, { status: "ok", latency_ms: 100, checked_at: new Date().toISOString() }])), + }), +) +for (const [file, body] of Object.entries({ + "routing.json": { down_agents: { [breakerShell]: "consecutive failures" }, down_expiry: { [breakerShell]: Date.now() / 1000 + 3600 } }, + "costs.json": { scores: {}, fetched_at: Date.now() / 1000 }, + "selfupdate.json": { checked_at: Date.now() / 1000, 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 }, + // subagent cap persistence: this session is terminated BEFORE boot → the cap gate outranks the stand-down + "subagent-cap.json": { ses_d3cap: { at: Date.now(), tokens: 150_000 } }, +} as Record<string, unknown>)) { + writeFileSync(join(d3State, file), JSON.stringify(body)) +} +// project A: dispatch off + lang configured ONLY via the AGENTS.md marker (settings.json has no lang block) +const d3ProjectA = mkdtempSync(join(tmpdir(), "switchman-d3-project-a-")) +mkdirSync(join(d3ProjectA, ".switchman"), { recursive: true }) +writeFileSync(join(d3ProjectA, ".switchman", "settings.json"), JSON.stringify({ dispatch: "off" })) +writeFileSync(join(d3ProjectA, "AGENTS.md"), "switchman:lang conversation=en comments=en docs=en\n") +// project B: dispatch off + NO lang config anywhere → the lang hard gate must still deny task calls +const d3ProjectB = mkdtempSync(join(tmpdir(), "switchman-d3-project-b-")) +mkdirSync(join(d3ProjectB, ".switchman"), { recursive: true }) +writeFileSync(join(d3ProjectB, ".switchman", "settings.json"), JSON.stringify({ dispatch: "off" })) + +import { SwitchmanPlugin } from "../src/index" +import { loadManifest, loadRouting } from "../src/state" +import { renderRouteLine } from "../src/route-line" + +type D3Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> +const d3Client = { + provider: { list: async () => [] }, + session: { + async get(opts: any) { return { data: { id: opts?.path?.id, title: "T", directory: d3ProjectA } } }, + async list() { return { data: [] } }, + }, +} +async function d3Boot(projectDir: string, options: Record<string, unknown> = { matrix: { mode: "legacy" } }): Promise<D3Hooks> { + return SwitchmanPlugin({ client: d3Client, directory: projectDir } as any, options as any) +} +async function d3Task(hooks: D3Hooks, callID: string, subagentType: string, prompt: string, extraArgs: Record<string, unknown> = {}): Promise<string> { + const output: any = { args: { subagent_type: subagentType, prompt, ...extraArgs } } + await hooks["tool.execute.before"]!({ tool: "task", sessionID: "ses_d3main", callID } as any, output) + return String(output.args.subagent_type) +} +async function d3ExpectDeny(hooks: D3Hooks, callID: string, tool: string, args: Record<string, unknown>): Promise<string> { + try { + await hooks["tool.execute.before"]!({ tool, sessionID: "ses_d3main", callID } as any, { args } as any) + } catch (exc) { + return String((exc as Error).message ?? exc) + } + throw new Error(`expected deny throw did not happen: ${tool}`) +} +const MAIN_META = 'ROUTE_META {"lane":"main","role":"programmer","capability":"rw","modality":"text","source":"auto"}\nbody' + +describe("dispatch off: task deny classes stand down (allowed ungoverned)", () => { + let hooks: D3Hooks + test("plugin construction (project A, legacy)", async () => { + hooks = await d3Boot(d3ProjectA) + }, 20_000) + + test("breaker deny stands down: a breaker-downed shell dispatch is allowed", async () => { + expect(loadRouting().down_agents[breakerShell]).toBeTruthy() // fleet would deny via gate 4 + const landed = await d3Task(hooks, "d3-a1", breakerShell, MAIN_META) + expect(landed).toBe(breakerShell) + }) + + test("gate 7 rw/ro deny stands down: an rw task on an ro shell is allowed", async () => { + const ro = loadManifest().shells.find((s) => s.capability === "ro")! + const landed = await d3Task(hooks, "d3-a2", ro.name, 'ROUTE_META {"lane":"review","role":"planner","capability":"rw","modality":"text","source":"auto"}\nbody') + expect(landed).toBe(ro.name) + }) + + test("built-in agent deny stands down: explore allowed with no redirect rewriting", async () => { + const landed = await d3Task(hooks, "d3-a3", "explore", "scan the repo") + expect(landed).toBe("explore") + }) + + test("dynamic uninjected-shell deny stands down: a shell-shaped unregistered name is allowed", async () => { + const hooksDyn = await d3Boot(d3ProjectA, {}) + const landed = await d3Task(hooksDyn, "d3-a4", "glm-mx-nonexist-high", MAIN_META) + expect(landed).toBe("glm-mx-nonexist-high") + }, 20_000) +}) + +describe("dispatch off: non-dispatch surfaces stay on", () => { + let hooks: D3Hooks + test("plugin construction (project A + B, legacy)", async () => { + hooks = await d3Boot(d3ProjectA) + }, 20_000) + + test("subagent cap gate still denies a terminated-session resume (cap outranks the stand-down)", async () => { + const msg = await d3ExpectDeny(hooks, "d3-b1", "task", { subagent_type: breakerShell, task_id: "ses_d3cap", prompt: MAIN_META }) + expect(msg).toContain("can never be resumed") + }) + + test("lang hard gate still denies task calls in an unconfigured project (lang outranks the stand-down)", async () => { + const hooksB = await d3Boot(d3ProjectB) + const msg = await d3ExpectDeny(hooksB, "d3-b2", "task", { subagent_type: breakerShell, prompt: MAIN_META }) + expect(msg).toContain("language preference is not configured") + }, 20_000) + + test("breaker RECORDING still updates routing state under dispatch off (message.part.updated accounting)", async () => { + const shell = loadManifest().shells.find((s) => s.name !== breakerShell && s.pool === "glm")! + const part = { type: "tool", state: { status: "error", input: { subagent_type: shell.name }, error: "boom quota" } } + await hooks.event!({ event: { type: "message.part.updated", properties: { part } } } as any) + await hooks.event!({ event: { type: "message.part.updated", properties: { part } } } as any) + // 2 failures within the window trip the breaker; for a registered shell the key is the comboKey (= matrixKey) + const routing = loadRouting() + expect(routing.down_agents[shell.name] ?? routing.down_agents[shell.matrixKey]).toBeTruthy() + }) + + test("[ROUTE] line suppressed in a dispatch-off project; the lang line still renders", async () => { + const output = { system: [] as string[] } + await hooks["experimental.chat.system.transform"]!({ sessionID: "ses_d3main" } as any, output as any) + expect(output.system.some((l) => l === renderRouteLine())).toBe(false) + expect(output.system.some((l) => l.startsWith("[LANG]"))).toBe(true) + }) +}) diff --git a/test/dispatch-mode.test.ts b/test/dispatch-mode.test.ts new file mode 100644 index 0000000..034def6 --- /dev/null +++ b/test/dispatch-mode.test.ts @@ -0,0 +1,93 @@ +// [2026-09-14]-[D3 dispatch opt-out contract: top-level "dispatch": "off" in <workspace-dirname>/settings.json — +// exact-string parsing, fail-open fleet everywhere else, present-but-invalid note, and the broken-JSON warning once +// per process per path. The log callback is injected so every assertion is hermetic (no shared status-log file)] +import { describe, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { loadDispatchMode, parseDispatchMode } from "../src/dispatch-mode" + +function sandboxProject(): string { + const dir = mkdtempSync(join(tmpdir(), "switchman-dispatch-mode-")) + mkdirSync(join(dir, ".switchman"), { recursive: true }) + return dir +} + +describe("dispatch-mode: parseDispatchMode (pure)", () => { + test("exact string: only the exact \"off\" opts out (case/whitespace variants are fleet)", () => { + expect(parseDispatchMode('{"dispatch":"off"}')).toEqual({ mode: "off", broken: false, invalidValue: false }) + expect(parseDispatchMode('{"v":1,"lang":{"conversation":"en","comments":"en","docs":"en"},"dispatch":"off"}').mode).toBe("off") + expect(parseDispatchMode('{"dispatch":"OFF"}')).toMatchObject({ mode: "fleet", invalidValue: true, rawValue: "OFF" }) + expect(parseDispatchMode('{"dispatch":"off "}')).toMatchObject({ mode: "fleet", invalidValue: true, rawValue: "off " }) + expect(parseDispatchMode('{"dispatch":" off"}').mode).toBe("fleet") + }) + test("fail-open: absent field / other values / non-string values → fleet", () => { + expect(parseDispatchMode("{}")).toEqual({ mode: "fleet", broken: false, invalidValue: false }) + expect(parseDispatchMode('{"lang":{"conversation":"en","comments":"en","docs":"en"}}')).toMatchObject({ mode: "fleet", invalidValue: false }) + expect(parseDispatchMode('{"dispatch":"fleet"}')).toMatchObject({ mode: "fleet", invalidValue: true, rawValue: "fleet" }) + expect(parseDispatchMode('{"dispatch":"on"}')).toMatchObject({ mode: "fleet", invalidValue: true, rawValue: "on" }) + expect(parseDispatchMode('{"dispatch":true}')).toMatchObject({ mode: "fleet", invalidValue: true, rawValue: "true" }) + expect(parseDispatchMode('{"dispatch":42}')).toMatchObject({ mode: "fleet", invalidValue: true, rawValue: "42" }) + expect(parseDispatchMode('{"dispatch":null}').mode).toBe("fleet") + }) + test("broken JSON is flagged (caller warns); valid non-object JSON is plain fleet (no note)", () => { + expect(parseDispatchMode("{nope")).toEqual({ mode: "fleet", broken: true, invalidValue: false }) + expect(parseDispatchMode('{"dispatch":"off",')).toEqual({ mode: "fleet", broken: true, invalidValue: false }) + expect(parseDispatchMode('"off"')).toEqual({ mode: "fleet", broken: false, invalidValue: false }) + expect(parseDispatchMode("null")).toEqual({ mode: "fleet", broken: false, invalidValue: false }) + }) +}) + +describe("dispatch-mode: loadDispatchMode (per-call disk read, never throws)", () => { + test("settings.json with dispatch:\"off\" → off; missing file → fleet; no log noise", () => { + const offDir = sandboxProject() + writeFileSync(join(offDir, ".switchman", "settings.json"), JSON.stringify({ v: 1, dispatch: "off" })) + const logs: string[] = [] + expect(loadDispatchMode(offDir, ".switchman", (m) => logs.push(m))).toBe("off") + expect(logs).toEqual([]) + + const emptyDir = sandboxProject() + expect(loadDispatchMode(emptyDir, ".switchman", (m) => logs.push(m))).toBe("fleet") + expect(logs).toEqual([]) + }) + test("present-but-invalid value → one note, fleet behavior; the note fires once per process per path", () => { + const dir = sandboxProject() + writeFileSync(join(dir, ".switchman", "settings.json"), JSON.stringify({ dispatch: "OFF" })) + const logs: string[] = [] + const log = (m: string) => logs.push(m) + expect(loadDispatchMode(dir, ".switchman", log)).toBe("fleet") + expect(loadDispatchMode(dir, ".switchman", log)).toBe("fleet") + expect(loadDispatchMode(dir, ".switchman", log)).toBe("fleet") + expect(logs.length).toBe(1) + expect(logs[0]).toContain('.switchman/settings.json "dispatch" present but not exactly "off"') + expect(logs[0]).toContain("OFF") + expect(logs[0]).toContain("fleet behavior") + }) + test("broken settings.json → warning with the exact copy, once per process per path; a second path warns separately", () => { + const dirA = sandboxProject() + const dirB = sandboxProject() + writeFileSync(join(dirA, ".switchman", "settings.json"), "{not json") + writeFileSync(join(dirB, ".switchman", "settings.json"), "{also broken") + const logs: string[] = [] + const log = (m: string) => logs.push(m) + // fleet behavior, warning emitted once per path (three reads of A, one of B) + expect(loadDispatchMode(dirA, ".switchman", log)).toBe("fleet") + expect(loadDispatchMode(dirA, ".switchman", log)).toBe("fleet") + expect(loadDispatchMode(dirB, ".switchman", log)).toBe("fleet") + expect(loadDispatchMode(dirA, ".switchman", log)).toBe("fleet") + expect(logs.length).toBe(2) + expect(logs[0]).toBe('[opencode-switchman] .switchman/settings.json is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)') + expect(logs[1]).toBe('[opencode-switchman] .switchman/settings.json is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)') + }) + test("coexistence: a lang block and dispatch:\"off\" in the same file both parse (extra top-level fields ignored by the lang parser)", () => { + const dir = sandboxProject() + writeFileSync(join(dir, ".switchman", "settings.json"), JSON.stringify({ + v: 1, + lang: { conversation: "zh-CN", comments: "en", docs: "en" }, + dispatch: "off", + })) + const logs: string[] = [] + expect(loadDispatchMode(dir, ".switchman", (m) => logs.push(m))).toBe("off") + expect(logs).toEqual([]) + }) +}) diff --git a/test/index-options.test.ts b/test/index-options.test.ts index 9e56f32..fc5c5a2 100644 --- a/test/index-options.test.ts +++ b/test/index-options.test.ts @@ -9,6 +9,7 @@ process.env.SWITCHMAN_STATE = mkdtempSync(join(tmpdir(), "switchman-options-stat writeFileSync(join(process.env.SWITCHMAN_STATE, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) import { SwitchmanPlugin } from "../src/index" +import { parseJsonc, validateUserConfig } from "../src/config" test("config hook still injects shells when the plugin is declared without options", async () => { const hooks = await SwitchmanPlugin({ client: { provider: { list: async () => [] } } } as any, undefined as any) @@ -16,3 +17,29 @@ test("config hook still injects shells when the plugin is declared without optio await hooks.config!(cfg as any) expect(Object.keys((cfg as any).agent ?? {}).length).toBeGreaterThan(0) }, 15_000) + +// [2026-09-15]-[context.subagentSoftTiers retired (fraction coefficients → shared absolute main-session thresholds): +// the option is gone from the config surface, legacy values pass through harmlessly; context.subagentForceTokens is +// optional — absent follows forceTokens, present-but-invalid → deleted with SWM037 (fail-open)] +test("context.subagentSoftTiers retired; subagentForceTokens optional, invalid override deleted (SWM037)", () => { + // defaults no longer carry either field (the retired key no longer exists on the type) + const base = validateUserConfig({}) + expect("subagentSoftTiers" in base.config.context).toBe(false) + expect(base.config.context.subagentForceTokens).toBeUndefined() + expect(base.diagnostics.filter((d) => d.level === "error")).toEqual([]) + // retired option: legacy jsonc values pass through harmlessly (unknown keys are not validated, no diagnostics) + const legacy = parseJsonc(`{"context":{"subagentSoftTiers":[0.4,0.8]}}`) + const legacyChecked = validateUserConfig("value" in legacy ? legacy.value : {}) + expect(legacyChecked.diagnostics.filter((d) => d.level === "error")).toEqual([]) + // valid jsonc override passes through untouched + const ok = parseJsonc(`{"context":{"subagentForceTokens":150000}}`) + const okChecked = validateUserConfig("value" in ok ? ok.value : {}) + expect(okChecked.config.context.subagentForceTokens).toBe(150_000) + expect(okChecked.diagnostics.filter((d) => d.level === "error")).toEqual([]) + // present-but-invalid override (outside 20k..1M / non-finite / wrong type) → deleted + SWM037, cap falls back to forceTokens + for (const bad of [19_999, 1_000_001, Number.NaN, "big", null]) { + const checked = validateUserConfig({ context: { subagentForceTokens: bad as any } }) + expect(checked.config.context.subagentForceTokens).toBeUndefined() + expect(checked.diagnostics.some((d) => d.code === "SWM037" && d.path === "context.subagentForceTokens")).toBe(true) + } +}) diff --git a/test/lang-config.test.ts b/test/lang-config.test.ts index 7bead4a..1327e41 100644 --- a/test/lang-config.test.ts +++ b/test/lang-config.test.ts @@ -8,7 +8,7 @@ import { join } from "node:path" import { normalizeLangValue, parseLangSettings, parseAgentsMdLangMarker, loadLangConfig, saveLangConfig, renderAskDirective, renderLangLine, parseQuestionAnswers, saveLangFromQuestion, langGateDecision, - hasLangMarkerQuestions, LANG_SETTINGS_FILE, + hasLangMarkerQuestions, LANG_SETTINGS_FILE, UI_LOCALE_ASK_TEXT, normalizeUiLocale, detectUiLocale, } from "../src/lang-config" import { validateUserConfig, resolveEffectiveOptions } from "../src/config" import { DEFAULT_LANG_CANDIDATES } from "../src/types" @@ -157,6 +157,82 @@ describe("lang-config: IO (load/save/capture)", () => { }) }) +// [2026-09-14]-[D4 locale-following ask: the 11-tag question table localizes ONLY the user-facing question texts — +// the `switchman-lang n/3: ` marker prefix (the plugin-side capture anchor) stays byte-stable across every locale, +// and the directive body/deny copy stay English. Locale chain = env LC_ALL → LANG → "en" (opencode exposes no +// locale surface to plugins), read at ask time, fail-open] +describe("lang-config: locale-following ask (D4)", () => { + const TAGS = ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de", "it", "pt", "ru"] + + test("marker prefix `switchman-lang n/3: ` byte-exact across 11 tags × 3 questions", () => { + for (const tag of TAGS) { + const asks = UI_LOCALE_ASK_TEXT[tag]! + expect(asks).toHaveLength(3) + for (let i = 0; i < 3; i++) expect(asks[i]!.startsWith(`switchman-lang ${i + 1}/3: `)).toBe(true) + const d = renderAskDirective(DEFAULT_LANG_CANDIDATES, tag) + expect(d).toContain("switchman-lang 1/3: ") + expect(d).toContain("switchman-lang 2/3: ") + expect(d).toContain("switchman-lang 3/3: ") + } + }) + + test("zh-CN rendering matches the approved copy; the directive body stays English", () => { + expect(UI_LOCALE_ASK_TEXT["zh-CN"]).toEqual([ + "switchman-lang 1/3: 本项目的对话语言(你的回复与推理)?", + "switchman-lang 2/3: 代码注释与提交信息用什么语言?", + "switchman-lang 3/3: 生成的文档(计划、PRD、设计文档、报告)用什么语言?", + ]) + const d = renderAskDirective(DEFAULT_LANG_CANDIDATES, "zh-CN") + expect(d).toContain("本项目的对话语言(你的回复与推理)?") + expect(d).toContain("never write the settings file yourself") + expect(d).toContain("HARD GATE") + }) + + test("unknown locale → English fallback (fail-open en)", () => { + expect(normalizeUiLocale("xx-YY")).toBeNull() + expect(detectUiLocale({}).locale).toBe("en") + const d = renderAskDirective(DEFAULT_LANG_CANDIDATES, "xx-YY") + expect(d).toContain("Conversation language for this project (your replies and reasoning)?") + // default parameter keeps existing single-argument callers on English questions + expect(renderAskDirective(DEFAULT_LANG_CANDIDATES)).toBe(renderAskDirective(DEFAULT_LANG_CANDIDATES, "en")) + }) + + test("normalization: env-style and script values map onto known tags", () => { + expect(normalizeUiLocale("zh_CN.UTF-8")).toBe("zh-CN") + expect(normalizeUiLocale("zh-HK")).toBe("zh-TW") + expect(normalizeUiLocale("zh-Hant")).toBe("zh-TW") + expect(normalizeUiLocale("zh-TW")).toBe("zh-TW") + expect(normalizeUiLocale("zh_SG")).toBe("zh-CN") + expect(normalizeUiLocale("en_US.UTF-8")).toBe("en") + expect(normalizeUiLocale("ja_JP")).toBe("ja") + expect(normalizeUiLocale("ko_KR.eucKR")).toBe("ko") + expect(normalizeUiLocale(" RU ")).toBe("ru") + expect(normalizeUiLocale("pt_BR")).toBe("pt") + expect(normalizeUiLocale("es_MX")).toBe("es") + expect(normalizeUiLocale("fr_FR@euro")).toBe("fr") + expect(normalizeUiLocale("xx-YY")).toBeNull() + expect(normalizeUiLocale("")).toBeNull() + expect(normalizeUiLocale(42)).toBeNull() + }) + + test("env chain order: LC_ALL wins over LANG; unrecognized values fall through to the next step", () => { + expect(detectUiLocale({ LC_ALL: "zh_CN.UTF-8", LANG: "en_US.UTF-8" })).toEqual({ locale: "zh-CN", via: "LC_ALL" }) + expect(detectUiLocale({ LANG: "ja_JP.UTF-8" })).toEqual({ locale: "ja", via: "LANG" }) + expect(detectUiLocale({ LC_ALL: "", LANG: "de_DE.UTF-8" })).toEqual({ locale: "de", via: "LANG" }) + expect(detectUiLocale({ LC_ALL: "bogus", LANG: "ko_KR" })).toEqual({ locale: "ko", via: "LANG" }) + expect(detectUiLocale({ LC_ALL: "bogus", LANG: "also-bogus" })).toEqual({ locale: "en", via: "default" }) + expect(detectUiLocale({ LC_ALL: "bogus" })).toEqual({ locale: "en", via: "default" }) + }) + + test("capture round-trip: localized questions keep the marker-match anchor locale-independent", () => { + for (const tag of TAGS) { + const [q1, q2, q3] = UI_LOCALE_ASK_TEXT[tag]! + const out = `User has answered your questions: "${q1}"="简体中文", "${q2}"="English", "${q3}"="日本語"` + expect(parseQuestionAnswers(out)).toEqual(["简体中文", "English", "日本語"]) + } + }) +}) + describe("lang-config: config surface", () => { test("defaults fill the lang section; bad values fall back with SWM037", () => { const ok = validateUserConfig({}) diff --git a/test/route-line.test.ts b/test/route-line.test.ts new file mode 100644 index 0000000..c69cae9 --- /dev/null +++ b/test/route-line.test.ts @@ -0,0 +1,62 @@ +// [2026-09-14]-[D2 per-turn [ROUTE] line contract: one static text (pinned verbatim — it is protocol copy, drift here is +// a protocol change), gate rule = rules||banner (zero-injection wish respected, same as the watermark/TODO lines), and +// the wiring pushes it after [WATERMARK:SESSION]/[TODO] inside the rules||banner block. The dispatch-mode opt-out gate +// is owned by dispatch:"off" (D3, not in this change)] +import { expect, test } from "bun:test" +import { mkdtempSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { renderRouteLine, routeLineEnabled } from "../src/route-line" + +test("route line: static text pin (protocol copy, verbatim)", () => { + expect(renderRouteLine()).toBe("[ROUTE] token economy (IRON RULE): before each substantive action, declare in one sentence — [DISPATCH] self or delegate (§6) — weighing the measured context ([WATERMARK:SESSION]): hands-on spends and grows this session's context on every later turn, a dispatch spends a fresh shell context and returns a summary; long or heavy context favors dispatch, trivia (below the delegation floor, known-path reads, workspace bookkeeping, fleet coordination) stays hands-on.") +}) + +test("route line gate: any of rules/banner on keeps the line, both off suppresses, dispatch-off hides it", () => { + expect(routeLineEnabled(true, true, false)).toBe(true) + expect(routeLineEnabled(true, false, false)).toBe(true) + expect(routeLineEnabled(false, true, false)).toBe(true) + expect(routeLineEnabled(false, false, false)).toBe(false) + // [2026-09-14]-[D3: dispatch:"off" is the single opt-out for the routing-discipline surface] + expect(routeLineEnabled(true, true, true)).toBe(false) + expect(routeLineEnabled(true, false, true)).toBe(false) + expect(routeLineEnabled(false, true, true)).toBe(false) + expect(routeLineEnabled(false, false, true)).toBe(false) +}) + +const configDir = mkdtempSync(join(tmpdir(), "switchman-route-config-")) +const stateDir = mkdtempSync(join(tmpdir(), "switchman-route-state-")) +const projectDir = mkdtempSync(join(tmpdir(), "switchman-route-project-")) +process.env.OPENCODE_CONFIG_DIR = configDir +process.env.SWITCHMAN_STATE = stateDir +writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) + +import { SwitchmanPlugin } from "../src/index" + +const fakeClient = { + provider: { list: async () => [] }, + session: { + async get(opts: any) { return { data: { id: opts?.path?.id, title: "T", directory: projectDir } } }, + async list() { return { data: [] } }, + }, +} + +async function boot(rawOptions: Record<string, unknown>) { + const hooks = await SwitchmanPlugin({ client: fakeClient, directory: projectDir } as any, { matrix: { mode: "legacy" }, ...rawOptions } as any) + const system = async (sessionID: string) => { + const output = { system: [] as string[] } + await hooks["experimental.chat.system.transform"]!({ sessionID } as any, output as any) + return output.system + } + return { system } +} + +test("route line wiring: pushed on main-session turns by default, suppressed when rules and banner are both off", async () => { + const on = await boot({}) + const sysOn = await on.system("ses_route_main") + expect(sysOn.filter((l) => l === renderRouteLine()).length).toBe(1) + + const off = await boot({ rules: { enabled: false }, banner: { enabled: false } }) + const sysOff = await off.system("ses_route_main2") + expect(sysOff.some((l) => l === renderRouteLine())).toBe(false) +}, 30_000) diff --git a/test/routing.test.ts b/test/routing.test.ts index dcd45d7..d885612 100644 --- a/test/routing.test.ts +++ b/test/routing.test.ts @@ -165,11 +165,21 @@ describe("six-gate order", () => { const d = denyOf("copilot-mx-terra-high", meta(), s) expect(d).toContain("temporarily unavailable") }) - test("14 META missing/malformed → deny with sample", () => { - expect(denyOf("glm-mx-53-high", "裸任务无 META")).toContain("missing ROUTE_META") - expect(denyOf("glm-mx-53-high", "ROUTE_META {broken\n任务")).toContain("malformed") + // [2026-09-14]-[D5 gate-6 downgrade-to-observe: missing/malformed → allowed with a lane-synthesized META + note; + // a PRESENT-but-wrong line (invalid field value / missing required field) still denies with the sample hint]- + test("14 META missing/malformed → allowed with the synthesized-from-lane note; present-but-wrong still denies", () => { + const rMissing = decOf("glm-mx-53-high", "裸任务无 META") + expect(rMissing.deny).toBeNull() + expect(rMissing.note).toContain("synthesized from lane") + const rMalformed = decOf("glm-mx-53-high", "ROUTE_META {broken\n任务") + expect(rMalformed.deny).toBeNull() + expect(rMalformed.note).toContain("synthesized from lane") + // present-but-wrong: a parseable line missing required fields is a producer error → deny stays const d = denyOf("glm-mx-53-high", 'ROUTE_META {"lane":"main","modality":"text"}\n任务') expect(d).toContain("missing required field") + // present-but-wrong: an invalid field value denies too + const d2 = denyOf("glm-mx-53-high", 'ROUTE_META {"lane":"main","role":"programmer","capability":"bogus","source":"auto"}\n任务') + expect(d2).toContain("invalid ROUTE_META") }) test("15 same-family reviewer → deny (cross-family re-review gate)", () => { const d = denyOf("glm-mx-53-high", meta("review", "reviewer", "glm", "ro"), snap()) diff --git a/test/shell-context-advisory.test.ts b/test/shell-context-advisory.test.ts new file mode 100644 index 0000000..4930a44 --- /dev/null +++ b/test/shell-context-advisory.test.ts @@ -0,0 +1,115 @@ +// [2026-09-14]-[subagent soft tiers wiring contract (D1): system.transform's shell branch replaces the bare early-return — +// a dispatched shell session (never internal title/compaction/summary) gets at most one [SHELL-CONTEXT] advisory per tier, +// tracking the shell watermark (conserve → hand-off); subagentCap:false disables the advisories, a terminated session +// stays silent (the deny message governs), and session.deleted re-arms the dedup map] +// [2026-09-15]-[tiers now sit at the MAIN session's absolute soft/hard lines (60k/80k defaults) and the default shell cap +// follows forceTokens (120k) — advisory copy below pins 120k as the effective cap] +import { expect, test } from "bun:test" +import { mkdtempSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const configDir = mkdtempSync(join(tmpdir(), "switchman-shelladv-config-")) +const stateDir = mkdtempSync(join(tmpdir(), "switchman-shelladv-state-")) +const projectDir = mkdtempSync(join(tmpdir(), "switchman-shelladv-project-")) +process.env.OPENCODE_CONFIG_DIR = configDir +process.env.SWITCHMAN_STATE = stateDir +writeFileSync(join(stateDir, "model-catalog.json"), JSON.stringify({ fetched_at: Date.now(), etag: null, index: {} })) + +import { SwitchmanPlugin } from "../src/index" + +const fakeClient = { + provider: { list: async () => [] }, + session: { + async get(opts: any) { return { data: { id: opts?.path?.id, title: "T", directory: projectDir } } }, + async list() { return { data: [] } }, + }, +} + +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 boot(rawOptions: Record<string, unknown> = {}) { + // legacy mode (deterministic sessionAgent classification — same recipe as todo-nudge/subagent-cap tests) + const hooks = await SwitchmanPlugin({ client: fakeClient, directory: projectDir } as any, { matrix: { mode: "legacy" }, ...rawOptions } as any) + const emit = (event: any) => hooks.event!({ event } as any) + const seedShell = async (sessionId: string, agent = "glm-mx-53f-low") => + emit({ type: "session.created", properties: { info: { id: sessionId, agent } } }) + const mark = async (sessionId: string, input: number) => + emit({ type: "message.updated", properties: { sessionID: sessionId, info: assistantTokens(input) } }) + const system = async (sessionID: string) => { + const output = { system: [] as string[] } + await hooks["experimental.chat.system.transform"]!({ sessionID } as any, output as any) + return output.system + } + const deny = (sessionId: string, callID: string) => + hooks["tool.execute.before"]!({ tool: "read", sessionID: sessionId, callID } as any, { args: {} } as any) + return { emit, seedShell, mark, system, deny } +} + +const advisory = (sys: string[]) => sys.find((l) => l.startsWith("[SHELL-CONTEXT]")) + +test("shell advisory: tier 1 conserve fires once, tier 2 hand-off once, then quiet; termination silences", async () => { + const { seedShell, mark, system, deny } = await boot() + const sid = "ses_adv_shell" + await seedShell(sid) + + // sub-tier-1 measurement (44k) → no advisory, and the shell branch still skips rules/banner/LANG + await mark(sid, 40_000) + let sys = await system(sid) + expect(advisory(sys)).toBeUndefined() + + // crossing tier 1: 60k input → 64k measured ≥ 60k (shared soft line), < 80k → conserve line, numbers rendered from the live measurement + await mark(sid, 60_000) + sys = await system(sid) + expect(advisory(sys)).toBe("[SHELL-CONTEXT] measured shell context ≈ 64k/120k (conserve): stop batch reads and long pastes — switch to targeted grep and cite only the needed excerpts; finish the current work unit before starting anything new; keep outputs compact.") + + // same tier again → suppressed (once-per-tier dedup) + expect(advisory(await system(sid))).toBeUndefined() + + // crossing tier 2: 80k input → 84k ≥ 80k (shared hard line) → hand-off line with the inline HANDOFF marker + await mark(sid, 80_000) + sys = await system(sid) + expect(advisory(sys)?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 84k/120k (hand-off):")).toBe(true) + expect(advisory(sys)).toContain("`HANDOFF: inline · progress: n/m · next: <one sentence>`") + + // tier 2 delivered → quiet again + expect(advisory(await system(sid))).toBeUndefined() + + // crossing the hard cap (116k input → 120k measured ≥ the 120k shared force line) terminates the session → the deny message governs, advisories stop + await mark(sid, 116_000) + expect(advisory(await system(sid))).toBeUndefined() + await expect(deny(sid, "call_adv_deny")).rejects.toThrow("SUBAGENT CONTEXT CAP REACHED") +}, 30_000) + +test("shell advisory: subagentCap:false disables the advisories entirely", async () => { + const { seedShell, mark, system } = await boot({ context: { subagentCap: false } }) + const sid = "ses_adv_nocap" + await seedShell(sid) + await mark(sid, 90_000) // would be deep into tier 2 with the cap on + expect(advisory(await system(sid))).toBeUndefined() +}, 30_000) + +test("shell advisory: internal and main sessions never receive it; session.deleted re-arms the dedup", async () => { + const { emit, seedShell, mark, system } = await boot() + // internal session (title) — even with a huge watermark it gets nothing + await seedShell("ses_adv_title", "title") + await mark("ses_adv_title", 90_000) + expect(advisory(await system("ses_adv_title"))).toBeUndefined() + + // main session — measured watermark lands in the main map, not the shell map; no advisory either + await mark("ses_adv_main", 90_000) + expect(advisory(await system("ses_adv_main"))).toBeUndefined() + + // session.deleted clears shellWatermark + the dedup map: after deletion the same measurements re-arm tier 1 + const sid = "ses_adv_gone" + await seedShell(sid) + await mark(sid, 60_000) + expect(advisory(await system(sid))?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 64k/120k (conserve):")).toBe(true) + expect(advisory(await system(sid))).toBeUndefined() + await emit({ type: "session.deleted", properties: { info: { id: sid } } }) + await mark(sid, 60_000) + expect(advisory(await system(sid))?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 64k/120k (conserve):")).toBe(true) +}, 30_000) diff --git a/test/shells-select.test.ts b/test/shells-select.test.ts index ea6802b..a8328b4 100644 --- a/test/shells-select.test.ts +++ b/test/shells-select.test.ts @@ -87,3 +87,35 @@ describe("selectInjectableDefs (pool-config keepModelIds)", () => { for (const name of ["cp-mx-m2-high", "cp-mx-m2-high-ro", "cp-mx-m3-high", "cp-mx-m3-high-ro"]) expect(kept).toContain(name) }) }) + +// [2026-09-11]-[injection mode "configured": favorites/visible set non-empty → skip algorithmic chain picks; the face is +// keepModels (configured models) ∪ keepModelIds (pool-config) ∪ custom-lane references — runtime dispatch is already gated +// by activation ∩ pool selection, so off-configured chain picks are dead per-request task-tool-description context] +describe("selectInjectableDefs (skipChainPicks / configured mode)", () => { + test("face narrows to exactly the configured models' faces — chain-head models outside the configured set drop out", () => { + const kept = selectInjectableDefs(defs, { ...opts, skipChainPicks: true, keepModels: new Set(["github-copilot/m2"]) }).map((d) => d.name).sort() + // m1 is the S-tier chain head everywhere, but it is not configured → both faces dropped + expect(kept).toEqual(["cp-mx-m2-high", "cp-mx-m2-high-ro"]) + }) + test("composes with pool-config keepModelIds (pool members stay injectable without chain picks)", () => { + const kept = selectInjectableDefs(defs, { + ...opts, + skipChainPicks: true, + keepModels: new Set(["github-copilot/m2"]), + keepModelIds: new Set(["m3"]), + }).map((d) => d.name).sort() + expect(kept).toEqual(["cp-mx-m2-high", "cp-mx-m2-high-ro", "cp-mx-m3-high", "cp-mx-m3-high-ro"]) + }) + test("custom-lane references stay force-kept under skipChainPicks", () => { + const kept = selectInjectableDefs(defs, { + ...opts, + skipChainPicks: true, + keepModels: new Set(["github-copilot/m2"]), + customLanes: { main: ["cp-mx-m1-high-ro"] }, + }).map((d) => d.name).sort() + expect(kept).toEqual(["cp-mx-m1-high-ro", "cp-mx-m2-high", "cp-mx-m2-high-ro"]) + }) + test("skipChainPicks with no keep sets at all fail-opens back to the full set (caller gates it on a non-empty configured set)", () => { + expect(selectInjectableDefs(defs, { ...opts, skipChainPicks: true })).toEqual(defs) + }) +}) diff --git a/test/subagent-cap.test.ts b/test/subagent-cap.test.ts index 59a8086..ab3b2e8 100644 --- a/test/subagent-cap.test.ts +++ b/test/subagent-cap.test.ts @@ -20,8 +20,9 @@ writeFileSync(join(projectDir, ".switchman", "settings.json"), JSON.stringify({ import { SwitchmanPlugin } from "../src/index" import { - DEFAULT_SUBAGENT_CAP_TOKENS, MAX_SUBAGENT_CAP_TOKENS, MIN_SUBAGENT_CAP_TOKENS, + MAX_SUBAGENT_CAP_TOKENS, MIN_SUBAGENT_CAP_TOKENS, subagentCapOf, capByWindow, subagentCapDenyMessage, subagentResumeDenyMessage, + subagentSoftTiersOf, shellSoftTier, shellSoftTierMessage, shellSoftTierDecision, } from "../src/context-watch" type Hooks = Awaited<ReturnType<typeof SwitchmanPlugin>> @@ -58,9 +59,11 @@ async function seedShellSession(hooks: Hooks, sessionId: string, agent = "glm-mx } 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) + // [2026-09-15]-[subagentForceTokens optional: absent follows forceTokens (shared hard line); present values keep the clamp] + test("subagentCapOf: absent → follows forceTokens (120k default), clamped override, disabled → null", () => { + expect(subagentCapOf(undefined)).toBe(120_000) + expect(subagentCapOf({})).toBe(120_000) + expect(subagentCapOf({ forceTokens: 90_000 })).toBe(90_000) 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) @@ -85,15 +88,101 @@ describe("subagent cap: pure decision layer", () => { }) }) +// [2026-09-14]-[subagent soft tiers (D1): two graceful advisories precede the hard termination backstop; delivered at +// most once per tier via system.transform's shell branch, ending with the inline HANDOFF marker the dispatcher relays +// per agents-md §2 item 5] +// [2026-09-15]-[tiers switch from fraction coefficients to the MAIN session's ABSOLUTE soft/hard thresholds expressed +// against the force anchor (subagentForceTokens when valid, else forceTokens); the window-clamped effective cap still +// pulls them down proportionally — a tier never exceeds the real termination line] +describe("subagent soft tiers: pure decision layer", () => { + test("tier derivation: shared absolute thresholds against the force anchor, fail-open defaults", () => { + // default config (no overrides): main-session 60k soft / 80k hard against the 120k force anchor + expect(subagentSoftTiersOf(undefined)).toEqual([0.5, 80_000 / 120_000]) + expect(subagentSoftTiersOf({})).toEqual([0.5, 80_000 / 120_000]) + // subagentForceTokens override: the absolute 60k/80k lines preserved against the 100k anchor + expect(subagentSoftTiersOf({ subagentForceTokens: 100_000 })).toEqual([0.6, 0.8]) + // custom main-session thresholds ride along + expect(subagentSoftTiersOf({ softTokens: 30_000, hardTokens: 60_000, forceTokens: 120_000 })).toEqual([0.25, 0.5]) + // invalid anchor → forceTokens + expect(subagentSoftTiersOf({ subagentForceTokens: Number.NaN, forceTokens: 200_000 })).toEqual([0.3, 0.4]) + // misconfigured thresholds (soft ≥ force, or f-ordering violated) → fail-open pure-defaults derivation + expect(subagentSoftTiersOf({ softTokens: 130_000, hardTokens: 140_000, forceTokens: 120_000 })).toEqual([0.5, 80_000 / 120_000]) + expect(subagentSoftTiersOf({ softTokens: 90_000, hardTokens: 80_000, forceTokens: 120_000 })).toEqual([0.5, 80_000 / 120_000]) + expect(subagentSoftTiersOf({ softTokens: 120_000, hardTokens: 125_000, forceTokens: 120_000 })).toEqual([0.5, 80_000 / 120_000]) + }) + test("tier firing at the shared absolute lines: ≈60k conserve / ≈80k hand-off against a 120k effective cap", () => { + const tiers = subagentSoftTiersOf(undefined) + const cap = 120_000 + expect(shellSoftTier(59_999, cap, tiers)).toBe(0) + expect(shellSoftTier(60_000, cap, tiers)).toBe(1) + expect(shellSoftTier(79_999, cap, tiers)).toBe(1) + expect(shellSoftTier(80_000, cap, tiers)).toBe(2) + }) + test("subagentForceTokens override keeps the absolute 60k/80k lines against a 100k cap", () => { + const tiers = subagentSoftTiersOf({ subagentForceTokens: 100_000 }) + const cap = subagentCapOf({ subagentForceTokens: 100_000 })! + expect(tiers).toEqual([0.6, 0.8]) + expect(shellSoftTier(59_999, cap, tiers)).toBe(0) + expect(shellSoftTier(60_000, cap, tiers)).toBe(1) + expect(shellSoftTier(79_999, cap, tiers)).toBe(1) + expect(shellSoftTier(80_000, cap, tiers)).toBe(2) + }) + test("small window-clamped cap pulls the tiers down proportionally (a tier never exceeds the termination line)", () => { + const tiers = subagentSoftTiersOf(undefined) + // 90% of a ~26.7k window → 24k effective cap + const clamped = capByWindow(120_000, 26_667) + expect(clamped).toBe(24_000) + // 12k conserve / 16k hand-off + expect(shellSoftTier(11_999, clamped, tiers)).toBe(0) + expect(shellSoftTier(12_000, clamped, tiers)).toBe(1) + expect(shellSoftTier(15_999, clamped, tiers)).toBe(1) + expect(shellSoftTier(16_000, clamped, tiers)).toBe(2) + expect(shellSoftTier(24_000, clamped, tiers)).toBe(2) + for (const f of tiers) expect(Math.floor(f * clamped)).toBeLessThanOrEqual(clamped) + }) + test("tier copy verbatim pins (absolute k rendered from the effective cap, HANDOFF inline-only)", () => { + expect(shellSoftTierMessage(1, 62_400, 100_000)).toBe( + "[SHELL-CONTEXT] measured shell context ≈ 62k/100k (conserve): stop batch reads and long pastes — switch to targeted grep and cite only the needed excerpts; finish the current work unit before starting anything new; keep outputs compact.", + ) + expect(shellSoftTierMessage(2, 80_000, 100_000)).toBe( + "[SHELL-CONTEXT] measured shell context ≈ 80k/100k (hand-off): open no new files or edits; finish the current unit, then end your FINAL message with a compact handover block (completed; key findings with file:line; remaining; next steps) followed by the marker line `HANDOFF: inline · progress: n/m · next: <one sentence>` (m = the delegation's work units, n = completed). Your final message is returned to the delegating session as the task result.", + ) + }) + test("once-per-tier dedup, subagentCap:false and terminated sessions stay silent (pure semantics)", () => { + const tiers = subagentSoftTiersOf(undefined) + // below tier 1: quiet, delivered state unchanged + expect(shellSoftTierDecision({ terminated: false, tokens: 40_000, cap: 100_000, tiers, delivered: 0 })).toEqual({ line: null, delivered: 0 }) + // tier 1 fires once; a second request at the same tier is suppressed + const t1 = shellSoftTierDecision({ terminated: false, tokens: 60_000, cap: 100_000, tiers, delivered: 0 }) + expect(t1.delivered).toBe(1) + expect(t1.line).toContain("[SHELL-CONTEXT]") + expect(t1.line).toContain("(conserve)") + expect(shellSoftTierDecision({ terminated: false, tokens: 60_000, cap: 100_000, tiers, delivered: 1 }).line).toBeNull() + // the higher tier fires exactly one more line (never re-delivers tier 1's copy) + const t2 = shellSoftTierDecision({ terminated: false, tokens: 90_000, cap: 100_000, tiers, delivered: 1 }) + expect(t2.delivered).toBe(2) + expect(t2.line).toContain("(hand-off)") + expect(t2.line).toContain("HANDOFF: inline") + expect(shellSoftTierDecision({ terminated: false, tokens: 90_000, cap: 100_000, tiers, delivered: 2 }).line).toBeNull() + // subagentCap: false → advisories off (they exist to make the cap graceful) + expect(shellSoftTierDecision({ terminated: false, tokens: 90_000, cap: null, tiers, delivered: 0 })).toEqual({ line: null, delivered: 0 }) + // no measurement yet → quiet + expect(shellSoftTierDecision({ terminated: false, tokens: undefined, cap: 100_000, tiers, delivered: 0 })).toEqual({ line: null, delivered: 0 }) + // terminated session → no advisory (the hard cap's deny message governs from here) + expect(shellSoftTierDecision({ terminated: true, tokens: 90_000, cap: 100_000, tiers, delivered: 0 })).toEqual({ line: null, delivered: 0 }) + }) +}) + describe("subagent cap: plugin wiring", () => { - test("shell session crossing 100k → tools denied, task_id resume denied, registry persisted", async () => { + // [2026-09-15]-[default cap now follows forceTokens (120k): crossing values shifted from 100k to the shared line] + test("shell session crossing the shared 120k line → 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) + // crossing: measured context = 116_000 + 4_000 = 120k ≥ cap + await mark(hooks, "ses_shell_cap", 116_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") @@ -109,7 +198,7 @@ describe("subagent cap: plugin wiring", () => { // 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.tokens).toBe(120_000) expect(reg.ses_shell_cap.agent).toBe("glm-mx-53f-low") }, 30_000) From a9a80ffe7a79f09b365b3db23ee8cbaf16cad6d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B1=B3=E6=96=AF=E7=89=B9=E6=8A=98=E8=85=BE?= <814442321@qq.com> Date: Tue, 15 Sep 2026 10:00:29 +0800 Subject: [PATCH 2/4] feat: read-only bash allowlist for ro shells 1. ro shells' bash goes from a blanket deny to a permission object: catch-all "*" deny first, allow entries for read-only git subcommands (diff/log/show/status/blame/...), listing-only forms of mutable git commands, and search/inspect utilities (rg/grep/ls/cat/head/tail/...); edit stays denied 2. find/sed/awk/echo stay disallowed (mutation forms: -delete/-exec, -i, redirection writes); compound commands judged per segment so chained mutations still fall to the catch-all deny 3. one-line RO note appended to the ro shell prompt so review shells report findings instead of attempting writes; tests pin the allowlist shape, prompt suffix, and mutation exclusions --- src/shells.ts | 78 ++++++++++++++++++++++++++++++++++++-- test/shells-select.test.ts | 65 ++++++++++++++++++++++++++++++- 2 files changed, 139 insertions(+), 4 deletions(-) diff --git a/src/shells.ts b/src/shells.ts index f9e6629..21cacaf 100644 --- a/src/shells.ts +++ b/src/shells.ts @@ -58,18 +58,90 @@ export const SHELL_BODY = [ "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") +// [2026-09-15]-[ro shells gain a read-only bash allowlist: bare `bash: "deny"` blocked even `git diff` for review/observe +// shells. permission.bash becomes an object — opencode semantics: wildcard "*" = zero-or-more chars, LAST matching rule +// wins (so the catch-all deny sits first, specific allows after), and compound commands are judged per segment (each +// segment must pass the rules on its own)]-[impact: ro shells can inspect (git view subcommands + search/inspect +// utilities) while edits and every other command stay denied; rw shells unchanged (no permission key)] +// One-line prompt suffix for ro shells only: pre-arm the restriction so review shells report findings instead of attempting writes. +export const RO_SHELL_NOTE = "Bash is limited to view/search commands (git diff/log/show/status, rg, grep, cat, ls, etc.); file edits and state-changing commands are denied — report findings, never attempt writes." + +/** [2026-09-15]-[read-only bash allowlist (opencode permission object; see header note above). Order matters: catch-all + * "*" deny FIRST, specific "allow" entries after (last matching rule wins). Deliberately NOT allowed: find / sed / awk / + * echo — all carry mutation forms (find -delete/-exec, sed -i, `echo … > file` redirection writes). Residual caveat: a + * parsed `git diff … > out` redirect may pass the pattern — accepted, `edit: "deny"` still covers the edit/write/patch + * tools. Compound commands are judged per segment by opencode, so `git diff && rm …` still falls to the catch-all deny] */ +export const RO_BASH_PERMISSION: Record<string, "allow" | "deny"> = { + "*": "deny", + // git read-only subcommands with arbitrary (non-mutating) arguments + "git status*": "allow", + "git diff*": "allow", + "git log*": "allow", + "git show*": "allow", + "git blame*": "allow", + "git rev-parse*": "allow", + "git ls-files*": "allow", + "git grep*": "allow", + "git shortlog*": "allow", + "git describe*": "allow", + "git merge-base*": "allow", + "git stash list*": "allow", + // git listing forms only — bare/arg variants mutate (branch -d/-m, tag -d, remote add/rm), so allow ONLY the listing shapes + "git branch": "allow", + "git branch -a*": "allow", + "git branch -v*": "allow", + "git branch --list*": "allow", + "git branch --show-current": "allow", + "git tag": "allow", + "git tag -l*": "allow", + "git tag --list*": "allow", + "git tag -n *": "allow", + "git remote": "allow", + "git remote -v": "allow", + "git worktree list*": "allow", + "git config --get*": "allow", + "git config --list*": "allow", + "git config -l*": "allow", + // search / inspect utilities (read-only by nature) + "rg*": "allow", + "grep*": "allow", + "ls*": "allow", + "fd*": "allow", + "cat*": "allow", + "head*": "allow", + "tail*": "allow", + "wc*": "allow", + "tree*": "allow", + "stat*": "allow", + "file*": "allow", + "du*": "allow", + "df*": "allow", + "pwd": "allow", + "which*": "allow", + "sort*": "allow", + "uniq*": "allow", + "basename*": "allow", + "dirname*": "allow", + "realpath*": "allow", + "date": "allow", + "whoami": "allow", +} + /** Single shell → opencode AgentConfig (for config-hook injection) */ export function shellAgentConfig(s: ShellRegEntry): Record<string, unknown> { + const ro = s.capability === "ro" const cfg: Record<string, unknown> = { description: shellDescription(s), mode: "subagent", model: `${s.provider}/${s.modelId}`, - prompt: SHELL_BODY, + // [2026-09-15]-[ro shells append the one-line bash-restriction note so the model pre-empts denied write attempts]- + prompt: ro ? `${SHELL_BODY}\n${RO_SHELL_NOTE}` : SHELL_BODY, } const options = effortOptions(s.family, s.effort, s.modelId, s.provider) if (options) cfg.options = options - if (s.capability === "ro") { - cfg.permission = { edit: "deny", bash: "deny" } + if (ro) { + // fresh copy per config: opencode owns the injected object, shared references would couple agent entries + cfg.permission = { edit: "deny", bash: { ...RO_BASH_PERMISSION } } } return cfg } diff --git a/test/shells-select.test.ts b/test/shells-select.test.ts index a8328b4..4f1bcaa 100644 --- a/test/shells-select.test.ts +++ b/test/shells-select.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test" -import { selectInjectableDefs } from "../src/shells" +import { selectInjectableDefs, shellAgentConfig, SHELL_BODY, RO_SHELL_NOTE } from "../src/shells" import type { ShellDefinition } from "../src/catalog" +import type { ShellRegEntry } from "../src/types" // [2026-09-04]-[English localization: translate comments; no test-logic change] // [2026-09-02]-[context-slimming fixtures: injection face = six-lane chain selection ∪ custom lanes; empty candidates fail-open back to the full set] @@ -119,3 +120,65 @@ describe("selectInjectableDefs (skipChainPicks / configured mode)", () => { expect(selectInjectableDefs(defs, { ...opts, skipChainPicks: true })).toEqual(defs) }) }) + +// [2026-09-15]-[ro shells gain a read-only bash allowlist: bare `bash: "deny"` blocked even `git diff` for review shells; +// permission.bash is now an object (catch-all "*" deny first, specific allows after) and the ro prompt carries a +// one-line restriction note; rw shells stay key-less and byte-identical] +describe("shellAgentConfig (ro read-only bash allowlist)", () => { + // [2026-09-15]-[read-only bash allowlist fixtures: minimal ShellRegEntry shapes, one per capability face]- + function reg(capability: "rw" | "ro"): ShellRegEntry { + return { + name: `cp-mx-m1-high${capability === "ro" ? "-ro" : ""}`, + provider: "github-copilot", modelId: "m1", pool: "copilot", family: "gpt", + effort: "high", capability, vision: false, + matrixKey: "github-copilot|m1|high", status: "enabled", comboKey: "github-copilot|m1|high", + } + } + + test("ro shell: edit stays denied, bash is an allowlist object with the catch-all deny first", () => { + const cfg = shellAgentConfig(reg("ro")) + const permission = cfg.permission as { edit: string; bash: Record<string, string> } + expect(permission.edit).toBe("deny") + expect(typeof permission.bash).toBe("object") + expect(permission.bash["*"]).toBe("deny") + expect(Object.keys(permission.bash)[0]).toBe("*") + }) + + test("ro shell: allowlist contains the specified git view / listing / search patterns", () => { + const bash = (shellAgentConfig(reg("ro")).permission as { bash: Record<string, string> }).bash + for (const pattern of ["git diff*", "git log*", "rg*", "git stash list*"]) { + expect(bash[pattern]).toBe("allow") + } + }) + + test("ro shell: no pattern may allow mutating commands (git push/commit) or mutation-capable utilities (find/sed)", () => { + const bash = (shellAgentConfig(reg("ro")).permission as { bash: Record<string, string> }).bash + for (const banned of ["git push*", "git commit*", "find*", "sed*"]) { + expect(bash[banned]).toBeUndefined() + } + // defense in depth: no key at all opens a path to push/commit/find/sed + for (const key of Object.keys(bash)) { + expect(key.startsWith("git push")).toBe(false) + expect(key.startsWith("git commit")).toBe(false) + expect(key.startsWith("find")).toBe(false) + expect(key.startsWith("sed")).toBe(false) + } + }) + + test("ro shell: allow-entry count sanity (>= 35) to catch accidental truncation of the literal list", () => { + const bash = (shellAgentConfig(reg("ro")).permission as { bash: Record<string, string> }).bash + expect(Object.values(bash).filter((v) => v === "allow").length).toBeGreaterThanOrEqual(35) + }) + + test("ro shell: prompt = SHELL_BODY + one-line RO_SHELL_NOTE suffix", () => { + const prompt = shellAgentConfig(reg("ro")).prompt as string + expect(prompt.startsWith(SHELL_BODY)).toBe(true) + expect(prompt.endsWith(RO_SHELL_NOTE)).toBe(true) + }) + + test("rw shell: no permission key at all, prompt stays the bare SHELL_BODY", () => { + const cfg = shellAgentConfig(reg("rw")) + expect(cfg.permission).toBeUndefined() + expect(cfg.prompt).toBe(SHELL_BODY) + }) +}) From ccc51106bee6d2d1328605d174c8642949627c72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B1=B3=E6=96=AF=E7=89=B9=E6=8A=98=E8=85=BE?= <814442321@qq.com> Date: Tue, 15 Sep 2026 10:00:29 +0800 Subject: [PATCH 3/4] feat: default context watermarks 50k/90k/130k 1. soft 60->50k (earlier conserve signal), hard 80->90k (more wrap-up room before reads close), force 120->130k (longer auto-handover runway); both default sites (config.ts, context-watch.ts thresholdsOf) synced with a pairing comment 2. shell subagent advisories and the shared termination line follow automatically: conserve/hand-off sit at the 50k/90k lines, default subagent cap 130k, window clamping recomputed 3. tests, CHANGELOG, and bilingual reference docs synced for the 1.1.0 batch --- CHANGELOG.md | 4 +- ...-28-opencode-switchman-technical-design.md | 7 +- docs/reference.md | 10 +-- docs/reference.zh.md | 10 +-- src/assets/agents-md.ts | 2 +- src/config.ts | 3 +- src/context-watch.ts | 11 +-- src/index.ts | 3 +- test/auto-handover.test.ts | 4 +- test/ctx-pause.test.ts | 10 +-- test/dispatch-gates.test.ts | 19 ++--- test/shell-context-advisory.test.ts | 28 +++---- test/subagent-cap.test.ts | 74 +++++++++---------- 13 files changed, 96 insertions(+), 89 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fd5c41..0b782cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,13 +7,15 @@ This project follows [Semantic Versioning](https://semver.org/). Release notes d ### Added - **Injection face mode `configured` (`injection.mode`)** — a third shell-injection mode that narrows the per-request task-tool description to exactly what can actually dispatch: when a favorites/visible set is configured, runtime dispatch is already gated by activation (configured ∪ session models) ∩ pool selection, so off-configured chain picks are dead context. `configured` skips the six-lane chain picks and injects only the configured models' shells, plus custom-lane and pool-config force-keeps (both stay dispatch-capable). With no favorites/visible set configured it behaves identically to `chain` (fail-open). Startup-level: restart to apply. -- **Shell subagent soft tiers with inline HANDOFF relay (shared absolute thresholds)** — shell subagents previously jumped straight from "no signal" to the hard-cap termination. Two graceful advisories now precede it, reusing the MAIN session's absolute soft/hard thresholds (soft 60k conserve / hard 80k hand-off by default — subagent context is equally token-expensive as main-session context), so there are no user-facing fraction coefficients: a conserve advisory (stop batch reads and long pastes, switch to targeted grep, keep outputs compact) and a hand-off advisory (finish the current unit, then end the final message with a compact handover block followed by the marker line `HANDOFF: inline · progress: n/m · next: <one sentence>`; that final message returns to the delegating session as the task result). The window-clamped effective cap still pulls the tiers down proportionally, so a tier can never exceed the real termination line and small-window shells keep headroom before it. Both report the measured numbers in absolute k, fire at most once per tier per shell session (in-memory dedup, cleared on session deletion; a restart re-arms), and ride the same per-turn system-prompt surface as the session watermark — the hard cap stays the termination backstop, and `subagentCap: false` disables the advisories together with it. The dispatcher side ships in the same release: the bundled protocol §2 gains the shell-handoff-relay rule (treat the handover block as the authoritative remaining-work state; start a fresh re-seeded dispatch, never resume the spent session). Config surface: the tiers follow the session's `softTokens`/`hardTokens`; the shell's termination line follows `forceTokens` by default, overridable via the now-optional `context.subagentForceTokens` (validated 20k..1M; invalid → deleted, falling back to `forceTokens`, fail-open). Restart to apply. +- **Shell subagent soft tiers with inline HANDOFF relay (shared absolute thresholds)** — shell subagents previously jumped straight from "no signal" to the hard-cap termination. Two graceful advisories now precede it, reusing the MAIN session's absolute soft/hard thresholds (soft 50k conserve / hard 90k hand-off by default — subagent context is equally token-expensive as main-session context), so there are no user-facing fraction coefficients: a conserve advisory (stop batch reads and long pastes, switch to targeted grep, keep outputs compact) and a hand-off advisory (finish the current unit, then end the final message with a compact handover block followed by the marker line `HANDOFF: inline · progress: n/m · next: <one sentence>`; that final message returns to the delegating session as the task result). The window-clamped effective cap still pulls the tiers down proportionally, so a tier can never exceed the real termination line and small-window shells keep headroom before it. Both report the measured numbers in absolute k, fire at most once per tier per shell session (in-memory dedup, cleared on session deletion; a restart re-arms), and ride the same per-turn system-prompt surface as the session watermark — the hard cap stays the termination backstop, and `subagentCap: false` disables the advisories together with it. The dispatcher side ships in the same release: the bundled protocol §2 gains the shell-handoff-relay rule (treat the handover block as the authoritative remaining-work state; start a fresh re-seeded dispatch, never resume the spent session). Config surface: the tiers follow the session's `softTokens`/`hardTokens`; the shell's termination line follows `forceTokens` by default, overridable via the now-optional `context.subagentForceTokens` (validated 20k..1M; invalid → deleted, falling back to `forceTokens`, fail-open). Restart to apply. - **Per-turn `[ROUTE]` routing-discipline line** — main sessions now get one `[ROUTE]` line per turn, pushed after `[WATERMARK:SESSION]`/`[TODO]` under the same rules/banner visibility switch (both off = no line, respecting the zero-injection wish). It carries only what the injected lines lack today: the token cost model (hands-on spends and grows this session's context on every later turn; a dispatch spends a fresh shell context and returns a summary) and the declaration discipline, which protocol §6 widens from "before a major action" to "before each substantive action (the enumeration below is the minimum set, not the ceiling)". The line renders from a single pure module, so the text can never drift between surfaces. Restart to apply. - **Language-preference ask follows the UI locale** — the first-run ask's three question texts are now localized into all 11 candidate tags (en, zh-CN, zh-TW, ja, ko, es, fr, de, it, pt, ru), detected at ask time from the environment (`LC_ALL` → `LANG`, env-style values like `zh_CN.UTF-8` normalized — `zh-HK` maps to `zh-TW` — with an English fallback when nothing matches) and surfaced once per ask activation in the status log (`lang ask locale=…`). Only the question texts localize: the `switchman-lang n/3:` marker prefix, the directive body and the gate's deny copy stay byte-stable English, so the plugin-side answer capture works identically in every locale. Restart to apply. - **`dispatch: "off"` project opt-out** — a project can now stand down all dispatch governance by setting the top-level `"dispatch": "off"` in `.switchman/settings.json` (the same file the lang config lives in; read per call, so toggling takes effect on the next task call without a restart). Only the exact string `"off"` opts out — anything else (or an absent field) keeps fleet behavior, and a present-but-different value gets a one-time status-log note. When off, task calls are allowed ungoverned: the whole task path stands down (uninjected-shell and built-in-agent denies with their auto-redirects, all six gates including the breaker deny and the ROUTE_META/semantics checks). Deliberately still on: the subagent hard cap and its resume deny, the language gate, read/watermark gates, auto-handover, breaker failure recording, and the banner/watermark/TODO/`[LANG]` lines — the per-turn `[ROUTE]` line is the only prompt surface that hides. A `.switchman/settings.json` that is not valid JSON at all now warns once per process in the status log (`… is not valid JSON — ignored (lang config falls back to the AGENTS.md marker; "dispatch":"off" not applied)`); the "exists but no valid lang block" case stays silent as before. Restart to apply. ### Changed +- **Default context watermarks retuned 60/80/120k → 50/90/130k** — `context.softTokens` drops to 50,000 (the conserve/scan signal fires earlier), `context.hardTokens` rises to 90,000 (more wrap-up room before reads close) and `context.forceTokens` to 130,000 (longer auto-handover runway). Shell subagent advisories and the shared hard cap follow automatically: the conserve/hand-off tiers now sit at the 50k/90k lines and the default termination line is 130k (still clamped to 90% of the model's context window when known). Explicit `context.*` values in user jsonc are untouched. Restart to apply. +- **Read-only shells gain a read-only bash allowlist** — `ro` shells (the review/observe capability faces) previously denied **all** bash (`permission: { edit: "deny", bash: "deny" }`), so a reviewer could not even run `git diff` on the code it was auditing. `edit: "deny"` stays, and `bash` becomes an opencode permission object: a catch-all `"*": "deny"` first, then `allow` entries (opencode semantics: last matching rule wins, wildcard = zero-or-more chars, compound commands judged per segment) for read-only git subcommands with arbitrary arguments (`git status/diff/log/show/blame/rev-parse/ls-files/grep/shortlog/describe/merge-base`, `git stash list`), listing-only forms of the mutable git commands (`git branch`/`git tag`/`git remote` bare and listing flags, `git worktree list`, `git config --get/--list/-l`), and search/inspect utilities (`rg`, `grep`, `ls`, `fd`, `cat`, `head`, `tail`, `wc`, `tree`, `stat`, `file`, `du`, `df`, `pwd`, `which`, `sort`, `uniq`, `basename`, `dirname`, `realpath`, `date`, `whoami`). `find`/`sed`/`awk`/`echo` stay disallowed (they carry mutation forms: `-delete`/`-exec`, `-i`, `>` redirection); a parsed `git diff … > out` redirect may still pass its pattern — accepted, since `edit: "deny"` covers the edit/write/patch tools; compound commands are judged per segment, so `git diff && rm …` falls to the catch-all deny. The ro shell prompt gains a one-line note stating the restriction so review shells report findings instead of attempting writes. Restart to apply. - **ROUTE_META gate downgraded from deny to synthesize-and-observe** — a delegation prompt with a missing or unparseable ROUTE_META line is no longer hard-denied: the gate synthesizes a lane-default META (lane from the shell's lane, the lane's default role, matching capability/modality, `source: auto`) and lets the dispatch through to the semantic checks with a status-log note. This also removes the three inconsistent corners where the old deny still bit (auto-redirect off, the review lane, synthesis failure) and collapses the prompt-rewriting synthesis retries into the gate itself — redirected dispatches now carry the prompt as-is. Behavior change on upgrade: projects that relied on the missing-META deny as a discipline prod lose it (the `[ROUTE]` line's declaration discipline is the replacement surface); a **present-but-wrong** META (an illegal field value, or a parseable line missing required fields) still denies with the sample attached — only absence is synthesized. Declaring META remains the contract that unlocks cross-family review ranking and `source: user` pinning. Restart to apply. ## [1.0.4] - 2026-09-11 diff --git a/docs/2026-08-28-opencode-switchman-technical-design.md b/docs/2026-08-28-opencode-switchman-technical-design.md index 33120bc..01d29f5 100644 --- a/docs/2026-08-28-opencode-switchman-technical-design.md +++ b/docs/2026-08-28-opencode-switchman-technical-design.md @@ -14,6 +14,7 @@ > - v1.0: design finalized (shell matrix / six gates / ROUTE_META / breaker / quota awareness / cost awareness). > - v1.1: implementation-stage verification errata — banner hook moved to `experimental.chat.system.transform`; shell landing changed to config-hook injection (no file generation); the `tools` field deprecated in favor of `permission`; thinking efforts moved to agent `options`; task argument name confirmed as `subagent_type`; failure bookkeeping main path moved to `event`; the Copilot usage endpoint and model catalog were field-tested, closing two pending items; added the three-pool quota switches, cost tiebreaker, and the token read-only red line. > - v1.2: full-matrix shape established — enabled models × all declared thinking efforts; the enabled surface takes the model-management pin list as its first source of truth; the effort source of truth moved to models.dev `reasoning_options`. +> - v1.3 ([2026-09-15]): ro-shell permission errata — bare `bash: "deny"` blocked even `git diff` for review shells; `permission.bash` is now a read-only allowlist object (catch-all `"*": "deny"` first, specific allows after — opencode judges the last matching rule, per compound segment), covering git view subcommands, listing-only git forms, and search/inspect utilities; the ro prompt appends a one-line restriction note (§2.2, §2.3). ## 1. Requirements Overview @@ -80,8 +81,8 @@ cfg.agent["copilot-mx-luna-low"] = { mode: "subagent", model: "github-copilot/gpt-5.6-luna", options: { reasoningEffort: "low" }, // thinking effort mapped per family (§3.6) - permission: { edit: "deny", bash: "deny" }, // ro shells are read-only; rw shells omit this key - prompt: "<body of the 5 general rules>", // role contract / trust stated facts without re-checking / minimal necessity with file:line / verify before delivery / report honestly + permission: { edit: "deny", bash: { "*": "deny", "git diff*": "allow", "rg*": "allow", … } }, // [2026-09-15] ro shells: edit denied + read-only bash allowlist (git view subcommands, search/inspect utilities); rw shells omit this key + prompt: "<body of the 5 general rules>", // role contract / trust stated facts without re-checking / minimal necessity with file:line / verify before delivery / report honestly — ro shells append a one-line bash-restriction note } ``` @@ -212,7 +213,7 @@ The plugin **stores no keys of its own and goes through no proxy**: credentials ### 3.3 Shells = Config-Hook Injection - The plugin's `config(cfg)` hook loads `shells.json` and injects `cfg.agent[shell name]` for every enabled shell (shape in §2.3); user-defined agents are never overwritten. -- Frontmatter mapping: the `tools` field is deprecated → `permission` (ro shells deny `edit`/`bash`); `thoughtLevel` has no corresponding field → `options` (§2.9). +- Frontmatter mapping: the `tools` field is deprecated → `permission` (ro shells deny `edit` and use a read-only bash allowlist — [2026-09-15], see the v1.3 errata above); `thoughtLevel` has no corresponding field → `options` (§2.9). - Global AGENTS.md injection has no per-agent switch; the fixed token cost is accepted. - Risk fallback: if config injection does not take effect, degrade to writing `~/.config/opencode/agent/*.md` at startup (dual-track alternative, isolated behind a single switch in shells.ts). diff --git a/docs/reference.md b/docs/reference.md index c72d3a8..8f13a85 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -125,8 +125,8 @@ The plugin loads the repo's `dist` bundle directly; after `git pull`, re-run `bu | `matrix.mode / watch` | `auto / true` | Activation matrix: `auto` by host (desktop = visible models / CLI/TUI = favorites), `app`/`tui` force a mode, `legacy` restores the static matrix; `watch` recomputes and fully refreshes probes on surface changes (mode/watch are startup-level; restart to apply) | | `banner.enabled` | `true` | Four-line banner injection | | `rules.enabled / delegationFloor` | `true / 3000` | Bundled dispatcher rules (AGENTS.md) injection; `delegationFloor` is the self-do token floor interpolated into the rules (dispatch by default below it is a violation) | -| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 60000 / 80000 / 120000 / 1500 / true` | **Measured session watermark + self-read budget**: the plugin measures each main session's context from message token usage and injects a live `[WATERMARK:SESSION]` line every turn (with per-turn growth and remaining-turns-to-hard estimates). Every self-read is costed against `readBudgetTokens` from turn 1: over-budget reads are auto-bounded (a `limit` is auto-appended) or denied with exact bounded-retry params, and a per-turn 2× cap stops read chains; un-estimable tool outputs are charged post-hoc. Verification/delivery bash (git, test/lint, build) always passes; unbounded history dumps (`git log -p` without `-n`) are always denied with a scoping hint; past `hardTokens` read-class closes (wrap-up mode); past `forceTokens` the banner demands compaction and, with `autoHandover: true` (default), `/handover` fires automatically: full fork backup + compaction, the running task continues on the summarized context. Shell subagent sessions are exempt from this watermark and get their own single hard cap instead (see `context.subagentForceTokens` / `context.subagentCap` below); all three thresholds are additionally capped at 90% of the current session model's context window when known (models.dev) | -| `context.subagentForceTokens / subagentCap` | `follows forceTokens (120000) / true` | **Subagent context hard cap + soft-tier advisories**: 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 when overridden and additionally capped at 90% of the shell model's context window; absent → follows the main session's `forceTokens`, one absolute termination line shared by default. Two graceful advisories precede the termination, reusing the main session's absolute soft/hard thresholds (`softTokens` = conserve, `hardTokens` = hand-off — subagent context is equally token-expensive); the window-clamped effective cap pulls them down proportionally, so a tier never exceeds the real termination line. On crossing the cap, 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. Each advisory tier fires at most once per shell session (in-memory dedup, cleared on session deletion; a restart re-arms); the dispatcher protocol's relay rule treats that handover as the authoritative remaining-work state (fresh re-seeded dispatch, never resume the spent session). Later `task` calls resuming a terminated session 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 and disables the advisories. A present-but-invalid `subagentForceTokens` override (non-finite / outside 20k..1M) is deleted with an SWM037 diagnostic, falling back to `forceTokens` (fail-open) | +| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 50000 / 90000 / 130000 / 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` | `follows forceTokens (130000) / true` | **Subagent context hard cap + soft-tier advisories**: 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 when overridden and additionally capped at 90% of the shell model's context window; absent → follows the main session's `forceTokens`, one absolute termination line shared by default. Two graceful advisories precede the termination, reusing the main session's absolute soft/hard thresholds (`softTokens` = conserve, `hardTokens` = hand-off — subagent context is equally token-expensive); the window-clamped effective cap pulls them down proportionally, so a tier never exceeds the real termination line. On crossing the cap, 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. Each advisory tier fires at most once per shell session (in-memory dedup, cleared on session deletion; a restart re-arms); the dispatcher protocol's relay rule treats that handover as the authoritative remaining-work state (fresh re-seeded dispatch, never resume the spent session). Later `task` calls resuming a terminated session 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 and disables the advisories. A present-but-invalid `subagentForceTokens` override (non-finite / outside 20k..1M) is deleted with an SWM037 diagnostic, falling back to `forceTokens` (fail-open) | | `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), `configured` = [2026-09-11] when a favorites/visible set is configured, only those models' shells are injected (custom-lane/pool-config force-keeps stay) — off-configured chain picks can never pass the runtime activation gate anyway, so this removes dead per-request context; with nothing configured it behaves like `chain`. 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 | @@ -146,7 +146,7 @@ After starting opencode, every system prompt of the primary model carries a live ``` [ROUTES] economy: glm-53f-low→glm-47-off→glm-5t-off | mechanical: glm-53f-high→glm-47-off | main: glm-53f-high | hard: glm-53-high | vision: glm-53f-high | review: glm-53-high-ro [WATERMARK] GLM 5h 10% weekly 38% (refreshed 09-11 10:00) | Copilot credits 0% left (refreshes 2026-10-01) | DeepSeek balance exhausted | advice: ... -[WATERMARK:SESSION] measured session context ~37k (soft 60k/hard 80k/force 100k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 +[WATERMARK:SESSION] measured session context ~37k (soft 50k/hard 90k/force 130k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 [LIMITS] down: none | reviewer prefers cross-family (same-family self-review = DOWNGRADED, allowed only when no cross-family reviewer exists) | api-billed & unknown models sink by coefficient (explicit billing=subscription wins) | matrix: cli·watch/ok | manual capability rank: 9 models, task-pool selection: 6 pools active (/modelRank /poolConfig to adjust) [TODO] 0/6 done · in_progress: draft the README section — keep todowrite current (update as each item starts/finishes) [LANG] conversation=en comments=en docs=en (source: project settings) — reply and reason in the conversation language; code comments, commit messages, and generated docs follow their own settings @@ -237,7 +237,7 @@ opencode-switchman splits orchestration into three layers: | vision | observer image reading | vision-capable models, medium→high→xhigh→max effort | | review | reviewer / expert panel | **forced hetero-family** (against same-family blind spots), high→xhigh→max effort | -Effort preference is a routing layer of its own: each lane prefers the thinking levels listed above (first supported level is the default), and `off`-effort shells serve only as lane-level fallback — they enter a chain only when no thinking-level candidate is available (e.g. models that only support on/off), never ahead of one. Shells are likewise partitioned by capability face before ranking: the review lane draws only from `ro` (read-only) shells, all other lanes only from `rw` shells, with cross-face fallback only when a lane's own pool is empty. +Effort preference is a routing layer of its own: each lane prefers the thinking levels listed above (first supported level is the default), and `off`-effort shells serve only as lane-level fallback — they enter a chain only when no thinking-level candidate is available (e.g. models that only support on/off), never ahead of one. Shells are likewise partitioned by capability face before ranking: the review lane draws only from `ro` (read-only) shells, all other lanes only from `rw` shells, with cross-face fallback only when a lane's own pool is empty. Read-only shells run with `edit: "deny"` plus a **read-only bash allowlist** (git view subcommands — `git status/diff/log/show/blame/rev-parse/ls-files/grep/shortlog/describe/merge-base`, `git stash list`, and the listing-only forms of `git branch/tag/remote/worktree/config` — plus search/inspect utilities such as `rg`, `grep`, `cat`, `ls`, `head`, `tail`, `stat`, `tree`); everything else, including `find`/`sed`/`awk`/`echo` (mutation forms), falls to a catch-all deny, and the ro prompt carries a one-line note telling the shell to report findings instead of attempting writes. Water levels only affect ordering (use it, don't waste it); the only hard block is "this call cannot possibly succeed" (quota definitively exhausted or hard gate hit). Pay-as-you-go (`billing: "api"`) providers are never denied for auto routing — they sink within their capability tier via the 0.85 coefficient, and unknown-provider models sink via the 0.75 penalty, so no vendor-specific tail-seat or deny rule is needed. @@ -321,7 +321,7 @@ Routing is now an explicit, traceable score rather than a hidden preference list ## 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`, optional — absent follows the main session's `forceTokens`, i.e. 120,000 tokens by default, so one absolute termination line is shared; clamped 20k..1M when present, 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. Two graceful advisories precede the termination, reusing the main session's absolute soft/hard thresholds (`softTokens` conserve / `hardTokens` hand-off — subagent context is equally token-expensive as main-session context), with the window-clamped effective cap pulling them down proportionally. On crossing the cap, 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). +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`, optional — absent follows the main session's `forceTokens`, i.e. 130,000 tokens by default, so one absolute termination line is shared; clamped 20k..1M when present, 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. Two graceful advisories precede the termination, reusing the main session's absolute soft/hard thresholds (`softTokens` conserve / `hardTokens` hand-off — subagent context is equally token-expensive as main-session context), with the window-clamped effective cap pulling them down proportionally. On crossing the cap, 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. diff --git a/docs/reference.zh.md b/docs/reference.zh.md index fb4fdd6..d99b7d5 100644 --- a/docs/reference.zh.md +++ b/docs/reference.zh.md @@ -125,8 +125,8 @@ bun run build # 生成 dist/opencode-switchman.js | `matrix.mode / watch` | `auto / true` | 激活矩阵:`auto` 按宿主自动(desktop=可见模型 / CLI/TUI=favorites),`app`/`tui` 强制指定,`legacy` 旧静态矩阵;`watch`=配置面变化即重算并全量刷新探针(mode/watch 为启动级,重启生效) | | `banner.enabled` | `true` | 四行横幅注入开关 | | `rules.enabled / delegationFloor` | `true / 3000` | 调度员规程(AGENTS.md)随包注入开关;`delegationFloor`=自做底价(token),注入规程时插值 | -| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 60000 / 80000 / 120000 / 1500 / true` | **会话上下文水位实测+自读预算闸**:插件从消息 token usage 实测主会话上下文并每轮注入 `[WATERMARK:SESSION]` 行(附每轮增速与距硬水位剩余轮数估算)。自读从第 1 轮起按 `readBudgetTokens` 计费:预估超限的读取自动追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮另有 2× 上限阻断连续读取,无法预估的工具输出事后记账。验证/交付类 bash(git、测试/lint、构建)全水位放行;无界历史翻查(如不带 `-n` 的 `git log -p`)任何水位一律拦截并附收窄提示;超硬水位读取类关闭(收尾模式);超压水位横幅强制立即压缩,且 `autoHandover: true`(默认)时自动触发 `/handover`:完整分叉备份+压缩,未完成的任务在摘要上下文上继续。壳子代理会话不适用本水位,改走自身的单道硬顶(见 `context.subagentForceTokens` / `context.subagentCap`);三档水位在可知时额外以当前会话模型上下文窗口(models.dev)的 90% 封顶 | -| `context.subagentForceTokens / subagentCap` | `跟随 forceTokens(120000)/ true` | **子代理上下文硬顶+软档提醒**:壳子代理会话只有一道硬顶(实测=最新 assistant 消息的 input + output + reasoning + cache.read,与会话水位同口径),显式覆盖时钳制 20k..1M,并额外以壳模型上下文窗口的 90% 封顶;缺省跟随主会话 `forceTokens`,默认共享同一条绝对终止线。硬顶终止之前有两档柔性提醒,直接复用主会话的绝对软/硬阈值(`softTokens`=省着用,`hardTokens`=收尾交接——子代理上下文与主会话上下文同等昂贵);有效上限(含窗口封顶)按比例下拉两档,档位永不超过真实终止线。触顶即拒绝该会话所有后续工具调用并下达收尾指令,子代理的下一份纯文本答复(详细的工作进度总结)直接作为任务结果返回委派方,会话永久终止。每档每次会话最多触发一次(进程内去重,会话删除即清除;重启后重新武装);调度规程的交接转发规则把该交接块视为剩余工作的权威状态(全新派发、只注入所需上下文,绝不续接已耗尽的会话)。此后带 `task_id` 恢复该会话的 `task` 调用一律永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响;`subagentCap: false` 既阻止新的终止也一并关闭提醒。`subagentForceTokens` 覆盖值非法(非有限数 / 超出 20k..1M)时删除该覆盖并报 SWM037 诊断,回退跟随 `forceTokens`(fail-open) | +| `context.gates / softTokens / hardTokens / forceTokens / readBudgetTokens / autoHandover` | `true / 50000 / 90000 / 130000 / 1500 / true` | **会话上下文水位实测+自读预算闸**:插件从消息 token usage 实测主会话上下文并每轮注入 `[WATERMARK:SESSION]` 行(附每轮增速与距硬水位剩余轮数估算)。自读从第 1 轮起按 `readBudgetTokens` 计费:预估超限的读取自动追加 `limit` 有界放行,或以精确的有界重试参数拒绝;每轮另有 2× 上限阻断连续读取,无法预估的工具输出事后记账。验证/交付类 bash(git、测试/lint、构建)全水位放行;无界历史翻查(如不带 `-n` 的 `git log -p`)任何水位一律拦截并附收窄提示;超硬水位读取类关闭(收尾模式);超压水位横幅强制立即压缩,且 `autoHandover: true`(默认)时自动触发 `/handover`:完整分叉备份+压缩,未完成的任务在摘要上下文上继续。壳子代理会话不适用本水位,改走自身的单道硬顶(见 `context.subagentForceTokens` / `context.subagentCap`);三档水位在可知时额外以当前会话模型上下文窗口(models.dev)的 90% 封顶 | +| `context.subagentForceTokens / subagentCap` | `跟随 forceTokens(130000)/ true` | **子代理上下文硬顶+软档提醒**:壳子代理会话只有一道硬顶(实测=最新 assistant 消息的 input + output + reasoning + cache.read,与会话水位同口径),显式覆盖时钳制 20k..1M,并额外以壳模型上下文窗口的 90% 封顶;缺省跟随主会话 `forceTokens`,默认共享同一条绝对终止线。硬顶终止之前有两档柔性提醒,直接复用主会话的绝对软/硬阈值(`softTokens`=省着用,`hardTokens`=收尾交接——子代理上下文与主会话上下文同等昂贵);有效上限(含窗口封顶)按比例下拉两档,档位永不超过真实终止线。触顶即拒绝该会话所有后续工具调用并下达收尾指令,子代理的下一份纯文本答复(详细的工作进度总结)直接作为任务结果返回委派方,会话永久终止。每档每次会话最多触发一次(进程内去重,会话删除即清除;重启后重新武装);调度规程的交接转发规则把该交接块视为剩余工作的权威状态(全新派发、只注入所需上下文,绝不续接已耗尽的会话)。此后带 `task_id` 恢复该会话的 `task` 调用一律永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响;`subagentCap: false` 既阻止新的终止也一并关闭提醒。`subagentForceTokens` 覆盖值非法(非有限数 / 超出 20k..1M)时删除该覆盖并报 SWM037 诊断,回退跟随 `forceTokens`(fail-open) | | `builtinAgents.mode` | `deny` | 内置 explore/general 与壳路由抢任务且此前放行;`deny`=拦截附 economy/main 改派建议,`allow`=恢复放行 | | `injection.mode` | `chain` | 壳注入面:`chain`=六档链精选∪favorites/可见集(task 工具描述每会话省约 6-10k token,链外模型点名走 denyUninjected 提示);`all`=可用全集(旧行为);`configured`=[2026-09-11] 配置了 favorites/可见集时仅注入这些模型的壳(自定义泳道/pool-config 强制保留照旧)——链外精选本就过不了运行时 activation 门,删掉纯死的每请求上下文;未配置时与 `chain` 行为一致。启动级,重启生效 | | `dispatch.autoRedirect` | `true` | 派发被拒时在途改写 `subagent_type` 到拒绝消息已点名的链首候选(单跳、同快照守卫复检)——首次派发直接落在最优可用壳上,不再烧「拒绝-重试」轮次;`false` 恢复拒绝-重试 | @@ -146,7 +146,7 @@ bun run build # 生成 dist/opencode-switchman.js ``` [ROUTES] economy: glm-53f-low→glm-47-off→glm-5t-off | mechanical: glm-53f-high→glm-47-off | main: glm-53f-high | hard: glm-53-high | vision: glm-53f-high | review: glm-53-high-ro [WATERMARK] GLM 5h 10% weekly 38% (refreshed 09-11 10:00) | Copilot credits 0% left (refreshes 2026-10-01) | DeepSeek balance exhausted | advice: ... -[WATERMARK:SESSION] measured session context ~37k (soft 60k/hard 80k/force 100k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 +[WATERMARK:SESSION] measured session context ~37k (soft 50k/hard 90k/force 130k) | growth ~5k/turn, ~8 turns to hard | self-read this turn 178/3000 [LIMITS] down: none | reviewer prefers cross-family (same-family self-review = DOWNGRADED, allowed only when no cross-family reviewer exists) | api-billed & unknown models sink by coefficient (explicit billing=subscription wins) | matrix: cli·watch/ok | manual capability rank: 9 models, task-pool selection: 6 pools active (/modelRank /poolConfig to adjust) [TODO] 0/6 done · in_progress: 撰写 README 章节 — keep todowrite current (update as each item starts/finishes) [LANG] conversation=zh-CN comments=en docs=en (source: project settings) — 用会话语言回复与推理;代码注释、提交信息与生成文档各随其设置 @@ -237,7 +237,7 @@ opencode-switchman 把编排拆成三层,各司其职: | vision | observer 看图 | 视觉模型,medium→high→xhigh→max 档 | | review | reviewer / 专家席 审案 | **强制异模型族**(防同族盲区),high→xhigh→max 档 | -思考档位偏好是独立的一层路由算法:每档按上表偏好序选思考档(首个被支持的档位即默认档);`off` 档只作 lane 级兜底——仅当该档没有思考档候选可用时(如只支持开/关的模型)才进链,绝不排到思考档候选之前。壳在排序前还按能力面划池:review 只从 `ro`(只读)壳池选,其余 lane 只从 `rw` 壳池选,仅当本池为空才跨池兜底。 +思考档位偏好是独立的一层路由算法:每档按上表偏好序选思考档(首个被支持的档位即默认档);`off` 档只作 lane 级兜底——仅当该档没有思考档候选可用时(如只支持开/关的模型)才进链,绝不排到思考档候选之前。壳在排序前还按能力面划池:review 只从 `ro`(只读)壳池选,其余 lane 只从 `rw` 壳池选,仅当本池为空才跨池兜底。只读壳以 `edit: "deny"` 运行,并配**只读 bash 白名单**(git 查看类子命令——`git status/diff/log/show/blame/rev-parse/ls-files/grep/shortlog/describe/merge-base`、`git stash list`,以及 `git branch/tag/remote/worktree/config` 的仅列表形态——加上 `rg`、`grep`、`cat`、`ls`、`head`、`tail`、`stat`、`tree` 等检索/查看工具);其余命令(含带变异形态的 `find`/`sed`/`awk`/`echo`)全部落到兜底 deny,ro 提示词末尾附一行说明,要求只汇报结论、绝不尝试写入。 水位只影响排序(用满不浪费),唯一硬拦是「调用必失败」(额度确定耗尽或硬门命中);按量计费(`billing: "api"`)provider 在自动路由中不会被 deny——它们经 0.85 系数在同能力档内沉底,未知 provider 模型经 0.75 惩罚沉底,无需任何厂商专属的链尾席位或 deny 规则。 @@ -321,7 +321,7 @@ ROUTE_META {"lane":"main","role":"programmer","producer_family":"glm","capabilit ## 子代理上下文硬顶 -主会话享有软/硬/压三档水位+自动交接;被委派的壳子代理会话此前完全没有上下文控制,一路跑过 18 万 token 也无人拦截。现在每个壳子代理会话只有一道硬顶(`context.subagentForceTokens`,可选——缺省跟随主会话 `forceTokens`,即默认 120,000 token,与主会话共享同一条绝对终止线;显式覆盖时钳制 20k..1M,并在可知时额外以壳模型上下文窗口的 90% 封顶),实测口径与会话水位相同:最新 assistant 消息的 input + output + reasoning + cache.read。硬顶终止之前有两档柔性提醒,直接复用主会话的绝对软/硬阈值(`softTokens` 省着用 / `hardTokens` 收尾交接——子代理上下文与主会话上下文同等昂贵),有效上限按比例下拉两档。触顶后,插件拒绝该子代理会话内的所有后续工具调用并下达收尾指令;子代理随后给出的纯文本答复——一份详细的工作进度总结(已完成 / 关键发现含 file:line 证据 / 未完成 / 下一步)——即作为任务结果返回给委派方,会话随即永久终止(终止事件写入状态日志)。合规两侧预先约定:子代理系统提示的壳规则第 6 条(首次触顶拒绝即停止、交回总结),随包调度员规程第 2 节约定编排侧契约(绝不重试已终止的会话;重新派发、只注入所需上下文)。 +主会话享有软/硬/压三档水位+自动交接;被委派的壳子代理会话此前完全没有上下文控制,一路跑过 18 万 token 也无人拦截。现在每个壳子代理会话只有一道硬顶(`context.subagentForceTokens`,可选——缺省跟随主会话 `forceTokens`,即默认 130,000 token,与主会话共享同一条绝对终止线;显式覆盖时钳制 20k..1M,并在可知时额外以壳模型上下文窗口的 90% 封顶),实测口径与会话水位相同:最新 assistant 消息的 input + output + reasoning + cache.read。硬顶终止之前有两档柔性提醒,直接复用主会话的绝对软/硬阈值(`softTokens` 省着用 / `hardTokens` 收尾交接——子代理上下文与主会话上下文同等昂贵),有效上限按比例下拉两档。触顶后,插件拒绝该子代理会话内的所有后续工具调用并下达收尾指令;子代理随后给出的纯文本答复——一份详细的工作进度总结(已完成 / 关键发现含 file:line 证据 / 未完成 / 下一步)——即作为任务结果返回给委派方,会话随即永久终止(终止事件写入状态日志)。合规两侧预先约定:子代理系统提示的壳规则第 6 条(首次触顶拒绝即停止、交回总结),随包调度员规程第 2 节约定编排侧契约(绝不重试已终止的会话;重新派发、只注入所需上下文)。 终止是永久且有意的:此后任何通过 `task_id` 恢复该会话的 `task` 调用都会被永久拒绝(持久登记 `~/.config/opencode/opencode-switchman/subagent-cap.json`,重启不失效),不带 `task_id` 的全新派发不受影响。理由:子代理是可复现的工人(其规格写在委派 prompt 里),「终止并交回」优于「压缩后续跑」。`context.subagentCap: false` 只阻止新的终止——已终止的会话不复活。 diff --git a/src/assets/agents-md.ts b/src/assets/agents-md.ts index dcb8fa0..b11be30 100644 --- a/src/assets/agents-md.ts +++ b/src/assets/agents-md.ts @@ -5,7 +5,7 @@ // [2026-09-04]-[protocol slim-down v2: after mechanizing the watermark rules (context-watch hard gate + [WATERMARK:SESSION] // measured line), removed the advisory long text; added the built-in explore/general ban and the minimal delegation sample; // {{DELEGATION_FLOOR}}/{{SOFT}}/{{HARD}}/{{FORCE}} are interpolated by the index.ts transform per user jsonc (defaults -// 3k/60k/80k/120k); {{WORKSPACE_DIR}} = the per-session artifact workspace relative path (or a neutralized section +// 3k/50k/90k/130k since the 2026-09-15 watermark retune); {{WORKSPACE_DIR}} = the per-session artifact workspace relative path (or a neutralized section // when the workspace is disabled)] // [2026-09-05]-[git UX split: delivery git exempt at every watermark tier and never delegated; unbounded archaeology git // (log -p / range diff / blame without -L) reclassified as scanning — scope or delegate (kept in sync with context-watch.ts)] diff --git a/src/config.ts b/src/config.ts index 180e0c1..cf575e7 100644 --- a/src/config.ts +++ b/src/config.ts @@ -47,7 +47,8 @@ export interface UserConfig { export interface LoadedUserConfig { path: string; config: UserConfig; diagnostics: ConfigDiagnostic[]; generated: boolean } // [2026-09-15]-[subagentForce entry dropped: the shell hard line follows forceTokens by default (subagentForceTokens optional override)] -export const DEFAULT_CONTEXT_TOKENS = { soft: 60_000, hard: 80_000, force: 120_000 } as const +// [2026-09-15]-[default context watermarks retuned 60/80/120k → 50/90/130k; thresholdsOf in src/context-watch.ts must stay in sync] +export const DEFAULT_CONTEXT_TOKENS = { soft: 50_000, hard: 90_000, force: 130_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) */ diff --git a/src/context-watch.ts b/src/context-watch.ts index 8144f65..099b911 100644 --- a/src/context-watch.ts +++ b/src/context-watch.ts @@ -14,11 +14,12 @@ export type WatermarkLevel = "ok" | "soft" | "hard" | "force" export interface ContextThresholds { soft: number; hard: number; force: number } +// Sync note: these fallbacks must stay in sync with DEFAULT_CONTEXT_TOKENS in src/config.ts (currently 50k/90k/130k). export function thresholdsOf(options: ContextOptions | undefined): ContextThresholds { return { - soft: options?.softTokens ?? 60_000, - hard: options?.hardTokens ?? 80_000, - force: options?.forceTokens ?? 120_000, + soft: options?.softTokens ?? 50_000, + hard: options?.hardTokens ?? 90_000, + force: options?.forceTokens ?? 130_000, } } @@ -194,7 +195,7 @@ const fmtK = (n: number): string => `${Math.round(n / 1000)}k` // [2026-09-15]-[subagent soft tiers switch from fraction coefficients to the MAIN session's ABSOLUTE soft/hard // thresholds: subagent context is equally token-expensive as main-session context, so the two graceful advisories -// (conserve → hand-off) reuse softTokens/hardTokens (defaults 60k/80k) with no user-facing coefficients, expressed +// (conserve → hand-off) reuse softTokens/hardTokens (defaults 50k/90k) with no user-facing coefficients, expressed // against the force anchor (subagentForceTokens when a valid finite number, else forceTokens). The window-clamped // effective cap (capByWindow, already applied at the call site) still pulls the tiers down proportionally, so a tier // never exceeds the real termination line and small-window shells keep headroom before termination; misconfigured @@ -207,7 +208,7 @@ export function subagentSoftTiersOf( const anchor = typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? raw : t.force const f0 = t.soft / anchor const f1 = t.hard / anchor - if (!(f0 > 0 && f0 < f1 && f1 < 1)) return [60_000 / 120_000, 80_000 / 120_000] + if (!(f0 > 0 && f0 < f1 && f1 < 1)) return [50_000 / 130_000, 90_000 / 130_000] // fail-open: pure-defaults derivation, in sync with DEFAULT_CONTEXT_TOKENS return [f0, f1] } diff --git a/src/index.ts b/src/index.ts index a9e4d56..34cfe52 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1518,7 +1518,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => { const rulesAlreadyPresent = Array.isArray(output.system) && output.system.some((p) => typeof p === "string" && p.includes(rulesMarker)) if (options.rules!.enabled && !rulesAlreadyPresent) { - // [2026-09-04]-[rules interpolation: delegation floor and the three watermark thresholds come from user jsonc (defaults 3k/60k/80k/120k)] + // [2026-09-04]-[rules interpolation: delegation floor and the three watermark thresholds come from user jsonc] + // [2026-09-15]-[default watermarks retuned 60/80/120k → 50/90/130k (DEFAULT_CONTEXT_TOKENS in src/config.ts)] const t = sessionThresholds(input.sessionID) let rules = AGENTS_MD.trimEnd() .replaceAll("{{DELEGATION_FLOOR}}", String(options.rules!.delegationFloor ?? DEFAULT_DELEGATION_FLOOR)) diff --git a/test/auto-handover.test.ts b/test/auto-handover.test.ts index 6c21487..1004fc5 100644 --- a/test/auto-handover.test.ts +++ b/test/auto-handover.test.ts @@ -40,8 +40,8 @@ test("auto-handover: backup leg bounded, compaction fired detached, cooldown gua const hooks = await SwitchmanPlugin({ client: fakeClient, directory: "/w" } as any, undefined as any) const output = { message: async () => {} } as any - // seed a force-tier measured watermark via message.updated (input+output+reasoning+cache.read) - await hooks.event!({ event: { type: "message.updated", properties: { sessionID: "ses_auto_main", info: { role: "assistant", tokens: { input: 120_000, output: 1_000, reasoning: 1_000, cache: { read: 2_000 } } } } } as any }) + // seed a force-tier measured watermark via message.updated (input+output+reasoning+cache.read; 126k input → 130k measured = the 130k force line) + await hooks.event!({ event: { type: "message.updated", properties: { sessionID: "ses_auto_main", info: { role: "assistant", tokens: { input: 126_000, output: 1_000, reasoning: 1_000, cache: { read: 2_000 } } } } } as any }) // seed the session model face the summarize payload needs (chat.params: input.model is a Model object {providerID, id}) await hooks["chat.params"]!({ sessionID: "ses_auto_main", model: { providerID: "copilot", id: "glm-5.3" } } as any, output) diff --git a/test/ctx-pause.test.ts b/test/ctx-pause.test.ts index da586ba..ed747a5 100644 --- a/test/ctx-pause.test.ts +++ b/test/ctx-pause.test.ts @@ -59,7 +59,7 @@ test("ctx-pause: marker suspends the hard-tier read gate for this session only; const sid = "ses_ctxpa_main" const other = "ses_ctxpa_other" - await watermark(sid, 85_000) // defaults 60k/80k/120k → hard tier + await watermark(sid, 90_000) // defaults 50k/90k/130k → hard tier await expect(glob(sid)).rejects.toThrow(/hard watermark/) // pause marker → gate open (no throw, args untouched) @@ -71,7 +71,7 @@ test("ctx-pause: marker suspends the hard-tier read gate for this session only; expect(readStatusLog().split(`ctx control paused for session ${sid}`).length - 1).toBe(1) // session scoping: another session at the same tier stays gated - await watermark(other, 85_000) + await watermark(other, 90_000) await expect(glob(other)).rejects.toThrow(/hard watermark/) // resume restores enforcement; idempotent on re-fire @@ -91,7 +91,7 @@ test("ctx-pause: transform-path capture (real host shape — parts live on the m messages: [{ info: { id: msgId, role: "user", sessionID: sid }, parts: [{ type: "text", text }] }], } as any) - await watermark(sid, 85_000) // hard tier armed + await watermark(sid, 90_000) // hard tier armed await expect(glob(sid)).rejects.toThrow(/hard watermark/) await turn("msg_t1", `${CTX_PAUSE_MARKER} pause this session`) // info has NO parts field — the real shape @@ -152,8 +152,8 @@ test("ctx-pause: watermark line keeps numbers + PAUSED notice; resume returns ti expect(line).toContain("resume with /ctx-resume") expect(line).not.toContain("[WARNING]") - // resume → tiered directives return (85k ≥ hard 80k) - await assistant(85_000) + // resume → tiered directives return (95k ≥ hard 90k) + await assistant(95_000) await user(sid, `${CTX_RESUME_MARKER} resume`) sys = await system(sid) line = sys.find((l) => l.startsWith("[WATERMARK:SESSION]")) diff --git a/test/dispatch-gates.test.ts b/test/dispatch-gates.test.ts index c4237fc..711d42b 100644 --- a/test/dispatch-gates.test.ts +++ b/test/dispatch-gates.test.ts @@ -27,17 +27,18 @@ describe("context-watch: token estimation and watermark levels", () => { expect(watermarkLevel(80_000, t)).toBe("hard") expect(watermarkLevel(100_000, t)).toBe("force") }) - test("thresholdsOf: defaults 60k/80k/120k", () => { - expect(thresholdsOf(undefined)).toEqual({ soft: 60_000, hard: 80_000, force: 120_000 }) + // [2026-09-15]-[default context watermarks retuned 60/80/120k → 50/90/130k (DEFAULT_CONTEXT_TOKENS); pins updated, semantics unchanged] + test("thresholdsOf: defaults 50k/90k/130k", () => { + expect(thresholdsOf(undefined)).toEqual({ soft: 50_000, hard: 90_000, force: 130_000 }) }) // [2026-09-05]-[window cap: effective thresholds are capped at 90% of the session model's context window; order preserved, fail-open] test("capThresholdsByWindow: 90% cap, order preserved, fail-open on unknown window", () => { - const t = { soft: 60_000, hard: 80_000, force: 120_000 } + const t = { soft: 50_000, hard: 90_000, force: 130_000 } expect(capThresholdsByWindow(t, undefined)).toEqual(t) expect(capThresholdsByWindow(t, Number.NaN)).toEqual(t) expect(capThresholdsByWindow(t, 0)).toEqual(t) - expect(capThresholdsByWindow(t, 200_000)).toEqual({ soft: 60_000, hard: 80_000, force: 120_000 }) - expect(capThresholdsByWindow(t, 128_000)).toEqual({ soft: 60_000, hard: 80_000, force: 115_200 }) + expect(capThresholdsByWindow(t, 200_000)).toEqual({ soft: 50_000, hard: 90_000, force: 130_000 }) + expect(capThresholdsByWindow(t, 128_000)).toEqual({ soft: 50_000, hard: 90_000, force: 115_200 }) expect(capThresholdsByWindow(t, 32_000)).toEqual({ soft: 28_800, hard: 28_800, force: 28_800 }) }) }) @@ -176,11 +177,11 @@ describe("gates: built-in subagent blocking", () => { describe("config: new behavior-section validation", () => { const base = { version: 1, providers: {}, extensions: {} } - test("defaults: context 60/80/120k, gates on, builtinAgents deny, injection chain, floor 3000", () => { + test("defaults: context 50/90/130k, gates on, builtinAgents deny, injection chain, floor 3000", () => { const { config, diagnostics } = validateUserConfig(base) expect(diagnostics.filter((d) => d.level === "error")).toEqual([]) // [2026-09-15]-[subagentForceTokens omitted (absent follows forceTokens); the subagentSoftTiers field is retired] - expect(config.context).toEqual({ gates: true, softTokens: 60_000, hardTokens: 80_000, forceTokens: 120_000, readBudgetTokens: 1_500, autoHandover: true, subagentCap: true }) + expect(config.context).toEqual({ gates: true, softTokens: 50_000, hardTokens: 90_000, forceTokens: 130_000, readBudgetTokens: 1_500, autoHandover: true, subagentCap: true }) expect(config.builtinAgents.mode).toBe("deny") expect(config.injection.mode).toBe("chain") expect(config.rules.delegationFloor).toBe(3_000) @@ -193,10 +194,10 @@ describe("config: new behavior-section validation", () => { }) test("out-of-order/non-positive-integer watermarks revert the whole section to defaults with SWM037", () => { const r1 = validateUserConfig({ ...base, context: { softTokens: 80_000, hardTokens: 80_000, forceTokens: 100_000 } }) - expect(r1.config.context.softTokens).toBe(60_000) + expect(r1.config.context.softTokens).toBe(50_000) expect(r1.diagnostics.some((d) => d.code === "SWM037")).toBe(true) const r2 = validateUserConfig({ ...base, context: { softTokens: -1, hardTokens: 80_000, forceTokens: 100_000 } }) - expect(r2.config.context.softTokens).toBe(60_000) + expect(r2.config.context.softTokens).toBe(50_000) }) test("bad enum values revert to defaults", () => { const r = validateUserConfig({ ...base, builtinAgents: { mode: "maybe" }, injection: { mode: 42 }, rules: { delegationFloor: "low" } }) diff --git a/test/shell-context-advisory.test.ts b/test/shell-context-advisory.test.ts index 4930a44..e5e3bcc 100644 --- a/test/shell-context-advisory.test.ts +++ b/test/shell-context-advisory.test.ts @@ -2,8 +2,8 @@ // a dispatched shell session (never internal title/compaction/summary) gets at most one [SHELL-CONTEXT] advisory per tier, // tracking the shell watermark (conserve → hand-off); subagentCap:false disables the advisories, a terminated session // stays silent (the deny message governs), and session.deleted re-arms the dedup map] -// [2026-09-15]-[tiers now sit at the MAIN session's absolute soft/hard lines (60k/80k defaults) and the default shell cap -// follows forceTokens (120k) — advisory copy below pins 120k as the effective cap] +// [2026-09-15]-[tiers now sit at the MAIN session's absolute soft/hard lines (50k/90k defaults) and the default shell cap +// follows forceTokens (130k) — advisory copy below pins 130k as the effective cap] import { expect, test } from "bun:test" import { mkdtempSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" @@ -61,25 +61,25 @@ test("shell advisory: tier 1 conserve fires once, tier 2 hand-off once, then qui let sys = await system(sid) expect(advisory(sys)).toBeUndefined() - // crossing tier 1: 60k input → 64k measured ≥ 60k (shared soft line), < 80k → conserve line, numbers rendered from the live measurement - await mark(sid, 60_000) + // crossing tier 1: 50k input → 54k measured ≥ 50k (shared soft line), < 90k → conserve line, numbers rendered from the live measurement + await mark(sid, 50_000) sys = await system(sid) - expect(advisory(sys)).toBe("[SHELL-CONTEXT] measured shell context ≈ 64k/120k (conserve): stop batch reads and long pastes — switch to targeted grep and cite only the needed excerpts; finish the current work unit before starting anything new; keep outputs compact.") + expect(advisory(sys)).toBe("[SHELL-CONTEXT] measured shell context ≈ 54k/130k (conserve): stop batch reads and long pastes — switch to targeted grep and cite only the needed excerpts; finish the current work unit before starting anything new; keep outputs compact.") // same tier again → suppressed (once-per-tier dedup) expect(advisory(await system(sid))).toBeUndefined() - // crossing tier 2: 80k input → 84k ≥ 80k (shared hard line) → hand-off line with the inline HANDOFF marker - await mark(sid, 80_000) + // crossing tier 2: 90k input → 94k ≥ 90k (shared hard line) → hand-off line with the inline HANDOFF marker + await mark(sid, 90_000) sys = await system(sid) - expect(advisory(sys)?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 84k/120k (hand-off):")).toBe(true) + expect(advisory(sys)?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 94k/130k (hand-off):")).toBe(true) expect(advisory(sys)).toContain("`HANDOFF: inline · progress: n/m · next: <one sentence>`") // tier 2 delivered → quiet again expect(advisory(await system(sid))).toBeUndefined() - // crossing the hard cap (116k input → 120k measured ≥ the 120k shared force line) terminates the session → the deny message governs, advisories stop - await mark(sid, 116_000) + // crossing the hard cap (126k input → 130k measured ≥ the 130k shared force line) terminates the session → the deny message governs, advisories stop + await mark(sid, 126_000) expect(advisory(await system(sid))).toBeUndefined() await expect(deny(sid, "call_adv_deny")).rejects.toThrow("SUBAGENT CONTEXT CAP REACHED") }, 30_000) @@ -106,10 +106,10 @@ test("shell advisory: internal and main sessions never receive it; session.delet // session.deleted clears shellWatermark + the dedup map: after deletion the same measurements re-arm tier 1 const sid = "ses_adv_gone" await seedShell(sid) - await mark(sid, 60_000) - expect(advisory(await system(sid))?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 64k/120k (conserve):")).toBe(true) + await mark(sid, 50_000) + expect(advisory(await system(sid))?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 54k/130k (conserve):")).toBe(true) expect(advisory(await system(sid))).toBeUndefined() await emit({ type: "session.deleted", properties: { info: { id: sid } } }) - await mark(sid, 60_000) - expect(advisory(await system(sid))?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 64k/120k (conserve):")).toBe(true) + await mark(sid, 50_000) + expect(advisory(await system(sid))?.startsWith("[SHELL-CONTEXT] measured shell context ≈ 54k/130k (conserve):")).toBe(true) }, 30_000) diff --git a/test/subagent-cap.test.ts b/test/subagent-cap.test.ts index ab3b2e8..0fd7d0e 100644 --- a/test/subagent-cap.test.ts +++ b/test/subagent-cap.test.ts @@ -60,9 +60,9 @@ async function seedShellSession(hooks: Hooks, sessionId: string, agent = "glm-mx describe("subagent cap: pure decision layer", () => { // [2026-09-15]-[subagentForceTokens optional: absent follows forceTokens (shared hard line); present values keep the clamp] - test("subagentCapOf: absent → follows forceTokens (120k default), clamped override, disabled → null", () => { - expect(subagentCapOf(undefined)).toBe(120_000) - expect(subagentCapOf({})).toBe(120_000) + test("subagentCapOf: absent → follows forceTokens (130k default), clamped override, disabled → null", () => { + expect(subagentCapOf(undefined)).toBe(130_000) + expect(subagentCapOf({})).toBe(130_000) expect(subagentCapOf({ forceTokens: 90_000 })).toBe(90_000) expect(subagentCapOf({ subagentForceTokens: 250_000 })).toBe(250_000) expect(subagentCapOf({ subagentForceTokens: 1 })).toBe(MIN_SUBAGENT_CAP_TOKENS) @@ -96,47 +96,47 @@ describe("subagent cap: pure decision layer", () => { // pulls them down proportionally — a tier never exceeds the real termination line] describe("subagent soft tiers: pure decision layer", () => { test("tier derivation: shared absolute thresholds against the force anchor, fail-open defaults", () => { - // default config (no overrides): main-session 60k soft / 80k hard against the 120k force anchor - expect(subagentSoftTiersOf(undefined)).toEqual([0.5, 80_000 / 120_000]) - expect(subagentSoftTiersOf({})).toEqual([0.5, 80_000 / 120_000]) - // subagentForceTokens override: the absolute 60k/80k lines preserved against the 100k anchor - expect(subagentSoftTiersOf({ subagentForceTokens: 100_000 })).toEqual([0.6, 0.8]) + // default config (no overrides): main-session 50k soft / 90k hard against the 130k force anchor + expect(subagentSoftTiersOf(undefined)).toEqual([50_000 / 130_000, 90_000 / 130_000]) + expect(subagentSoftTiersOf({})).toEqual([50_000 / 130_000, 90_000 / 130_000]) + // subagentForceTokens override: the absolute 50k/90k lines preserved against the 100k anchor + expect(subagentSoftTiersOf({ subagentForceTokens: 100_000 })).toEqual([0.5, 0.9]) // custom main-session thresholds ride along expect(subagentSoftTiersOf({ softTokens: 30_000, hardTokens: 60_000, forceTokens: 120_000 })).toEqual([0.25, 0.5]) // invalid anchor → forceTokens - expect(subagentSoftTiersOf({ subagentForceTokens: Number.NaN, forceTokens: 200_000 })).toEqual([0.3, 0.4]) + expect(subagentSoftTiersOf({ subagentForceTokens: Number.NaN, forceTokens: 200_000 })).toEqual([0.25, 0.45]) // misconfigured thresholds (soft ≥ force, or f-ordering violated) → fail-open pure-defaults derivation - expect(subagentSoftTiersOf({ softTokens: 130_000, hardTokens: 140_000, forceTokens: 120_000 })).toEqual([0.5, 80_000 / 120_000]) - expect(subagentSoftTiersOf({ softTokens: 90_000, hardTokens: 80_000, forceTokens: 120_000 })).toEqual([0.5, 80_000 / 120_000]) - expect(subagentSoftTiersOf({ softTokens: 120_000, hardTokens: 125_000, forceTokens: 120_000 })).toEqual([0.5, 80_000 / 120_000]) + expect(subagentSoftTiersOf({ softTokens: 130_000, hardTokens: 140_000, forceTokens: 120_000 })).toEqual([50_000 / 130_000, 90_000 / 130_000]) + expect(subagentSoftTiersOf({ softTokens: 90_000, hardTokens: 80_000, forceTokens: 120_000 })).toEqual([50_000 / 130_000, 90_000 / 130_000]) + expect(subagentSoftTiersOf({ softTokens: 120_000, hardTokens: 125_000, forceTokens: 120_000 })).toEqual([50_000 / 130_000, 90_000 / 130_000]) }) - test("tier firing at the shared absolute lines: ≈60k conserve / ≈80k hand-off against a 120k effective cap", () => { + test("tier firing at the shared absolute lines: ≈50k conserve / ≈90k hand-off against a 130k effective cap", () => { const tiers = subagentSoftTiersOf(undefined) - const cap = 120_000 - expect(shellSoftTier(59_999, cap, tiers)).toBe(0) - expect(shellSoftTier(60_000, cap, tiers)).toBe(1) - expect(shellSoftTier(79_999, cap, tiers)).toBe(1) - expect(shellSoftTier(80_000, cap, tiers)).toBe(2) + const cap = 130_000 + expect(shellSoftTier(49_999, cap, tiers)).toBe(0) + expect(shellSoftTier(50_000, cap, tiers)).toBe(1) + expect(shellSoftTier(89_999, cap, tiers)).toBe(1) + expect(shellSoftTier(90_000, cap, tiers)).toBe(2) }) - test("subagentForceTokens override keeps the absolute 60k/80k lines against a 100k cap", () => { + test("subagentForceTokens override keeps the absolute 50k/90k lines against a 100k cap", () => { const tiers = subagentSoftTiersOf({ subagentForceTokens: 100_000 }) const cap = subagentCapOf({ subagentForceTokens: 100_000 })! - expect(tiers).toEqual([0.6, 0.8]) - expect(shellSoftTier(59_999, cap, tiers)).toBe(0) - expect(shellSoftTier(60_000, cap, tiers)).toBe(1) - expect(shellSoftTier(79_999, cap, tiers)).toBe(1) - expect(shellSoftTier(80_000, cap, tiers)).toBe(2) + expect(tiers).toEqual([0.5, 0.9]) + expect(shellSoftTier(49_999, cap, tiers)).toBe(0) + expect(shellSoftTier(50_000, cap, tiers)).toBe(1) + expect(shellSoftTier(89_999, cap, tiers)).toBe(1) + expect(shellSoftTier(90_000, cap, tiers)).toBe(2) }) test("small window-clamped cap pulls the tiers down proportionally (a tier never exceeds the termination line)", () => { const tiers = subagentSoftTiersOf(undefined) // 90% of a ~26.7k window → 24k effective cap const clamped = capByWindow(120_000, 26_667) expect(clamped).toBe(24_000) - // 12k conserve / 16k hand-off - expect(shellSoftTier(11_999, clamped, tiers)).toBe(0) - expect(shellSoftTier(12_000, clamped, tiers)).toBe(1) - expect(shellSoftTier(15_999, clamped, tiers)).toBe(1) - expect(shellSoftTier(16_000, clamped, tiers)).toBe(2) + // ≈9.2k conserve / ≈16.6k hand-off (default 50k/90k tiers against the 130k anchor, pulled down with the cap) + expect(shellSoftTier(9_229, clamped, tiers)).toBe(0) + expect(shellSoftTier(9_230, clamped, tiers)).toBe(1) + expect(shellSoftTier(16_614, clamped, tiers)).toBe(1) + expect(shellSoftTier(16_615, clamped, tiers)).toBe(2) expect(shellSoftTier(24_000, clamped, tiers)).toBe(2) for (const f of tiers) expect(Math.floor(f * clamped)).toBeLessThanOrEqual(clamped) }) @@ -151,13 +151,13 @@ describe("subagent soft tiers: pure decision layer", () => { test("once-per-tier dedup, subagentCap:false and terminated sessions stay silent (pure semantics)", () => { const tiers = subagentSoftTiersOf(undefined) // below tier 1: quiet, delivered state unchanged - expect(shellSoftTierDecision({ terminated: false, tokens: 40_000, cap: 100_000, tiers, delivered: 0 })).toEqual({ line: null, delivered: 0 }) + expect(shellSoftTierDecision({ terminated: false, tokens: 30_000, cap: 100_000, tiers, delivered: 0 })).toEqual({ line: null, delivered: 0 }) // tier 1 fires once; a second request at the same tier is suppressed - const t1 = shellSoftTierDecision({ terminated: false, tokens: 60_000, cap: 100_000, tiers, delivered: 0 }) + const t1 = shellSoftTierDecision({ terminated: false, tokens: 50_000, cap: 100_000, tiers, delivered: 0 }) expect(t1.delivered).toBe(1) expect(t1.line).toContain("[SHELL-CONTEXT]") expect(t1.line).toContain("(conserve)") - expect(shellSoftTierDecision({ terminated: false, tokens: 60_000, cap: 100_000, tiers, delivered: 1 }).line).toBeNull() + expect(shellSoftTierDecision({ terminated: false, tokens: 50_000, cap: 100_000, tiers, delivered: 1 }).line).toBeNull() // the higher tier fires exactly one more line (never re-delivers tier 1's copy) const t2 = shellSoftTierDecision({ terminated: false, tokens: 90_000, cap: 100_000, tiers, delivered: 1 }) expect(t2.delivered).toBe(2) @@ -174,15 +174,15 @@ describe("subagent soft tiers: pure decision layer", () => { }) describe("subagent cap: plugin wiring", () => { - // [2026-09-15]-[default cap now follows forceTokens (120k): crossing values shifted from 100k to the shared line] - test("shell session crossing the shared 120k line → tools denied, task_id resume denied, registry persisted", async () => { + // [2026-09-15]-[default cap now follows forceTokens (130k): crossing values shifted to the shared 130k line] + test("shell session crossing the shared 130k line → 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 = 116_000 + 4_000 = 120k ≥ cap - await mark(hooks, "ses_shell_cap", 116_000) + // crossing: measured context = 126_000 + 4_000 = 130k ≥ cap + await mark(hooks, "ses_shell_cap", 126_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") @@ -198,7 +198,7 @@ describe("subagent cap: plugin wiring", () => { // 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(120_000) + expect(reg.ses_shell_cap.tokens).toBe(130_000) expect(reg.ses_shell_cap.agent).toBe("glm-mx-53f-low") }, 30_000) From 937e39cb006da5badec806bb307929aaf6527b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=B1=B3=E6=96=AF=E7=89=B9=E6=8A=98=E8=85=BE?= <814442321@qq.com> Date: Tue, 15 Sep 2026 10:01:26 +0800 Subject: [PATCH 4/4] chore(release): v1.1.0 --- CHANGELOG.md | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b782cf..9a932bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ 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] +## [1.1.0] - 2026-09-15 ### Added diff --git a/package.json b/package.json index b0c3c6c..a234e81 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-switchman", - "version": "1.0.4", + "version": "1.1.0", "description": "OpenCode orchestration plugin: six-lane shell matrix dispatch (hard ROUTE_META validation / breaker self-healing / probes / three-pool quota awareness / cost-aware tiebreaker)", "license": "MIT", "repository": {