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,194 @@
1
+ /**
2
+ * Build the ordered candidate route chain for a tier and backend preference.
3
+ * @module dsh-agent-router/lib/router/candidates
4
+ */
5
+
6
+ import { recommendCatalogRoutes } from '../classifier.js'
7
+ import { SUPPORTED_CLIS, probeLocalClis } from '../cli-runners.js'
8
+ import { routeKey } from '../ledger.js'
9
+ import { sortedNormalTiers, tierBand } from '../tier-presets.js'
10
+ import {
11
+ discoverLiveDshCatalog,
12
+ isDshRouteAllowed,
13
+ readParentRoute,
14
+ readSessionModelPolicy,
15
+ readSubagentModelSelectionStatus,
16
+ } from './catalog.js'
17
+ import { selectCliCandidates } from './cli-select.js'
18
+ import { isLocalProviderId, resolveLocalModelRoutes } from './local-models.js'
19
+
20
+ /**
21
+ * Build ordered candidate list for a tier & backend preference.
22
+ * @param {{
23
+ * ctx: any,
24
+ * caller: any,
25
+ * tier: string,
26
+ * preferBackend?: string,
27
+ * policies: any,
28
+ * store: any,
29
+ * cfg?: Record<string, any>,
30
+ * }} options
31
+ */
32
+ export async function buildCandidates({ ctx, caller, tier, preferBackend, policies, store, cfg }) {
33
+ const policy = policies[tier] || sortedNormalTiers(policies)[0]?.[1] || policies.T2
34
+ const band = tierBand(tier, policies)
35
+ const catalog = await discoverLiveDshCatalog(ctx)
36
+ const hostPolicy = readSubagentModelSelectionStatus(ctx)
37
+ const sessionAllowlist = caller
38
+ ? readSessionModelPolicy(caller)
39
+ : (hostPolicy.enabled ? hostPolicy.allowedModels : null)
40
+ const parentRoute = readParentRoute(caller)
41
+ const localClis = probeLocalClis()
42
+ const allowLocalModels = cfg?.allowLocalModels === true
43
+ const selectionNotes = []
44
+
45
+ const dshCandidates = []
46
+ const blockedDshRoutes = []
47
+ const seenDsh = new Set()
48
+ for (const entry of policy.dsh || []) {
49
+ const id = `${entry.provider}/${entry.model}`
50
+ if (seenDsh.has(id)) continue
51
+ if (isDshRouteAllowed(entry, catalog, sessionAllowlist, parentRoute)) {
52
+ seenDsh.add(id)
53
+ dshCandidates.push({ kind: 'dsh', ...entry })
54
+ } else {
55
+ const reason = sessionAllowlist !== null
56
+ ? 'not in subagent-model-selection-settings allowedModels'
57
+ : (parentRoute && (entry.provider !== parentRoute.provider || entry.model !== parentRoute.model)
58
+ ? 'subagent-model-selection disabled; limited to parent route'
59
+ : 'provider/model not registered in ctx.llm')
60
+ blockedDshRoutes.push({ route: id, reason })
61
+ }
62
+ }
63
+ // If configured routes had zero live/allowed matches, try smart catalog synthesis first
64
+ if (dshCandidates.length === 0 && catalog.available) {
65
+ const catalogArray = Array.from(catalog.providers.entries())
66
+ // Local providers stay out of automatic discovery unless the user opted in.
67
+ .filter(([id, entry]) => allowLocalModels || !isLocalProviderId(id, entry?.info))
68
+ .map(([id, entry]) => ({
69
+ id,
70
+ models: entry.models ? Array.from(entry.models).map(mid => ({ id: mid })) : [],
71
+ }))
72
+ const recommended = recommendCatalogRoutes(catalogArray, { tier, tiers: policies, parentRoute })
73
+ for (const rec of recommended) {
74
+ const id = `${rec.provider}/${rec.model}`
75
+ if (!seenDsh.has(id) && isDshRouteAllowed(rec, catalog, sessionAllowlist, parentRoute)) {
76
+ seenDsh.add(id)
77
+ dshCandidates.push(rec)
78
+ }
79
+ }
80
+ }
81
+ // If sessionAllowlist had routes not explicitly listed in tier config, append them as backup
82
+ if (sessionAllowlist && dshCandidates.length === 0) {
83
+ for (const allowed of sessionAllowlist) {
84
+ const id = `${allowed.provider}/${allowed.model}`
85
+ if (!seenDsh.has(id) && isDshRouteAllowed(allowed, catalog, sessionAllowlist, parentRoute)) {
86
+ seenDsh.add(id)
87
+ dshCandidates.push({ kind: 'dsh', provider: allowed.provider, model: allowed.model, note: 'Session allowlist fallback' })
88
+ }
89
+ }
90
+ }
91
+ // If no allowlist exists and parentRoute is known, ensure parent route is available as fallback
92
+ let parentFallbackUsed = false
93
+ if (dshCandidates.length === 0 && parentRoute && isDshRouteAllowed(parentRoute, catalog, sessionAllowlist, parentRoute)) {
94
+ parentFallbackUsed = true
95
+ dshCandidates.push({ kind: 'dsh', provider: parentRoute.provider, model: parentRoute.model, note: 'Parent route fallback' })
96
+ }
97
+
98
+ // Opt-in local models: only when explicitly enabled, and only routes the
99
+ // current session policy would also accept for a normal DSH provider.
100
+ const localModelRoutes = []
101
+ if (allowLocalModels) {
102
+ const configuredProviders = Array.isArray(cfg?.localProviders) ? cfg.localProviders : []
103
+ const discovered = resolveLocalModelRoutes(catalog, { configured: configuredProviders, tier, band })
104
+ for (const route of discovered) {
105
+ const id = `${route.provider}/${route.model}`
106
+ if (seenDsh.has(id)) continue
107
+ if (!isDshRouteAllowed(route, catalog, sessionAllowlist, parentRoute)) {
108
+ blockedDshRoutes.push({ route: id, reason: 'local model blocked by current subagent model policy' })
109
+ continue
110
+ }
111
+ seenDsh.add(id)
112
+ localModelRoutes.push(route)
113
+ }
114
+ if (localModelRoutes.length > 0) {
115
+ // Cheap/local work benefits T1–T2; keep frontier tiers ahead of local models.
116
+ const insertAt = band === 'light' || band === 'standard' ? 0 : dshCandidates.length
117
+ dshCandidates.splice(insertAt, 0, ...localModelRoutes)
118
+ selectionNotes.push(`local-models: ${localModelRoutes.length} opt-in local route(s) included for ${tier}`)
119
+ } else {
120
+ selectionNotes.push('local-models: enabled, but no enumerable local provider/model was found in ctx.llm')
121
+ }
122
+ }
123
+
124
+ const cliSelection = cfg?.cliSelection === 'adaptive' ? 'adaptive' : 'static'
125
+ const cliPick = selectCliCandidates({
126
+ entries: policy.cli || [],
127
+ localClis,
128
+ tier,
129
+ band,
130
+ cliSelection,
131
+ routeMetrics: typeof store?.getRouteMetrics === 'function' ? store.getRouteMetrics() : {},
132
+ })
133
+ const cliCandidates = cliPick.candidates
134
+ selectionNotes.push(...cliPick.notes)
135
+
136
+ let ordered = []
137
+ const effectivePrefer = preferBackend && preferBackend !== 'auto'
138
+ ? preferBackend
139
+ : (policy.preferBackend || 'auto')
140
+
141
+ if (effectivePrefer === 'dsh') {
142
+ // When T1 falls back to an expensive parent route and fast local CLIs are available, keep DSH fallback only if no CLI exists or user explicitly forced 'dsh'
143
+ ordered = [...dshCandidates, ...cliCandidates]
144
+ } else if (effectivePrefer === 'cli') {
145
+ ordered = [...cliCandidates, ...dshCandidates]
146
+ } else if (SUPPORTED_CLIS.includes(effectivePrefer)) {
147
+ const picked = cliCandidates.filter(c => c.backend === effectivePrefer)
148
+ if (picked.length > 0) {
149
+ ordered = picked
150
+ } else if (localClis[effectivePrefer]?.installed) {
151
+ ordered = [{ kind: 'cli', backend: effectivePrefer, binPath: localClis[effectivePrefer].path, note: 'Explicit CLI backend' }]
152
+ }
153
+ } else {
154
+ // 'auto': interleave DSH first for T1/T2 (unless T1 only has parent-route fallback and CLIs exist), or CLI+DSH balanced for T3/T4
155
+ if (band === 'heavy' || band === 'review') {
156
+ const maxLen = Math.max(dshCandidates.length, cliCandidates.length)
157
+ for (let i = 0; i < maxLen; i++) {
158
+ if (dshCandidates[i]) ordered.push(dshCandidates[i])
159
+ if (cliCandidates[i]) ordered.push(cliCandidates[i])
160
+ }
161
+ } else if (band === 'light' && parentFallbackUsed && cliCandidates.length > 0) {
162
+ ordered = [...cliCandidates, ...dshCandidates]
163
+ } else {
164
+ ordered = [...dshCandidates, ...cliCandidates]
165
+ }
166
+ }
167
+
168
+ const healthy = []
169
+ const cooled = []
170
+ const now = Date.now()
171
+ for (const c of ordered) {
172
+ const key = routeKey(c)
173
+ const health = store.checkHealth(key, now)
174
+ if (health.available) {
175
+ healthy.push({ ...c, key })
176
+ } else {
177
+ cooled.push({ ...c, key, cooldownRemainingMs: health.remainingMs, cooldownReason: health.reason })
178
+ }
179
+ }
180
+
181
+ return {
182
+ candidates: healthy.length > 0 ? healthy : cooled,
183
+ allCooled: healthy.length === 0 && cooled.length > 0,
184
+ cooled,
185
+ blockedDshRoutes,
186
+ localClis,
187
+ localModelsEnabled: allowLocalModels,
188
+ localModelRoutes,
189
+ cliSelection,
190
+ selectionNotes,
191
+ subagentModelSelectionEnabled: sessionAllowlist !== null,
192
+ parentFallbackUsed,
193
+ }
194
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Live DSH catalog, session model policy, and route reachability helpers.
3
+ * @module dsh-agent-router/lib/router/catalog
4
+ */
5
+
6
+ export function readSessionModelPolicy(agent) {
7
+ try {
8
+ const events = agent?.session?.snapshotEvents?.()
9
+ if (!Array.isArray(events)) return null
10
+ for (let i = events.length - 1; i >= 0; i--) {
11
+ const ev = events[i]
12
+ if (ev?.type === 'subagent/model-selection-policy' && Array.isArray(ev.data?.allowedModels)) {
13
+ return ev.data.allowedModels
14
+ }
15
+ }
16
+ } catch {
17
+ // Ignore when session snapshot is unavailable
18
+ }
19
+ return null
20
+ }
21
+
22
+ export function readParentRoute(agent) {
23
+ try {
24
+ const reqCfg = agent?.session?.requestHeader?.()?.config
25
+ if (reqCfg && typeof reqCfg.provider === 'string' && typeof reqCfg.model === 'string') {
26
+ return { provider: reqCfg.provider, model: reqCfg.model }
27
+ }
28
+ } catch {}
29
+ const opts = agent?.agentOptions || agent?.options || agent?.session?.header?.agentOptions
30
+ if (opts && typeof opts.provider === 'string' && typeof opts.model === 'string') {
31
+ return { provider: opts.provider, model: opts.model }
32
+ }
33
+ return null
34
+ }
35
+
36
+ export function readSubagentModelSelectionStatus(ctx) {
37
+ try {
38
+ const svc = ctx.get?.('subagentModelSelection')
39
+ if (svc && typeof svc.current === 'function') {
40
+ const cur = svc.current()
41
+ return {
42
+ available: true,
43
+ enabled: cur?.enabled === true,
44
+ allowedModels: Array.isArray(cur?.allowedModels) ? cur.allowedModels : [],
45
+ }
46
+ }
47
+ } catch {}
48
+ return { available: false, enabled: false, allowedModels: [] }
49
+ }
50
+
51
+ export async function discoverLiveDshCatalog(ctx) {
52
+ const llm = ctx.get?.('llm')
53
+ if (!llm || typeof llm.listProviders !== 'function') {
54
+ return { available: false, providers: new Map() }
55
+ }
56
+ const providers = new Map()
57
+ try {
58
+ const list = llm.listProviders() || []
59
+ for (const p of list) {
60
+ let modelIds = null
61
+ if (typeof llm.listModels === 'function') {
62
+ try {
63
+ const models = await llm.listModels(p.id)
64
+ if (Array.isArray(models)) {
65
+ modelIds = new Set(models.map(m => m.id))
66
+ }
67
+ } catch {
68
+ modelIds = null
69
+ }
70
+ }
71
+ providers.set(p.id, { info: p, models: modelIds })
72
+ }
73
+ return { available: true, providers }
74
+ } catch {
75
+ return { available: false, providers: new Map() }
76
+ }
77
+ }
78
+
79
+ export function isDshRouteAllowed(route, catalog, sessionAllowlist, parentRoute) {
80
+ if (sessionAllowlist !== null) {
81
+ const inAllowlist = sessionAllowlist.some(
82
+ a => a.provider === route.provider && a.model === route.model,
83
+ )
84
+ if (!inAllowlist) return false
85
+ } else if (parentRoute) {
86
+ if (route.provider !== parentRoute.provider || route.model !== parentRoute.model) {
87
+ return false
88
+ }
89
+ }
90
+ if (!catalog.available) return true
91
+ const prov = catalog.providers.get(route.provider)
92
+ if (!prov) return false
93
+ if (prov.models !== null && !prov.models.has(route.model)) return false
94
+ return true
95
+ }
96
+
97
+ export async function listDetailedCatalog(ctx) {
98
+ const llm = ctx.get?.('llm')
99
+ if (!llm || typeof llm.listProviders !== 'function') return []
100
+ const out = []
101
+ try {
102
+ const providers = llm.listProviders() || []
103
+ for (const p of providers) {
104
+ let models = []
105
+ if (typeof llm.listModels === 'function') {
106
+ try {
107
+ const list = await llm.listModels(p.id)
108
+ if (Array.isArray(list)) {
109
+ models = list.map(m => ({
110
+ id: m.id,
111
+ name: m.name || m.id,
112
+ efforts: Array.isArray(m.reasoning?.efforts) ? m.reasoning.efforts.map(e => e.id) : [],
113
+ }))
114
+ }
115
+ } catch {}
116
+ }
117
+ out.push({ id: p.id, name: p.name || p.id, models })
118
+ }
119
+ } catch {}
120
+ return out
121
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Local CLI candidate selection.
3
+ *
4
+ * `static` keeps exactly the per-tier CLI chain from config. `adaptive` keeps
5
+ * that chain as the authoritative top-down order and appends other installed
6
+ * CLIs; only the appended block is re-ranked with historical metrics.
7
+ * @module dsh-agent-router/lib/router/cli-select
8
+ */
9
+
10
+ import { SUPPORTED_CLIS } from '../cli-runners.js'
11
+ import { rankCandidatesWithMetrics, routeKey } from '../ledger.js'
12
+
13
+ /** Tier-heuristic order used when supplementing installed CLIs. */
14
+ const TIER_CLI_ORDER = Object.freeze({
15
+ T1: ['gemini', 'antigravity', 'claude', 'opencode', 'codex'],
16
+ T2: ['codex', 'antigravity', 'opencode', 'claude', 'gemini'],
17
+ T3: ['claude', 'antigravity', 'codex', 'gemini', 'opencode'],
18
+ T4: ['claude', 'antigravity', 'codex', 'gemini', 'opencode'],
19
+ })
20
+
21
+ const BAND_TO_TIER = Object.freeze({ light: 'T1', standard: 'T2', heavy: 'T3', review: 'T4' })
22
+
23
+ /**
24
+ * @param {{
25
+ * entries?: Array<{ backend: string, model?: string, effort?: string, note?: string }>,
26
+ * localClis: Record<string, { installed?: boolean, path?: string|null }>,
27
+ * tier: string,
28
+ * band?: 'light'|'standard'|'heavy'|'review',
29
+ * cliSelection?: 'static'|'adaptive',
30
+ * routeMetrics?: Record<string, any>,
31
+ * }} options
32
+ * @returns {{ candidates: any[], notes: string[] }}
33
+ */
34
+ export function selectCliCandidates({
35
+ entries = [],
36
+ localClis = {},
37
+ tier = 'T2',
38
+ band,
39
+ cliSelection = 'static',
40
+ routeMetrics = {},
41
+ } = {}) {
42
+ const notes = []
43
+ const candidates = []
44
+ const seen = new Set()
45
+
46
+ for (const entry of entries) {
47
+ if (!entry || !SUPPORTED_CLIS.includes(entry.backend)) continue
48
+ const bin = localClis[entry.backend]
49
+ if (!bin?.installed) continue
50
+ seen.add(entry.backend)
51
+ candidates.push({ kind: 'cli', ...entry, binPath: bin.path })
52
+ }
53
+
54
+ if (cliSelection !== 'adaptive') {
55
+ return { candidates, notes }
56
+ }
57
+
58
+ const order = TIER_CLI_ORDER[BAND_TO_TIER[band] || tier] || SUPPORTED_CLIS
59
+ const supplemental = []
60
+ for (const backend of order) {
61
+ if (seen.has(backend)) continue
62
+ const bin = localClis[backend]
63
+ if (!bin?.installed) continue
64
+ seen.add(backend)
65
+ supplemental.push({
66
+ kind: 'cli',
67
+ backend,
68
+ binPath: bin.path,
69
+ note: `Adaptive selection: installed ${backend} CLI auto-added for ${tier}`,
70
+ })
71
+ notes.push(`cli-adaptive: auto-added installed ${backend} CLI for ${tier}`)
72
+ }
73
+
74
+ if (supplemental.length === 0) {
75
+ return { candidates, notes }
76
+ }
77
+
78
+ const keyed = supplemental.map(candidate => ({ ...candidate, key: routeKey(candidate) }))
79
+ const ranked = rankCandidatesWithMetrics(keyed, routeMetrics, { tier, band, enabled: true })
80
+ for (const adjustment of ranked.adjustments) {
81
+ notes.push(`cli-adaptive: ${adjustment}`)
82
+ }
83
+ return { candidates: [...candidates, ...ranked.candidates], notes }
84
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Effective-config resolution and persistence (Profile editor first, legacy
3
+ * ledger override second, built-in defaults last).
4
+ * @module dsh-agent-router/lib/router/config-manager
5
+ */
6
+
7
+ import { unwrapConfigObject } from '../config-schema.js'
8
+ import { buildBaseConfig, sanitizeConfigInput } from '../config-normalize.js'
9
+ import { CONFIG_VERSION } from '../defaults.js'
10
+ import { normalizeTierEntries, validateTierEntries } from '../tier-presets.js'
11
+
12
+ /**
13
+ * @param {{
14
+ * ctx: any,
15
+ * store: import('../ledger.js').RouterStore,
16
+ * queue: import('../job-runner.js').RouterJobRunner,
17
+ * legacyConfig: import('../legacy-config.js').LegacyConfigStore,
18
+ * baseConfig: Record<string, any>,
19
+ * raw: any,
20
+ * }} deps
21
+ */
22
+ export function createConfigManager({ ctx, store, queue, legacyConfig, baseConfig, raw }) {
23
+ const canUseProfileEditor = () => {
24
+ const entry = ctx.fiber?.entry
25
+ const editor = ctx.get?.('configEditor')
26
+ if (!entry || !editor || typeof editor.edit !== 'function') return null
27
+ try {
28
+ const entries = typeof editor.entries === 'function' ? editor.entries() : [entry]
29
+ if (Array.isArray(entries) && !entries.includes(entry)) return null
30
+ } catch {}
31
+ return { entry, editor }
32
+ }
33
+
34
+ const hasProfileOverride = () => {
35
+ const ed = canUseProfileEditor()
36
+ if (!ed) return false
37
+ try {
38
+ const cfg = ed.entry.options?.config
39
+ return Boolean(cfg && typeof cfg === 'object' && Object.keys(cfg).length > 0)
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ const getConfigSource = () => {
46
+ if (hasProfileOverride()) return 'profile-patch'
47
+ if (legacyConfig.getConfig() !== null) return 'legacy-state'
48
+ return 'default'
49
+ }
50
+
51
+ const currentConfig = () => {
52
+ const uiOverride = legacyConfig.getConfig()
53
+ const resolved = uiOverride ? sanitizeConfigInput(uiOverride, baseConfig) : baseConfig
54
+ store.cooldownMs = resolved.cooldownMs
55
+ store.setMaxRuns(resolved.maxRuns)
56
+ store.setFilePath(resolved.ledgerFile)
57
+ queue.setMaxConcurrent(resolved.maxConcurrentCli)
58
+ queue.setUseNativeJobs(resolved.useNativeJobs)
59
+ return resolved
60
+ }
61
+
62
+ const saveRouterConfig = async (candidate) => {
63
+ const src = candidate && typeof candidate === 'object' ? candidate : {}
64
+ const candidateLayout = src.tierLayout === 'custom'
65
+ || (src.tierLayout === undefined && src.tiers !== undefined && Number(src.configVersion) >= CONFIG_VERSION)
66
+ const checkedTiers = normalizeTierEntries(src.tiers, {
67
+ authoritative: candidateLayout,
68
+ baseTiers: baseConfig.tiers,
69
+ })
70
+ const tierProblems = [...checkedTiers.issues, ...validateTierEntries(checkedTiers.tiers)]
71
+ if (tierProblems.length > 0) {
72
+ throw new Error(`配置无效:${tierProblems.join(';')}`)
73
+ }
74
+ const next = sanitizeConfigInput(candidate, baseConfig)
75
+ // Drop absent optional keys: the YAML patch writer omits `undefined`, and
76
+ // configEditor compares the written row with this object by deep equality.
77
+ for (const key of Object.keys(next)) {
78
+ if (next[key] === undefined) delete next[key]
79
+ }
80
+ const ed = canUseProfileEditor()
81
+ if (ed) {
82
+ await ed.editor.edit(ed.entry, () => next)
83
+ // Keep store override clear so profile cordis.patch.yml is the single source of truth
84
+ if (legacyConfig.getConfig() !== null) legacyConfig.clearConfig()
85
+ Object.assign(baseConfig, next)
86
+ } else {
87
+ legacyConfig.setConfig(next)
88
+ }
89
+ store.cooldownMs = next.cooldownMs
90
+ store.setMaxRuns(next.maxRuns)
91
+ store.setFilePath(next.ledgerFile)
92
+ queue.setMaxConcurrent(next.maxConcurrentCli)
93
+ queue.setUseNativeJobs(next.useNativeJobs)
94
+ return { ok: true, config: next, configSource: getConfigSource(), warnings: checkedTiers.warnings }
95
+ }
96
+
97
+ const resetRouterConfig = async () => {
98
+ const ed = canUseProfileEditor()
99
+ if (ed) {
100
+ await ed.editor.edit(ed.entry, () => ({}))
101
+ }
102
+ legacyConfig.clearConfig()
103
+ const freshDefaults = buildBaseConfig(unwrapConfigObject(raw))
104
+ Object.assign(baseConfig, freshDefaults)
105
+ store.cooldownMs = freshDefaults.cooldownMs
106
+ store.setMaxRuns(freshDefaults.maxRuns)
107
+ store.setFilePath(freshDefaults.ledgerFile)
108
+ queue.setMaxConcurrent(freshDefaults.maxConcurrentCli)
109
+ queue.setUseNativeJobs(freshDefaults.useNativeJobs)
110
+ const config = currentConfig()
111
+ return { ok: true, config, configSource: getConfigSource() }
112
+ }
113
+
114
+ return {
115
+ canUseProfileEditor,
116
+ hasProfileOverride,
117
+ getConfigSource,
118
+ currentConfig,
119
+ saveRouterConfig,
120
+ resetRouterConfig,
121
+ }
122
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Read-only environment diagnostics for the router UI, `router_status doctor`,
3
+ * and troubleshooting docs. Never mutates config, the ledger, or DSH state.
4
+ * @module dsh-agent-router/lib/router/doctor
5
+ */
6
+
7
+ import { SUPPORTED_CLIS, discoverCliModels, probeLocalClis } from '../cli-runners.js'
8
+ import { readCostMeterSnapshot } from '../integrations.js'
9
+ import { inspectMount } from '../profile-mount.js'
10
+ import { discoverLiveDshCatalog, readSubagentModelSelectionStatus } from './catalog.js'
11
+ import { listLocalProviderIds, resolveLocalModelRoutes } from './local-models.js'
12
+
13
+ function summarize(checks) {
14
+ const summary = { ok: 0, warn: 0, fail: 0 }
15
+ for (const check of checks) summary[check.status] = (summary[check.status] ?? 0) + 1
16
+ return summary
17
+ }
18
+
19
+ /**
20
+ * Build a structured diagnostics report.
21
+ * @param {{
22
+ * ctx: any,
23
+ * cfg: Record<string, any>,
24
+ * store: import('../ledger.js').RouterStore,
25
+ * queue: import('../job-runner.js').RouterJobRunner,
26
+ * }} runtime
27
+ * @returns {Promise<{
28
+ * ok: boolean,
29
+ * status: 'ok'|'warn'|'fail',
30
+ * checks: Array<{ id: string, status: 'ok'|'warn'|'fail'|'info', message: string, hint?: string }>,
31
+ * summary: { ok: number, warn: number, fail: number },
32
+ * suggestions: string[],
33
+ * }>}
34
+ */
35
+ export async function buildDoctorReport({ ctx, cfg, store, queue }) {
36
+ const checks = []
37
+ const push = (id, status, message, hint) => {
38
+ checks.push({ id, status, message, ...(hint ? { hint } : {}) })
39
+ }
40
+
41
+ // 1. DSH native LLM catalog
42
+ const catalog = await discoverLiveDshCatalog(ctx)
43
+ const providerCount = catalog.available ? catalog.providers.size : 0
44
+ if (!catalog.available) {
45
+ push('dsh-catalog', 'fail', 'ctx.llm is unavailable; DSH native routes cannot be planned.', 'Run inside DSH and restart after installing or upgrading this plugin.')
46
+ } else if (providerCount === 0) {
47
+ push('dsh-catalog', 'fail', 'No DSH LLM providers are registered.', 'Register at least one provider in DSH, or use local CLI routes only.')
48
+ } else {
49
+ push('dsh-catalog', 'ok', `${providerCount} DSH provider(s) reachable.`)
50
+ }
51
+
52
+ // 2. subagent-model-selection (required for native subagents to switch models)
53
+ const selection = readSubagentModelSelectionStatus(ctx)
54
+ if (!selection.available) {
55
+ push('subagent-model-selection', 'warn', 'DSH subagent-model-selection is not exposed in this build.', 'Native subagents will follow the parent route; external CLIs are unaffected.')
56
+ } else if (!selection.enabled) {
57
+ push('subagent-model-selection', 'warn', 'subagent-model-selection-settings is disabled.', 'Enable it and add tier models to allowedModels so native subagents can switch models.')
58
+ } else {
59
+ push('subagent-model-selection', 'ok', `Enabled with ${selection.allowedModels.length} allowed model(s).`)
60
+ }
61
+
62
+ // 3. Local agent CLIs
63
+ const localClis = probeLocalClis()
64
+ const installed = SUPPORTED_CLIS.filter(name => localClis[name]?.installed)
65
+ if (installed.length === 0) {
66
+ push('local-clis', 'warn', 'No supported local agent CLI was found on PATH.', 'Install claude, codex, gemini, opencode, or antigravity (agy), or keep DSH routes in each tier.')
67
+ } else {
68
+ const cliModels = discoverCliModels()
69
+ const defaults = installed
70
+ .map(name => (cliModels[name]?.defaultModel ? `${name} (${cliModels[name].defaultModel})` : name))
71
+ .join(', ')
72
+ push('local-clis', 'ok', `Installed: ${defaults}.`)
73
+ }
74
+
75
+ // 4. CLI selection strategy
76
+ if (cfg.cliSelection === 'adaptive') {
77
+ push('cli-selection', 'ok', 'CLI selection is adaptive: installed CLIs are auto-added and re-ranked by recent metrics.')
78
+ } else {
79
+ push('cli-selection', 'ok', 'CLI selection is static: each tier uses exactly its configured CLI chain.', 'Set cliSelection to "adaptive" to auto-include installed CLIs and use EWMA history.')
80
+ }
81
+
82
+ // 5. Opt-in local models
83
+ const configuredProviders = Array.isArray(cfg.localProviders) ? cfg.localProviders : []
84
+ if (!cfg.allowLocalModels) {
85
+ push('local-models', 'ok', 'Local/self-hosted models are disabled (default).', 'Enable allowLocalModels to include Ollama, LM Studio, vLLM, and similar DSH providers.')
86
+ } else {
87
+ const detected = listLocalProviderIds(catalog, configuredProviders)
88
+ const routes = resolveLocalModelRoutes(catalog, { configured: configuredProviders, tier: 'T2', limit: 5 })
89
+ if (routes.length === 0) {
90
+ push('local-models', 'warn', `Local models enabled, but no enumerable local provider/model was found${detected.length ? ` (providers: ${detected.join(', ')})` : ''}.`, 'Register a local OpenAI-compatible provider in DSH, or list its provider id in localProviders.')
91
+ } else {
92
+ push('local-models', 'ok', `Local routes available: ${routes.map(r => `${r.provider}/${r.model}`).join(', ')}.`)
93
+ }
94
+ }
95
+
96
+ // 6. Native background jobs
97
+ const hasNativeJobs = Boolean(ctx.get?.('jobs'))
98
+ if (cfg.useNativeJobs && !hasNativeJobs) {
99
+ push('native-jobs', 'warn', 'useNativeJobs is enabled but ctx.jobs is unavailable; the built-in queue is used.', 'Disable useNativeJobs to silence this, or upgrade DSH to a build that exposes ctx.jobs.')
100
+ } else {
101
+ push('native-jobs', 'ok', hasNativeJobs ? 'DSH native job registry detected.' : 'Using the built-in bounded background queue.')
102
+ }
103
+
104
+ // 7. Optional dsh-cost-meter link
105
+ const costMeter = await readCostMeterSnapshot(ctx)
106
+ push(
107
+ 'cost-meter',
108
+ 'ok',
109
+ costMeter.available
110
+ ? `dsh-cost-meter linked${costMeter.budget?.enabled ? ' with budget limits' : ''}.`
111
+ : 'dsh-cost-meter is not installed (optional).',
112
+ )
113
+
114
+ // 8. Ledger & cooldowns
115
+ const stats = store.stats()
116
+ const cooldowns = store.activeCooldowns()
117
+ push('ledger', 'ok', `Ledger: ${store.filePath} · ${stats.total} run(s) · ${cooldowns.length} cooldown(s).`)
118
+
119
+ // 9. Install mount mode (standard bundle vs hand-written insert)
120
+ let mount = null
121
+ try {
122
+ mount = inspectMount()
123
+ } catch (error) {
124
+ mount = { state: 'unknown', reason: error instanceof Error ? error.message : String(error) }
125
+ }
126
+ if (mount && (mount.state === 'manual' || mount.state === 'duplicate')) {
127
+ const location = mount.profileDir || mount.files?.homePatch || 'unknown profile'
128
+ push(
129
+ 'mount',
130
+ 'warn',
131
+ `Non-standard ${mount.state} mount detected in ${location}.`,
132
+ Array.isArray(mount.guidance) && mount.guidance.length > 0
133
+ ? mount.guidance.join(' ')
134
+ : 'Remove the hand-written - insert: block, run npm run profile:repair, and restart DSH.',
135
+ )
136
+ } else if (!mount || mount.state === 'unknown') {
137
+ push(
138
+ 'mount',
139
+ 'info',
140
+ mount?.reason || 'Mount state is unknown (plugin is not installed in a profile, or the profile is ambiguous).',
141
+ Array.isArray(mount?.guidance) && mount.guidance.length > 0 ? mount.guidance.join(' ') : undefined,
142
+ )
143
+ } else {
144
+ push('mount', 'ok', `Standard bundle install detected${mount.profile ? ` (${mount.profile})` : ''}.`)
145
+ }
146
+
147
+ // 10. Background queue
148
+ const activeJobs = queue.listActive()
149
+ push('background-queue', 'ok', activeJobs.length > 0 ? `${activeJobs.length} active background job(s).` : 'No active background jobs.')
150
+
151
+ const summary = summarize(checks)
152
+ return {
153
+ ok: summary.fail === 0,
154
+ status: summary.fail > 0 ? 'fail' : (summary.warn > 0 ? 'warn' : 'ok'),
155
+ checks,
156
+ summary,
157
+ suggestions: checks.filter(check => check.hint && check.status !== 'ok').map(check => check.hint),
158
+ }
159
+ }