dsh-agent-router 1.9.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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +304 -0
  3. package/README.md +304 -0
  4. package/client.js +3061 -0
  5. package/cordis.patch.yml +20 -0
  6. package/docs/ARCHITECTURE_DIAGNOSIS_AND_PLAN.md +414 -0
  7. package/docs/DETAIL.ja.md +1 -0
  8. package/docs/DETAIL.md +1 -0
  9. package/docs/DETAIL.zh.md +1 -0
  10. package/docs/IMPLEMENTATION_PLAN.md +99 -0
  11. package/docs/ITERATION_PLAN_2026-11.md +377 -0
  12. package/docs/RELEASE.md +133 -0
  13. package/docs/RELEASE_CHECKLIST.md +88 -0
  14. package/docs/preview.svg +69 -0
  15. package/docs/preview.zh.svg +63 -0
  16. package/icon.svg +16 -0
  17. package/index.js +24 -0
  18. package/lib/classifier.js +405 -0
  19. package/lib/cli/discover.js +187 -0
  20. package/lib/cli/invoke.js +294 -0
  21. package/lib/cli/parsers.js +234 -0
  22. package/lib/cli/shared.js +145 -0
  23. package/lib/cli-runners.js +39 -0
  24. package/lib/config-limits.js +67 -0
  25. package/lib/config-normalize.js +147 -0
  26. package/lib/config-presets.js +89 -0
  27. package/lib/config-schema.js +347 -0
  28. package/lib/defaults.js +117 -0
  29. package/lib/diagnose-fallback.js +96 -0
  30. package/lib/error-classify.js +160 -0
  31. package/lib/eval-routing.js +96 -0
  32. package/lib/guardrails.js +70 -0
  33. package/lib/integrations.js +173 -0
  34. package/lib/job-runner.js +287 -0
  35. package/lib/ledger.js +360 -0
  36. package/lib/legacy-config.js +34 -0
  37. package/lib/model-capabilities.js +135 -0
  38. package/lib/model-score.js +65 -0
  39. package/lib/plugin.js +184 -0
  40. package/lib/profile-mount.js +524 -0
  41. package/lib/route-edit.js +82 -0
  42. package/lib/router/candidates.js +194 -0
  43. package/lib/router/catalog.js +121 -0
  44. package/lib/router/cli-select.js +84 -0
  45. package/lib/router/config-manager.js +122 -0
  46. package/lib/router/doctor.js +159 -0
  47. package/lib/router/local-models.js +126 -0
  48. package/lib/router/policy.js +61 -0
  49. package/lib/router/rpc.js +263 -0
  50. package/lib/router/system-prompt.js +29 -0
  51. package/lib/router/tools.js +1028 -0
  52. package/lib/router/util.js +99 -0
  53. package/lib/rpc-contract.js +46 -0
  54. package/lib/sessions.js +59 -0
  55. package/lib/task-queue.js +201 -0
  56. package/lib/tier-presets.js +595 -0
  57. package/lib/typert.host.js +79 -0
  58. package/lib/update-check.js +205 -0
  59. package/lib/worktree-lock.js +86 -0
  60. package/lib/worktree.js +268 -0
  61. package/locale/en.json +7 -0
  62. package/locale/ja.json +7 -0
  63. package/locale/zh.json +7 -0
  64. package/package.json +136 -0
  65. package/scripts/profile-maintenance.mjs +287 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
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.en.md ADDED
@@ -0,0 +1,304 @@
1
+ <div align="center">
2
+
3
+ # dsh-agent-router
4
+
5
+ **Route each task to the right model: one router for DSH native subagents and local agent CLIs**
6
+
7
+ [![CI](https://github.com/qingxuan233/dsh-agent-router/actions/workflows/ci.yml/badge.svg)](https://github.com/qingxuan233/dsh-agent-router/actions/workflows/ci.yml)
8
+ [![Node](https://img.shields.io/badge/node-%3E%3D24.9.0-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
9
+ [![DSH](https://img.shields.io/badge/DSH-0.2.2--rc.x-4f46e5)](https://github.com/deepseek-ai/deepseek-harness)
10
+ [![dependencies](https://img.shields.io/badge/runtime%20dependencies-0-0ea5e9)](#development--verification)
11
+ [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
12
+
13
+ [中文](README.md) | English
14
+
15
+ </div>
16
+
17
+ `dsh-agent-router` is a zero-runtime-dependency [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) plugin. It classifies task difficulty against configurable tiers (default T1–T4), then routes the work either to **DSH native subagents** or to local **Claude Code / Codex / Gemini / OpenCode** CLIs, with health cooldowns, failure escalation, session resume, Git worktree isolation, and a visual editor inside the DSH Plugin Detail page.
18
+
19
+ > In one line: **don't burn a frontier model on a light task, and don't hand a hard task to the cheapest model; queue DSH models and local CLIs through one policy.**
20
+
21
+ ---
22
+
23
+ ## Why
24
+
25
+ - **Cost and latency**: search, summaries, and doc edits do not need a flagship model; cross-module refactors and audits should not go to the cheapest one.
26
+ - **Capability boundaries**: DSH native subagents and external CLIs differ; manual switching loses context and sessions.
27
+ - **Control**: failed routes must fail over or escalate, repeated failures must cool down, and long jobs must run in the background, be cancelable, and resume later.
28
+ - **Visibility**: edit each tier's model chain in the Plugin Detail page instead of hand-writing YAML.
29
+
30
+ ---
31
+
32
+ ## Features
33
+
34
+ | Feature | Description |
35
+ |---|---|
36
+ | **Configurable tiers (default T1–T4)** | Default Light / Standard / Hard / Review presets; apply a 4/3/2-tier layout or add, remove, rename, and re-range tiers with custom routing chains and escalation targets. |
37
+ | **One chain for both executors** | DSH native models and `claude` / `codex` / `gemini` / `opencode` / `antigravity` (`agy`) CLIs share one ordered candidate chain. |
38
+ | **Adaptive CLI selection** | `cliSelection: adaptive` adds installed CLIs and re-ranks only the auto-added block by EWMA; your explicit chain is always tried top to bottom. |
39
+ | **Optional local models** | Only with `allowLocalModels: true` are already-registered local/self-hosted DSH providers (Ollama, LM Studio, vLLM, …) considered. Disabled by default. |
40
+ | **Cooldowns + escalation** | Exponential-backoff cooldowns; when a whole tier fails, escalation follows the configured next normal tier (default T1→T2→T3). |
41
+ | **Async background queue** | `background: true` uses a bounded queue (prefers DSH `ctx.jobs`), wakes the parent on completion, and supports cancel/progress. |
42
+ | **Session resume** | Persists `runId`, DSH child session ids, and CLI `session_id` / `thread_id` for follow-ups. |
43
+ | **Worktree isolation** | Auto-creates a temporary worktree for concurrent writes in a Git repo, with `inspect_worktree_diff` / `merge_worktree` / `cleanup_worktree`. |
44
+ | **Ecosystem links** | Optionally reads `dsh-cost-meter` budget/peak state and `dsh-context` pressure to prefer cheap or local routes. |
45
+ | **Visual config + diagnostics** | Manage global policy, tier layout, and every tier chain in-app, then run a one-click environment doctor. |
46
+
47
+ ---
48
+
49
+ ## Tools
50
+
51
+ | Tool | Purpose |
52
+ |---|---|
53
+ | `router_plan` | Classify and preview the ranked chain (confidence, blocked routes, cooldowns, EWMA/budget hints) without executing. |
54
+ | `router_dispatch` | Route and run a task with failover, escalation, background queue, session persistence, and worktree isolation. |
55
+ | `router_continue` | Continue a DSH child or CLI session by `run_id` or subagent name. |
56
+ | `router_status` | Inspect overview, runs, config, background jobs, worktree actions; `action: "doctor"` runs environment diagnostics. |
57
+
58
+ ---
59
+
60
+ ## Quick Start
61
+
62
+ ```bash
63
+ # Install from GitHub
64
+ dsh plugin --profile desktop add git+https://github.com/qingxuan233/dsh-agent-router.git
65
+
66
+ # Or link a local checkout for development
67
+ dsh plugin --profile desktop add link:/path/to/dsh-agent-router
68
+ ```
69
+
70
+ > The CLI above only writes the dependency and does not register `dsh.profile.bundles`. For a standard bundle mount, use `npm run profile:install` from the “Install modes” section below, or install from the DSH plugin page.
71
+
72
+ 1. **Fully restart DSH** after installing or switching package paths (client bundle and Typert RPC manifest are cached).
73
+ 2. Open **Plugins → Installed → dsh-agent-router**, pick a tier layout, and adjust each tier chain.
74
+ 3. Click **Save Configuration**; changes apply immediately without restart.
75
+ 4. If unsure, click **Run diagnostics**, or call `router_status` with `doctor`.
76
+
77
+ > Runtime: Node.js `>= 24.9.0`, DSH `>= 0.2.2-rc.1 < 0.3.0-0`.
78
+
79
+ ---
80
+
81
+ ## Install modes and duplicate-mount check
82
+
83
+ This plugin must be installed as a **standard bundle**: the dependency is listed in the profile `package.json` and in `dsh.profile.bundles`, and DSH applies the package's own `cordis.patch.yml`.
84
+
85
+ - Do **not** copy the package's `- insert:` block into the profile (or home-level) `cordis.patch.yml`. A manual mount makes DSH refuse uninstall with “其他配置仍在使用这个组合包的组件” (“other configs still use components from this bundle”).
86
+ - On a `manual` / `duplicate` mount, the Plugin Detail page shows a warning above the tier editor, startup logs include the profile path, and the `doctor` action reports a `mount` check.
87
+ - Repair: run `node node_modules/dsh-agent-router/scripts/profile-maintenance.mjs repair` in the profile directory (repo developers can use `npm run profile:repair`). Every file that changes is backed up to `$DSH_HOME/backups/agent-router-mount-<timestamp>/` first; the hand-written `- insert:` blocks are removed and the bundle registration is completed. **Fully restart DSH** afterwards.
88
+ - Read-only check: `npm run profile:check` from the repo, or `node node_modules/dsh-agent-router/scripts/profile-maintenance.mjs check` for installed users. Uninstall requires that no manual mount remains; `profile-maintenance.mjs uninstall` refuses and asks you to repair first.
89
+ - Fresh install or registration fix: from the repo, run `npm run profile:install -- --profile desktop --spec "github:qingxuan233/dsh-agent-router#main"`. It runs `pnpm add` and writes `dsh.profile.bundles`, matching a standard bundle install from the DSH plugin page.
90
+ - Note: `dsh plugin --profile desktop add ...` only writes the dependency and does **not** register `dsh.profile.bundles`; on its own it does not create a standard bundle mount in current DSH builds.
91
+
92
+ ---
93
+
94
+ ## Configuration
95
+
96
+ ### Global fields
97
+
98
+ | Field | Default | Description |
99
+ |---|---|---|
100
+ | `preferBackend` | `auto` | Global backend bias: `auto` / `dsh` / `cli` / a specific CLI name. |
101
+ | `autoEscalate` | `true` | Escalate to the next tier when every candidate in a tier fails. |
102
+ | `budgetGuard` | `true` | Use `dsh-cost-meter` budget data to prefer economical/local routes near the limit. |
103
+ | `peakAvoidance` | `false` | Prefer non-DeepSeek / local CLIs during DeepSeek 2x peak pricing. |
104
+ | `adaptiveRanking` | `true` | Adjust ordering with historical EWMA latency and success rate. |
105
+ | `cliSelection` | `static` | `static` follows the configured CLI chain; `adaptive` also adds installed CLIs and ranks only the auto-added block by history. |
106
+ | `allowLocalModels` | `false` | Include local/self-hosted DSH providers as candidates. |
107
+ | `localProviders` | `[]` | Explicit provider ids treated as local; empty means auto-detect by id/name/baseURL. |
108
+ | `defaultBackground` | `false` | Run external CLI dispatches in the background by default. |
109
+ | `useNativeJobs` | `true` | Prefer DSH `ctx.jobs`; fall back to the built-in queue when unavailable. |
110
+ | `maxConcurrentCli` | `3` | Max concurrent background CLI jobs. |
111
+ | `cooldownMs` | `180000` | Base cooldown after a failed route (exponential backoff). |
112
+ | `defaultTimeoutMs` | `300000` | Default CLI timeout. |
113
+ | `maxRuns` | `200` | Recent runs retained in the ledger. |
114
+ | `ledgerFile` | `~/.dsh/agent-router/state.json` | Optional custom ledger path. |
115
+ | `tierLayout` | `default` | `default` merges overrides over the built-in tiers; `custom` makes `tiers` authoritative so removed tiers stay removed. The UI writes `custom`. |
116
+ | `tiers.<id>` | built-in | Each tier has `name` / `description` / `role` (`normal` or `review`) / `minScore` / `maxScore` / `preferBackend` / `escalateTo` / `dsh[]` / `cli[]`. Ids start with a letter and may contain digits, `-`, `_`. |
117
+
118
+ ### Profile example
119
+
120
+ ```yaml
121
+ - id: agent-router
122
+ config:
123
+ preferBackend: auto
124
+ autoEscalate: true
125
+ cliSelection: adaptive
126
+ allowLocalModels: false
127
+ tiers:
128
+ T1:
129
+ preferBackend: dsh
130
+ dsh:
131
+ - { provider: deepseek-account, model: deepseek-chat }
132
+ T3:
133
+ preferBackend: auto
134
+ cli:
135
+ - { backend: claude, model: opus, effort: high }
136
+ ```
137
+
138
+ ### Enabling local models (optional)
139
+
140
+ ```yaml
141
+ - id: agent-router
142
+ config:
143
+ allowLocalModels: true
144
+ localProviders: [] # auto-detect ollama / lmstudio / vllm, or list ids explicitly
145
+ tiers:
146
+ T1:
147
+ preferBackend: dsh
148
+ dsh:
149
+ - { provider: ollama, model: qwen2.5-coder }
150
+ ```
151
+
152
+ The provider must already be **registered in DSH `ctx.llm`** and able to list models. The plugin never starts model servers, proxies requests, or stores credentials.
153
+
154
+ ---
155
+
156
+ ## Tier model (default T1–T4, configurable)
157
+
158
+ Without any config change the original four tiers still apply:
159
+
160
+ | Tier | Role | Score range | Typical work | Default strategy |
161
+ |---|---|---|---|---|
162
+ | **T1 Light** | normal | 0 – 1.5 | search, file scan, log summary, format conversion, simple Q&A | Low-cost Flash/eco models first, then fast CLIs. |
163
+ | **T2 Standard** | normal | 1.5 – 3 | scoped implementation, normal bugs, unit tests, scripts | Coding-specialized models or `codex` / `opencode` / `antigravity`. |
164
+ | **T3 Hard** | normal | 3 – no limit | cross-module refactors, complex algorithms, deep debugging | Frontier reasoning models or `claude opus`, balanced DSH/CLI. |
165
+ | **T4 Review** | review | excluded from score mapping | code review, security audit, cross-validation | Heterogeneous-family read-only/plan CLIs to avoid self-review. |
166
+
167
+ Classification uses review/code/research intent, hard-engineering keywords, task length, checklist size, and referenced file count. Negated hard signals and pasted code/log blocks are ignored, domain-specific weights keep read-only research lighter, and low confidence near the next normal-tier boundary promotes when several complexity signals agree (default remains T2→T3). Review intent only applies when the task contains no mutating action verb (fix / implement / update / remove, etc.), so “fix the bug found in review” is routed as a normal coding task; use an explicit review tier when you want a read-only pass. Output includes `tier`, `tierName`, `confidence`, `confidenceScore`, and explainable `signals`/`reasons`.
168
+
169
+ ### Tier layout presets
170
+
171
+ The Plugin Detail page offers three one-click layouts. Only names and score ranges change; tiers with the same id keep their model chains:
172
+
173
+ | Layout | Tiers | When to use |
174
+ |---|---|---|
175
+ | **Default 4-tier** | T1(0–1.5) / T2(1.5–3) / T3(3–∞) / T4(review) | Same behavior as the old version; recommended for most users. |
176
+ | **Compact 3-tier** | T1(0–2) / T2(2–∞) / T4(review) | Skip the middle tier but keep a dedicated review tier. |
177
+ | **Fast 2-tier** | T1(0–2.5) / T3(2.5–∞) | Only “fast” and “deep”; review intent falls back to the highest normal tier. |
178
+
179
+ ### Adding and removing tiers
180
+
181
+ - **Add**: enter a name and choose a template (blank normal / light / standard / hard / review). The plugin generates the id and score range; appending after an unbounded tier automatically caps that tier's upper bound.
182
+ - **Remove**: confirmation required; at least one normal tier must remain; any `escalateTo` pointing at the removed tier is rewritten to its escalation target or the next normal tier.
183
+ - **Review tier**: `role: review`; excluded from score mapping and only selected for review/audit intent. If several review tiers exist, the one that sorts first by id handles review intent (the others stay reachable via an explicit tier or an escalation target). If no review tier exists, review tasks use the highest normal tier.
184
+ - **Escalation**: the dropdown shows tier names; normal tiers may target any other tier, and review tiers default to no escalation.
185
+
186
+ ### Score ranges (advanced)
187
+
188
+ - Normal tiers use `[minScore, maxScore)`; leave `maxScore` blank for no upper limit.
189
+ - Ranges stay under “Advanced settings”; most users never need them. Overlapping ranges, duplicate names, invalid routes, and invalid escalation targets are repaired automatically and reported as auto-fixes on save/import; only issues that cannot be repaired safely (for example a map with no normal tier) are blocked.
190
+ - Hand-edited Profile YAML, legacy `state.json`, and UI imports share the same normalization rules, so a config that loads from YAML is no longer rejected when pasted into the import box.
191
+ - Gaps between ranges are allowed; ranges do not have to be contiguous.
192
+
193
+ ### Migrating from configVersion 1
194
+
195
+ Old configs (`configVersion: 1`, only T1–T4 chains) migrate automatically to `configVersion: 2`:
196
+
197
+ - Old `label` becomes `name`; `description`, `role`, `minScore`, and `maxScore` are filled in.
198
+ - T4 is recognized as the review tier (`role: review`) and is excluded from score mapping.
199
+ - Missing tiers are filled from the default four-tier preset; user `dsh` / `cli` / `preferBackend` / `escalateTo` values are preserved.
200
+ - Unknown fields are preserved. The first UI save writes `tierLayout: custom` plus the complete tier map; afterwards removed tiers stay removed.
201
+ - Migration happens in memory at startup, so the YAML may still show `configVersion: 1` until the first save; behavior is unaffected.
202
+
203
+ ---
204
+
205
+ ## Adaptive CLI selection
206
+
207
+ - **static (default)**: uses exactly each tier's `cli[]` order and only filters out missing CLIs.
208
+ - **adaptive**: on top of the configured chain it:
209
+ 1. appends installed CLIs that were not configured (tier-heuristic order);
210
+ 2. re-ranks only the auto-added block using EWMA latency and recent success;
211
+ 3. keeps your explicit CLI order top-to-bottom and never changes an explicit `model` / `effort`.
212
+ - Antigravity CLI ships as `agy`; the plugin maps the backend id automatically. Complete one interactive login before headless use.
213
+ - Every CLI must be installed and logged in by the user; the plugin only probes `PATH` and local config files, and never reads tokens.
214
+
215
+ ---
216
+
217
+ ## Diagnostics and troubleshooting
218
+
219
+ Click **Run diagnostics** in the Plugin Detail page, or ask the agent to call:
220
+
221
+ ```json
222
+ { "action": "doctor" }
223
+ ```
224
+
225
+ `router_status` checks the DSH `ctx.llm` catalog, `subagent-model-selection`, local CLIs, CLI selection mode, local models, `ctx.jobs`, `dsh-cost-meter`, the ledger, and the background queue, with actionable hints.
226
+
227
+ | Symptom | Checklist |
228
+ |---|---|
229
+ | Blank settings page / `service unavailable` | Fully restart DSH after upgrading; confirm the plugin is enabled; run diagnostics to verify RPC mounting. |
230
+ | Native subagents don't switch models | Enable `subagent-model-selection-settings` and add target models to `allowedModels`. |
231
+ | CLI shows as missing | Ensure the command is on `PATH` and logged in; on Windows the plugin resolves `.cmd` shims. |
232
+ | Local models never appear | Confirm the provider is registered in DSH `ctx.llm` and lists models; optionally set `localProviders`. |
233
+ | No worktree created | The directory is not a Git repo or writes are read-only; non-Git dirs fall back to normal execution. |
234
+ | Routes stay cooled down | Use `router_status` `clear_cooldowns`, and inspect recent failure reasons. |
235
+
236
+ ---
237
+
238
+ ## Scope and non-goals
239
+
240
+ **Fits**
241
+
242
+ - Routing between DSH native models and local agent CLIs by difficulty.
243
+ - Workflows that need failover, escalation, cooldowns, session resume, background jobs, and worktree isolation.
244
+ - Users who already have CLIs installed/logged in, or local/remote models registered in DSH.
245
+
246
+ **Not responsible for**
247
+
248
+ - **No model proxy**: no HTTP gateway, no API forwarding, no API-key management.
249
+ - **No model hosting/downloads**: local models must be registered and running in DSH first.
250
+ - **No DSH lifecycle replacement**: it only calls `startActivation` / `sendMessage`, obeying DSH depth, permission, and allowlist limits.
251
+ - **No CLI guarantee**: installation, login, quota, and version compatibility are the user's responsibility.
252
+ - **No business-code editing**: apart from what dispatched subagents/CLIs do, the plugin does not edit code.
253
+ - **Worktree only for Git repos**: bare repos or insufficient permissions fall back.
254
+ - **Not a generic job queue**: the background queue only serves this plugin's dispatches.
255
+
256
+ ---
257
+
258
+ ## Security and privacy
259
+
260
+ - The ledger lives at `~/.dsh/agent-router/state.json` (overridable via `ledgerFile`) and stores run status, cooldowns, and aggregate metrics.
261
+ - CLI discovery reads only model names and defaults from common config files, never credentials.
262
+ - Local-model detection is string matching on provider id/name/baseURL; it performs no network probing.
263
+ - Everything runs locally; the plugin has no telemetry or external reporting.
264
+
265
+ ---
266
+
267
+ ## Development & verification
268
+
269
+ ```bash
270
+ npm run build:client # regenerate client.js after editing client/src/
271
+ npm test # unit tests (classification, routing, queue, schema, doctor, …)
272
+ npm run verify # manifest, schema, locale, Typert parity, syntax
273
+ npm run release:check # version, market index, npm pack contents and size
274
+ npm run smoke:dsh # real DSH temporary-profile load smoke (auto-skips if dsh is absent)
275
+ npm run market:index # regenerate the local market index
276
+ ```
277
+
278
+ > This repository only performs local verification and artifact generation. `npm publish`, tagging, and market index deployment require explicit maintainer approval. See [docs/RELEASE.md](docs/RELEASE.md).
279
+
280
+ ### Repository layout
281
+
282
+ | Path | Purpose |
283
+ |---|---|
284
+ | `index.js` | Host entry: `apply` / `inject` / tool registration |
285
+ | `lib/` | Router core: classification, tiers, config, candidates, sessions, ledger |
286
+ | `lib/router/rpc.js` | RPC service exposed to the browser client |
287
+ | `client/src/` | Browser bundle sources; `client.js` is generated |
288
+ | `scripts/` | Build, verification, market index, smoke tests |
289
+ | `test/` | `node --test` suites (unit, CLI fixtures, contract e2e) |
290
+ | `docs/` | Architecture detail, release process, marketplace copy |
291
+ | `market/` | Generated marketplace index and icons |
292
+
293
+ ### Contributing
294
+
295
+ - Setup, the four gates, and commit conventions are in [CONTRIBUTING.md](CONTRIBUTING.md).
296
+ - Release history is in [CHANGELOG.md](CHANGELOG.md).
297
+ - Report security issues privately via [SECURITY.md](SECURITY.md); do not open a public issue.
298
+ - Community standards are in [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
299
+
300
+ ---
301
+
302
+ ## License
303
+
304
+ MIT
package/README.md ADDED
@@ -0,0 +1,304 @@
1
+ <div align="center">
2
+
3
+ # dsh-agent-router
4
+
5
+ **按任务难度把工作分给对的模型:DSH 原生子智能体 + 本机 Agent CLI 的统一路由器**
6
+
7
+ [![CI](https://github.com/qingxuan233/dsh-agent-router/actions/workflows/ci.yml/badge.svg)](https://github.com/qingxuan233/dsh-agent-router/actions/workflows/ci.yml)
8
+ [![Node](https://img.shields.io/badge/node-%3E%3D24.9.0-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
9
+ [![DSH](https://img.shields.io/badge/DSH-0.2.2--rc.x-4f46e5)](https://github.com/deepseek-ai/deepseek-harness)
10
+ [![dependencies](https://img.shields.io/badge/runtime%20dependencies-0-0ea5e9)](#开发与验证)
11
+ [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
12
+
13
+ 中文 | [English](README.en.md)
14
+
15
+ </div>
16
+
17
+ `dsh-agent-router` 是一个零运行时依赖的 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) 插件:先按可配置难度档位(默认 T1–T4)判断任务难度,再把任务路由到 **DSH 原生子智能体**或本机 **Claude Code / Codex / Gemini / OpenCode / Antigravity** CLI;带健康冷却、失败升阶、会话续接、Git Worktree 隔离,并在插件详情页可视化配置、保存即生效。
18
+
19
+ > 一句话:**轻任务别用重模型,重任务别用小模型;本机 CLI 与 DSH 模型统一排队。**
20
+
21
+ ---
22
+
23
+ ## 为什么需要它
24
+
25
+ - **成本与延迟**:搜索、摘要、改文档不需要旗舰模型;跨模块重构和审查也不该交给最便宜的模型。
26
+ - **能力边界**:DSH 原生子智能体与外部 CLI 各有长短,手动切换容易中断上下文、丢失会话。
27
+ - **可控性**:路由失败要能自动降级/升阶,连续失败要能熔断,长任务要能后台跑、可取消、可续接。
28
+ - **可视化**:不用手写 YAML,在插件详情页直接调整每档模型链并热保存。
29
+
30
+ ---
31
+
32
+ ## 核心能力
33
+
34
+ | 能力 | 说明 |
35
+ |---|---|
36
+ | **可配置难度档位(默认 T1–T4)** | 默认轻量检索 / 标准编码 / 困难架构 / 异构审查四档;可套用四档/三档/两档模板,也可增删档位并自定义名称、说明、分数区间、路由链与升阶目标。 |
37
+ | **双执行端统一调度** | DSH 原生模型与 `claude` / `codex` / `gemini` / `opencode` / `antigravity`(`agy`)CLI 共用一条候选链,按优先级与健康度依次尝试。 |
38
+ | **CLI 自适应选择** | `cliSelection: adaptive` 时自动补充本机已安装的 CLI,仅对自动追加的候选做 EWMA 微调;显式配置链始终自上而下依次尝试。 |
39
+ | **可选本地模型** | `allowLocalModels: true` 后,才把 DSH 中已注册的本地/自托管 Provider(Ollama、LM Studio、vLLM 等)纳入候选;默认完全关闭。 |
40
+ | **健康冷却 + 失败升阶** | 失败进入指数退避冷却并顺延下一候选;同档全失败且开启 `autoEscalate` 时按配置的下一普通档升阶(默认 T1→T2→T3)。 |
41
+ | **后台异步队列** | `background: true` 走有界并发队列(优先 DSH 原生 `ctx.jobs`),完成后唤醒主对话,支持取消与查看进度。 |
42
+ | **会话续接** | 持久化 `runId`、DSH 子会话 ID 与 CLI `session_id` / `thread_id`,随时对同一上下文追问。 |
43
+ | **Worktree 隔离与合入** | 并发写同一 Git 仓库时自动创建临时 Worktree;支持 `inspect_worktree_diff` / `merge_worktree` / `cleanup_worktree`。 |
44
+ | **生态联动** | 可选读取 `dsh-cost-meter` 预算与峰谷状态、`dsh-context` 主上下文占用,预算紧张时优先低价/本地 CLI。 |
45
+ | **可视化配置 + 环境诊断** | 插件详情页管理全局策略、档位布局与各档路由链,一键运行诊断检查 catalog、子智能体模型开关、CLI、本地模型与后台队列。 |
46
+
47
+ ---
48
+
49
+ ## 提供工具
50
+
51
+ | 工具 | 用途 |
52
+ |---|---|
53
+ | `router_plan` | 只做定级与候选预演(含置信度、阻塞原因、冷却、EWMA/预算提示),不执行任务。 |
54
+ | `router_dispatch` | 按难度路由并执行任务;支持降级、升阶、后台队列、会话保存与 Worktree 隔离。 |
55
+ | `router_continue` | 用 `run_id` 或子智能体名续接 DSH 子会话 / CLI 会话。 |
56
+ | `router_status` | 查看概览、运行记录、配置、后台任务、Worktree 操作;新增 `action: "doctor"` 环境诊断。 |
57
+
58
+ ---
59
+
60
+ ## 快速开始
61
+
62
+ ```bash
63
+ # 从 GitHub 安装
64
+ dsh plugin --profile desktop add git+https://github.com/qingxuan233/dsh-agent-router.git
65
+
66
+ # 或本地开发软链
67
+ dsh plugin --profile desktop add link:/path/to/dsh-agent-router
68
+ ```
69
+
70
+ > 上面的 CLI 只写入依赖,不会登记 `dsh.profile.bundles`。要形成标准 bundle 挂载,请使用下文「安装方式与重复挂载自检」中的 `npm run profile:install`,或直接从 DSH 插件页安装。
71
+
72
+ 1. 安装或切换来源后 **完整重启一次 DSH**(客户端 bundle 与 Typert RPC 清单会被缓存)。
73
+ 2. 打开 **插件 → 已安装 → dsh-agent-router**,选择档位方案,并按任务难度维护每一档的模型链。
74
+ 3. 点击 **保存配置**,立即热生效;无需重启。
75
+ 4. 不确定环境是否就绪时,点 **运行诊断**(或在对话中调用 `router_status` 的 `doctor`)。
76
+
77
+ > 运行环境:Node.js `>= 24.9.0`,DSH `>= 0.2.2-rc.1 < 0.3.0-0`。
78
+
79
+ ---
80
+
81
+ ## 安装方式与重复挂载自检
82
+
83
+ 本插件必须通过 **标准 bundle 安装**:依赖写入 profile 的 `package.json`,并列入 `dsh.profile.bundles`,由 DSH 自动应用包内 `cordis.patch.yml`。
84
+
85
+ - **不要**把本包 `cordis.patch.yml` 里的 `- insert:` 块复制到 profile(或 home 级)`cordis.patch.yml`。手工挂载会让 DSH 卸载时提示“其他配置仍在使用这个组合包的组件”。
86
+ - 检测到 `manual` / `duplicate` 挂载时:插件详情页会在档位编辑器上方显示警告,启动日志会输出 profile 路径,`router_status` 的 `doctor` 会新增 `mount` 检查项。
87
+ - 修复:在 profile 目录执行 `node node_modules/dsh-agent-router/scripts/profile-maintenance.mjs repair`(仓库开发者可用 `npm run profile:repair`)。修复会先把将修改的文件备份到 `$DSH_HOME/backups/agent-router-mount-<时间戳>/`,再移除手工 `- insert:` 块并补全 bundle 注册,完成后需**完整重启 DSH**。
88
+ - 只读检查:仓库根执行 `npm run profile:check`;已安装用户执行 `node node_modules/dsh-agent-router/scripts/profile-maintenance.mjs check`。卸载前必须没有手工挂载;`profile-maintenance.mjs uninstall` 检测到时会拒绝执行并提示先修复。
89
+ - 新装或修复注册:在仓库根执行 `npm run profile:install -- --profile desktop --spec "github:qingxuan233/dsh-agent-router#main"`。该命令会执行 `pnpm add` 并写入 `dsh.profile.bundles`,等价于 DSH 插件页的标准 bundle 安装。
90
+ - 注意:`dsh plugin --profile desktop add ...` 只写入依赖,**不会**登记 `dsh.profile.bundles`;单用它在当前 DSH 版本下不会形成标准 bundle 挂载。
91
+
92
+ ---
93
+
94
+ ## 配置
95
+
96
+ ### 全局字段
97
+
98
+ | 字段 | 默认 | 说明 |
99
+ |---|---|---|
100
+ | `preferBackend` | `auto` | 全局执行端倾向:`auto` / `dsh` / `cli` / 具体 CLI 名。 |
101
+ | `autoEscalate` | `true` | 同档候选全部失败时是否自动升阶。 |
102
+ | `budgetGuard` | `true` | 联动 `dsh-cost-meter`,预算接近上限时优先低价/本地路由。 |
103
+ | `peakAvoidance` | `false` | DeepSeek 2× 峰时优先非 DeepSeek / 本地 CLI。 |
104
+ | `adaptiveRanking` | `true` | 用历史 EWMA 延迟与成功率微调候选顺序。 |
105
+ | `cliSelection` | `static` | `static` 严格按配置链;`adaptive` 自动补充已安装 CLI,仅对自动追加项按历史排序。 |
106
+ | `allowLocalModels` | `false` | 是否把本地/自托管 DSH 模型纳入候选。 |
107
+ | `localProviders` | `[]` | 明确视为本地模型的 Provider ID;留空则按 ID/名称/baseURL 自动识别。 |
108
+ | `defaultBackground` | `false` | 外部 CLI 是否默认后台异步执行。 |
109
+ | `useNativeJobs` | `true` | 后台任务优先使用 DSH `ctx.jobs`,不可用时回退内置队列。 |
110
+ | `maxConcurrentCli` | `3` | 后台 CLI 最大并发数。 |
111
+ | `cooldownMs` | `180000` | 路由失败后的基础冷却时长(指数退避)。 |
112
+ | `defaultTimeoutMs` | `300000` | CLI 默认超时。 |
113
+ | `maxRuns` | `200` | 调度账本保留的最近运行记录数。 |
114
+ | `ledgerFile` | `~/.dsh/agent-router/state.json` | 自定义账本路径。 |
115
+ | `tierLayout` | `default` | `default` 表示按 id 合并内置档位;`custom` 表示 `tiers` 为权威集合(删除的档位不会复活)。UI 保存时写入 `custom`。 |
116
+ | `tiers.<id>` | 内置 | 每档包含 `name` / `description` / `role`(`normal` 或 `review`)/ `minScore` / `maxScore` / `preferBackend` / `escalateTo` / `dsh[]` / `cli[]`;id 由字母开头,可含数字、`-`、`_`。 |
117
+
118
+ ### Profile 预置示例
119
+
120
+ ```yaml
121
+ - id: agent-router
122
+ config:
123
+ preferBackend: auto
124
+ autoEscalate: true
125
+ cliSelection: adaptive
126
+ allowLocalModels: false # 需要本地模型时再打开
127
+ tiers:
128
+ T1:
129
+ preferBackend: dsh
130
+ dsh:
131
+ - { provider: deepseek-account, model: deepseek-chat }
132
+ T3:
133
+ preferBackend: auto
134
+ cli:
135
+ - { backend: claude, model: opus, effort: high }
136
+ ```
137
+
138
+ ### 启用本地模型(可选)
139
+
140
+ ```yaml
141
+ - id: agent-router
142
+ config:
143
+ allowLocalModels: true
144
+ localProviders: [] # 留空自动识别 ollama / lmstudio / vllm 等
145
+ tiers:
146
+ T1:
147
+ preferBackend: dsh
148
+ dsh:
149
+ - { provider: ollama, model: qwen2.5-coder }
150
+ ```
151
+
152
+ 前提:该本地 Provider 必须**已经注册在 DSH `ctx.llm`**,并能列出模型;插件不负责启动模型服务、不代理请求、不保存任何凭据。
153
+
154
+ ---
155
+
156
+ ## 档位模型(默认 T1–T4,可配置)
157
+
158
+ 不修改配置时仍是原来的四档:
159
+
160
+ | 档位 | 角色 | 分数区间 | 典型任务 | 默认策略 |
161
+ |---|---|---|---|---|
162
+ | **T1 轻量检索** | normal | 0 – 1.5 | 搜索、文件扫描、日志摘要、格式转换、简单问答 | 低成本 Flash / eco 模型优先,其次快速 CLI。 |
163
+ | **T2 标准开发** | normal | 1.5 – 3 | 明确模块开发、常规 Bug、单测、脚本 | 编码特化模型或 `codex` / `opencode` / `antigravity`。 |
164
+ | **T3 复杂攻坚** | normal | 3 – 无上限 | 跨模块重构、复杂算法、深水区排错 | 旗舰推理模型或 `claude opus`,DSH 与 CLI 均衡。 |
165
+ | **T4 审查验收** | review | 不参与分数映射 | 代码审查、安全审计、交叉验收 | 默认异构模型家族的只读/计划模式 CLI,避免自审自。 |
166
+
167
+ 定级依据包括 review/code/research 意图、复杂工程关键词、任务长度、清单条目数与引用文件数;会忽略否定词后的复杂信号和代码块/日志中的关键词,按领域使用不同权重。审查意图仅在任务不含写操作动词(如 fix / implement / update / 删除)时生效,例如「修复 review 里发现的问题」会按普通编码任务处理;需要只读审查时请显式指定审查档或把请求写成纯审查。置信度较低、接近下一普通档边界且多个复杂度信号一致时会升到下一档(默认仍是 T2→T3);输出含 `tier`、`tierName`、`confidence`、`confidenceScore` 与可解释的 `signals`/`reasons`。
168
+
169
+ ### 档位模板
170
+
171
+ 插件详情页顶部提供三种一键方案,只调整档位布局与分数区间,同 id 档位保留原有模型链:
172
+
173
+ | 方案 | 档位 | 适用场景 |
174
+ |---|---|---|
175
+ | **默认四档** | T1(0–1.5) / T2(1.5–3) / T3(3–∞) / T4(review) | 与旧版行为完全一致,推荐大多数用户。 |
176
+ | **精简三档** | T1(0–2) / T2(2–∞) / T4(review) | 不想维护中间档,但需要独立审查档。 |
177
+ | **极速两档** | T1(0–2.5) / T3(2.5–∞) | 只分“快速/深度”;审查意图自动回退到最高普通档。 |
178
+
179
+ ### 新增与删除档位
180
+
181
+ - **新增**:输入档位名称并选择模板(空白普通档 / 轻量 / 标准 / 困难 / 审查档),插件自动生成 id 和分数区间;新增在末尾时会自动收窄上一档的无上限区间。
182
+ - **删除**:删除前需要确认;至少保留一个普通档;指向被删档位的 `escalateTo` 会自动改到被删档位的升阶目标或下一普通档。
183
+ - **审查档**:`role: review`,不参与分数映射,仅承接 review/audit 意图;存在多个审查档时,由 id 排序最靠前的一个承接审查意图(其余仍可通过显式档位或升阶目标使用);没有审查档时审查任务回退到最高普通档。
184
+ - **升阶目标**:下拉框显示档位名称;普通档可指向任意其他档位,审查档默认不升阶。
185
+
186
+ ### 分数区间(进阶设置)
187
+
188
+ - 普通档使用 `[minScore, maxScore)`;`maxScore` 留空表示无上限。
189
+ - 分数区间默认收在“进阶设置”里,普通用户无需修改;区间重叠、名称重复、无效路由或无效升阶目标会被自动修复并在保存/导入时提示修复项;只有“修复后仍没有普通档”这类无法安全降级的问题才会被拦截。
190
+ - 手工改 Profile YAML 或旧 `state.json` 与 UI 导入采用同一套归一化规则:非法但可修复的字段自动修复,缺失档位按模板补齐,不再出现「YAML 能加载、粘贴导入却报错」的不一致。
191
+ - 区间允许留空档(例如 0–1、2–3),不要求连续。
192
+
193
+ ### 从 configVersion 1 迁移
194
+
195
+ 旧配置(`configVersion: 1`、只有 T1–T4 路由链)会自动迁移到 `configVersion: 2`:
196
+
197
+ - 旧 `label` 自动转为档位 `name`,并补齐 `description`、`role`、`minScore`、`maxScore`;
198
+ - T4 识别为审查档(`role: review`),不参与分数映射;
199
+ - 缺失档位按默认四档补齐,用户已有的 `dsh` / `cli` / `preferBackend` / `escalateTo` 保留;
200
+ - 未知字段保留;首次在 UI 保存后写入 `tierLayout: custom` 与完整档位,之后删除的档位不会因合并而复活;
201
+ - 迁移在启动时内存生效,因此旧 YAML 在首次保存前仍显示 `configVersion: 1`,行为不受影响。
202
+
203
+ ---
204
+
205
+ ## CLI 自适应选择
206
+
207
+ - **static(默认)**:完全遵循每档 `cli[]` 的顺序,只过滤未安装的 CLI,行为最可预期。
208
+ - **adaptive**:在配置链基础上:
209
+ 1. 自动追加本机已安装但未写入配置的 CLI(按档位启发式排序);
210
+ 2. 仅对自动追加的候选使用 EWMA 延迟与近期成功率微调;
211
+ 3. 你显式配置的 CLI 始终按列表自上而下依次尝试,不改变显式 `model` / `effort`。
212
+ - Antigravity CLI 的可执行文件是 `agy`,插件会自动映射;首次使用前需先完成一次交互式登录。
213
+ - 所有 CLI 都必须自行安装并完成登录;插件只探测 `PATH` 与本地配置文件,不读取 token。
214
+
215
+ ---
216
+
217
+ ## 环境诊断与故障排查
218
+
219
+ 在插件详情页点 **运行诊断**,或让 Agent 调用:
220
+
221
+ ```json
222
+ { "action": "doctor" }
223
+ ```
224
+
225
+ `router_status` 会逐项检查:DSH `ctx.llm` 目录、`subagent-model-selection` 开关、本机 CLI、CLI 选择模式、本地模型、`ctx.jobs`、`dsh-cost-meter`、账本与后台队列,并给出可操作建议。
226
+
227
+ | 现象 | 排查 |
228
+ |---|---|
229
+ | 设置页空白 / `service unavailable` | 更新后完整重启 DSH;确认插件已启用;运行诊断查看 RPC 是否挂载。 |
230
+ | 原生子智能体不换模型 | 开启 `subagent-model-selection-settings`,并把目标模型加入 `allowedModels`。 |
231
+ | CLI 显示未安装 | 确认命令在 `PATH` 中、已登录;Windows 下插件会解析 `.cmd` 包装器。 |
232
+ | 本地模型没有出现 | 确认 Provider 已在 DSH `ctx.llm` 注册且能列出模型;必要时在 `localProviders` 显式填写。 |
233
+ | Worktree 未创建 | 目录不是 Git 仓库,或当前为只读权限;非 Git 目录会降级为普通执行。 |
234
+ | 路由一直冷却 | 用 `router_status` 的 `clear_cooldowns`,或检查最近的失败原因。 |
235
+
236
+ ---
237
+
238
+ ## 适用边界(明确不做什么)
239
+
240
+ **适用**
241
+
242
+ - 在 DSH 中按难度分配 DSH 原生模型 / 本机 Agent CLI。
243
+ - 需要失败降级、升阶、熔断、会话续接、后台队列与 Worktree 隔离的多 Agent 工作流。
244
+ - 已自行安装并登录本机 CLI,或已在 DSH 注册本地/远程模型的用户。
245
+
246
+ **不适用 / 不负责**
247
+
248
+ - **不代理模型请求**:不内置 HTTP 网关、不转发 API、不管理 API Key。
249
+ - **不托管或下载模型**:本地模型必须由用户先在 DSH 中注册并运行。
250
+ - **不替代 DSH 生命周期管理**:插件只调用 `startActivation` / `sendMessage`,遵循 DSH 的深度、权限与 allowlist 限制。
251
+ - **不保证 CLI 可用性**:CLI 的安装、登录、配额、版本兼容由用户负责。
252
+ - **不修改业务代码**:除被派发的子智能体/CLI 自身产生的改动外,插件不做代码编辑。
253
+ - **Worktree 仅限 Git 仓库**:非 Git 目录、裸仓库或权限不足时会降级。
254
+ - **不是通用任务队列**:后台队列面向本插件的 CLI/子智能体派发,不承接任意 DSH 任务。
255
+
256
+ ---
257
+
258
+ ## 安全与隐私
259
+
260
+ - 账本只写入 `~/.dsh/agent-router/state.json`(可用 `ledgerFile` 覆盖),记录运行状态、冷却与聚合指标。
261
+ - CLI 探测只读取常见配置文件的**模型名**与默认模型,不读取或上报密钥。
262
+ - 本地模型识别只基于 Provider ID / 名称 / baseURL 字符串匹配,不发起网络探测。
263
+ - 所有执行均在用户本机;插件不含遥测与外部上报。
264
+
265
+ ---
266
+
267
+ ## 开发与验证
268
+
269
+ ```bash
270
+ npm run build:client # 修改 client/src/ 后重新生成 client.js
271
+ npm test # 单元测试(定级、路由、队列、Schema、诊断等)
272
+ npm run verify # 清单、Schema、locale、Typert 三方一致、语法
273
+ npm run release:check # 版本、市场索引、npm pack 文件与体积
274
+ npm run smoke:dsh # 真实 DSH 临时 profile 加载冒烟(未安装时自动跳过)
275
+ npm run market:index # 生成本地市场索引 market/index.json
276
+ ```
277
+
278
+ > 当前仓库只做本地校验与产物生成;`npm publish`、打 tag、市场索引上线等对外发布动作需维护者人工确认。发布清单见 [docs/RELEASE.md](docs/RELEASE.md)。
279
+
280
+ ### 仓库结构
281
+
282
+ | 路径 | 说明 |
283
+ |---|---|
284
+ | `index.js` | Host 入口:`apply` / `inject` / 工具注册 |
285
+ | `lib/` | 路由核心:定级、档位、配置、候选、会话、账本 |
286
+ | `lib/router/rpc.js` | 暴露给浏览器端的 RPC 服务 |
287
+ | `client/src/` | 浏览器 bundle 源码;`client.js` 是构建产物 |
288
+ | `scripts/` | 构建、校验、市场索引、冒烟测试 |
289
+ | `test/` | `node --test` 测试(单元、CLI fixture、契约 E2E) |
290
+ | `docs/` | 架构细节、发布流程、市场文案 |
291
+ | `market/` | 生成的市场索引与图标 |
292
+
293
+ ### 参与贡献
294
+
295
+ - 开发环境、四道门禁与提交规范见 [CONTRIBUTING.md](CONTRIBUTING.md)。
296
+ - 变更记录见 [CHANGELOG.md](CHANGELOG.md)。
297
+ - 安全问题请通过 [SECURITY.md](SECURITY.md) 的私有渠道报告,不要公开提交漏洞细节。
298
+ - 社区行为准则见 [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)。
299
+
300
+ ---
301
+
302
+ ## License
303
+
304
+ MIT