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,126 @@
1
+ /**
2
+ * Opt-in local/self-hosted model discovery.
3
+ *
4
+ * The router never proxies models or stores provider credentials: it only adds
5
+ * providers that are already registered in DSH `ctx.llm` and look local
6
+ * (Ollama, LM Studio, vLLM, llama.cpp, …) when the user explicitly enables them.
7
+ * @module dsh-agent-router/lib/router/local-models
8
+ */
9
+
10
+ import { scoreModelForTier } from '../model-score.js'
11
+
12
+ /** Provider-id / name keywords that identify a local OpenAI-compatible runtime. */
13
+ const LOCAL_PROVIDER_KEYWORDS = Object.freeze([
14
+ 'ollama',
15
+ 'lmstudio',
16
+ 'lm-studio',
17
+ 'lm_studio',
18
+ 'vllm',
19
+ 'llamacpp',
20
+ 'llama.cpp',
21
+ 'llama-cpp',
22
+ 'llama_cpp',
23
+ 'llama',
24
+ 'sglang',
25
+ 'text-generation-webui',
26
+ 'oobabooga',
27
+ 'kobold',
28
+ 'koboldcpp',
29
+ 'tabby',
30
+ 'tabbyapi',
31
+ 'jan',
32
+ 'mlx',
33
+ 'local',
34
+ ])
35
+
36
+ const LOCAL_HOST_RE = /localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]/
37
+
38
+ function providerHaystack(id, info) {
39
+ const fields = [
40
+ id,
41
+ info?.id,
42
+ info?.name,
43
+ info?.baseURL,
44
+ info?.baseUrl,
45
+ info?.endpoint,
46
+ info?.config?.baseURL,
47
+ info?.config?.baseUrl,
48
+ info?.config?.endpoint,
49
+ ]
50
+ return fields.filter(v => typeof v === 'string' && v).join(' ').toLowerCase()
51
+ }
52
+
53
+ /**
54
+ * Whether a DSH provider looks like a local / self-hosted model runtime.
55
+ * @param {string} id
56
+ * @param {any} [info]
57
+ */
58
+ export function isLocalProviderId(id, info) {
59
+ const hay = providerHaystack(id, info)
60
+ if (!hay) return false
61
+ if (LOCAL_HOST_RE.test(hay)) return true
62
+ return LOCAL_PROVIDER_KEYWORDS.some(keyword => hay.includes(keyword))
63
+ }
64
+
65
+ function providerMatchesConfig(id, configured) {
66
+ if (configured.length === 0) return null
67
+ const lower = id.toLowerCase()
68
+ return configured.some(entry => entry.toLowerCase() === lower) || null
69
+ }
70
+
71
+ /**
72
+ * List provider ids that should be treated as local models.
73
+ * @param {{ available: boolean, providers: Map<string, { info?: any, models?: Set<string>|null }> }} catalog
74
+ * @param {string[]} [configured] Explicit provider ids; empty means auto-detect.
75
+ * @returns {string[]}
76
+ */
77
+ export function listLocalProviderIds(catalog, configured = []) {
78
+ if (!catalog?.available || !(catalog.providers instanceof Map)) return []
79
+ const out = []
80
+ for (const [id, entry] of catalog.providers) {
81
+ if (configured.length > 0) {
82
+ if (providerMatchesConfig(id, configured)) out.push(id)
83
+ continue
84
+ }
85
+ if (isLocalProviderId(id, entry?.info)) out.push(id)
86
+ }
87
+ return out
88
+ }
89
+
90
+ /**
91
+ * Build ordered DSH candidate routes for the user's local providers.
92
+ * Only models already enumerable from the live catalog are returned.
93
+ * @param {{ available: boolean, providers: Map<string, { info?: any, models?: Set<string>|null }> }} catalog
94
+ * @param {{ configured?: string[], tier?: string, band?: string, limit?: number }} [options]
95
+ * @returns {{ kind: 'dsh', provider: string, model: string, note: string }[]}
96
+ */
97
+ export function resolveLocalModelRoutes(catalog, { configured = [], tier = 'T2', band, limit = 3 } = {}) {
98
+ if (!catalog?.available || !(catalog.providers instanceof Map)) return []
99
+ const routes = []
100
+ for (const [id, entry] of catalog.providers) {
101
+ if (configured.length > 0) {
102
+ if (!providerMatchesConfig(id, configured)) continue
103
+ } else if (!isLocalProviderId(id, entry?.info)) {
104
+ continue
105
+ }
106
+ const models = entry?.models
107
+ if (!(models instanceof Set) || models.size === 0) continue
108
+ const scored = []
109
+ for (const model of models) {
110
+ const score = scoreModelForTier(model, band || tier)
111
+ if (score <= -50) continue
112
+ scored.push({ model, score })
113
+ }
114
+ scored.sort((a, b) => b.score - a.score)
115
+ for (const item of scored.slice(0, 2)) {
116
+ routes.push({
117
+ kind: 'dsh',
118
+ provider: id,
119
+ model: item.model,
120
+ note: 'Local model (opt-in)',
121
+ })
122
+ if (routes.length >= limit) return routes
123
+ }
124
+ }
125
+ return routes
126
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Ecosystem-aware candidate re-ranking (adaptive EWMA, peak pricing, budget guard,
3
+ * context pressure hints).
4
+ * @module dsh-agent-router/lib/router/policy
5
+ */
6
+
7
+ import { isDeepSeekFamilyRoute } from '../integrations.js'
8
+ import { rankCandidatesWithMetrics } from '../ledger.js'
9
+
10
+ export function applyEcosystemPolicies(candidates, { tier, band, costSnap, contextSnap, cfg, routeMetrics }) {
11
+ const bandKey = band || (tier === 'T1' ? 'light' : (tier === 'T3' ? 'heavy' : (tier === 'T4' ? 'review' : 'standard')))
12
+ const notes = []
13
+ let ordered = candidates.slice()
14
+
15
+ // 0. Adaptive EWMA latency & reliability re-ranking.
16
+ // Explicit local-CLI order is authoritative (top-down); only DSH candidates
17
+ // move, and CLI slots keep their relative positions.
18
+ if (cfg.adaptiveRanking !== false && routeMetrics) {
19
+ const dshOnly = ordered.filter(c => c.kind !== 'cli')
20
+ if (dshOnly.length > 1) {
21
+ const ranked = rankCandidatesWithMetrics(dshOnly, routeMetrics, { tier, band: bandKey, enabled: true })
22
+ let cursor = 0
23
+ ordered = ordered.map(c => (c.kind === 'cli' ? c : ranked.candidates[cursor++]))
24
+ for (const adj of ranked.adjustments) {
25
+ notes.push(`adaptive-routing: ${adj}`)
26
+ }
27
+ }
28
+ }
29
+
30
+ // 1. dsh-cost-meter peak avoidance: deprioritize DeepSeek-family routes during 2x peak hours
31
+ if (cfg.peakAvoidance && costSnap?.available && costSnap.peak?.isPeak) {
32
+ const nonPeak = ordered.filter(c => !isDeepSeekFamilyRoute(c))
33
+ const peakRoutes = ordered.filter(c => isDeepSeekFamilyRoute(c))
34
+ if (nonPeak.length > 0 && peakRoutes.length > 0) {
35
+ ordered = [...nonPeak, ...peakRoutes]
36
+ notes.push('dsh-cost-meter: peak 2x pricing active — deprioritized DeepSeek-family routes')
37
+ }
38
+ }
39
+
40
+ // 2. dsh-cost-meter budget guard: when near/at budget limit, prefer low-cost/CLI routes over expensive T3 DSH models
41
+ if (cfg.budgetGuard && costSnap?.available && (costSnap.budget?.exhausted || (costSnap.budget?.nearLimit && bandKey === 'heavy'))) {
42
+ const cliOrLight = ordered.filter(c => c.kind === 'cli' || /flash|eco|mini/i.test(c.model || ''))
43
+ const others = ordered.filter(c => !(c.kind === 'cli' || /flash|eco|mini/i.test(c.model || '')))
44
+ if (cliOrLight.length > 0) {
45
+ ordered = [...cliOrLight, ...others]
46
+ notes.push(
47
+ costSnap.budget.exhausted
48
+ ? `dsh-cost-meter: budget exhausted (${costSnap.symbol}${costSnap.budget.used.toFixed(2)}/${costSnap.symbol}${costSnap.budget.amount.toFixed(2)}) — preferring local CLI / low-cost routes`
49
+ : `dsh-cost-meter: budget near limit (${Math.round(costSnap.budget.ratio * 100)}%) — preferring economical routes`,
50
+ )
51
+ }
52
+ }
53
+
54
+ // 3. dsh-context / session pressure: warn when parent context is already heavy
55
+ if (contextSnap?.available && contextSnap.high) {
56
+ const pct = Math.round((contextSnap.ratio ?? 0) * 100)
57
+ notes.push(`context-pressure: parent context at ${pct}% — offloading work to isolated child/CLI protects main window`)
58
+ }
59
+
60
+ return { candidates: ordered, notes }
61
+ }
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Typert RPC service used by the Plugin Detail page (client.js) to view and
3
+ * edit live routing rules.
4
+ * @module dsh-agent-router/lib/router/rpc
5
+ */
6
+
7
+ import { buildPresetConfig, buildExportPayload, parseImportPayload } from '../config-presets.js'
8
+ import { buildEvalReport, evalReportToCsv } from '../eval-routing.js'
9
+ import { classifyTask } from '../classifier.js'
10
+ import { discoverCliModels, probeLocalClis } from '../cli-runners.js'
11
+ import { readCostMeterSnapshot } from '../integrations.js'
12
+ import { applyCapabilityPolicy, inferTaskRequirements } from '../model-capabilities.js'
13
+ import { inspectMount } from '../profile-mount.js'
14
+ import { RPC_ENDPOINTS, contractVersion } from '../rpc-contract.js'
15
+ import { resolveTierRef, sortTierEntries, tierBand } from '../tier-presets.js'
16
+ import { TYPERT } from '../typert.host.js'
17
+ import { checkForUpdate } from '../update-check.js'
18
+ import { buildCandidates } from './candidates.js'
19
+ import { listDetailedCatalog, readSubagentModelSelectionStatus } from './catalog.js'
20
+ import { buildDoctorReport } from './doctor.js'
21
+ import { isLocalProviderId } from './local-models.js'
22
+ import { applyEcosystemPolicies } from './policy.js'
23
+ import { toLosslessJson } from './util.js'
24
+
25
+ /**
26
+ * Resolve an optional tier id/name from the UI preview into a real tier key.
27
+ * @param {unknown} ref
28
+ * @param {Record<string, any>} tiers
29
+ */
30
+ function resolveTestTier(ref, tiers) {
31
+ if (ref === undefined || ref === null || String(ref).trim() === '') return undefined
32
+ const id = resolveTierRef(ref, tiers)
33
+ if (!id) {
34
+ const available = sortTierEntries(tiers)
35
+ .map(([tierId]) => `${tierId} (${tiers?.[tierId]?.name || tierId})`)
36
+ .join(', ')
37
+ throw new Error(`unknown tier "${ref}"; available tiers: ${available || 'none'}`)
38
+ }
39
+ return id
40
+ }
41
+
42
+ /**
43
+ * @param {any} ctx
44
+ * @param {{
45
+ * store: import('../ledger.js').RouterStore,
46
+ * queue: import('../job-runner.js').RouterJobRunner,
47
+ * currentConfig: () => Record<string, any>,
48
+ * getConfigSource: () => string,
49
+ * saveRouterConfig: (candidate: any) => Promise<any>,
50
+ * resetRouterConfig: () => Promise<any>,
51
+ * canUseProfileEditor: () => any,
52
+ * legacyConfig: import('../legacy-config.js').LegacyConfigStore,
53
+ * }} runtime
54
+ */
55
+ export function mountRouterRpc(ctx, runtime) {
56
+ const {
57
+ store,
58
+ queue,
59
+ currentConfig,
60
+ getConfigSource,
61
+ saveRouterConfig,
62
+ resetRouterConfig,
63
+ canUseProfileEditor,
64
+ legacyConfig,
65
+ } = runtime
66
+
67
+ const rpcService = {
68
+ async getState() {
69
+ const config = currentConfig()
70
+ const catalog = await listDetailedCatalog(ctx)
71
+ let mount = null
72
+ try {
73
+ mount = inspectMount()
74
+ } catch (error) {
75
+ mount = { state: 'unknown', reason: error instanceof Error ? error.message : String(error) }
76
+ }
77
+ return {
78
+ contract: {
79
+ version: contractVersion(),
80
+ endpoints: [...RPC_ENDPOINTS],
81
+ },
82
+ config,
83
+ configSource: getConfigSource(),
84
+ hasCustomOverride: getConfigSource() !== 'default',
85
+ hasLegacyOverride: legacyConfig.getConfig() !== null && canUseProfileEditor() !== null,
86
+ catalog,
87
+ localProvidersDetected: catalog.filter(entry => isLocalProviderId(entry.id, entry)).map(entry => entry.id),
88
+ localClis: probeLocalClis(),
89
+ cliModels: discoverCliModels(),
90
+ subagentModelSelection: readSubagentModelSelectionStatus(ctx),
91
+ costMeter: await readCostMeterSnapshot(ctx),
92
+ cooldowns: store.activeCooldowns(),
93
+ activeJobs: queue.listActive(),
94
+ routeMetrics: store.getRouteMetrics(),
95
+ stats: store.stats(),
96
+ recentRuns: store.listRuns(15),
97
+ mount,
98
+ }
99
+ },
100
+ async saveConfig(args) {
101
+ return saveRouterConfig(args?.config ?? args)
102
+ },
103
+ async resetConfig() {
104
+ return resetRouterConfig()
105
+ },
106
+ async importLegacyConfig() {
107
+ const legacy = legacyConfig.getConfig()
108
+ if (!legacy) return { ok: false, error: 'No legacy state.json config found' }
109
+ return saveRouterConfig(legacy)
110
+ },
111
+ async applyPreset(args) {
112
+ const name = String(args?.preset ?? '').trim()
113
+ return saveRouterConfig(buildPresetConfig(currentConfig(), name))
114
+ },
115
+ async exportConfig() {
116
+ return buildExportPayload(currentConfig())
117
+ },
118
+ async importConfig(args) {
119
+ const payload = args?.payload ?? args?.config ?? args
120
+ return saveRouterConfig(parseImportPayload(payload))
121
+ },
122
+ async exportMetrics(args) {
123
+ const limit = Math.max(1, Math.min(500, Number(args?.limit) || 200))
124
+ const report = buildEvalReport(store.listRuns(limit), { limit })
125
+ if (args?.format === 'csv') {
126
+ return { format: 'csv', csv: evalReportToCsv(report), stats: store.stats() }
127
+ }
128
+ return { format: 'json', report, stats: store.stats() }
129
+ },
130
+ async cancelRun(args) {
131
+ const runId = String(args?.runId ?? args?.run_id ?? '').trim()
132
+ if (!runId) throw new Error('cancelRun requires runId')
133
+ const res = queue.cancel(runId, 'cancelled from UI')
134
+ if (res.cancelled) {
135
+ store.upsertRun({ runId, status: 'cancelled', progress: 'cancelled from UI' })
136
+ }
137
+ return { ok: true, runId, ...res }
138
+ },
139
+ async clearCooldowns(args) {
140
+ const cleared = store.clearCooldowns(args?.key)
141
+ return { ok: true, cleared }
142
+ },
143
+ async testPlan(args) {
144
+ const task = String(args?.task ?? '').trim()
145
+ if (!task) throw new Error('testPlan requires a non-empty task string')
146
+ const cfg = currentConfig()
147
+ const requestedTier = resolveTestTier(args?.tier, cfg.tiers)
148
+ const classification = classifyTask({ task, tier: requestedTier, domain: args?.domain, tiers: cfg.tiers })
149
+ const plan = await buildCandidates({
150
+ ctx,
151
+ caller: null,
152
+ tier: classification.tier,
153
+ preferBackend: args?.prefer_backend || cfg.preferBackend,
154
+ policies: cfg.tiers,
155
+ store,
156
+ cfg,
157
+ })
158
+ const costSnap = await readCostMeterSnapshot(ctx)
159
+ const adjusted = applyEcosystemPolicies(plan.candidates, {
160
+ tier: classification.tier,
161
+ band: tierBand(classification.tier, cfg.tiers),
162
+ costSnap,
163
+ contextSnap: { available: false },
164
+ cfg,
165
+ routeMetrics: store.getRouteMetrics(),
166
+ })
167
+ const requirements = inferTaskRequirements(task)
168
+ const capability = applyCapabilityPolicy(adjusted.candidates, requirements)
169
+ const policy = cfg.tiers[classification.tier]
170
+ return toLosslessJson({
171
+ classification,
172
+ policyLabel: policy?.name || policy?.label || classification.tier,
173
+ requirements,
174
+ candidates: capability.candidates.map(c => ({
175
+ kind: c.kind,
176
+ key: c.key,
177
+ ...(c.note ? { note: c.note } : {}),
178
+ })),
179
+ cooled: plan.cooled.map(c => ({ key: c.key, remainingMs: c.cooldownRemainingMs })),
180
+ ecosystemNotes: [...adjusted.notes, ...capability.notes, ...plan.selectionNotes],
181
+ })
182
+ },
183
+ async getRunStatus(args) {
184
+ const runId = String(args?.runId ?? args?.run_id ?? '').trim()
185
+ if (!runId) throw new Error('getRunStatus requires runId')
186
+ const run = store.findRun(runId)
187
+ const job = queue.get(runId)
188
+ const terminal = new Set(['completed', 'failed', 'cancelled', 'killed'])
189
+ const status = job?.status || run?.status || 'unknown'
190
+ const startedAt = job?.startedAt ?? run?.startedAt ?? run?.createdAt ?? null
191
+ const finishedAt = job?.finishedAt ?? (terminal.has(status) ? (run?.updatedAt ?? null) : null)
192
+ let elapsedMs = job?.elapsedMs
193
+ if (typeof elapsedMs !== 'number' && startedAt) {
194
+ elapsedMs = Math.max(0, (finishedAt || Date.now()) - startedAt)
195
+ }
196
+ return {
197
+ runId: run?.runId || runId,
198
+ status,
199
+ progress: job?.progress || run?.progress || null,
200
+ elapsedMs: typeof elapsedMs === 'number' ? elapsedMs : null,
201
+ tier: job?.tier || run?.tier || null,
202
+ backend: job?.backend || run?.backend || null,
203
+ routeKey: run?.routeKey || null,
204
+ currentCandidate: run?.routeKey || null,
205
+ sessionId: run?.sessionId || null,
206
+ attempts: Array.isArray(run?.attempts) ? run.attempts : [],
207
+ startedAt,
208
+ finishedAt,
209
+ }
210
+ },
211
+ async diagnose() {
212
+ return buildDoctorReport({ ctx, cfg: currentConfig(), store, queue })
213
+ },
214
+ async checkUpdate(args) {
215
+ return checkForUpdate({ force: Boolean(args?.force) })
216
+ },
217
+ }
218
+
219
+ const missingHandlers = RPC_ENDPOINTS.filter(name => typeof rpcService[name] !== 'function')
220
+ if (missingHandlers.length > 0) {
221
+ throw new Error(`dsh-agent-router: RPC contract is missing handlers for ${missingHandlers.join(', ')}`)
222
+ }
223
+
224
+ Object.defineProperty(rpcService, 'typertRemote', {
225
+ configurable: false,
226
+ enumerable: false,
227
+ writable: false,
228
+ value: {
229
+ service: rpcService,
230
+ serviceKey: 'dsh-agent-router',
231
+ namespace: 'dsh-agent-router',
232
+ },
233
+ })
234
+ if (typeof ctx.provide === 'function') {
235
+ ctx.provide('dsh-agent-router', rpcService)
236
+ }
237
+ if (typeof ctx.inject === 'function') {
238
+ ctx.inject(['typert'], (typertCtx) => {
239
+ const registry = typertCtx.typert
240
+ if (!registry || typeof registry.getPackage !== 'function') return
241
+ if (!registry.getPackage('dsh-agent-router', 'host')) {
242
+ // Normal package-name loader entries are auto-registered by @deepseek-ai/dsh-typert-loader;
243
+ // register manually only in tests/non-loader compositions or file:-URL dev reloaders.
244
+ const entryName = ctx.fiber?.entry?.options?.name
245
+ if (!ctx.fiber?.entry || (typeof entryName === 'string' && entryName.startsWith('file:'))) {
246
+ return registry.register?.(TYPERT)
247
+ }
248
+ return
249
+ }
250
+ // Hot-upgrade compatibility: if DSH cached an older ./typert manifest missing new methods, register them cleanly
251
+ const missing = TYPERT.invocations.filter(def => !registry.local?.get?.(`${def.namespace}/${def.method}`))
252
+ if (missing.length > 0) {
253
+ return registry.register?.({
254
+ package: 'dsh-agent-router-compat',
255
+ face: 'host',
256
+ schemas: [],
257
+ model: { services: [], events: [], objects: [] },
258
+ invocations: missing.map(def => ({ ...def, id: `dsh-agent-router-compat#dsh-agent-router/${def.method}` })),
259
+ })
260
+ }
261
+ })
262
+ }
263
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * System prompt section describing router tools and usage guidance.
3
+ * @module dsh-agent-router/lib/router/system-prompt
4
+ */
5
+
6
+ import { DISPATCH_TOOL } from './tools.js'
7
+
8
+ export function registerRouterSystemPrompt(ctx) {
9
+ // Inject concise orchestration & difficulty-routing guidance when router_dispatch is visible
10
+ const sectionOrder = typeof ctx.systemPrompt?.getSectionOrder === 'function'
11
+ ? (ctx.systemPrompt.getSectionOrder('TOOL_SUBAGENT') ?? 2800) + 10
12
+ : 2810
13
+ ctx.systemPrompt.section({
14
+ name: 'tool:agent_router',
15
+ order: sectionOrder,
16
+ text: (context) => {
17
+ const visible = context.scope === undefined
18
+ ? ctx.tools.get(DISPATCH_TOOL)
19
+ : ctx.tools.get(DISPATCH_TOOL, context.scope, context.toolSet)
20
+ if (visible === undefined) return ''
21
+ return [
22
+ 'Multi-agent difficulty routing (`router_plan`, `router_dispatch`, `router_continue`, `router_status`):',
23
+ '- Route subtasks by complexity. Tiers are configurable; the default four-tier preset is T1 (search/summary/light) -> fast flash models; T2 (scoped coding/tests) -> coding models/Codex; T3 (architecture/complex debug) -> frontier models/Claude Opus; T4 (independent review/audit) -> heterogeneous cross-family reviewer. Use `router_status({ action: "config" })` to inspect custom tier ids/names.',
24
+ '- For parallel write tasks via external CLIs, set `use_worktree: true` (or `background: true` for non-blocking execution); inspect diffs with `router_status({ action: "inspect_worktree_diff" })` and merge cleanly via `merge_worktree`.',
25
+ '- Reuse existing CLI or subagent context with `router_continue` instead of restarting from scratch.',
26
+ ].join('\n')
27
+ },
28
+ })
29
+ }