rea
morluto
Reverse engineer anything with agents, from app behavior down to native binaries.
2869949486/dsh-opencode-routing
dsh plugin: OpenCode Go control panel - account pool with automatic failover, quota routing that falls back to a DeepSeek official subscription on upstream limits and returns after 10 stable minutes, a current-route banner, upstream status with error codes, and a per-model usage dashboard (10 languages)
PROJECT TOPICS
INSTALL REFERENCE
dsh plugin --profile web add github:2869949486/dsh-opencode-routing
该命令指向仓库当前默认分支;尚无绑定当前 commit 的完整验证结果。
PROJECT README
English · 简体中文 · 繁體中文 · 日本語 · 한국어 · Русский
A DeepSeek Harness (dsh) plugin that merges two earlier plugins
into one package: an OpenCode account pool with automatic A→B failover and quota routing, plus a
per-account / per-model usage dashboard. Both live on a single Settings page, "OpenCode 账户与用量".
settings.section, refreshed every 60 s; a header card that answers "which route, peak or off-peak,
when is the next probe"; accounts can be added, edited, reordered and probed; the model table carries capability tags;
both tables pan by dragging; the UI speaks 10 languages (browser language wins).GET /opencode-usage.json (usage, ?refresh=1 forces a refresh) and
GET|POST /opencode-quota-router.json (pool and routing; actions below).npm i dsh-opencode-routing
The package ships its own cordis.patch.yml: it declares the opencode-go / opencode-free providers and a
single insert (id: opencode-router). The usage: and router: sub-objects hold each half's settings (both
halves own a path, so they cannot share one flat namespace).
- insert:
- id: opencode-router
name: 'dsh-opencode-routing'
config:
usageUrl: https://opencode.ai/inference/go/v1/usage
apiKeyRef: OPENCODE_API_KEY
usage:
path: /opencode-usage
plan: go
router:
path: /opencode-quota-router
routes:
- primary: { provider: opencode-go, model: deepseek-v4.1-flash }
fallback: { provider: deepseek-account, model: deepseek-flash }
Top-level keys apply to both halves (usageUrl, apiKeyRef, probeIntervalMs, …); keys inside a sub-object only
override that half.
llm/stream waterfall.agent.model.select()), so the durable request header and assistant source follow the chosen side.Pool order is usage order. Exactly one account is "current" at any time, and its key is mirrored into the credential
reference the provider reads (default OPENCODE_API_KEY). Switching accounts therefore needs no provider config
change: resolveApiKey runs on every streaming call, after the llm/stream router selects the account.
QUOTA / ACCOUNT_QUOTA / 429 once the official allowance is confirmed spent, or
on an auth-class error (AUTH, INVALID_CREDENTIAL, MISSING_CREDENTIAL, ACCOUNT_SIGN_IN_REQUIRED,
CLIENT_UPGRADE_REQUIRED), the current account is marked unusable (until the window resets, or for 30 minutes on
auth failure), routing moves to the next enabled account and retries the same step — the turn is never downgraded.fallback (DeepSeek account by default), with a
zero-token GET /inference/go/v1/usage probe every 30 minutes (or at the rolling window reset) that returns to the
plan automatically.router.fallbackOnCapacity: true, a 429 whose message matches
overloaded / at capacity / prefill_cap_refused / ttft_admission_refused falls back to the official
subscription even while the allowance is intact. The first probe after that fallback runs after
router.capacityFallbackDelayMs (60 s), because a capacity refusal clears in seconds to minutes. The Settings page
has a Switch to the official subscription / Switch back to OpenCode button; the same actions are available as
POST /opencode-quota-router.json {"action":"fallback"} and {"action":"primary"}.llm/stream call, so only a
primary attempt that has not produced a single chunk is rerouted. Once the first token is out, the stream belongs
to the caller and its failure is passed through unchanged (a half-written answer is never silently restarted) —
but the plan still moves, so the step retry lands on the official subscription instead of walking into the same
wall. Later steps follow the route through agent.model.select() alignment.router.recoveryProbeIntervalMs
(60 s), and only hands the traffic back after router.recoverStableMs (10 min) of consecutive successful probes.
One failed probe resets the window to zero. This is what stops a flapping upstream from switching back and forth on
every other request. A probe only proves the allowance endpoint answers — a rate-limited upstream answers it
perfectly well — so the window also requires OpenCode's published status to stop reporting our model as degraded
(recovery.blocked = "published" says that is what is holding it). When the feed itself is unreachable the probe
is all there is, and the window proceeds.OpenCode publishes the same verdict its status page shows as JSON: GET https://status.opencode.ai/api/status,
no authentication, refreshed about once a minute. It carries the overall verdict, one row per plan (Console, logs,
inference, Go, pay-as-you-go, free inference), one row per model with the reason and the live speed, and every
incident with its start time. The plugin reads it directly (Host side, cached for router.statusRefreshMs, 60 s
by default) and puts it beside the local probe in one upstream status card — probe on the left, published verdict
on the right, one refresh button in the head. The two cards of the previous version covered the same ground and are now
merged. While both halves are green the whole card folds into one line — verdict chips, age of the last probe, the two
buttons — and opens by itself the moment either half is not (2.12.0; a closed <details> costs 44 px instead of 300):
upstream reason reads "the upstream provider is degraded — not your key and not your allowance, switch to the
official subscription and keep working", because that is the actionable form of a Degraded badge.status.opencode.ai when the tooltip is not enough.recovery.blocked: probe or published).This is the difference between "my requests are failing" and "OpenCode says Go is degraded because of an upstream provider": the local probe knows that it failed, the published feed knows why, and only the second one tells you whether switching to the official subscription would help.
The first screen keeps only "which route", "is it peak right now", "how is the upstream", "how much allowance": everything else folds or de-duplicates. With the live data the page fell from ~2930 px to ~1050 px at 940 wide.
The first card on the Settings page answers three questions in one place — whose money the next sentence spends, whether that sentence is billed at peak, and when the router looks at the upstream again:
HH:MM:SS countdown to the flip and that flip's
Beijing wall-clock time. It follows the live route: OpenCode's calendar on the pool, DeepSeek's holiday-aware one on
the subscription. They disagree only on Chinese statutory holidays, and only then does a second row show both sides.An automatic switch — in either direction — drops a notice in the top-left corner of the main UI, under the logo, so nobody has to sit on the Settings page to find out:
It reads the same GET /opencode-quota-router.json every 20 seconds and only reacts to a change of mode, so the
first poll after a page load is not treated as a switch and refreshing never fabricates a notice.
DSH also renders its own retry strip (「1 个上游不可用 / opencode.ai: connect_timeout ×3 · 约 1s 后重试」). It is drawn by the frame, it is translucent, it cannot be closed, and it lands on top of the brand mark. The plugin does not patch the frame; it adopts that element in the DOM:
left: 112px), makes it fully opaque, caps it at 560px;Matching is textual (上游不可用 / upstream … unavailable / connect_timeout / 后重试), it only adopts the innermost
matching node, and it only walks up to four levels looking for a small fixed/absolute/sticky box, so page text is safe.
2.11.1 adds two things, both of them real failures seen in the wild:
opacity / left
with it, so the guard no longer applies a style once — it re-asserts on every mutation (including attributes), and a
dismissed notice cannot come back.fixed/absolute strips in the top 220px
(no dismissal yet means no hunting, so unrelated empty panels are left alone).The frame stamps a provider badge ("OpenCode Go", with an icon) onto the model trigger at the bottom of the composer. That badge describes the session's configuration, not the live route: while requests fall back to the subscription it still reads OpenCode Go, so the one place on screen that claims to say where traffic goes is wrong.
The plugin uses the frame's own extension point — conversation.input.model.label, a session-scoped single slot — and
replaces the label used by the trigger and the menu's current value. So:
DeepSeek V4.1 Flash);official fallback tag follows it, whose tooltip spells out that requests are
going to the DeepSeek subscription and that the tag vanishes with the route;No DOM patching and no frame edits: the model and its badge arrive as the slot's owner props, and the plugin simply chooses not to draw the badge.
The Settings page puts one status card for the upstream itself under the header card — local probe on the left, OpenCode's published verdict on the right, one refresh button in the shared head — above the account and model tables. It stays collapsed to a single line while both halves are green and opens by itself the moment either is not (2.12.0):
Two verdict chips — the local probe (正常 / 降级 (Degraded) / 回退中 / 恢复观察 / 未知) and the published one (正常 / 降级 / 中断 / 维护, rendered as 「官方 降级」). Hovering either (and the model pills below) explains in one sentence what that state means and what to do about it, e.g. rate limited — wait 1–10 minutes, use another account, or switch to the official subscription and keep working.
刷新 re-reads every account's usage and re-probes the upstream (POST {"action":"status"}). Opening the page
never probes, so the card shows the snapshot as of the last check.
One row per model: the classified code, how many failures happened this round, the HTTP status, and whether the model is quarantined. The last raw upstream message is kept for the tooltip.
The recovery countdown: while in fallback the card shows the progress bar towards the ten clean minutes, so "when do I get the plan back" has an actual number. A failed probe restarts the bar.
错误码与解决办法: a collapsible table listing every code the card can show, with the fix for each — rate limit, capacity, quota, payment, auth, missing key, sign-in, client upgrade, model unavailable, bad request, context overflow, timeout, server error, network error, content filter, and the unknown bucket.
A local-network row (2.11.0): it probes opencode.ai and api.deepseek.com side by side, states a verdict, and
carries a 重新自检 button (POST {"action":"netcheck"}, which bypasses the 30-second cache):
| Verdict | Meaning | What to do |
|---|---|---|
| 本机能连通 | both hosts answer | any throttling right now is upstream's own |
| 本机网络/代理有问题 | neither host answers | the break is local: Clash / TUN / corporate network / proxy |
| 本机 DNS 解析失败 | neither host resolves | point DNS at 223.5.5.5 or 1.1.1.1, restart Clash's DNS |
| 只有 OpenCode 连不上 | published API answers, opencode.ai does not | the break is OpenCode's side; switching subscription is right |
The probe is a HEAD request, and any HTTP answer counts as reachable (401 included): the question is whether the
path works, not whether you hold a key.
The verdict is deliberately sticky: two failures inside the 30-minute window read as 降级 even when a retry has already succeeded, because a model that fails and recovers on retry is exactly the flapping this card is meant to surface. Switching back to the pool (automatically or by hand) clears the marks and starts a fresh round.
The official /inference/go/v1/usage endpoint only returns rounded rolling / weekly / monthly percentages and
no per-model breakdown, while the plan meters each model separately (5 h = 20 % of the monthly allowance, week =
50 %, month = 100 %). So the page shows two sets of numbers:
$DSH_HOME/sessions for the last 40 days and only
counts assistant/message events whose provider starts with opencode, priced at the public rates (including
DeepSeek's 2× peak window). Usage from other tools has no local record."查看用量" opens a per-account dialog with the three windows, their reset times and the probe result (it probes that account only and never switches models).
The peak card reads the calendar of the route you are on — OpenCode's on the pool, DeepSeek's holiday-aware one on
the subscription — with the current period, an HH:MM:SS countdown to the flip and that flip's Beijing time; the two
calendars are shown side by side only on Chinese statutory holidays, the one case where they disagree (2.12.1 replaced the
24-hour strip with the countdown). Capability glyphs in the model table carry a tooltip explaining what the tag
means, the header links to the OpenCode Console subscription page, and a floating arrow returns to the top once you have
scrolled down. Every price cell shows the cached-input, uncached-input and output line, so a cached hit (the green row)
can be compared directly with what the official API would charge for the same tokens.
Prices are not hardcoded: the plugin reads OpenCode's public pricing table (pricingUrl, daily, cached in
$DSH_HOME/opencode-routing-pricing.json) and takes the plan price, every per-model rate and every monthly allowance
from it. POST /opencode-usage.json with {"action":"syncPricing"} forces a refresh; pricingSync: false keeps the
built-in table instead. The dialog follows the harness appearance setting (light / dark / follow system) by sampling the
painted page background, so it never lands dark-on-dark.
"编辑密钥" fetches the account's current key from GET /opencode-quota-router.json?key=<account id> and pre-fills the
input (a local-only endpoint; the list snapshot only ever carries a mask). Model names follow vendor casing
(deepseek-v4.1-flash → DeepSeek V4.1 Flash); vendors with a published brand mark render as an inline SVG, the rest
keep a letter badge. "下次探测" is a real timer (30 minutes by default) and the page re-renders every second, so it
counts down; opening the page only reads the snapshot and never triggers a probe.
"此刻用哪个更划算" is derived from the subscription leverage: Go charges $10 for $100 of list-priced allowance (≈ ¥710), so OpenCode always costs 10 % of the official price — 90 % cheaper. Real data never favours the official API.
The capability column comes from the same catalog endpoint (/inference/go/v1/models): modalities.input and
capabilities are rendered as text / image / video / audio / PDF, tool calls, reasoning, plus context length.
Zero-priced models show "无限" (unlimited).
DeepSeek's off-peak window is everything outside Beijing time Mon–Fri 09:00–12:00 and 14:00–18:00 (lunch break, nights, weekends and statutory holidays included) at exactly half the peak price. OpenCode only treats UTC Mon–Fri 01–04 and 06–10 as peak and ignores Chinese statutory holidays (anomalyco/opencode#53071, maintainer: "Go pricing follows our own schedule, not DeepSeek's holiday calendar.").
The plugin ships the 2026–2031 Chinese statutory holiday table. It is only applied to the official side when
holidayAware: true is set (usage.holidayAware); it defaults to off because OpenCode keeps charging peak on those
days. The table lives in usage.js as HOLIDAYS, and isChinaHoliday() can be called on its own.
The subscription price and its allowance can be overridden with usage.planPriceUsd / usage.planAllowanceUsd; the
discount on the page is derived from those two numbers, so a plan change from OpenCode is a config edit, not a patch.
GET /opencode-quota-router.json returns {version, mode, reason, cause, active, activeLabel, updatedAt, checkedAt, nextProbeAt, probeIntervalMs, usage, accounts[], quarantine[], routes[], lastFailure, upstream}; account keys are
always masked (hint). upstream is the status card's payload: {state, code, mode, cause, since, checkedAt, windowMs, lastFailure, recovery, models[], recent[]} where state is one of healthy / degraded / fallback /
recovering / unknown, code is one of rate_limit, capacity, quota, payment, auth, missing_key,
sign_in, upgrade, not_found, bad_request, context, timeout, server, network, filter, error, ok,
and recovery is {active, stableSince, stableForMs, requiredMs, remainingMs, attempts, lastProbeAt, probeIntervalMs}. official is the published-status card's payload: {ok, error, errorAt, url, fetchedAt, ageMs, stale, status, since, updatedAt, services[], active[], models[]} — status is the overall verdict
(operational / degraded / outage / maintenance / unknown), services[] is {id, status, reason, since}
for inference / go / payg / free (Console and logs are left out), models[] is {model, status, reason, service, ttftMs, tps} for each route's primary model, and active[] lists the still-open incidents as {id, service, status, reason, startedAt, models[]}. When the feed cannot be read, ok is false and error says why;
the card shows that and routing is untouched. POST to the same path with {action, ...}:
| action | arguments | effect |
|---|---|---|
add |
label?, key |
create an account (key ≥ 8 chars), store it and probe |
update |
id, label? / enabled? / key? |
rename, disable/enable, rotate the key |
remove |
id |
delete an account and its key (one is always kept) |
activate |
id |
switch to it now |
move |
id, direction: up\|down |
reorder |
probe |
id? |
probe every account (and refresh the status), or just one |
status |
— | re-probe the upstream and refresh the status card (the 刷新 button) |
reset |
— | clear the exhausted/auth marks and return to the pool |
fallback |
— | switch routing to the official subscription now |
primary |
— | switch routing back to the OpenCode pool now |
GET /opencode-usage.json returns {plan, configuredPlan, detectedPlan, holidayAware, peak, usage, accounts[], activeAccount, models[], totals}; ?refresh=1 forces a fresh official snapshot first.
UI strings live in DICT in client.js: zh (source), zh-tw, en, plus es / fr / de / pt / ja / ko /
ru (inlined from translation files by scripts/merge-i18n.mjs; a missing key falls back to en, then to the key
itself). localeOf() matches the browser language prefix and separates Simplified from Traditional Chinese.
node test.mjs
No model quota is required: fake context, fake credential store, fake webServer, and a local usage endpoint that answers per API key. Coverage: composite mounting, account adoption, single-model quarantine, A→B failover with key mirroring, per-account probing, whole-pool fallback, reset, settings-action validation, the usage view (capability tags, unlimited models, peak/off-peak maths, billing lines), the single-account degradation, the status card (classification of a 429 as a rate limit, the kept raw message, the failure counter), the published-status half (services, per-model rows, a broken feed costing freshness but not routing) and the recovery window (one clean probe is not enough, a failed probe restarts it, a degraded feed does not even start it, a full window switches back and the next request goes to the pool again), plus a limit that lands after the first token (not retried in place, but the step retry continues on the fallback route).
dsh-opencode-quota-router and dsh-opencode-usage-settings are its predecessors; everything they did is merged
here. Both are marked deprecated on npm and point at this package. Their GitHub repositories are retired; this one is
the single source.
Issues and pull requests are welcome — see CONTRIBUTING.md. Run node test.mjs before opening a PR.
MIT — see LICENSE.
CLASSIFICATION EVIDENCE
系统优先读取 GitHub Topics,再与站内分类词典和词根规则比对。当前命中: deepseek-harness。