dsh-autorouter 0.0.0-stage → 0.2.0

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 ADDED
@@ -0,0 +1,78 @@
1
+ # Changelog
2
+
3
+ Notable changes to `dsh-autorouter`. The shape follows
4
+ [Keep a Changelog](https://keepachangelog.com/) and the project uses semantic versioning.
5
+ Every version below was a working bundle: the suite passes on each tagged commit.
6
+
7
+ ## Unreleased
8
+
9
+ - **a fresh install ships no route plan**: `DEFAULT_PROFILE` is gone and
10
+ `normalizeConfig` no longer re-adds default profiles, so nothing is routed until the
11
+ operator builds a chain from the providers they actually have credentials for. The routes tab
12
+ explains the empty state, and an unknown model reports "no profile yet" instead of a
13
+ four-entry list. A configuration that already exists on disk is never rewritten.
14
+ - locale completeness is now a test, not a habit: both dictionaries must carry the same keys,
15
+ and every `t('…')` the page uses must exist in both.
16
+ - README is English-first with a Chinese translation next to it; the package gained a
17
+ licence, keywords and author metadata.
18
+
19
+ ## 0.1.15
20
+ - feat(ui): drop the gateway enable switch too
21
+
22
+ ## 0.1.14
23
+ - feat(ui): drop the per-profile enable switch
24
+ - docs: describe the post-restart self-check and the current behaviour
25
+
26
+ ## 0.1.13
27
+ - fix: never report a failed routed call as success
28
+
29
+ ## 0.1.12
30
+ - fix: drop an effort the target cannot declare instead of failing the call
31
+
32
+ ## 0.1.11
33
+ - fix: never hand the host metadata its validator rejects
34
+
35
+ ## 0.1.10
36
+ - feat: drop the peak/off-peak preset and let the page try one real request
37
+ - fix(ui): name the old-host case when the try check has no route
38
+
39
+ ## 0.1.9
40
+ - fix: answer a save with the written config, not a lagging projection
41
+ - feat: show which host build the page is talking to
42
+
43
+ ## 0.1.8
44
+ - feat: let one named time window cover several disjoint stretches
45
+
46
+ ## 0.1.7
47
+ - feat(ui): give every time window its own fallback chain
48
+
49
+ ## 0.1.6
50
+ - fix(ui): fold time windows and policy into the card as visible sections
51
+
52
+ ## 0.1.5
53
+ - feat(ui): keep windows and policy inside each profile card, split live status into its own tab
54
+
55
+ ## 0.1.4
56
+ - feat: drop the request budget and let the settings cards collapse
57
+ - chore: pin line endings to LF so a checkout never rewrites the sources
58
+ - fix(ui): drop the unlabelled selector dot from the profile card
59
+
60
+ ## 0.1.3
61
+ - feat: route strictly by chain order and add peak/off-peak time windows
62
+ - docs(ui): explain the request budget and drop dead weight labels
63
+ - fix: await settings.replace so a save response carries the new revision
64
+
65
+ ## 0.1.2
66
+ - fix: mark the Config schema volatile so settings.describe projects it
67
+
68
+ ## 0.1.1
69
+ - fix: declare @deepseek-ai peers so the linked bundle resolves at import
70
+ - test: boot apply() and client registration against stubbed peers
71
+ - docs: record the peerDependencies rule and the recompose-without-restart path
72
+ - fix(client): keep profile input focus, follow host dark scheme, add nav icon
73
+ - fix: resolve the settings row by entry id, follow the painted theme for select popups
74
+ - docs: the settings section needs a profile row
75
+
76
+ ## 0.1.0
77
+ - feat: AutoRouter provider with settings page, routing core and tests
78
+ - fix(http): probe provider directory shapes and keep conflict config live
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ruixin Zhan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,225 @@
1
- # Temporary Holding Version
1
+ # AutoRouter (`dsh-autorouter`)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English | [简体中文](README.zh-CN.md)
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`.
7
+
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.
11
+
12
+ ```
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
17
+ ```
18
+
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.
46
+
47
+ ## Install
48
+
49
+ This repository is installed into a profile with `link:`:
50
+
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" ] } }
55
+ ```
56
+
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`).
62
+
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:
67
+
68
+ ```js
69
+ export const Config = z.object({ /* … */ }).extra('volatile', true)
70
+ ```
71
+
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`:
77
+
78
+ ```yaml
79
+ - id: llm-autorouter
80
+ name: dsh-autorouter
81
+ config: {}
82
+ ```
83
+
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
+ ```
160
+
161
+ ## Routing order
162
+
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.
167
+
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.
175
+
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.
180
+
181
+ ## Host API
182
+
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 |
191
+
192
+ Every route is `auth: 'required'` and is served on the DSH port that already exists — no extra
193
+ listener is opened.
194
+
195
+ ## Known limitations
196
+
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.
203
+
204
+ ## Development
205
+
206
+ ```bash
207
+ node --test "test/*.test.js"
208
+ ```
209
+
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.
220
+
221
+ One real completion still has to be confirmed inside DSH.
222
+
223
+ ## License
224
+
225
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,191 @@
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)。
@@ -0,0 +1,13 @@
1
+ # The dsh-autorouter profile-bundle patch: ONE plugin row added over the
2
+ # profile's bundle stack (`dsh.profile.bundles` order, later layers win per
3
+ # row). The plugin needs the `llm`, `settings` and `webServer` services, which
4
+ # dsh-base already provides, so its position after the base bundles is enough.
5
+ #
6
+ # A patch replaces the targeted row's whole `config` rather than merging into
7
+ # it. This row ships neutral defaults (`normalizeConfig` fills the rest); the
8
+ # profile-layer `cordis.patch.yml` override wins and is what the Settings page
9
+ # writes through `settings.replace`.
10
+ - insert:
11
+ - id: llm-autorouter
12
+ name: 'dsh-autorouter'
13
+ config: {}