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,99 @@
1
+ /**
2
+ * Shared helpers for the Host router modules.
3
+ * @module dsh-agent-router/lib/router/util
4
+ */
5
+
6
+ export function describeThrown(value) {
7
+ try {
8
+ return value instanceof Error ? `${value.name}: ${value.message}` : String(value)
9
+ } catch {
10
+ return 'unrenderable error'
11
+ }
12
+ }
13
+
14
+ /** Structured error for tool arguments rejected before any side effect. */
15
+ export class ToolArgumentError extends Error {
16
+ constructor(toolName, issues) {
17
+ super(`${toolName} invalid arguments: ${issues.map(issue => issue.message).join('; ')}`)
18
+ this.name = 'ToolArgumentError'
19
+ this.code = 'invalid_arguments'
20
+ this.tool = toolName
21
+ this.issues = issues
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Validate top-level tool arguments against the registered JSON Schema subset
27
+ * (required / type / enum / numeric bounds / item count). Kept intentionally
28
+ * small so nested payloads stay governed by their own normalizers.
29
+ */
30
+ export function validateToolArguments(toolName, schema, args) {
31
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
32
+ throw new ToolArgumentError(toolName, [{ path: '', message: 'arguments must be an object' }])
33
+ }
34
+ const issues = []
35
+ for (const key of schema.required || []) {
36
+ const value = args[key]
37
+ if (value === undefined || value === null || value === '') {
38
+ issues.push({ path: key, message: `${key} is required` })
39
+ }
40
+ }
41
+ for (const [key, rule] of Object.entries(schema.properties || {})) {
42
+ const value = args[key]
43
+ if (value === undefined || value === null) continue
44
+ const fail = (expected) => issues.push({ path: key, message: `${key} must be ${expected}` })
45
+ if (rule.type === 'string' && typeof value !== 'string') fail('a string')
46
+ if (rule.type === 'boolean' && typeof value !== 'boolean') fail('a boolean')
47
+ if (rule.type === 'integer' && !Number.isInteger(value)) fail('an integer')
48
+ if (rule.type === 'number' && (typeof value !== 'number' || !Number.isFinite(value))) fail('a finite number')
49
+ if (rule.type === 'array' && !Array.isArray(value)) fail('an array')
50
+ if (rule.enum && !rule.enum.includes(value)) fail(`one of ${rule.enum.join(', ')}`)
51
+ if (typeof value === 'number') {
52
+ if (rule.minimum !== undefined && value < rule.minimum) fail(`>= ${rule.minimum}`)
53
+ if (rule.maximum !== undefined && value > rule.maximum) fail(`<= ${rule.maximum}`)
54
+ }
55
+ if (Array.isArray(value)) {
56
+ if (rule.minItems !== undefined && value.length < rule.minItems) fail(`at least ${rule.minItems} items`)
57
+ if (rule.maxItems !== undefined && value.length > rule.maxItems) fail(`at most ${rule.maxItems} items`)
58
+ }
59
+ }
60
+ if (issues.length > 0) throw new ToolArgumentError(toolName, issues)
61
+ return args
62
+ }
63
+
64
+ /**
65
+ * Recursively normalize a return payload into lossless JSON:
66
+ * omits `undefined` object properties, replaces `undefined` array slots
67
+ * and non-finite numbers (`NaN`, `Infinity`, `-0`) with JSON-safe values.
68
+ */
69
+ export function toLosslessJson(value, seen = new WeakSet()) {
70
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
71
+ return value
72
+ }
73
+ if (typeof value === 'number') {
74
+ if (!Number.isFinite(value)) return null
75
+ return Object.is(value, -0) ? 0 : value
76
+ }
77
+ if (value === undefined || typeof value !== 'object') {
78
+ return null
79
+ }
80
+ if (seen.has(value)) return null
81
+ seen.add(value)
82
+ try {
83
+ if (Array.isArray(value)) {
84
+ return value.map(item => (item === undefined ? null : toLosslessJson(item, seen)))
85
+ }
86
+ const out = {}
87
+ for (const [k, v] of Object.entries(value)) {
88
+ if (v === undefined) continue
89
+ out[k] = toLosslessJson(v, seen)
90
+ }
91
+ return out
92
+ } finally {
93
+ seen.delete(value)
94
+ }
95
+ }
96
+
97
+ export function callerCwd(agent) {
98
+ return agent?.cwd || agent?.session?.header?.cwd || process.cwd()
99
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Single source of truth for the Typert RPC endpoint surface.
3
+ *
4
+ * Consumed by the Host descriptor (`lib/typert.host.js`), the RPC mount
5
+ * (`lib/router/rpc.js`), and the browser client (inlined by
6
+ * `scripts/build-client.mjs`). Add a method to all three by editing this list.
7
+ *
8
+ * @module dsh-agent-router/lib/rpc-contract
9
+ */
10
+
11
+ export const RPC_ENDPOINTS = Object.freeze([
12
+ 'getState',
13
+ 'saveConfig',
14
+ 'resetConfig',
15
+ 'clearCooldowns',
16
+ 'testPlan',
17
+ 'diagnose',
18
+ 'getRunStatus',
19
+ 'cancelRun',
20
+ 'importLegacyConfig',
21
+ 'applyPreset',
22
+ 'exportConfig',
23
+ 'importConfig',
24
+ 'exportMetrics',
25
+ 'checkUpdate',
26
+ ])
27
+
28
+ /**
29
+ * Stable short hash of the endpoint surface.
30
+ *
31
+ * Both the Host and the browser bundle compute this from the same list, so a
32
+ * running Host that predates a newly added endpoint is detectable at runtime
33
+ * instead of failing with a bare HTTP 404.
34
+ *
35
+ * @param {readonly string[]} [endpoints]
36
+ * @returns {string}
37
+ */
38
+ export function contractVersion(endpoints = RPC_ENDPOINTS) {
39
+ const text = [...endpoints].sort().join('|')
40
+ let hash = 0x811c9dc5
41
+ for (let i = 0; i < text.length; i += 1) {
42
+ hash ^= text.charCodeAt(i)
43
+ hash = Math.imul(hash, 0x01000193) >>> 0
44
+ }
45
+ return `rpc-${hash.toString(16).padStart(8, '0')}`
46
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Session registry derived from the run ledger.
3
+ *
4
+ * Keeps resume/cleanup decisions in one place instead of ad-hoc filtering in
5
+ * tools and RPC handlers.
6
+ *
7
+ * @module dsh-agent-router/lib/sessions
8
+ */
9
+
10
+ /**
11
+ * @param {Array<Record<string, any>>} runs
12
+ */
13
+ export function listSessions(runs = []) {
14
+ const bySession = new Map()
15
+ for (const run of Array.isArray(runs) ? runs : []) {
16
+ const sessionId = run?.sessionId
17
+ if (!sessionId) continue
18
+ const updatedAt = Number(run.updatedAt ?? run.createdAt ?? 0)
19
+ const prev = bySession.get(sessionId)
20
+ if (!prev || updatedAt >= prev.updatedAt) {
21
+ bySession.set(sessionId, {
22
+ sessionId,
23
+ runId: run.runId || null,
24
+ backend: run.backend || null,
25
+ tier: run.tier || null,
26
+ status: run.status || 'unknown',
27
+ updatedAt,
28
+ })
29
+ }
30
+ }
31
+ return [...bySession.values()].sort((a, b) => b.updatedAt - a.updatedAt)
32
+ }
33
+
34
+ /**
35
+ * Keep the most recent `keep` sessions (and optionally drop older runs).
36
+ * Runs without a session id are always retained.
37
+ *
38
+ * @param {Array<Record<string, any>>} runs
39
+ * @param {{ keep?: number, maxAgeMs?: number|null, now?: number }} [opts]
40
+ */
41
+ export function pruneSessions(runs = [], { keep = 50, maxAgeMs = null, now = Date.now() } = {}) {
42
+ const source = Array.isArray(runs) ? runs : []
43
+ const keepCount = Math.max(1, Number(keep) || 50)
44
+ const recent = new Set(listSessions(source).slice(0, keepCount).map(entry => entry.sessionId))
45
+ const kept = []
46
+ const removed = []
47
+ for (const run of source) {
48
+ const sessionId = run?.sessionId
49
+ if (!sessionId) {
50
+ kept.push(run)
51
+ continue
52
+ }
53
+ const updatedAt = Number(run.updatedAt ?? run.createdAt ?? 0)
54
+ const tooOld = maxAgeMs !== null && updatedAt > 0 && now - updatedAt > maxAgeMs
55
+ if (recent.has(sessionId) && !tooOld) kept.push(run)
56
+ else removed.push(run)
57
+ }
58
+ return { kept, removed, sessions: listSessions(kept) }
59
+ }
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Bounded-concurrency asynchronous CLI task queue for `dsh-agent-router`.
3
+ * Manages queued / running background dispatches, cancellation, and parent cleanup.
4
+ *
5
+ * @module dsh-agent-router/lib/task-queue
6
+ */
7
+
8
+ export class CliTaskQueue {
9
+ /**
10
+ * @param {{ maxConcurrent?: number }} [options]
11
+ */
12
+ constructor(options = {}) {
13
+ this.maxConcurrent = Math.max(1, Number(options.maxConcurrent ?? 3))
14
+ this.jobs = new Map()
15
+ this.pendingIds = []
16
+ this.runningIds = new Set()
17
+ this.disposed = false
18
+ }
19
+
20
+ setMaxConcurrent(n) {
21
+ const parsed = Math.max(1, Number(n || 3))
22
+ this.maxConcurrent = parsed
23
+ this.#pump()
24
+ }
25
+
26
+ /**
27
+ * Enqueue a background CLI task.
28
+ * @param {{
29
+ * runId: string,
30
+ * parentSessionId?: string,
31
+ * description: string,
32
+ * tier: string,
33
+ * backend: string,
34
+ * execute: (ctx: { signal: AbortSignal, updateProgress: (note: string) => void }) => Promise<any>,
35
+ * onUpdate?: (job: any) => void,
36
+ * onDone?: (job: any, outcome: any, error?: unknown) => void,
37
+ * }} spec
38
+ */
39
+ enqueue(spec) {
40
+ if (this.disposed) {
41
+ throw new Error('CliTaskQueue is disposed')
42
+ }
43
+ const controller = new AbortController()
44
+ const job = {
45
+ runId: spec.runId,
46
+ parentSessionId: spec.parentSessionId || null,
47
+ description: spec.description,
48
+ tier: spec.tier,
49
+ backend: spec.backend,
50
+ status: 'queued',
51
+ progress: 'Queued',
52
+ createdAt: Date.now(),
53
+ startedAt: null,
54
+ finishedAt: null,
55
+ controller,
56
+ execute: spec.execute,
57
+ onUpdate: spec.onUpdate,
58
+ onDone: spec.onDone,
59
+ }
60
+ this.jobs.set(spec.runId, job)
61
+ this.pendingIds.push(spec.runId)
62
+ this.#pump()
63
+ return this.snapshotOf(job)
64
+ }
65
+
66
+ snapshotOf(job) {
67
+ if (!job) return null
68
+ const now = Date.now()
69
+ const base = job.startedAt || job.createdAt
70
+ const end = job.finishedAt || now
71
+ return {
72
+ runId: job.runId,
73
+ parentSessionId: job.parentSessionId,
74
+ description: job.description,
75
+ tier: job.tier,
76
+ backend: job.backend,
77
+ status: job.status,
78
+ progress: job.progress,
79
+ createdAt: job.createdAt,
80
+ startedAt: job.startedAt,
81
+ finishedAt: job.finishedAt,
82
+ elapsedMs: Math.max(0, end - base),
83
+ }
84
+ }
85
+
86
+ get(runId) {
87
+ return this.snapshotOf(this.jobs.get(runId))
88
+ }
89
+
90
+ listActive() {
91
+ const out = []
92
+ for (const job of this.jobs.values()) {
93
+ if (job.status === 'queued' || job.status === 'running') {
94
+ out.push(this.snapshotOf(job))
95
+ }
96
+ }
97
+ return out
98
+ }
99
+
100
+ cancel(runId, reason = 'cancelled by caller') {
101
+ const job = this.jobs.get(runId)
102
+ if (!job) return { found: false, cancelled: false }
103
+ if (job.status !== 'queued' && job.status !== 'running') {
104
+ return { found: true, cancelled: false, status: job.status }
105
+ }
106
+ const wasQueued = job.status === 'queued'
107
+ job.status = 'cancelled'
108
+ job.progress = reason
109
+ job.finishedAt = Date.now()
110
+ if (wasQueued) {
111
+ const idx = this.pendingIds.indexOf(runId)
112
+ if (idx >= 0) this.pendingIds.splice(idx, 1)
113
+ try { job.onUpdate?.(this.snapshotOf(job)) } catch {}
114
+ try { job.onDone?.(this.snapshotOf(job), { ok: false, error: reason }, undefined) } catch {}
115
+ this.#trimFinished()
116
+ } else {
117
+ job.controller.abort(new Error(reason))
118
+ }
119
+ return { found: true, cancelled: true, status: job.status }
120
+ }
121
+
122
+ cancelByParent(parentSessionId, reason = 'parent session disposed') {
123
+ if (!parentSessionId) return 0
124
+ let count = 0
125
+ for (const job of this.jobs.values()) {
126
+ if (job.parentSessionId === parentSessionId && (job.status === 'queued' || job.status === 'running')) {
127
+ if (this.cancel(job.runId, reason).cancelled) count++
128
+ }
129
+ }
130
+ return count
131
+ }
132
+
133
+ dispose() {
134
+ this.disposed = true
135
+ for (const job of this.jobs.values()) {
136
+ if (job.status === 'queued' || job.status === 'running') {
137
+ this.cancel(job.runId, 'plugin unloaded')
138
+ }
139
+ }
140
+ }
141
+
142
+ #pump() {
143
+ while (!this.disposed && this.runningIds.size < this.maxConcurrent && this.pendingIds.length > 0) {
144
+ const nextId = this.pendingIds.shift()
145
+ const job = this.jobs.get(nextId)
146
+ if (!job || job.status !== 'queued') continue
147
+ this.#start(job)
148
+ }
149
+ }
150
+
151
+ #start(job) {
152
+ job.status = 'running'
153
+ job.startedAt = Date.now()
154
+ job.progress = 'Running…'
155
+ this.runningIds.add(job.runId)
156
+ try { job.onUpdate?.(this.snapshotOf(job)) } catch {}
157
+
158
+ const updateProgress = (note) => {
159
+ if (job.status !== 'running') return
160
+ job.progress = String(note || '').slice(0, 180)
161
+ try { job.onUpdate?.(this.snapshotOf(job)) } catch {}
162
+ }
163
+
164
+ Promise.resolve()
165
+ .then(() => job.execute({ signal: job.controller.signal, updateProgress }))
166
+ .then(
167
+ (outcome) => {
168
+ this.runningIds.delete(job.runId)
169
+ if (job.status !== 'cancelled') {
170
+ job.status = outcome?.ok ? 'completed' : 'failed'
171
+ job.finishedAt = Date.now()
172
+ job.progress = outcome?.ok ? 'Completed' : (outcome?.error || 'Failed').slice(0, 180)
173
+ }
174
+ try { job.onDone?.(this.snapshotOf(job), outcome, undefined) } catch {}
175
+ },
176
+ (err) => {
177
+ this.runningIds.delete(job.runId)
178
+ if (job.status !== 'cancelled') {
179
+ job.status = 'failed'
180
+ job.finishedAt = Date.now()
181
+ job.progress = (err instanceof Error ? err.message : String(err)).slice(0, 180)
182
+ }
183
+ try { job.onDone?.(this.snapshotOf(job), { ok: false, error: job.progress }, err) } catch {}
184
+ },
185
+ )
186
+ .finally(() => {
187
+ this.#trimFinished()
188
+ this.#pump()
189
+ })
190
+ }
191
+
192
+ #trimFinished() {
193
+ if (this.jobs.size <= 100) return
194
+ for (const [id, job] of this.jobs) {
195
+ if (this.jobs.size <= 60) break
196
+ if (job.status !== 'queued' && job.status !== 'running') {
197
+ this.jobs.delete(id)
198
+ }
199
+ }
200
+ }
201
+ }