Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "opencode-switchman",
"version": "1.1.0",
"version": "1.1.1",
"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": {
Expand Down
5 changes: 4 additions & 1 deletion src/assets/agents-md.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
// [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)]
// [2026-09-17]-[broad-search clarify: §5 gains the ask-first rule for whole-project searches (mechanically enforced by
// the search clarify gate in src/index.ts + pure helpers in src/search-clarify.ts; jsonc search.clarify:false disables)]
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.
Expand Down Expand Up @@ -69,8 +71,9 @@ Task artifacts (plans, implementation progress, process-control notes, design do
## 4. Verification and Re-Review
- Logic changes must be verified once; changes >20 lines, multiple call sites, or long output → hand to tester; >300 lines or core/security/data logic → reviewer re-review (review chain, cross-family preferred — same-family self-review only as a last-resort DOWNGRADED seat).

## 5. Self-read budget (always on, every turn)
## 5. Self-read Budget and Broad-Search Clarify (always on, every turn)
Each self-read is costed against a per-call injection budget (default ~1500 tokens; the live cap rides the \`[WATERMARK:SESSION]\` banner line). Reads over the cap are auto-bounded or rejected with exact bounded-retry params (\`read <file> limit=N offset=M\`); once the per-turn self-read cap is spent, delegate the turn's remaining reads to an economy shell. Watermarks are lifecycle advice only: past {{SOFT}} prefer delegating new scans; past {{HARD}} wrap up (verification/delivery bash stays open; state-changing git is delivery — run it yourself, never delegate it); at {{FORCE}} compact immediately. Unbounded history dumps (e.g. \`git log -p\` without \`-n\`) are rejected at any context size — scope them or delegate.
Broad-search clarify: the session's first whole-project search (glob \`**\` without a path scope, pathless grep, or recursive rg/grep -r/find/fd at the project root) is denied once by the plugin with an ask-first error — relay that marker question to the user verbatim (more precise file/directory guidance?). With narrower guidance, redo the search scoped to it (never silently widen back to whole-project while that scope holds); without guidance or on a decline, retry the same call (it passes once the ask completed). Retrying the search without asking is a violation. Disable via jsonc \`search.clarify:false\`.

## 6. Major-Action Reporting and the Expert Panel
- [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.
Expand Down
11 changes: 9 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export interface UserConfig {
workspace: { enabled: boolean; dirname: string }
// [2026-09-05]-[project language preference: conversation/comments/docs language — first-run ask + per-turn [LANG] iron-rule line]
lang: { enabled: boolean; ask: boolean; candidates: string[] }
// [2026-09-17]-[broad-search clarify: whole-project searches ask the user for narrower guidance once per session]
search: { clarify: boolean }
// [2026-09-06]-[tmux pane mirroring: live subagent attach panes in the home tmux window's right column]
tmux: { enabled: boolean; rightPct: number; maxPanes: number; mini: boolean }
lanes: Partial<Record<Lane, string[]>>
Expand All @@ -52,7 +54,7 @@ export const DEFAULT_CONTEXT_TOKENS = { soft: 50_000, hard: 90_000, force: 130_0
export const DEFAULT_DELEGATION_FLOOR = 3_000

/** Factory defaults for behavior sections (fillMissing baseline; only bad-typed values fall back and report SWM037) */
export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "capability" | "matrix" | "banner" | "rules" | "context" | "builtinAgents" | "injection" | "dispatch" | "relay" | "workspace" | "lang" | "tmux" | "lanes"> {
export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "capability" | "matrix" | "banner" | "rules" | "context" | "builtinAgents" | "injection" | "dispatch" | "relay" | "workspace" | "lang" | "search" | "tmux" | "lanes"> {
return {
quota: { glmFiveHourReservePct: 90, deepseekLowBalanceWarnCny: 10 },
cost: { enabled: true },
Expand All @@ -68,6 +70,7 @@ export function defaultBehaviorConfig(): Pick<UserConfig, "quota" | "cost" | "ca
relay: { image: true },
workspace: { enabled: true, dirname: ".switchman" },
lang: { enabled: true, ask: true, candidates: [...DEFAULT_LANG_CANDIDATES] },
search: { clarify: true },
tmux: { enabled: true, rightPct: 60, maxPanes: 3, mini: false },
lanes: {},
}
Expand Down Expand Up @@ -205,6 +208,8 @@ export function validateUserConfig(value: unknown): { config: UserConfig; diagno
if (typeof filled.lang.enabled !== "boolean") bad("lang.enabled", () => { filled.lang.enabled = defaults.lang.enabled })
if (typeof filled.lang.ask !== "boolean") bad("lang.ask", () => { filled.lang.ask = defaults.lang.ask })
if (!Array.isArray(filled.lang.candidates) || filled.lang.candidates.length === 0 || !filled.lang.candidates.every((c: unknown) => typeof c === "string" && c.trim() === c && !!c.trim() && c.length <= 48)) bad("lang.candidates", () => { filled.lang.candidates = structuredClone(defaults.lang.candidates) })
// [2026-09-17]-[broad-search clarify switch]
if (typeof filled.search.clarify !== "boolean") bad("search.clarify", () => { filled.search.clarify = defaults.search.clarify })
// [2026-09-06]-[tmux pane mirroring: enabled/mini booleans; rightPct integer 10..90; maxPanes integer 1..4]
if (typeof filled.tmux.enabled !== "boolean") bad("tmux.enabled", () => { filled.tmux.enabled = defaults.tmux.enabled })
if (!Number.isInteger(filled.tmux.rightPct) || filled.tmux.rightPct < 10 || filled.tmux.rightPct > 90) bad("tmux.rightPct", () => { filled.tmux.rightPct = defaults.tmux.rightPct })
Expand Down Expand Up @@ -278,6 +283,8 @@ export function resolveEffectiveOptions(raw: unknown, cfg: UserConfig): { option
workspace: has(o, "workspace") ? { ...cfg.workspace, ...o.workspace } : cfg.workspace,
// [2026-09-05]-[project language preference switch: same merge pattern (jsonc baseline, tuple explicit keys override)]
lang: has(o, "lang") ? { ...cfg.lang, ...o.lang } : cfg.lang,
// [2026-09-17]-[broad-search clarify switch: same merge pattern]
search: has(o, "search") ? { ...cfg.search, ...o.search } : cfg.search,
// [2026-09-06]-[tmux pane mirroring switches: same merge pattern]
tmux: has(o, "tmux") ? { ...cfg.tmux, ...o.tmux } : cfg.tmux,
lanes: has(o, "lanes") ? o.lanes : cfg.lanes,
Expand All @@ -293,7 +300,7 @@ export function resolveEffectiveOptions(raw: unknown, cfg: UserConfig): { option
lmarenaCheck: has(o.capability, "lmarenaCheck") ? o.capability!.lmarenaCheck! : cfg.capability.lmarenaCheck,
},
}
for (const section of ["cost", "banner", "rules", "lanes", "matrix", "capability", "context", "builtinAgents", "injection", "dispatch", "relay", "workspace", "lang", "tmux"] as const) if (has(o, section)) legacySections.push(section)
for (const section of ["cost", "banner", "rules", "lanes", "matrix", "capability", "context", "builtinAgents", "injection", "dispatch", "relay", "workspace", "lang", "search", "tmux"] as const) if (has(o, section)) legacySections.push(section)
return { options, legacySections }
}
export function routePolicy(config: UserConfig, legacy?: Partial<Record<Pool, boolean>>): RoutePolicy {
Expand Down
43 changes: 43 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import type { SwitchmanOptions, Lane, LaneResult, Pool, ShellRegEntry, ModelKey
import { WorkspaceTracker, DEFAULT_WORKSPACE_DIRNAME, type EnsuredWorkspace } from "./workspace"
import { TmuxPaneManager, serverOriginOf } from "./tmux"
import { loadLangConfig, renderLangLine, renderAskDirective, saveLangFromQuestion, langGateDecision, LANG_GATE_TOOLS, hasLangMarkerQuestions, detectUiLocale } from "./lang-config"
import { SEARCH_CLARIFY_TOOLS, SEARCH_CLARIFY_MAX_DENIES, isBroadSearchCall, describeSearchCall, searchClarifyDenyMessage, hasSearchMarkerQuestion } from "./search-clarify"
import { renderRouteLine, routeLineEnabled } from "./route-line"
import { loadDispatchMode } from "./dispatch-mode"
import { detectMode, readConfigured, normalizeProviderListResponse } from "./activation"
Expand Down Expand Up @@ -213,6 +214,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => {
// [2026-09-07]-[lang hard gate: per-session waiver set — a completed marker question call that did NOT persist a
// config (user declined / unparsable output) opens the gate for this session so a decline never deadlocks writes]
const langGateWaived = new Set<string>()
// [2026-09-17]-[broad-search clarify gate: searchScopeAsked = sessions whose scope ask already completed (marker
// question captured, or anti-deadlock fail-open after repeated denies) — broad searches pass from then on;
// searchDenyCount = per-session deny counter backing the fail-open (a broken/unavailable question tool must
// never wedge a session on its own broad search)]
const searchScopeAsked = new Set<string>()
const searchDenyCount = new Map<string, number>()
// [2026-09-06]-[tmux pane mirroring: dispatched subagent sessions open as live `opencode attach` panes in the home
// tmux window — main pane left / subagent column right (max 3 visible, FIFO replacement on completion); inert
// outside tmux, fail-open everywhere. pendingTask = dispatch intents recorded per main session, consumed by the
Expand Down Expand Up @@ -1694,6 +1701,34 @@ 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-17]-[broad-search clarify gate: a main session's first whole-project search (glob '**' unscoped /
// pathless grep / recursive rg|grep -r|find|fd at the project root) is denied with an ask-first error — the
// user is asked ONCE for more precise file guidance (marker question); narrower guidance re-scopes the retry,
// no guidance (or a decline) re-runs it (the latch opens on marker-question completion; after 2 denies without
// an ask the gate fail-opens for the session — anti-deadlock). Shell/internal sessions exempt (a delegated
// scouter IS the sanctioned broad-search path); detection is conservative (uncertain shapes pass); not ctx
// control — /ctx-pause does not suspend it; search.clarify:false disables entirely]
try {
const scSid = (input as any).sessionID as string | undefined
if (scSid && SEARCH_CLARIFY_TOOLS.has(input.tool) && !isShellOrInternalSession(scSid)
&& options.search!.clarify && !searchScopeAsked.has(scSid)) {
if (isBroadSearchCall(input.tool, output.args)) {
const n = (searchDenyCount.get(scSid) ?? 0) + 1
searchDenyCount.set(scSid, n)
if (n > SEARCH_CLARIFY_MAX_DENIES) {
searchScopeAsked.add(scSid)
appendStatusLog(`search clarify gate: fail-open after ${SEARCH_CLARIFY_MAX_DENIES} denies without an ask — gate open for session ${scSid}`)
} else {
denySkip.add(input.callID)
appendStatusLog(`search clarify gate: tool '${input.tool}' denied (broad search, ask-first) in session ${scSid} (${n}/${SEARCH_CLARIFY_MAX_DENIES})`)
throw new Error(searchClarifyDenyMessage(describeSearchCall(input.tool, output.args)))
}
}
}
} catch (e) {
if (denySkip.has(input.callID)) throw e
// internal error on our side (never one of our own denies) → fail-open, do not break the tool path
}
// [2026-09-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,
Expand Down Expand Up @@ -1870,6 +1905,12 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => {
langGateWaived.add(hookInput.sessionID)
appendStatusLog(`lang gate: marker question completed without a saved config — gate waived for session ${hookInput.sessionID}`)
}
// [2026-09-17]-[broad-search clarify latch: our marker question completed (answered or declined — either
// way the user was asked) → broad searches pass for the rest of the session]
if (hasSearchMarkerQuestion(hookInput.args)) {
searchScopeAsked.add(hookInput.sessionID)
appendStatusLog(`search clarify: scope ask completed — gate open for session ${hookInput.sessionID}`)
}
} catch { /* fail-open */ }
}
const sid = hookInput.sessionID
Expand Down Expand Up @@ -2060,6 +2101,8 @@ export const SwitchmanPlugin: Plugin = async (input, rawOptions) => {
workspace.forget(sid)
langAsked.delete(sid)
langGateWaived.delete(sid)
searchScopeAsked.delete(sid)
searchDenyCount.delete(sid)
// [2026-09-06]-[tmux pane mirroring: deleted child frees its pane; deleted main drops its dispatch intents]
if (tmuxPanes.tracking(sid)) void tmuxPanes.noteChildEnd(sid)
pendingTask.delete(sid)
Expand Down
5 changes: 5 additions & 0 deletions src/provider-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,11 @@ export function renderDefaultConfigJsonc(): string {
// "maxPanes": 3, // max visible subagent panes (1..4; extra dispatches wait in a FIFO queue and take over freed panes)
// "mini": false // true = minimal attach interface instead of the full TUI
// },
// Broad-search clarify: the first whole-project search per main session (glob '**' unscoped / pathless grep /
// recursive rg|grep -r|find|fd) is denied once with an ask-first error — the user is asked for narrower file guidance.
// "search": {
// "clarify": true // master switch; false = broad searches run without the ask
// },
// Third-party/future extension data goes under namespace keys, not into providers.
"extensions": {}
}
Expand Down
Loading
Loading