GitHubChinese
opencode-switchman · v0.2.0
01 / 12
← → / swipe · loops
OPENCODE ORCHESTRATION PLUGIN

opencode-switchman

Turn the main model into a dispatcher · Six-lane shell matrix · Deterministic gating × Weighted scoring

dynamic shell matrix · desktop visible models ↔ TUI favorites 6 cognitive lanes 6 deterministic gates 174 behavior fixtures every provider · quota control for glm / deepseek / copilot
$ curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bashor$ npx -y opencode-switchman@latest
CORE VALUE

Fully-automated model matrix + autonomous decisions

= every token lands exactly where it matters. Not one wasted.

The activation matrix rebuilds itself in real time from desktop visible models / TUI favorites / live sessions; six gates and weighted scoring run on their own — you decide, the matrix spends.

Dynamic activation matrixWeighted scoring engineQuota-aware routingProbe / breaker / isolation self-healing
PROBLEM / The real pain of juggling subscriptions

One model driven into the ground,
while the rest expire in your account

You hold Copilot credits, a GLM Coding Plan and a DeepSeek balance — yet you keep flying blind on watermarks and paying full freight at peak hours.

PAIN_01

Cognitive mismatch

Flagship models running scan-and-count grunt work, tokens spent where they shouldn't be; lightweight models doing architecture design — rework ends up costing the most.

PAIN_02

Flying blind on quotas

GLM's 5-hour window exhausted yet you keep ramming into it, Copilot credits expiring at month-end unspent, DeepSeek balance drained before you notice.

PAIN_03

Single-point perspective

Review runs in the same model family as the producer, sharing the same blind spots — nothing ever gets caught.

PAIN_04

Loose protocol

"Hey, take a look at this" delegation is unstructured and unvalidated — sub-agents end up with vague tasks.

ARCHITECTURE / Three layers of orchestration

Cognition · Execution · Determinism, each in its own lane

The LLM handles cognitive decisions; the plugin handles everything computable deterministically — intelligence and rules, cleanly separated.

LAYER 01

Cognitive layer

COGNITIVE

The main model (dispatcher) plus the injected dispatcher protocol — profiling tasks in four dimensions and making delegation decisions.

  • Cognitive intensity × mechanical load × context × urgency
  • Do it yourself, or delegate
  • Pick lane and shell, write DELEGATION_V1
LAYER 02

Execution layer

EXECUTION

"Model × lane" empty-shell sub-agents, bound only to a model and thinking tier; roles are assigned dynamically by the delegation prompt.

  • programmer / tester / reviewer… 14 roles
  • ro shell = review-chain read-only
  • vision shell handles image tasks
LAYER 03

Deterministic layer

DETERMINISTIC

The plugin itself: zero probability, pure rules — every dispatcher decision is held inside hard constraints and explainable scores.

  • Six-gate interception · ROUTE_META hard validation
  • Capability-tiered weighted scoring
  • Probe / breaker / isolation self-healing · four-line banner injection
THE MATRIX / Shell matrix

Dynamic shells, activated from the surface you actually use

At startup the config hook injects the "model × effort" shell matrix into the agent registry. Desktop visible models and TUI favorites sync both ways with mtime arbitration; any surface change triggers a full probe recomputation immediately, while the 10-minute refresh keeps the matrix self-healing — zero manual upkeep.

N×E
visible models × declared efforts
10min
probe interval · TTL 600s
6×N
six lanes × every provider
sync
visible models ↔ favorites
shell = copilot/glm/ds -mx- model short name -off|low|high|max
Live · dispatchableDisabled / degraded
DYNAMIC MATRIX · LIVE PROBE · SELF-HEALING
SIX LANES / Six cognitive lanes

Token economics first principles: rework is the most expensive token

Six lanes by cognitive intensity, each backed by an optimal shell chain computed live by the plugin from capability tier / effort fit / health / watermarks / cost / peak windows.

economy LANE_1

Scan & count

clerk / scouter cheap sweeps — built for context protection.

lightweight models · low tier
mechanical LANE_2

Regression & scripts

tester / ops mechanical execution — high-frequency, verifiable.

lightweight models · high tier
main LANE_3

Primary delivery

programmer / uiux / data-analyst, your daily workhorses.

mainstream models · regular tier
hard LANE_4

Architecture core

planner load-bearing design — only the strongest models at max tier.

flagship models · max tier
vision LANE_5

Visual understanding

observer reads images — dedicated vision shells for image tasks.

vision models · on demand
review LANE_6 cross-family enforced

Review & re-audit

reviewer / expert panel — drop shells sharing the producer's family first, same family counts as self-review.

review chain · read-only shells
LIFECYCLE HOOKS / Four hooks

Hooked into every heartbeat of opencode's lifecycle

Four hooks cover the full chain: startup injection → dispatch interception → classified failure accounting → per-turn prompt injection.

config

Startup injection

Injects the full shell matrix into cfg.agent at opencode startup, and collects credentials across all providers (auth read-only, zero separate storage).

tool.execute.before

Dispatch interception

Runs six-gate deterministic validation before the task tool executes; on deny it attaches the reason plus a redirect candidate, and the main model reassigns seamlessly along the chain.

event

Failure classification

