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
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Lightweight model capability metadata and task requirement inference.
3
+ *
4
+ * Capabilities are best-effort: unknown models are never excluded, only sorted
5
+ * after known-compatible candidates. This keeps new models usable without a
6
+ * network probe or a manual capability registry.
7
+ *
8
+ * @module dsh-agent-router/lib/model-capabilities
9
+ */
10
+
11
+ const KNOWN_PATTERNS = [
12
+ {
13
+ pattern: /gemini-(?:3\.[5-9]|4)|gemini-pro|gemini-flash/i,
14
+ capabilities: { contextWindow: 1_000_000, tools: true, vision: true, structured: true },
15
+ },
16
+ {
17
+ pattern: /claude-(?:opus|sonnet|haiku)|anthropic\/claude/i,
18
+ capabilities: { contextWindow: 200_000, tools: true, vision: true, structured: true },
19
+ },
20
+ {
21
+ pattern: /deepseek-(?:reasoner|chat|v4)|deepseek-account/i,
22
+ capabilities: { contextWindow: 128_000, tools: true, vision: false, structured: true },
23
+ },
24
+ {
25
+ pattern: /(?:gpt-4o|gpt-4\.1|o3|o4)/i,
26
+ capabilities: { contextWindow: 128_000, tools: true, vision: true, structured: true },
27
+ },
28
+ {
29
+ pattern: /(?:kimi|glm|mimo|qwen|llama|mistral|yi-)/i,
30
+ capabilities: { contextWindow: 128_000, tools: true, vision: false, structured: false },
31
+ },
32
+ ]
33
+
34
+ const UNKNOWN_CAPABILITIES = Object.freeze({
35
+ contextWindow: null,
36
+ tools: null,
37
+ vision: null,
38
+ structured: null,
39
+ known: false,
40
+ })
41
+
42
+ /** CLI agents run a full agent loop with its own context management. */
43
+ const CLI_CAPABILITIES = Object.freeze({
44
+ contextWindow: null,
45
+ tools: true,
46
+ vision: null,
47
+ structured: null,
48
+ known: false,
49
+ })
50
+
51
+ /**
52
+ * @param {string} provider
53
+ * @param {string} model
54
+ */
55
+ export function lookupCapabilities(provider, model) {
56
+ const key = `${provider || ''}/${model || ''}`
57
+ if (!model) return { ...UNKNOWN_CAPABILITIES }
58
+ for (const entry of KNOWN_PATTERNS) {
59
+ if (entry.pattern.test(key)) {
60
+ return { ...entry.capabilities, known: true }
61
+ }
62
+ }
63
+ return { ...UNKNOWN_CAPABILITIES }
64
+ }
65
+
66
+ /**
67
+ * Infer coarse requirements from a task description.
68
+ * @param {string} task
69
+ */
70
+ export function inferTaskRequirements(task) {
71
+ const text = String(task || '')
72
+ return {
73
+ estimatedTokens: Math.ceil(text.length / 4),
74
+ needsVision: /(image|screenshot|picture|diagram|ocr|vision|截图|图片|图像|视觉|看图)/i.test(text),
75
+ needsStructured: /(json|yaml|schema|structured output|表格|csv)/i.test(text),
76
+ needsLongContext: /(long context|whole repo|entire repo|entire codebase|full codebase|全文|整个仓库|全仓库)/i.test(text),
77
+ }
78
+ }
79
+
80
+ function capabilitiesFor(candidate) {
81
+ if (candidate.kind === 'cli') return CLI_CAPABILITIES
82
+ return lookupCapabilities(candidate.provider, candidate.model)
83
+ }
84
+
85
+ /**
86
+ * Reorder candidates so known-compatible routes come first, unknown routes next,
87
+ * and known-insufficient routes last. Order within each bucket is preserved.
88
+ *
89
+ * @param {Array<Record<string, any>>} candidates
90
+ * @param {ReturnType<typeof inferTaskRequirements>} requirements
91
+ * @returns {{ candidates: any[], notes: string[] }}
92
+ */
93
+ export function applyCapabilityPolicy(candidates, requirements) {
94
+ if (!Array.isArray(candidates) || candidates.length <= 1 || !requirements) {
95
+ return { candidates: Array.isArray(candidates) ? candidates.slice() : [], notes: [] }
96
+ }
97
+ const hasRequirements = requirements.needsVision || requirements.needsStructured || requirements.needsLongContext
98
+ if (!hasRequirements) {
99
+ return { candidates: candidates.slice(), notes: [] }
100
+ }
101
+
102
+ const notes = []
103
+ const scored = candidates.map((candidate, index) => {
104
+ const caps = capabilitiesFor(candidate)
105
+ let bucket = 2
106
+ let reason = ''
107
+ if (requirements.needsVision) {
108
+ if (caps.vision === false) {
109
+ bucket = 0
110
+ reason = 'no vision support'
111
+ } else if (caps.vision === true) {
112
+ bucket = 3
113
+ }
114
+ }
115
+ if (requirements.needsStructured && caps.structured === false && bucket > 1) {
116
+ bucket = 1
117
+ reason = 'no structured-output support'
118
+ }
119
+ const neededTokens = Math.max(
120
+ requirements.estimatedTokens,
121
+ requirements.needsLongContext ? 200_000 : 0,
122
+ )
123
+ if (caps.contextWindow !== null && caps.contextWindow < neededTokens && bucket > 1) {
124
+ bucket = 1
125
+ reason = `context window ${caps.contextWindow} < ${neededTokens} tokens`
126
+ }
127
+ if (bucket <= 1 && reason) {
128
+ notes.push(`capability: ${candidate.key || `${candidate.provider}/${candidate.model}`} demoted (${reason})`)
129
+ }
130
+ return { candidate, bucket, index, caps }
131
+ })
132
+
133
+ scored.sort((a, b) => (b.bucket - a.bucket) || (a.index - b.index))
134
+ return { candidates: scored.map(entry => entry.candidate), notes }
135
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Model suitability scoring shared by the Host router and the Browser auto-match UI.
3
+ * Pure functions only, so the client build can inline this module verbatim.
4
+ * @module dsh-agent-router/lib/model-score
5
+ */
6
+
7
+ /**
8
+ * Classify a model ID into a coarse family for heterogeneity checks.
9
+ * @param {string} modelId
10
+ */
11
+ export function modelFamilyOf(modelId) {
12
+ const m = String(modelId || '').toLowerCase()
13
+ if (m.includes('deepseek')) return 'deepseek'
14
+ if (m.includes('claude')) return 'claude'
15
+ if (m.includes('gemini')) return 'gemini'
16
+ if (m.includes('gpt') || m.includes('codex') || /^o[134]/.test(m)) return 'openai'
17
+ if (m.includes('kimi') || m.includes('moonshot')) return 'moonshot'
18
+ if (m.includes('glm')) return 'zhipu'
19
+ if (m.includes('qwen')) return 'qwen'
20
+ if (m.includes('mimo')) return 'mimo'
21
+ return m.split(/[-_/]/)[0] || 'other'
22
+ }
23
+
24
+ /**
25
+ * Score a live DSH model ID for suitability in a tier.
26
+ * Accepts either a canonical T1-T4 key or a capability band
27
+ * (`light`/`standard`/`heavy`/`review`), so custom tier ids work unchanged.
28
+ * Enables zero-config out-of-the-box routing on any user's `ctx.llm` catalog.
29
+ * @param {string} modelId
30
+ * @param {'T1'|'T2'|'T3'|'T4'|'light'|'standard'|'heavy'|'review'} tier
31
+ * @param {string|null} [parentModel]
32
+ */
33
+ export function scoreModelForTier(modelId, tier, parentModel = null) {
34
+ const m = String(modelId || '').toLowerCase()
35
+ if (/image|tts|whisper|embedding|moderation/.test(m)) return -100
36
+ const isLight = /flash|eco|mini|lite|nano|haiku|fast|small|low\b/.test(m)
37
+ const isCoding = /code|coder|codex|sonnet|chat|medium|dev/.test(m)
38
+ const isHeavy = /pro\b|opus|reasoner|thinking|xhigh|high\b|max\b|r1\b|o3\b|orchestrator|hydrogen/.test(m)
39
+ const band = tier === 'T1' || tier === 'light'
40
+ ? 'light'
41
+ : (tier === 'T3' || tier === 'heavy'
42
+ ? 'heavy'
43
+ : (tier === 'T4' || tier === 'review' ? 'review' : 'standard'))
44
+ let score = 0
45
+ if (band === 'light') {
46
+ if (isLight) score += 30
47
+ if (/eco|lite|mini|haiku|low\b/.test(m)) score += 10
48
+ if (m === 'deepseek-chat') score += 20
49
+ if (isHeavy) score -= 25
50
+ } else if (band === 'standard') {
51
+ if (isCoding) score += 25
52
+ if (isLight && !/lite|nano|low\b/.test(m)) score += 10
53
+ if (m === 'deepseek-chat') score += 20
54
+ if (/xhigh|opus/.test(m)) score -= 10
55
+ } else if (band === 'heavy') {
56
+ if (isHeavy) score += 30
57
+ if (isLight && !/high/.test(m)) score -= 20
58
+ } else if (band === 'review') {
59
+ if (isHeavy) score += 25
60
+ if (isCoding) score += 10
61
+ if (parentModel && modelFamilyOf(modelId) !== modelFamilyOf(parentModel)) score += 20
62
+ if (isLight && !/high/.test(m)) score -= 15
63
+ }
64
+ return score
65
+ }
package/lib/plugin.js ADDED
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Plugin composition root: wires persisted state, config management, event
3
+ * listeners, tools, system prompt, and RPC together.
4
+ * @module dsh-agent-router/lib/plugin
5
+ */
6
+
7
+ import { randomUUID } from 'node:crypto'
8
+
9
+ import { nextEscalationTier } from './classifier.js'
10
+ import { unwrapConfigObject } from './config-schema.js'
11
+ import { buildBaseConfig } from './config-normalize.js'
12
+ import { LegacyConfigStore } from './legacy-config.js'
13
+ import { RouterStore } from './ledger.js'
14
+ import { RouterJobRunner } from './job-runner.js'
15
+ import { inspectMount } from './profile-mount.js'
16
+ import { createConfigManager } from './router/config-manager.js'
17
+ import { mountRouterRpc } from './router/rpc.js'
18
+ import { registerRouterSystemPrompt } from './router/system-prompt.js'
19
+ import { registerRouterTools } from './router/tools.js'
20
+ import { describeThrown } from './router/util.js'
21
+
22
+ export function install(ctx, raw) {
23
+ const settings = unwrapConfigObject(raw)
24
+ const baseConfig = buildBaseConfig(settings)
25
+
26
+ // Warn once about hand-written mounts; never block activation.
27
+ try {
28
+ const mount = inspectMount()
29
+ if (mount.state === 'manual' || mount.state === 'duplicate') {
30
+ ctx.logger?.warn?.(
31
+ `dsh-agent-router: 检测到非标准挂载(${mount.state}),profile: ${mount.profileDir || mount.files?.homePatch || 'unknown'}。请在 profile 目录运行 profile-maintenance.mjs repair 并重启 DSH。`,
32
+ )
33
+ }
34
+ } catch {
35
+ // Mount inspection is advisory only.
36
+ }
37
+
38
+ // The plugin ships its own settings UI, so opt out of the auto-generated form.
39
+ const settingsForms = ctx.get?.('settings')
40
+ if (settingsForms && typeof settingsForms.configure === 'function') {
41
+ ctx.effect?.(() => {
42
+ try {
43
+ return settingsForms.configure({ auto: false }, ctx.fiber)
44
+ } catch {
45
+ return () => {}
46
+ }
47
+ }, 'dsh-agent-router: settings page policy')
48
+ }
49
+
50
+ const store = new RouterStore({
51
+ filePath: baseConfig.ledgerFile,
52
+ maxRuns: baseConfig.maxRuns,
53
+ cooldownMs: baseConfig.cooldownMs,
54
+ logger: ctx.logger,
55
+ })
56
+ const queue = new RouterJobRunner({
57
+ ctx,
58
+ maxConcurrent: baseConfig.maxConcurrentCli,
59
+ useNativeJobs: baseConfig.useNativeJobs,
60
+ })
61
+ ctx.effect?.(() => () => queue.dispose(), 'dsh-agent-router: background job runner')
62
+
63
+ // Subscribe to volatile Config ref updates (from configEditor / cordis.patch.yml)
64
+ if (raw && typeof raw === 'object') {
65
+ for (const ref of Object.values(raw)) {
66
+ if (ref && typeof ref.subscribe === 'function') {
67
+ const unsub = ref.subscribe(() => {
68
+ const live = buildBaseConfig(unwrapConfigObject(raw))
69
+ Object.assign(baseConfig, live)
70
+ store.cooldownMs = live.cooldownMs
71
+ store.setMaxRuns(live.maxRuns)
72
+ store.setFilePath(live.ledgerFile)
73
+ queue.setMaxConcurrent(live.maxConcurrentCli)
74
+ queue.setUseNativeJobs(live.useNativeJobs)
75
+ })
76
+ ctx.effect?.(() => unsub, 'dsh-agent-router: volatile config sync')
77
+ }
78
+ }
79
+ }
80
+
81
+ const legacyConfig = new LegacyConfigStore(store)
82
+
83
+ const {
84
+ canUseProfileEditor,
85
+ getConfigSource,
86
+ currentConfig,
87
+ saveRouterConfig,
88
+ resetRouterConfig,
89
+ } = createConfigManager({ ctx, store, queue, legacyConfig, baseConfig, raw })
90
+
91
+ const activeWriteDirs = new Map()
92
+
93
+ const notifyParentAgent = (caller, text, source) => {
94
+ if (!caller) return
95
+ try {
96
+ const liveAgent = ctx.agents?.get?.(caller.id) || caller
97
+ if (liveAgent?.ctx?.fiber?.state !== undefined && liveAgent.ctx.fiber.state !== 2) return
98
+ const msg = {
99
+ id: randomUUID(),
100
+ role: 'user',
101
+ source: source || { kind: 'user' },
102
+ content: [{ type: 'text', text }],
103
+ }
104
+ if (liveAgent.status === 'running' && typeof liveAgent.steer === 'function') {
105
+ liveAgent.steer(msg)
106
+ } else if (typeof liveAgent.followup === 'function') {
107
+ liveAgent.followup(msg)
108
+ }
109
+ } catch (err) {
110
+ ctx.logger?.warn?.(`dsh-agent-router: could not notify parent agent: ${describeThrown(err)}`)
111
+ }
112
+ }
113
+
114
+ ctx.on?.('agent/disposed', ({ agent }) => {
115
+ const sid = agent?.session?.id || agent?.id
116
+ if (sid) queue.cancelByParent(sid, 'parent session disposed')
117
+ })
118
+
119
+ // Track DSH native subagent completions back into the ledger
120
+ ctx.on?.('subagent/end', (info) => {
121
+ if (!info) return
122
+ const run = store.findRun(info.id) || store.findRun(info.name)
123
+ if (!run || run.backend !== 'dsh') return
124
+ const ok = info.stopReason === 'completed'
125
+ const durationMs = run.startedAt ? Math.max(0, Date.now() - run.startedAt) : undefined
126
+ const lastText = Array.isArray(info.lastAssistantMessage)
127
+ ? info.lastAssistantMessage
128
+ .filter(b => b && b.type === 'text' && typeof b.text === 'string')
129
+ .map(b => b.text)
130
+ .join('')
131
+ .slice(0, 500)
132
+ : undefined
133
+ store.recordRouteMetric(run.routeKey, { ok, durationMs })
134
+ if (ok) {
135
+ store.recordSuccess(run.routeKey)
136
+ store.upsertRun({
137
+ runId: run.runId,
138
+ status: 'completed',
139
+ childId: info.id,
140
+ stopReason: info.stopReason,
141
+ ...(durationMs !== undefined ? { durationMs } : {}),
142
+ ...(lastText ? { summary: lastText } : {}),
143
+ })
144
+ } else {
145
+ const reason = `subagent ended: ${info.stopReason || 'failed'}`
146
+ store.recordFailure(run.routeKey, reason)
147
+ const liveTiers = currentConfig().tiers
148
+ const escTier = nextEscalationTier(run.tier, liveTiers)
149
+ store.upsertRun({
150
+ runId: run.runId,
151
+ status: 'failed',
152
+ childId: info.id,
153
+ stopReason: info.stopReason,
154
+ ...(durationMs !== undefined ? { durationMs } : {}),
155
+ escalationSuggested: escTier,
156
+ ...(lastText ? { summary: lastText } : {}),
157
+ })
158
+ if (escTier) {
159
+ ctx.logger?.info?.(`dsh-agent-router: DSH run ${run.runId} (${run.tier}) failed; consider router_dispatch with tier=${escTier}`)
160
+ }
161
+ }
162
+ })
163
+
164
+ registerRouterTools({
165
+ ctx,
166
+ store,
167
+ queue,
168
+ currentConfig,
169
+ getConfigSource,
170
+ notifyParentAgent,
171
+ activeWriteDirs,
172
+ })
173
+ registerRouterSystemPrompt(ctx)
174
+ mountRouterRpc(ctx, {
175
+ store,
176
+ queue,
177
+ currentConfig,
178
+ getConfigSource,
179
+ saveRouterConfig,
180
+ resetRouterConfig,
181
+ canUseProfileEditor,
182
+ legacyConfig,
183
+ })
184
+ }