dsh-autorouter 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,7 +4,15 @@ Notable changes to `dsh-autorouter`. The shape follows
4
4
  [Keep a Changelog](https://keepachangelog.com/) and the project uses semantic versioning.
5
5
  Every version below was a working bundle: the suite passes on each tagged commit.
6
6
 
7
- ## Unreleased
7
+ ## 0.2.1
8
+
9
+ - README rewritten in the house style of the sibling `research-team-preset` plugin: badge row,
10
+ at-a-glance table, install specs for both the plugins page and the CLI, first-run walkthrough,
11
+ one troubleshooting entry per symptom, and limitations stated as limitations.
12
+ - the Chinese translation now lives in `docs/README.zh-CN.md` and cross-links both ways; the root
13
+ `README.zh-CN.md` is gone, and `docs` ships in the package.
14
+
15
+ ## 0.2.0
8
16
 
9
17
  - **a fresh install ships no route plan**: `DEFAULT_PROFILE` is gone and
10
18
  `normalizeConfig` no longer re-adds default profiles, so nothing is routed until the
package/README.md CHANGED
@@ -1,225 +1,245 @@
1
- # AutoRouter (`dsh-autorouter`)
1
+ # AutoRouter
2
2
 
3
- English | [简体中文](README.zh-CN.md)
3
+ [![powered by dsh](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-ai/deepseek-harness) [![DSH 0.2.x](https://img.shields.io/badge/DSH-0.2.x-4D6BFE?style=flat-square)](https://github.com/deepseek-ai/deepseek-harness) [![license MIT](https://img.shields.io/badge/license-MIT-green?style=flat-square)](LICENSE)
4
4
 
5
- A DSH plugin that folds the provider/model routes **already registered in DSH** into one
6
- virtual provider, `AutoRouter`, so DSH itself only ever sees the single route `autorouter`.
5
+ **A DSH plugin that makes every provider and model you already registered look like one provider, with a fallback chain behind it.**
7
6
 
8
- It does not proxy HTTP and it does not hold keys. Every upstream attempt is dispatched
9
- through DSH's own `llm.stream()`, so each vendor's dialect, credentials, images and
10
- attachments, tool history and replay state stay with the adapter that already knows them.
7
+ **Version 0.2.1** · **Updated 2026-11-26**
11
8
 
9
+ <p align="center"><strong>English</strong> · <a href="docs/README.zh-CN.md">简体中文</a></p>
10
+
11
+ ---
12
+
13
+ ## Overview
14
+
15
+ AutoRouter registers one native DSH provider, `autorouter` (shown as **AutoRouter**), and routes each request along a chain of routes that already exist in the host. You keep using the credentials, dialects and model registrations DSH already knows; AutoRouter only decides which registered route serves this request, and what to do when that route fails.
16
+
17
+ It is not a proxy. Every attempt is dispatched through DSH's own `llm.stream()` to the provider that owns it, so images, attachments, tool history and replay state stay inside the adapter that understands them. There is no HTTP hop, no second key store, and no translation layer that could lose a field.
18
+
19
+ The plugin also owns the settings page under **Settings → AutoRouter**, where the chain, the per-window chains, the cooldowns and the live status are edited. Nothing about routing is hidden in a config file you have to hand-edit.
20
+
21
+ ## At a glance
22
+
23
+ | | |
24
+ | --- | --- |
25
+ | **Visible surface** | One provider id, `autorouter`; one picker row per profile, `AutoRouter / <profile>` |
26
+ | **Routing** | The chain array is the order: top to bottom, first usable route wins. No weights, no cost or quality scoring |
27
+ | **Failover** | Only before the first output block; `block-start` and any content delta commit the attempt. After that a failure is forwarded, not switched |
28
+ | **Spend accounting** | `usage` never commits an attempt; it is buffered and replayed before a switch, so the number never disappears |
29
+ | **Quota** | No local budget. The upstream's 429 and the per-route failure count are the signal; a route that keeps failing cools down |
30
+ | **Reasoning effort** | Inherited: the virtual model advertises the union of the chain's efforts, each attempt maps the request onto the target, clamping by default |
31
+ | **Time windows** | A window is a name for one or more disjoint stretches of the day, and owns a **complete fallback chain** of its own |
32
+ | **Sessions** | Sticky by `sessionId` for the sticky TTL, which keeps the upstream prompt cache warm |
33
+ | **Runtime** | A native `LlmAdapter`; every attempt is a nested `llm.stream()` on an already registered route |
34
+
35
+ ## Who it is for
36
+
37
+ - Setups with several routes for the same job — a subscription, a cheap mirror, an account with its own quota — where you want one picker entry instead of switching by hand.
38
+ - Work that must survive a route going down mid-project: `AUTH`, `QUOTA`, `RATE_LIMIT` and network failures move to the next route without touching the session.
39
+ - Anyone who wants the peak/off-peak ordering of the same routes to follow the clock instead of a manual switch.
40
+ - Users who would rather have the plan edited in a settings page than in YAML.
41
+
42
+ **Not for:** a single provider with a single key. Adding a chain of one only adds a layer; point the model at the route directly. It is also not a way to multiply one provider's quota — DSH binds one credential per route, so a "key pool" is a list of routes, each with its own credential.
43
+
44
+ ## Requirements
45
+
46
+ AutoRouter is a **profile-level DSH bundle**. It installs nothing else and enables nothing else: the routes it walks are the ones your profile already has.
47
+
48
+ | Capability | Provider | Notes |
49
+ | --- | --- | --- |
50
+ | DSH | [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) `0.2.x` | Developed against `0.2.2-rc.3`; the LLM service contract it uses (`registerAdapter`, `resolveModelInfo`, `prepareCall`) is stable across the series |
51
+ | At least one registered route | your own provider rows | `autorouter` walks `llm.listProviders()`; a route with no credential resolves but fails at request time |
52
+ | Node | `>= 22` | The host runs it; only matters when you test the package outside DSH |
53
+
54
+ **Optional:** a fallback-chain plugin such as `dsh-llm-fallbacks` is not required and not used. If both are installed they are independent providers; keep one of them in the picker to avoid routing the same request through two layers.
55
+
56
+ If the profile has no route with a working credential, AutoRouter still loads and the settings page still works — the `试一次` button reports the upstream failure that a real request would get.
57
+
58
+ ## Install
59
+
60
+ AutoRouter ships as a DSH bundle and is published on npm as `dsh-autorouter`.
61
+
62
+ ### Install from the DSH plugins page
63
+
64
+ 1. Open **Settings → Plugins** and click **Add**.
65
+ 2. Paste the install spec: `dsh-autorouter@0.2.1` for the npm package, `github:ZhanRuiXin/dsh-autorouter#v0.2.1` to pin the source, or `link:/absolute/path/to/dsh-autorouter` for a local checkout.
66
+ 3. **Restart DSH.** The host half registers the adapter and the HTTP routes at startup; the client half loads with the page.
67
+ 4. Open **Settings → AutoRouter**, create a profile, and add the routes you want in the chain.
68
+
69
+ ### Install from the CLI
70
+
71
+ ```text
72
+ dsh plugin add dsh-autorouter@0.2.1
12
73
  ```
13
- DSH ──► autorouter/<profile> ──► fallback chain
14
- ├─ opendesign/deepseek-v4.1-flash-eco
15
- ├─ commandcode/deepseek/deepseek-v4.1-flash
16
- └─ deepseek-account/deepseek-flash
74
+
75
+ To pin the source instead of the registry:
76
+
77
+ ```text
78
+ dsh plugin add github:ZhanRuiXin/dsh-autorouter#v0.2.1
17
79
  ```
18
80
 
19
- ## What it does
20
-
21
- - **One virtual route, many upstreams**: `AutoRouter / auto`, plus as many extra profiles as
22
- you want — one profile is one chain.
23
- - **Switches only before the first output block**: `block-start`, text, reasoning and
24
- tool-call deltas all commit the attempt; a failure after that is forwarded as-is instead of
25
- switching. `usage` does not commit, but it is buffered and replayed before a switch, so the
26
- spend is never lost.
27
- - **Cooldown and recovery**: a failed route cools down (honouring `Retry-After` when the
28
- upstream sends one, with half-open recovery), and a cooling route never enters the
29
- candidate set. AutoRouter keeps no request budget: the upstream's 429 is the real quota
30
- signal, and a local ledger only invents rate limits nobody can see.
31
- - **The settings page is the UI**: chain editing, cooldown, trigger codes, time windows,
32
- reasoning-effort mapping and live status all live under **Settings → AutoRouter**. Cards
33
- collapse (the state is remembered in `localStorage`), and every write still goes through the
34
- revision-checked settings document.
35
- - **Session stickiness**: the same `sessionId` prefers the route that served it last, which
36
- keeps the upstream prompt cache warm; a route is only re-chosen when the session passes its
37
- TTL or that route fails.
38
- - **Reasoning effort is inherited**: the virtual model advertises the union of the efforts
39
- declared along the chain; each attempt resolves the requested effort through
40
- `effortMap` → the target's `defaultEffort` → omit, clamping by default (switchable to
41
- `fail` or `drop`). If an upstream answers `UNSUPPORTED_REASONING_EFFORT` anyway, the
42
- parameter is dropped and the same route is retried once.
43
- - **Capabilities take the intersection, or the conservative value**: input modalities are
44
- intersected, the context window is the smallest known one, and `toolUpdate` is declared
45
- `addition-only` as soon as one route in the chain requires it.
81
+ > The bundle is profile-level: installing it in one profile does not enable it in another, and the settings page appears only in the profile where the row is enabled.
46
82
 
47
- ## Install
83
+ ## First run
84
+
85
+ A fresh install ships **no route plan** on purpose: nothing is routed until you build a chain from the providers you actually have. Start by opening **Settings → AutoRouter**:
86
+
87
+ 1. **+ New profile** — the profile id becomes the model id (`auto` → `AutoRouter / auto`).
88
+ 2. **Add route** — pick a provider and a model from the registered ones. Repeat for each route; the order in the card is the order they are tried.
89
+ 3. **Save**. The header version line should read `host v0.2.1`; if it says the host has not reported a version, DSH is still running the old process.
90
+ 4. **Try once** on the status tab. It sends one real minimal request through `autorouter/<profile>` and reports the route that served it, the elapsed time and the text.
91
+ 5. Pick `AutoRouter / <profile>` in the model picker, or point `agent-default-model` at `{ "provider": "autorouter", "model": "auto" }`.
48
92
 
49
- This repository is installed into a profile with `link:`:
93
+ A typical chain, in the order it is tried:
50
94
 
51
- ```jsonc
52
- // %USERPROFILE%\.dsh\profiles\desktop\package.json (or $DSH_HOME/profiles/desktop/package.json)
53
- "dependencies": { "dsh-autorouter": "link:<path to this checkout>" },
54
- "dsh": { "profile": { "bundles": [ /* … other bundles … */, "dsh-autorouter" ] } }
95
+ ```text
96
+ AutoRouter / auto
97
+ ├─ opendesign/deepseek-v4.1-flash-eco cheap mirror, first when it is up
98
+ ├─ commandcode/deepseek/deepseek-v4.1-flash
99
+ └─ deepseek-account/deepseek-flash the account that must not be wasted
55
100
  ```
56
101
 
57
- DSH resolves `@deepseek-ai/*` for a plugin only when that plugin declares them in
58
- `peerDependencies`. This package therefore declares `@deepseek-ai/schemastery` and
59
- `@deepseek-ai/dsh-llm`; without them the process reports
60
- `Cannot find package '@deepseek-ai/schemastery'` and the plugin row stays `inactive`
61
- (`cordis_inspect` will not show its Config as `schema`).
102
+ ## How a request is routed
103
+
104
+ Candidate selection is `chain order → usability → active time window → sticky pin`. Usability drops a route that is cooling down; the window reorders what is left; the sticky pin moves the route that served this session last to the front.
105
+
106
+ An attempt is committed the moment the adapter yields `block-start`, text, reasoning or a tool-call delta. Before that, a terminal failure with a trigger code (`AUTH`, `QUOTA`, `RATE_LIMIT`, `NETWORK`, and the HTTP statuses in the trigger list) moves to the next route. After it, the failure is forwarded exactly as the upstream reported it: a half-streamed answer is never silently restarted on another provider.
107
+
108
+ A route that fails is booked and cools down (`cooldownMs`, `5` minutes by default, with optional jitter). Retry-After from the upstream is honoured when `honorRetryAfter` is on. Repeated failures inside `failureWindowMs` back off exponentially up to `backoffMaxMs`. A cooling route is skipped, not removed, and comes back on its own; the **live status** tab lists each one and can clear a single cooldown.
109
+
110
+ `maxSwitches` is a fuse, not a target: the walk stops after that many switches in one step and reports the last failure instead of looping.
62
111
 
63
- Whether the settings page appears is decided by the schema, not by the profile row.
64
- `settings.describe()` only projects config that carries `meta.volatile`: `volatileForm()`
65
- returns `undefined` when it cannot find a volatile field anywhere in the schema, the entry is
66
- skipped entirely, and saving reports `no profile entry`. So `Config` must be marked live:
112
+ ## Reasoning effort
67
113
 
68
- ```js
69
- export const Config = z.object({ /* … */ }).extra('volatile', true)
114
+ DSH's default agent model carries `reasoningEffort: max`, and a chain mixes routes that declare different effort sets — or none at all. AutoRouter handles that instead of letting the request die before any I/O:
115
+
116
+ - The virtual model advertises the **union** of the efforts declared along the chain, so `max` stays selectable even if one route only declares `low` and `high`.
117
+ - Each attempt resolves the request as `entry.effortMap[effort]` → the target's declared `defaultEffort` → omit the parameter. `effortPolicy` decides what happens when the target cannot take it: `clamp` (default) uses the closest declared effort, `drop` omits it, `fail` refuses the attempt.
118
+ - A target that declares no reasoning at all is a known-no-reasoning target: the parameter is dropped rather than forwarded, because forwarding it makes DSH reject the call before the adapter runs. If an upstream still answers `UNSUPPORTED_REASONING_EFFORT`, the parameter is removed and the same route is retried once — a route is never abandoned for a parameter the caller could not have known about.
119
+
120
+ ## Time windows
121
+
122
+ A window is a label plus one or more `ranges` of local clock time, and it owns a complete ordering of the profile's routes. Hitting any of its ranges makes it the active window, and its `order` becomes the chain. Routes the window does not list keep their configured position and run last, so a window can never empty the candidate set.
123
+
124
+ ```text
125
+ deepseek-offpeak 00:30–08:30, 22:00–23:30 deepseek-account/* first, everything else after
126
+ default order the chain as edited on the default tab
70
127
  ```
71
128
 
72
- The row inserted by the bundle's own patch has the id `include:llm-autorouter`, and
73
- `describe()` reuses that id as its `ns`. The host side therefore matches `llm-autorouter`,
74
- then `include:llm-autorouter`, then `*:llm-autorouter`, instead of hard-coding one name.
75
- Adding a profile row of the same name is not required, but it lets you override the default
76
- `config`:
129
+ Ranges are half-open (`from` inclusive, `to` exclusive) and wrap when `from > to`; `from === to` means all day. Local time is the profile's `utcOffsetMinutes` (UTC+8 by default), so the plan does not shift when the machine's zone changes. A legacy single `{ from, to }` is folded into one range automatically.
130
+
131
+ In the settings page the window buttons sit above the chain: pick a button and the arrows reorder **that window's** chain; pick `default order` to edit the chain used when no window matches. A new window starts as a copy of the current chain.
132
+
133
+ ## The settings page
134
+
135
+ Three tabs, nothing else:
136
+
137
+ - **Routes** — one card per profile, the card head is the expand/collapse control. Inside, three sections separated by hairlines: **chain**, **time windows**, **policy**. There is no "selected profile": every setting lives in the card it belongs to, so a change can never land on a profile you were not looking at.
138
+ - **Live status** — cooldowns and failure counts per route, the sticky sessions, the request counters, `Try once`, and the `host vX.Y.Z` line. It is deliberately not on the routes tab: editing a chain should not have a table ticking every two seconds next to it.
139
+ - **JSON** — the whole configuration, editable, folded back into the form on apply.
140
+
141
+ **Save** is always clickable and answers with the configuration that was actually written, then refreshes the page from the server. **Undo** is the local inverse: it drops unsaved edits and restores the last saved configuration without a network round trip. Writes go through `settings.replace(ns, value, revision)`, so a stale tab gets `409` instead of overwriting someone else's save.
142
+
143
+ ## Where settings are stored
144
+
145
+ The configuration lives in the profile patch row that the bundle inserts, and the settings page writes it back there:
77
146
 
78
147
  ```yaml
79
148
  - id: llm-autorouter
80
149
  name: dsh-autorouter
81
- config: {}
150
+ config:
151
+ enabled: true
152
+ profiles:
153
+ - id: auto
154
+ name: Auto
155
+ chain: [ … ]
156
+ policy: { maxSwitches: 8, cooldownMs: 300000, sticky: true, … }
82
157
  ```
83
158
 
84
- Once it is installed (or after files change), recompose the plugin row:
85
- `plugin_manager set_plugin { target: "include:llm-autorouter", enabled: true }`.
86
- That only recomposes the bundle row — a change to host-side JS still needs a process restart,
87
- while a client-bundle change only needs a page refresh. After restarting DSH:
88
-
89
- 1. **Settings → AutoRouter** shows the settings page;
90
- 2. the model picker lists `AutoRouter / auto`;
91
- 3. pick it, or point `agent-default-model` at `{ provider: "autorouter", model: "auto" }`.
92
-
93
- ## Settings page
94
-
95
- The page has exactly three tabs: **routes**, **live status** and **JSON**.
96
-
97
- - **Routes**: one card per profile, and the card head is the expand/collapse control
98
- (clicking the title works too). Inside, three sections separated by hairlines — **chain**,
99
- **time windows** and **policy** — are all visible and collapse with the card; there is no
100
- longer any need to "select" a profile first, and no floating settings block outside a card.
101
- Above the chain sits a row of window buttons (`default order` plus one per window). The
102
- button you pick decides which chain you are editing: the up/down arrows reorder **that
103
- window's own fallback chain**, while `default order` edits the chain used when no window
104
- matches. Routes a window does not list still run last as a fallback, so a window can never
105
- empty the candidate set. Routes are picked from the registered providers and models, and
106
- `Probe` only checks metadata reachability (list models plus resolve model info) — it does
107
- not send a real request.
108
- - **Live status**: cooldown and failure counts per route, stats and sticky sessions, with a
109
- per-route cooldown reset. It deliberately does not sit on the routes tab, so editing a chain
110
- is not disturbed by a table that ticks every two seconds.
111
- - **JSON**: edit the whole configuration and fold it back into the form.
112
-
113
- Two header buttons: **Save** is always clickable (you do not have to make a change first) and
114
- refreshes the configuration and version on the page as soon as it succeeds; **Undo** throws
115
- away unsaved edits and returns to the last saved configuration without talking to the server.
116
-
117
- The **live status** tab also has **Try once** in its top right corner: it sends one real
118
- minimal request through `autorouter/<profile>` (default prompt
119
- `Reply with the single word: ok`, `maxTokens` 24) and returns the route that served it, the
120
- elapsed time and the text, or the terminal reason when it fails. The status card shows
121
- `host vX.Y.Z` — the version the host itself reports. If it does not match `package.json`, DSH
122
- is still running the old process and host-side edits cannot have taken effect.
123
-
124
- The page talks to the host over same-origin `/api/autorouter/*`, and configuration writes
125
- still go through `settings.replace(ns, value, revision)`, so concurrent edits are protected
126
- (a 409 asks you to reload).
127
-
128
- ## Configuration
129
-
130
- The configuration lives in the `config` of the profile row `llm-autorouter` and is written
131
- back by the settings page. Normalisation happens in `normalizeConfig` in `src/config.js`:
132
- every number is bounded, illegal, self-referential or duplicate routes are dropped, and each
133
- profile needs at least one chain.
134
-
135
- ```jsonc
136
- {
137
- "enabled": true,
138
- "debug": false,
139
- "profiles": [{
140
- "id": "auto", "name": "Auto", "enabled": true,
141
- "policy": { "maxSwitches": 8, "cooldownMs": 300000, "sticky": true,
142
- "effortPolicy": "clamp", "contextPolicy": "min",
143
- "timeWindows": [
144
- { "id": "offpeak", "label": "off-peak",
145
- "ranges": [{ "from": "00:30", "to": "08:30" },
146
- { "from": "22:00", "to": "23:30" }],
147
- "order": ["deepseek-account/deepseek-flash"] }
148
- ] },
149
- "chain": [
150
- { "id": "od", "provider": "opendesign", "model": "deepseek-v4.1-flash-eco",
151
- "cooldownMs": 300000 },
152
- { "id": "cc", "provider": "commandcode", "model": "deepseek/deepseek-v4.1-flash",
153
- "cooldownMs": 300000 },
154
- { "id": "ds", "provider": "deepseek-account", "model": "deepseek-flash",
155
- "cooldownMs": 300000 }
156
- ]
157
- }]
158
- }
159
+ ```text
160
+ %USERPROFILE%\.dsh\profiles\<profile>\cordis.patch.yml ($DSH_HOME/profiles/<profile>/cordis.patch.yml)
159
161
  ```
160
162
 
161
- ## Routing order
163
+ - The row id is `llm-autorouter`; the bundle's own patch inserts it as `include:llm-autorouter`, and the host matches `llm-autorouter`, `include:llm-autorouter`, then `*:llm-autorouter` instead of hard-coding one name.
164
+ - The config schema must stay `volatile` (`z.object({…}).extra('volatile', true)`). `settings.describe()` only projects config with a volatile field; without it the entry is skipped and every save reports `no profile entry`.
165
+ - The JSON tab is the escape hatch for a hand-edited document; a field AutoRouter does not know is preserved, an illegal route is dropped by `normalizeConfig` rather than crashing the walk.
166
+ - Cooldowns, counters and sticky sessions are **in-process**: a restart clears them, and they describe failures seen on this machine, not the upstream's real quota.
167
+
168
+ ## Configuration reference
162
169
 
163
- The chain array **is** the try order: top to bottom, the first usable route wins. There is no
164
- weighted rotation and no quality or cost scoring. An attempt only advances to the next route
165
- when it fails **before any output** and its error code or HTTP status matches the trigger set;
166
- once the first content block arrives, the failure is reported as-is.
170
+ | Setting | Where | Notes |
171
+ | --- | --- | --- |
172
+ | `profiles[].id` | config | Becomes the model id: `autorouter/<id>`; also the display name in the picker |
173
+ | `profiles[].chain[]` | config | Ordered routes; `provider` + `model` must exist in the host. `cooldownMs` and `effortMap` are per route |
174
+ | `profiles[].policy.maxSwitches` | config | Fuse for one step; the walk stops instead of looping |
175
+ | `policy.cooldownMs` / `cooldownJitterRatio` | config | Cooldown after a booked failure, plus optional spread so routes do not come back in lockstep |
176
+ | `policy.sticky` / `stickinessTtlMs` | config | Session stickiness and how long a pin survives before the route is re-chosen |
177
+ | `policy.triggerCodes` / `triggerStatuses` | config | What counts as "switch to the next route"; anything else is forwarded |
178
+ | `policy.honorRetryAfter` / `retryOnNetwork` | config | Upstream `Retry-After`, and whether transport failures are retryable |
179
+ | `policy.effortPolicy` / `contextPolicy` | config | `clamp` / `drop` / `fail`; `min` / `max` for the advertised context window |
180
+ | `policy.timeWindows[]` | config | `{ id, label, ranges[], utcOffsetMinutes, order[] }`; `order` is the window's full chain |
181
+ | `/api/autorouter/*` | host | Same-origin HTTP surface used by the page; `auth: 'required'` on the existing DSH port |
167
182
 
168
- **Time windows** do not change the route set, only the order: the window matching local time
169
- (UTC+8 by default) has **its own fallback chain** — what is stored is a list of route keys in
170
- `order`, i.e. the complete ordering — and routes it does not list keep their configured
171
- position at the end as a fallback. One window may cover several **disjoint** stretches of the
172
- day (`ranges`, for example 00:30–08:30 plus 22:00–23:30); hitting any of them counts, and they
173
- share the one chain. A legacy single `{ from, to }` is folded into one range automatically, so
174
- no migration is needed.
183
+ ## How it works
175
184
 
176
- The settings page switches which chain you edit with the window buttons above the chain, so
177
- "a different fallback chain per time window" is simply a matter of picking a button and
178
- reordering. A new window starts as a complete copy of the current chain and is then ordered
179
- independently.
185
+ - **Adapter** — `src/adapter.js` extends `LlmAdapter` and registers the single provider `autorouter`. `listModels` returns one row per profile, `resolveModel` builds the virtual model info from the chain (effort union, smallest known context window, `toolUpdate` taken conservatively), and `stream` hands the request to the walk.
186
+ - **Walk** — `src/router/walk.js` iterates the candidates, dispatches each attempt as a nested `llm.stream()` on the real provider, buffers `usage`, and re-throws only when it is before any output. It owns the fuse, the parameter repair and the replay envelope.
187
+ - **Classify** — `src/router/classify.js` turns a terminal finish into a switch/skip/forward decision from the trigger set, the status code and the request-scoped codes DSH reports (a request that is too big is not a broken route).
188
+ - **Effort** — `src/router/effort.js` builds the union, resolves one attempt's effort and reports the coercion so the transcript can explain a dropped `max`.
189
+ - **State** — `src/state.js` holds cooldowns, failure windows, counters and session pins; everything is in-process and disposable.
190
+ - **HTTP + client** — `src/http.js` serves `/api/autorouter/{state,config,catalog,probe,cooldown,selection,try}`, `index.js` wires the adapter, the routes and the settings row, and `client.js` registers the settings section plus its nav icon.
180
191
 
181
- ## Host API
192
+ `src/config.js`, `src/state.js` and `src/router/*` do not import `@deepseek-ai/*`, so the routing core runs and tests outside DSH; `test/plugin.test.js` stubs the peers for the integration path, and `test/client-render.test.js` renders the real page with a small React double.
182
193
 
183
- | Method | Path | Purpose |
184
- | --- | --- | --- |
185
- | GET | `/api/autorouter/state` | revision, redacted configuration and runtime state (cooldowns, stats, sticky sessions) |
186
- | GET/PUT | `/api/autorouter/config` | read/write the configuration; PUT carries `{value, revision}` |
187
- | GET | `/api/autorouter/catalog` | registered providers and models (excluding `autorouter`) |
188
- | POST | `/api/autorouter/probe` | `{provider, model}` metadata reachability check |
189
- | POST | `/api/autorouter/cooldown` | `{key}` clears one cooldown, `{}` clears all |
190
- | GET | `/api/autorouter/selection` | current candidate order and blocking reason per profile |
194
+ ## Troubleshooting
191
195
 
192
- Every route is `auth: 'required'` and is served on the DSH port that already exists — no extra
193
- listener is opened.
196
+ ### The settings page saves, then shows the old values
194
197
 
195
- ## Known limitations
198
+ The page asks the host for the configuration right after saving, and the host used to answer from a projection that lagged the write. Version `0.1.9` fixed it: the save response carries the configuration that was written, and the page no longer refetches the draft afterwards. If you still see it, check the `host vX.Y.Z` line — a host older than `0.1.9` is running the old code path.
196
199
 
197
- - The assistant message source is recorded as `autorouter/<profile>`, so DSH does not retain
198
- the upstream `replayState`; every turn resends the full history (the upstream prompt cache
199
- still helps, but replay-style adapters get no delta).
200
- - Cooldowns and stats are in-process and reset when DSH restarts; they reflect failures
201
- observed on this machine, not the upstream's real quota.
202
- - The catalog only reflects models DSH has registered; nothing is probed over the network.
200
+ ### `no profile entry "llm-autorouter"` on save
203
201
 
204
- ## Development
202
+ `settings.describe()` had no entry for this plugin, so the write had nowhere to land. Two causes, in order of likelihood:
205
203
 
206
- ```bash
207
- node --test "test/*.test.js"
208
- ```
204
+ - the running host is older than `0.1.2`, which is when the config schema was marked volatile;
205
+ - the bundle is installed but not enabled in this profile.
209
206
 
210
- `src/config.js`, `src/state.js` and `src/router/*` do not depend on `@deepseek-ai/*`, so they
211
- unit-test outside DSH. `test/plugin.test.js` maps `@deepseek-ai/dsh-llm` and
212
- `@deepseek-ai/schemastery` to local stubs through `test/stubs/hooks.mjs`, which means
213
- `apply()`, the request/response cycle of the HTTP routes (including the 409 revision conflict)
214
- and the registration shape of `client.js` run under plain Node. `test/client-render.test.js`
215
- needs no browser: a tiny React double drives the real rendering code in `client.js`, tab by
216
- tab (chains and per-window fallback chains, live status, JSON, collapsed state, nav icon). The
217
- `useState` call order is pinned in `SETTINGS_STATE`, so inserting a hook fails the test instead
218
- of quietly rendering a different page, and a child component's initial state can be pinned with
219
- `react.override('ProfileCard', ['w'])` to render one window's chain.
207
+ Restart DSH after updating and confirm the row is enabled in **Settings → Plugins**.
220
208
 
221
- One real completion still has to be confirmed inside DSH.
209
+ ### No `AutoRouter` row in the model picker
210
+
211
+ The adapter is registered by the host half at startup. Restart DSH and reload the page; a client-only refresh cannot register a provider. If the row is still missing, `cordis_inspect` on the `llm` service should list `autorouter` among the providers.
212
+
213
+ ### The routes tab says there is no profile yet
214
+
215
+ That is the shipped default: a fresh install routes nothing. Use **+ New profile**, add routes, save. An existing configuration is never rewritten by an upgrade.
216
+
217
+ ### `Try once` answers 404
218
+
219
+ The `/api/autorouter/try` route only exists in `0.1.10` and later. Restart DSH on the current build; the page names this case explicitly instead of showing a generic failure.
220
+
221
+ ### A route fails with `UNSUPPORTED_REASONING_EFFORT`
222
+
223
+ Fixed in `0.1.12`: an effort the target cannot declare is dropped (or clamped) instead of being forwarded, and a route that still rejects the parameter is retried once without it. If you see it on a current build, the profile's `effortPolicy` is `fail` — that is the setting refusing the call on purpose.
224
+
225
+ ### A route stays in cooldown
226
+
227
+ Cooldowns are per route and per process. The **live status** tab shows the remaining time and clears a single route; a restart clears all of them. Nothing is persisted, so an upgrade or restart does not inherit a stale cooldown.
228
+
229
+ ## Known limitations
230
+
231
+ - The assistant message source is recorded as `autorouter/<profile>`, so DSH does not retain the upstream `replayState`. Every turn resends the full history; the upstream prompt cache still helps, but a replay-style adapter gets no delta. Preserving it needs a route-tagged envelope and a source rewrite, which the host contract does not expose today.
232
+ - Cooldowns, counters and sticky pins are in-process. A restart starts from zero, and the numbers describe this machine's experience, not the upstream's quota ledger.
233
+ - The catalog only lists what DSH has registered. Nothing is discovered over the network, so a provider that is out of favour but still registered stays selectable.
234
+ - The model picker shows `AutoRouter / <profile>`; the profile id is the model id, so renaming a profile changes the model a session must ask for.
235
+ - There is no HTTP facade: AutoRouter is a native adapter, not an OpenAI-compatible endpoint. A `baseURL` gateway that would let non-DSH clients share the same chain is a separate design (`DESIGN.md` §9) and is not implemented.
222
236
 
223
237
  ## License
224
238
 
225
- MIT — see [LICENSE](LICENSE).
239
+ MIT. See [LICENSE](LICENSE).
240
+
241
+ ## Acknowledgements
242
+
243
+ Built on [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) and [Cordis](https://github.com/cordiverse/cordis). The failover contract deliberately copies the one `dsh-llm-fallbacks` established — switch only before output, book failures, never restart a half-streamed answer — so a session behaves the same whichever router is in the picker.
244
+
245
+ Design notes, the host contract this plugin is built against, and the failure matrix live in [DESIGN.md](DESIGN.md); the release history is in [CHANGELOG.md](CHANGELOG.md).
@@ -0,0 +1,245 @@
1
+ # AutoRouter
2
+
3
+ [![powered by dsh](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-ai/deepseek-harness) [![DSH 0.2.x](https://img.shields.io/badge/DSH-0.2.x-4D6BFE?style=flat-square)](https://github.com/deepseek-ai/deepseek-harness) [![license MIT](https://img.shields.io/badge/license-MIT-green?style=flat-square)](../LICENSE)
4
+
5
+ **一个 DSH 插件:把你已经登记过的 provider 与 model 收成一个 provider,后面挂一条回退链。**
6
+
7
+ **版本 0.2.1** · **更新于 2026-11-26**
8
+
9
+ <p align="center"><a href="../README.md">English</a> · <strong>简体中文</strong></p>
10
+
11
+ ---
12
+
13
+ ## 概述
14
+
15
+ AutoRouter 注册一个原生 DSH provider `autorouter`(显示为 **AutoRouter**),把每个请求沿一条「已经存在于宿主里」的路由链走一遍。凭据、方言、模型登记都还是 DSH 原来那套;AutoRouter 只决定这次请求由哪条已登记路由接,以及那条路由失败之后怎么办。
16
+
17
+ 它不是代理。每次尝试都通过 DSH 自己的 `llm.stream()` 派发给拥有该路由的适配器,所以图片、附件、工具历史与 replay state 都留在懂它们的适配器里。没有 HTTP 中转,没有第二份密钥库,也没有会丢字段的翻译层。
18
+
19
+ 插件同时负责 **设置 → AutoRouter** 这一页:链、各时段自己的链、冷却与实时状态都在这里改。路由行为不会藏在只能手改的配置文件里。
20
+
21
+ ## 一览
22
+
23
+ | | |
24
+ | --- | --- |
25
+ | **对外的面** | 一个 provider id `autorouter`;每个档位在模型选择器里是一行 `AutoRouter / <档位>` |
26
+ | **选路** | 链数组就是顺序:从上到下,第一条可用路由获胜。没有权重,没有成本/质量打分 |
27
+ | **失败切换** | 只在第一个输出块之前;`block-start` 与任何内容增量都会提交本次尝试。提交之后的失败原样转发,不换路由 |
28
+ | **花费记账** | `usage` 从不提交尝试;它被缓存,切换前补发,所以数字不会凭空消失 |
29
+ | **额度** | 本地不设额度。上游的 429 与每条路由的失败计数才是信号;一直失败的路由进入冷却 |
30
+ | **思考强度** | 继承:虚拟模型公布链上 effort 的并集,每次尝试把请求折算到目标上,默认 clamp |
31
+ | **时间段** | 一个时段由名字加若干不连续的钟点区间组成,并且拥有**自己完整的一条回退链** |
32
+ | **会话** | 按 `sessionId` 粘性,在 TTL 内落回上次成功的路由,保住上游 prompt cache |
33
+ | **运行时** | 原生 `LlmAdapter`;每次尝试都是对已登记路由的一次嵌套 `llm.stream()` |
34
+
35
+ ## 适合谁
36
+
37
+ - 同一件事有多条路线——一份订阅、一个便宜镜像、一个自带额度的账号——而你想在模型选择器里只看到一个条目,而不是手动切。
38
+ - 项目跑到一半不能因为某条路由挂掉就停:`AUTH`、`QUOTA`、`RATE_LIMIT` 与网络失败会切到下一条,会话本身不用动。
39
+ - 希望同一批路由的峰谷顺序跟着时钟走,而不是每次手动调。
40
+ - 更愿意在设置页里点,而不是编辑 YAML。
41
+
42
+ **不适合:** 只有一个 provider、一把密钥的场景。只有一条路由的链只是多套一层,直接把模型指到那条路由即可。这也不是「把一份额度变成多份」的办法——DSH 一条路由绑一份凭据,所谓密钥池就是一串各有凭据的路由。
43
+
44
+ ## 依赖
45
+
46
+ AutoRouter 是**profile 级 DSH bundle**。它不安装也不启用别的东西:它走的路由就是你 profile 里已有的那些。
47
+
48
+ | 能力 | 提供方 | 说明 |
49
+ | --- | --- | --- |
50
+ | DSH | [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) `0.2.x` | 开发基线 `0.2.2-rc.3`;它用到的 LLM 服务契约(`registerAdapter`、`resolveModelInfo`、`prepareCall`)在整个 0.2 系列稳定 |
51
+ | 至少一条已登记路由 | 你自己的 provider 行 | `autorouter` 走 `llm.listProviders()`;没有凭据的路由能解析,但会在真正请求时失败 |
52
+ | Node | `>= 22` | 由宿主运行;只有脱离 DSH 测试时才需要关心 |
53
+
54
+ **可选:** 不要求也不使用 `dsh-llm-fallbacks` 之类的回退链插件。两个都装时它们是彼此独立的 provider;请只把其中一个放进模型选择器,免得同一个请求被两层各路由一次。
55
+
56
+ 如果 profile 里没有任何一条可用凭据,AutoRouter 仍然会加载、设置页仍然可用——**试一次** 会把真实请求会遇到的失败原因原样报回来。
57
+
58
+ ## 安装
59
+
60
+ AutoRouter 以 DSH bundle 发行,npm 包名 `dsh-autorouter`。
61
+
62
+ ### 从 DSH 插件页安装
63
+
64
+ 1. 打开 **设置 → 插件**,点 **添加**。
65
+ 2. 粘贴安装说明:npm 包用 `dsh-autorouter@0.2.1`,钉住源码用 `github:ZhanRuiXin/dsh-autorouter#v0.2.1`,本地检出用 `link:/absolute/path/to/dsh-autorouter`。
66
+ 3. **重启 DSH。** 宿主侧在启动时注册适配器与 HTTP 路由,客户端侧随页面加载。
67
+ 4. 打开 **设置 → AutoRouter**,新建档位,把你要的路由加进链。
68
+
69
+ ### 从 CLI 安装
70
+
71
+ ```text
72
+ dsh plugin add dsh-autorouter@0.2.1
73
+ ```
74
+
75
+ 钉住源码而不是 registry:
76
+
77
+ ```text
78
+ dsh plugin add github:ZhanRuiXin/dsh-autorouter#v0.2.1
79
+ ```
80
+
81
+ > 这是 profile 级 bundle:装进一个 profile 不会在另一个里启用,设置页也只出现在启用了这一行的 profile 里。
82
+
83
+ ## 第一次运行
84
+
85
+ 全新安装**故意不带任何路由方案**:在你用真实拥有的 provider 搭出链之前,它不路由任何请求。先打开 **设置 → AutoRouter**:
86
+
87
+ 1. **+ 新建档位** —— 档位 id 就是模型 id(`auto` → `AutoRouter / auto`)。
88
+ 2. **添加路由** —— 从已登记的 provider 与模型里挑。要几条就加几条,卡片里的顺序就是尝试顺序。
89
+ 3. **保存**。头部版本行应显示 `host v0.2.1`;如果显示宿主没有报告版本,说明 DSH 还在跑旧进程。
90
+ 4. 在实时状态页点 **试一次**:它通过 `autorouter/<档位>` 真发一条极小请求,返回命中的路由、耗时与文本。
91
+ 5. 在模型选择器里选 `AutoRouter / <档位>`,或把 `agent-default-model` 指到 `{ "provider": "autorouter", "model": "auto" }`。
92
+
93
+ 一条典型的链,按尝试顺序:
94
+
95
+ ```text
96
+ AutoRouter / auto
97
+ ├─ opendesign/deepseek-v4.1-flash-eco 便宜镜像,能用时先走它
98
+ ├─ commandcode/deepseek/deepseek-v4.1-flash
99
+ └─ deepseek-account/deepseek-flash 不能随便烧的那个账号
100
+ ```
101
+
102
+ ## 请求怎么被路由
103
+
104
+ 候选顺序是 `链顺序 → 可用性 → 命中的时段 → 粘性钉住`。可用性会剔除正在冷却的路由;时段重排剩下的;粘性命中时,把上次服务这个会话的路由提到最前。
105
+
106
+ 适配器一旦产出 `block-start`、文本、思考或工具调用增量,这次尝试就算提交。提交之前,带触发码(`AUTH`、`QUOTA`、`RATE_LIMIT`、`NETWORK` 以及触发列表里的状态码)的终态失败会切到下一条。提交之后,失败按上游原样转发:半截的回答绝不会在另一个 provider 上悄悄重来。
107
+
108
+ 失败会被记账并进入冷却(`cooldownMs`,默认 5 分钟,可加抖动)。`honorRetryAfter` 打开时尊重上游的 `Retry-After`;`failureWindowMs` 内反复失败会按 `backoffMaxMs` 封顶指数退避。冷却中的路由是被跳过而不是被删除,会自己回来;**实时状态** 页列出每一条,并能单独清掉。
109
+
110
+ `maxSwitches` 是保险丝而不是目标:一步之内切换到这个数就停下,报最后一次失败,而不是无限循环。
111
+
112
+ ## 思考强度
113
+
114
+ DSH 的默认 agent 模型带 `reasoningEffort: max`,而一条链上各路由声明的 effort 集合并不相同,有的干脆不声明。AutoRouter 自己消化这件事,而不是让请求在任何 I/O 之前就死掉:
115
+
116
+ - 虚拟模型公布链上声明过的 effort 的**并集**,所以即使某条路由只声明 `low`/`high`,`max` 依然可选。
117
+ - 每次尝试按 `entry.effortMap[effort]` → 目标声明的 `defaultEffort` → 省略参数 的顺序折算。目标接不住时由 `effortPolicy` 决定:`clamp`(默认)用最接近的已声明 effort,`drop` 省略,`fail` 放弃这次尝试。
118
+ - 完全不声明 reasoning 的目标算「已知没有 reasoning」:参数直接丢掉而不是转发,因为转发会让 DSH 在适配器运行前就拒绝调用。如果上游仍然回 `UNSUPPORTED_REASONING_EFFORT`,去掉参数后对同一条路由重试一次——绝不因为一个调用方无从知道的参数而放弃一条路由。
119
+
120
+ ## 时间段
121
+
122
+ 一个时段是一个标签加一到多个本地钟点区间(`ranges`),并且拥有这个档位路由的完整一种排序。命中任意一个区间它就是当前时段,它的 `order` 就是链。时段没列出的路由保持配置顺序排在最后兜底,所以一个时段永远不会把候选清空。
123
+
124
+ ```text
125
+ deepseek-offpeak 00:30–08:30、22:00–23:30 先走 deepseek-account/*,其余在后
126
+ 默认顺序 在「默认顺序」标签下编辑的那条链
127
+ ```
128
+
129
+ 区间是半开区间(含 `from`、不含 `to`),`from > to` 时跨午夜环绕,`from === to` 表示全天。本地时间取档位的 `utcOffsetMinutes`(默认 UTC+8),所以机器时区变了方案也不会漂。旧配置里的单个 `{ from, to }` 会自动折算成一段。
130
+
131
+ 设置页把时段按钮放在链的上方:点哪个按钮,上下箭头改的就是**那个时段**的链;点 `默认顺序` 改的是没有命中任何时段时用的链。新建时段时以当前链的一份副本作为起点。
132
+
133
+ ## 设置页
134
+
135
+ 只有三个标签:
136
+
137
+ - **路由链** —— 一个档位一张卡片,卡片头部即展开/收起。卡片内部用分隔线分成三块:**路由链**、**时间段**、**策略**。没有「当前选中档位」这个概念:每个设置都在它所属的卡片里,改动不可能落到你没在看的那个档位上。
138
+ - **实时状态** —— 每条路由的冷却与失败计数、粘性会话、请求计数、**试一次**,以及 `host vX.Y.Z` 那行。它故意不在路由链页:编辑链的时候不该有一张每两秒跳一次的表在旁边。
139
+ - **JSON** —— 完整配置,可直接改,应用后回填表单。
140
+
141
+ **保存** 随时可点,返回的是真正写进去的那份配置,随后再用服务器刷新页面。**撤销** 是保存的本地逆运算:丢弃未保存的改动、回到上次保存的配置,不发请求。写入走 `settings.replace(ns, value, revision)`,一个过期的标签页会拿到 `409`,而不是覆盖别人刚保存的内容。
142
+
143
+ ## 设置存在哪里
144
+
145
+ 配置就在 bundle 插入的那条 profile patch 行里,设置页也写回那里:
146
+
147
+ ```yaml
148
+ - id: llm-autorouter
149
+ name: dsh-autorouter
150
+ config:
151
+ enabled: true
152
+ profiles:
153
+ - id: auto
154
+ name: Auto
155
+ chain: [ … ]
156
+ policy: { maxSwitches: 8, cooldownMs: 300000, sticky: true, … }
157
+ ```
158
+
159
+ ```text
160
+ %USERPROFILE%\.dsh\profiles\<profile>\cordis.patch.yml ($DSH_HOME/profiles/<profile>/cordis.patch.yml)
161
+ ```
162
+
163
+ - 行 id 是 `llm-autorouter`;bundle 自带的 patch 以 `include:llm-autorouter` 插入这一行,宿主按 `llm-autorouter`、`include:llm-autorouter`、`*:llm-autorouter` 依次匹配,而不是硬编码一个名字。
164
+ - 配置 schema 必须保持 `volatile`(`z.object({…}).extra('volatile', true)`)。`settings.describe()` 只投影带 volatile 字段的配置;没有它这一项会被整个跳过,保存时报 `no profile entry`。
165
+ - JSON 标签是手改文档的逃生口:AutoRouter 不认识的字段会被保留,非法路由由 `normalizeConfig` 丢弃而不是让走查崩掉。
166
+ - 冷却、计数与粘性会话都是**进程内**的:重启清零,而且它们描述的是本机看到的失败,不是上游真实配额。
167
+
168
+ ## 配置参考
169
+
170
+ | 设置 | 位置 | 说明 |
171
+ | --- | --- | --- |
172
+ | `profiles[].id` | 配置 | 就是模型 id:`autorouter/<id>`,也是选择器里显示的名字 |
173
+ | `profiles[].chain[]` | 配置 | 有序路由;`provider` + `model` 必须存在于宿主。`cooldownMs` 与 `effortMap` 按路由设置 |
174
+ | `profiles[].policy.maxSwitches` | 配置 | 一步之内的切换上限,到点停下而不是循环 |
175
+ | `policy.cooldownMs` / `cooldownJitterRatio` | 配置 | 记账后的冷却,以及可选的抖动,避免多条路由同时回来 |
176
+ | `policy.sticky` / `stickinessTtlMs` | 配置 | 会话粘性与钉住的有效期,过期后重新选路 |
177
+ | `policy.triggerCodes` / `triggerStatuses` | 配置 | 什么算「切下一条」;其余原样转发 |
178
+ | `policy.honorRetryAfter` / `retryOnNetwork` | 配置 | 上游 `Retry-After`,以及传输失败是否可重试 |
179
+ | `policy.effortPolicy` / `contextPolicy` | 配置 | `clamp` / `drop` / `fail`;对外公布窗口取 `min` / `max` |
180
+ | `policy.timeWindows[]` | 配置 | `{ id, label, ranges[], utcOffsetMinutes, order[] }`;`order` 是该时段的完整链 |
181
+ | `/api/autorouter/*` | 宿主 | 页面用的同源 HTTP 面;在 DSH 已有端口上 `auth: 'required'` |
182
+
183
+ ## 实现方式
184
+
185
+ - **适配器** —— `src/adapter.js` 继承 `LlmAdapter`,注册唯一的 provider `autorouter`。`listModels` 每个档位返回一行,`resolveModel` 用链拼出虚拟模型信息(effort 并集、已知最小上下文窗口、保守的 `toolUpdate`),`stream` 把请求交给走查。
186
+ - **走查** —— `src/router/walk.js` 遍历候选,每次尝试都是对真实 provider 的一次嵌套 `llm.stream()`,缓存 `usage`,只在「还没有任何输出」时重试;保险丝、参数修复与 replay 信封都在这里。
187
+ - **判定** —— `src/router/classify.js` 依据触发集合、状态码与 DSH 的请求级错误码,把终态结果判成切换/跳过/转发(请求太大不是路由坏了)。
188
+ - **强度** —— `src/router/effort.js` 求并集、折算单次尝试的 effort,并报告折算原因,让对话能解释一次被丢掉的 `max`。
189
+ - **状态** —— `src/state.js` 持有冷却、失败窗口、计数与会话钉住,全部在进程内、可丢弃。
190
+ - **HTTP 与客户端** —— `src/http.js` 提供 `/api/autorouter/{state,config,catalog,probe,cooldown,selection,try}`,`index.js` 装配适配器、路由与设置行,`client.js` 注册设置分区与导航图标。
191
+
192
+ `src/config.js`、`src/state.js`、`src/router/*` 不 import `@deepseek-ai/*`,因此路由核心可以脱离 DSH 运行与测试;`test/plugin.test.js` 为集成路径桩掉 peer,`test/client-render.test.js` 用一套极小的 React double 渲染真实页面。
193
+
194
+ ## 排错
195
+
196
+ ### 保存后页面又显示回旧值
197
+
198
+ 页面在保存后会向宿主再要一次配置,而旧宿主是从一个落后于写入的投影里回答的。`0.1.9` 修掉了:保存的响应直接带上真正写进去的配置,页面之后不再用重新拉取的草稿覆盖它。如果仍然出现,看 `host vX.Y.Z` 那行——低于 `0.1.9` 的宿主跑的还是旧代码。
199
+
200
+ ### 保存时报 `no profile entry "llm-autorouter"`
201
+
202
+ `settings.describe()` 里没有这个插件对应的项,写入无处可落。按可能性排序:
203
+
204
+ - 正在跑的宿主低于 `0.1.2`,也就是配置 schema 被打成 volatile 的那个版本;
205
+ - bundle 装了但这个 profile 里没启用。
206
+
207
+ 更新后重启 DSH,并在 **设置 → 插件** 里确认该行已启用。
208
+
209
+ ### 模型选择器里没有 `AutoRouter`
210
+
211
+ 适配器由宿主侧在启动时注册。重启 DSH 并刷新页面;只刷新页面注册不了 provider。若仍然没有,用 `cordis_inspect` 查 `llm` 服务的 provider 列表里是否出现 `autorouter`。
212
+
213
+ ### 路由链页说「还没有档位」
214
+
215
+ 这是出货默认值:全新安装不路由任何东西。用 **+ 新建档位** 加路由再保存。升级永远不会改写已存在的配置。
216
+
217
+ ### 试一次 返回 404
218
+
219
+ `/api/autorouter/try` 这条路由只在 `0.1.10` 之后存在。把 DSH 重启到当前版本;页面会明确提示这种情况,而不是给一个笼统的失败。
220
+
221
+ ### 某条路由报 `UNSUPPORTED_REASONING_EFFORT`
222
+
223
+ `0.1.12` 已修:目标接不住的 effort 会被丢弃(或 clamp)而不是转发,仍然被拒的会在去掉参数后对同一路由重试一次。如果你在较新版本上还看到它,说明该档位的 `effortPolicy` 是 `fail`——那是设置在按你的意愿拒绝这次调用。
224
+
225
+ ### 某条路由一直在冷却
226
+
227
+ 冷却是按路由、按进程的。**实时状态** 页显示剩余时间并能单独清掉;重启会清空全部。它不持久化,所以升级或重启不会继承一个陈旧的冷却。
228
+
229
+ ## 已知限制
230
+
231
+ - 助手消息来源记为 `autorouter/<档位>`,因此 DSH 不会保留上游的 `replayState`:每轮重发完整历史,上游 prompt cache 仍有帮助,但 replay 型适配器拿不到增量。要保住它需要「按路由打标签的信封 + 改写 source」,而目前的宿主契约没有暴露这一层。
232
+ - 冷却、计数与粘性钉住都在进程内:重启从零开始,数字是本机体验而不是上游配额账本。
233
+ - catalog 只列出 DSH 已登记的模型,不做联网发现,所以一个不常用但仍然登记着的 provider 依然可选。
234
+ - 模型选择器显示 `AutoRouter / <档位>`;档位 id 就是模型 id,改档位 id 就等于改会话要请求的模型。
235
+ - 没有 HTTP 门面:AutoRouter 是原生适配器,不是 OpenAI 兼容端点。让非 DSH 客户端共用同一条链的 `baseURL` 网关是另一套设计(`DESIGN.md` 第 9 节),尚未实现。
236
+
237
+ ## 许可
238
+
239
+ MIT,见 [LICENSE](../LICENSE)。
240
+
241
+ ## 致谢
242
+
243
+ 构建在 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 与 [Cordis](https://github.com/cordiverse/cordis) 之上。失败切换的契约刻意沿用 `dsh-llm-fallbacks` 已经确立的那一套——只在输出前切换、给失败记账、绝不重启半截的回答——这样无论选择器里放的是哪个路由器,会话行为都一致。
244
+
245
+ 设计说明、本插件所依赖的宿主契约与失败矩阵见 [DESIGN.md](../DESIGN.md);版本历史见 [CHANGELOG.md](../CHANGELOG.md)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-autorouter",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "AutoRouter — one DSH provider in front of a fallback chain over every registered route, with reasoning effort inherited from the caller.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,9 +41,9 @@
41
41
  "locale",
42
42
  "icon.svg",
43
43
  "README.md",
44
- "README.zh-CN.md",
45
44
  "CHANGELOG.md",
46
- "LICENSE"
45
+ "LICENSE",
46
+ "docs"
47
47
  ],
48
48
  "scripts": {
49
49
  "test": "node --test test/*.test.js"
package/README.zh-CN.md DELETED
@@ -1,191 +0,0 @@
1
- # AutoRouter (`dsh-autorouter`)
2
-
3
- [English](README.md) | 简体中文
4
-
5
- 一个 DSH 插件:把**已经登记在 DSH 里的** provider/model 聚合成一个虚拟 provider
6
- `AutoRouter`,DSH 侧只看到 `autorouter` 一条路由。
7
-
8
- 它不代理 HTTP,也不接管密钥。每个上游尝试都通过 DSH 自己的 `llm.stream()` 派发,
9
- 所以各家的方言、凭据、图片/附件、工具历史与 replay state 仍由原来的适配器处理。
10
-
11
- ```
12
- DSH ──► autorouter/<profile> ──► 回退链
13
- ├─ opendesign/deepseek-v4.1-flash-eco
14
- ├─ commandcode/deepseek/deepseek-v4.1-flash
15
- └─ deepseek-account/deepseek-flash
16
- ```
17
-
18
- ## 能力
19
-
20
- - **一条虚拟路由,多条上游**:`AutoRouter / auto`(可再加 profile,每个 profile 是一条链)。
21
- - **只在首个输出块之前切换**:`block-start`、文本、思考、工具调用增量都会提交本次尝试;
22
- 提交后失败原样转发,不再换路由。`usage` 不提交,但会缓存并在切换前补发,花费不丢。
23
- - **冷却与恢复**:失败的路由进入冷却(可配 `Retry-After`、半开恢复),冷却中的路由不会进候选。
24
- AutoRouter 不设请求额度:配额由上游的 429 决定,本地账本只会制造看不见的限流。
25
- - **设置页即 UI**:链编辑、冷却、触发码、时段窗口、思考强度映射、实时状态都在
26
- **设置 → AutoRouter** 里完成,卡片可收起(折叠状态记在 `localStorage`),写回仍是带 revision 的 settings 文档。
27
- - **会话粘性**:同一 `sessionId` 优先落回上次成功的路由,保住上游 prompt cache;
28
- 会话超过 TTL 或该路由失败后才重新选路。
29
- - **思考强度继承**:虚拟模型公布链上所有路由的 effort 并集;每次尝试按
30
- `effortMap` → 目标 `defaultEffort` → 省略 的顺序折算,默认 clamp(可改 fail/drop)。
31
- 上游报 `UNSUPPORTED_REASONING_EFFORT` 时,去掉该参数对同一路由重试一次。
32
- - **能力取交集/保守值**:输入模态取交集,上下文窗口取已知最小值,`toolUpdate` 只要有
33
- 一个路由要求 `addition-only` 就声明 `addition-only`。
34
-
35
- ## 安装
36
-
37
- 本仓库通过 `link:` 安装进 profile:
38
-
39
- ```jsonc
40
- // %USERPROFILE%\.dsh\profiles\desktop\package.json (or $DSH_HOME/profiles/desktop/package.json)
41
- "dependencies": { "dsh-autorouter": "link:<本仓库的检出路径>" },
42
- "dsh": { "profile": { "bundles": [ /* … 其他 bundle … */, "dsh-autorouter" ] } }
43
- ```
44
-
45
- DSH 只在插件声明了 `peerDependencies` 时才会把 `@deepseek-ai/*` 解析到安装目录。
46
- 本包因此声明了 `@deepseek-ai/schemastery` 与 `@deepseek-ai/dsh-llm`;漏掉它们时
47
- 进程会报 `Cannot find package '@deepseek-ai/schemastery'`,插件行停在 `inactive`
48
- (`cordis_inspect` 的 Config 状态不会是 `schema`)。
49
-
50
- 设置页出现的硬性条件在 schema 上,不在 profile 行上。`settings.describe()` 只投影
51
- 带 `meta.volatile` 的配置:`volatileForm()` 在整棵 schema 里找不到 volatile 字段时
52
- 返回 `undefined`,该行就被整个跳过,保存时报 `no profile entry`。所以 `Config` 必须
53
- 标成活的:
54
-
55
- ```js
56
- export const Config = z.object({ /* … */ }).extra('volatile', true)
57
- ```
58
-
59
- bundle 自带的 patch 插入的行 id 是 `include:llm-autorouter`,而 `describe()` 的 `ns`
60
- 沿用这个 id;宿主侧因此按 `llm-autorouter`、`include:llm-autorouter`、
61
- `*:llm-autorouter` 依次匹配,而不是硬编码一个名字。profile 里再补一条同名行不是必需,
62
- 但可以覆盖默认 `config`:
63
-
64
- ```yaml
65
- - id: llm-autorouter
66
- name: dsh-autorouter
67
- config: {}
68
- ```
69
-
70
- 装好后(或改了文件后)对插件行触发一次重组即可:`plugin_manager set_plugin { target: "include:llm-autorouter", enabled: true }`。
71
- 这只重组 bundle 行;宿主机 JS 的改动仍要重启进程才会生效,client bundle 刷新页面即可。
72
- 重启 DSH 后:
73
-
74
- 1. 设置 → **AutoRouter** 出现设置页;
75
- 2. 模型选择器出现 `AutoRouter / auto`;
76
- 3. 选择它,或把 `agent-default-model` 指到 `{ provider: "autorouter", model: "auto" }`。
77
-
78
- ## 设置页
79
-
80
- 设置页只有三个标签:**路由链**、**实时状态**、**JSON**。
81
-
82
- - **路由链**:一个档位一张卡片,卡片的头部就是展开/收起按钮(点标题也能收起)。
83
- 卡片内部分成带分隔线的三块:**路由链**、**时间段**、**策略**,都直接可见,跟着卡片一起
84
- 收起或展开;不再需要先"选中"某个档位,也没有飘在卡片外面的独立设置块。
85
- 路由链顶部有一排时段按钮(`默认顺序` + 每个时段一个)。点哪个时段,就是在编辑**那个时段
86
- 自己的回退链**:上下箭头只改这个时段的顺序,`默认顺序` 改的是没有命中任何时段时用的链。
87
- 时段没列到的路由仍然排在最后兜底,所以一个时段永远不会把候选清空。
88
- 路由可从已登记 provider 与模型里选,
89
- `Probe` 只做元数据可达性检查(列模型 + 解析模型信息),不发真实请求。
90
- - **实时状态**:每条路由的冷却/失败计数、统计与粘性会话;可单独清冷却。它不在路由链页,
91
- 免得编辑链时被一张每 2 秒跳动的表打扰。
92
- - **JSON**:直接编辑完整配置再回填表单。
93
-
94
- 头部两个按钮:**保存**随时可点(不必先产生改动),成功后立即刷新页面上的配置与版本号;
95
- **撤销**丢弃未保存的改动、回到上次保存的配置,不再重新请求服务器。
96
-
97
- **实时状态**页右上角有 **试一次**:它会用 `autorouter/<档位>` 真实发一条极小请求(默认
98
- `Reply with the single word: ok`,`maxTokens` 24),返回命中路由、耗时与文本;失败时把终态
99
- 原因带回来。状态卡同时显示 `host vX.Y.Z` —— 页面拿到的是宿主自己报的版本,和 `package.json`
100
- 对不上就说明 DSH 还在跑旧进程,此时改宿主侧代码不会生效。
101
-
102
- 页面通过同源 `/api/autorouter/*` 与宿主通信,配置写入仍走
103
- `settings.replace(ns, value, revision)`,因此有版本冲突保护(409 时提示重载)。
104
-
105
- ## 配置
106
-
107
- 配置存放在 profile 行 `llm-autorouter` 的 `config` 里,由设置页写回。
108
- 归一化入口是 `src/config.js` 的 `normalizeConfig`:所有数值有边界,非法/自指/重复路由会被丢弃,
109
- 每个 profile 至少要有一条链。
110
-
111
- ```jsonc
112
- {
113
- "enabled": true,
114
- "debug": false,
115
- "profiles": [{
116
- "id": "auto", "name": "Auto", "enabled": true,
117
- "policy": { "maxSwitches": 8, "cooldownMs": 300000, "sticky": true,
118
- "effortPolicy": "clamp", "contextPolicy": "min",
119
- "timeWindows": [
120
- { "id": "offpeak", "label": "低谷",
121
- "ranges": [{ "from": "00:30", "to": "08:30" },
122
- { "from": "22:00", "to": "23:30" }],
123
- "order": ["deepseek-account/deepseek-flash"] }
124
- ] },
125
- "chain": [
126
- { "id": "od", "provider": "opendesign", "model": "deepseek-v4.1-flash-eco",
127
- "cooldownMs": 300000 },
128
- { "id": "cc", "provider": "commandcode", "model": "deepseek/deepseek-v4.1-flash",
129
- "cooldownMs": 300000 },
130
- { "id": "ds", "provider": "deepseek-account", "model": "deepseek-flash",
131
- "cooldownMs": 300000 }
132
- ]
133
- }]
134
- }
135
- ```
136
-
137
- ## 选路顺序
138
-
139
- 链数组就是尝试顺序:从头到尾,第一条可用路由获胜;没有加权轮换,也没有质量/成本打分。
140
- 一次尝试只有在**输出前**失败、且错误码或状态码命中触发条件时才会切到下一条;
141
- 一旦收到第一个内容块,失败会原样上报,不再切换。
142
-
143
- **时间段**不改路由集合,只换顺序:命中当前本地时间(默认 UTC+8)的窗口有**自己的一条回退链**
144
- (保存的是路由键列表 `order`,就是完整顺序),未列出的路由保持配置顺序排在最后兜底。
145
- 一个时段可以覆盖多个**不连续**的时间段(`ranges`,例如 00:30–08:30 加 22:00–23:30),
146
- 命中任意一段都算命中,它们共用同一条链;旧配置里单个 `{ from, to }` 会被自动折算成一段,
147
- 不需要迁移。
148
- 设置页在路由链卡片顶部用时段按钮切换要编辑的那条链,所以「不同时段用不同回退链」就是
149
- 在这几个按钮之间切换后调顺序。新建时段时会拿当前链的一份完整副本作为起点,之后各时段
150
- 独立排序,互不影响。
151
-
152
- ## 宿主接口
153
-
154
- | 方法 | 路径 | 说明 |
155
- | --- | --- | --- |
156
- | GET | `/api/autorouter/state` | revision、脱敏配置、运行时状态(冷却/统计/粘性会话) |
157
- | GET/PUT | `/api/autorouter/config` | 读/写配置;PUT 带 `{value, revision}` |
158
- | GET | `/api/autorouter/catalog` | 已登记的 provider 与模型(排除 `autorouter`) |
159
- | POST | `/api/autorouter/probe` | `{provider, model}` 元数据可达性检查 |
160
- | POST | `/api/autorouter/cooldown` | `{key}` 清除单条冷却,`{}` 清全部 |
161
- | GET | `/api/autorouter/selection` | 当前各 profile 的候选顺序与阻塞原因 |
162
-
163
- 全部路由 `auth: 'required'`,监听在 DSH 已有的端口上,不新开 listener。
164
-
165
- ## 已知限制
166
-
167
- - 助手消息的来源记为 `autorouter/<profile>`,上游的 `replayState` 因此不会被 DSH 保留;
168
- 每轮会重发完整历史(上游 prompt cache 仍有帮助,但 replay 型适配器拿不到增量)。
169
- - 冷却与统计是进程内的,重启 DSH 后清零;它们只反映本机观察到的失败,不是上游的真实配额。
170
- - catalog 只反映 DSH 已登记的模型,不做联网探测。
171
-
172
- ## 开发
173
-
174
- ```bash
175
- node --test "test/*.test.js"
176
- ```
177
-
178
- `src/config.js`、`src/state.js`、`src/router/*` 不依赖 `@deepseek-ai/*`,可以脱离 DSH 单测。
179
- `test/plugin.test.js` 用 `test/stubs/hooks.mjs` 把 `@deepseek-ai/dsh-llm` 与
180
- `@deepseek-ai/schemastery` 映射到本地桩,因此 `apply()`、六个 HTTP 路由的收发
181
- (含 409 revision 冲突)和 `client.js` 的注册形状也能在纯 Node 下验证。
182
- `test/client-render.test.js` 不需要浏览器:它用一套极小的 React double 驱动 `client.js`
183
- 里真正的渲染代码,按 tab 逐个跑(路由链与时段回退链、实时状态、JSON、折叠状态、导航图标)。
184
- `useState` 的调用顺序写进 `SETTINGS_STATE`,插入一个 hook 会直接失败,而不是悄悄画出另一个页面;
185
- 子组件的初始状态可以用 `react.override('ProfileCard', ['w'])` 固定,用来渲染某个时段的链。
186
-
187
- 一次真实补全仍要在 DSH 里确认。
188
-
189
- ## 许可
190
-
191
- MIT,见 [LICENSE](LICENSE)。