Normalizes rate_limit / quota / auth / not_found / server / network / unknown, trips 600s breakers, and isolates real-dispatch failures for 10–30 minutes.

system.transform

Per-turn injection

Injects dispatcher rules plus the four-line banner into every LLM request; every rebuild logs scored candidates to routing-decisions.jsonl.

fail-open law: any hook exception only writes to stderr and never blocks the main flow; unknown quota is never hard-blocked, and breaker + probe back each other up — the plugin never becomes a single point of failure.

SIX GATES / Six-gate interception

Any gate hits, and it's a deny — with a redirect candidate attached

When the main model dispatches a sub-agent, the plugin validates deterministically before the task tool executes — order is priority.

01
Registry gate
shell not enabled / not probed
deny → no dispatch to unregistered faces
02
Probe / retired gate
combo down or model retired
deny → block unavailable or vanished models
03
Breaker / isolation gate
600s breaker or 10–30min real-failure isolation
deny → auto-recovers without poisoning the pool
04
Pool exhaustion gate
quota check will fail
deny → human-readable reason (GLM 100% / credits exhausted / DS overdue)
05
Protocol gate
ROUTE_META missing / invalid
deny → attach sample + valid-value table, auto-correct
06
Semantic gate
same-family review / rw→ro / image→non-vision shell
deny → review requires cross-family view and other semantic constraints
SCORING ENGINE / Automated decisions

Lane selection isn't guesswork — it's explicit weighted scoring

Candidate chains are computed live from curated capability tiers and six coefficients — the main model dispatches to the chain head, and the score trail is logged.

🎯

Capability tiers are irreversibleS/A/B/C

Curated base scores match exact → prefix → family → global fallback. A lower tier can never outrank a higher tier, even with better water or cost.

📈

Six-factor coefficientweighted

Score = base × effortFit × health × water × costBias × peak. Probe 429 becomes strained health, not a pool-wide jump to another vendor.

🧬

Water, cost and peak stay boundedbounded

Two quota windows use the tighter pressure; Copilot surplus near expiry can be boosted; GLM peak is only ×0.93 same-tier yield, never cross-tier exile.

🧾

Traceable decisionsjsonl

Every banner rebuild writes candidates and factor scores into a 200-line routing-decisions.jsonl ring buffer; immediate urgency still sorts by probe latency.

PROTOCOL / ROUTE_META protocol

One line, field-by-field validation of six keys

DELEGATION_V1 · embedded
# single-line protocol embedded in the delegation prompt (sample)
ROUTE_META {
  "lane":            "main",      // one of six lanes
  "role":           "programmer", // one of 14 roles
  "producer_family": "glm",      // true model family
  "capability":      "rw",         // rw | ro
  "modality":        "text",       // text | image
  "source":          "auto"        // auto | user
}
  • Protocol gate field-by-field validation — missing or invalid is an immediate deny, the error carries the correct sample, and the main model fixes it by copying.
  • producer_family hard constraint — copilot / glm are pools, not families; compared against the shell family at review to enforce cross-family audit.
  • Semantic linkage — lane=review forces ro shells, modality=image forces vision shells, source=auto forbids paid fallback.
  • Structured delegation — the DELEGATION_V1 template ships with the package; delegation prompts are self-contained, cacheable and validatable.
LIVE BANNER / Four-line banner

The dispatch basis, live and visible every turn

The system.transform hook injects into the system prompt every turn — the dispatcher always decides on the freshest facts.

[Routing]
economy: glm-53f-low→ds-v4fv-off | mechanical: glm-53f-high→ds-v4fv-off | main: ds-v4p-high | hard: ds-v4p-max …
[Watermark]
GLM 5h window 23% weekly 7% (refresh 09-04 10:00) | Copilot credits unlimited used 3885 | tip: push hard tasks to glm, save credits for key work
[Limits]
down: none | retired: 0 models | reviewer must be cross-family (producer family ≠ shell family) | DeepSeek tail fallback only
[Update]
new version available run /switchman-update or /switchman-ignore; local mode shows manual update guidance
SELF-HEALING / Self-healing data plane

Probe · Breaker · Isolation · fail-open

The data plane runs fully automatically: liveness, quota, pricing, scoring, classified failures and updates — no manual intervention.

🛰️

Probe matrix

Sends real requests to the three quota pools to check liveness. Surface changes trigger a full refresh immediately; the 10-minute cycle keeps temporary failures in the degradation chain.

model-matrix.json · probe/10min
🔥

Classify + isolate

Failures become rate_limit / quota / auth / not_found / server / network / unknown. Real-dispatch failures isolate a combo for 10–30 minutes; 3 consecutive 404s retire a model.

routing.json · failures.log
⬆️

Self-update path

Startup checks cache for 24h. Production installs expose /switchman-update for silent upgrade plus restart notice; /switchman-ignore is session-scoped and resets on restart.

[Update] · commands
GET STARTED

The advanced play for multi-subscribers:
every token spent where it counts

174 behavior-contract fixtures all green as the safety net · every opencode provider plugs in · glm / deepseek / copilot quota control

Six cognitive lanesWeighted scoring engineTraceable decisionsFailure isolationSelf-update commands
$ curl -fsSL https://raw.githubusercontent.com/mrzturn/opencode-switchman/main/scripts/setup.sh | bashor$ npx -y opencode-switchman@latest