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,287 @@
1
+ /**
2
+ * Background execution facade: use the DSH native `ctx.jobs` registry when it
3
+ * is available, otherwise fall back to the built-in bounded CLI queue.
4
+ *
5
+ * The public surface matches {@link CliTaskQueue} so tools, RPC, and config
6
+ * management stay unchanged.
7
+ *
8
+ * @module dsh-agent-router/lib/job-runner
9
+ */
10
+
11
+ import { CliTaskQueue } from './task-queue.js'
12
+
13
+ export const ROUTER_JOB_KIND = 'router-cli'
14
+
15
+ function snapshotOf(record) {
16
+ const now = Date.now()
17
+ const base = record.startedAt || record.createdAt
18
+ const end = record.finishedAt || now
19
+ return {
20
+ runId: record.runId,
21
+ parentSessionId: record.parentSessionId,
22
+ description: record.description,
23
+ tier: record.tier,
24
+ backend: record.backend,
25
+ status: record.status,
26
+ progress: record.progress,
27
+ createdAt: record.createdAt,
28
+ startedAt: record.startedAt,
29
+ finishedAt: record.finishedAt,
30
+ elapsedMs: Math.max(0, end - base),
31
+ ...(record.jobId ? { jobId: record.jobId } : {}),
32
+ }
33
+ }
34
+
35
+ export class RouterJobRunner {
36
+ /**
37
+ * @param {{ ctx: any, maxConcurrent?: number, useNativeJobs?: boolean }} options
38
+ */
39
+ constructor({ ctx, maxConcurrent, useNativeJobs = true } = {}) {
40
+ this.ctx = ctx
41
+ this.useNativeJobs = useNativeJobs !== false
42
+ this.fallback = new CliTaskQueue({ maxConcurrent })
43
+ this.records = new Map()
44
+ this.disposed = false
45
+ }
46
+
47
+ get jobsService() {
48
+ try {
49
+ return this.ctx?.get?.('jobs')
50
+ } catch {
51
+ return undefined
52
+ }
53
+ }
54
+
55
+ setMaxConcurrent(n) {
56
+ this.fallback.setMaxConcurrent(n)
57
+ }
58
+
59
+ setUseNativeJobs(enabled) {
60
+ this.useNativeJobs = enabled !== false
61
+ }
62
+
63
+ /**
64
+ * @param {{
65
+ * runId: string,
66
+ * parentSessionId?: string,
67
+ * description: string,
68
+ * tier: string,
69
+ * backend: string,
70
+ * toolCall?: { callId: string, rootCallId: string },
71
+ * execute: (ctx: { signal: AbortSignal, updateProgress: (note: string) => void }) => Promise<any>,
72
+ * onUpdate?: (job: any) => void,
73
+ * onDone?: (job: any, outcome: any, error?: unknown) => void,
74
+ * }} spec
75
+ */
76
+ enqueue(spec) {
77
+ if (this.disposed) throw new Error('RouterJobRunner is disposed')
78
+ const service = this.jobsService
79
+ if (this.useNativeJobs && service && typeof service.start === 'function') {
80
+ try {
81
+ return this.#enqueueNative(service, spec)
82
+ } catch {
83
+ // Native preflight refused (no attached controller, owner gone, ...):
84
+ // fall back to the process-local queue.
85
+ }
86
+ }
87
+ return this.fallback.enqueue(spec)
88
+ }
89
+
90
+ #enqueueNative(service, spec) {
91
+ const record = {
92
+ runId: spec.runId,
93
+ jobId: null,
94
+ parentSessionId: spec.parentSessionId || null,
95
+ description: spec.description,
96
+ tier: spec.tier,
97
+ backend: spec.backend,
98
+ status: 'running',
99
+ progress: 'Running…',
100
+ createdAt: Date.now(),
101
+ startedAt: Date.now(),
102
+ finishedAt: null,
103
+ controller: new AbortController(),
104
+ }
105
+ this.records.set(spec.runId, record)
106
+
107
+ const emit = () => {
108
+ try {
109
+ spec.onUpdate?.(snapshotOf(record))
110
+ } catch {
111
+ // Progress observers must not break the job lifecycle.
112
+ }
113
+ }
114
+
115
+ const jobId = service.start({
116
+ kind: ROUTER_JOB_KIND,
117
+ label: `${spec.runId}: ${spec.description || spec.backend || 'router cli'}`,
118
+ ...(record.parentSessionId ? { owner: record.parentSessionId } : {}),
119
+ ...(spec.toolCall ? { toolCall: spec.toolCall } : {}),
120
+ run: (job) => {
121
+ record.jobId = job.id
122
+ const reportProgress = (note) => {
123
+ record.progress = String(note || '').slice(0, 180)
124
+ try {
125
+ job.updateProgress(record.progress)
126
+ } catch {
127
+ // The ring may already be closed during teardown.
128
+ }
129
+ emit()
130
+ }
131
+ reportProgress(record.progress)
132
+
133
+ const done = (async () => {
134
+ try {
135
+ const outcome = await spec.execute({
136
+ signal: record.controller.signal,
137
+ updateProgress: reportProgress,
138
+ })
139
+ if (record.status === 'cancelled') {
140
+ try {
141
+ spec.onDone?.(snapshotOf(record), { ok: false, error: record.progress })
142
+ } catch {
143
+ // Completion observers must not break settlement.
144
+ }
145
+ return { status: 'killed', detail: record.progress }
146
+ }
147
+ record.status = outcome?.ok ? 'completed' : 'failed'
148
+ record.progress = outcome?.ok
149
+ ? 'Completed'
150
+ : String(outcome?.error || 'Failed').slice(0, 180)
151
+ record.finishedAt = Date.now()
152
+ if (outcome?.output) {
153
+ try {
154
+ job.append(String(outcome.output))
155
+ } catch {
156
+ // Settlement may have closed the ring first.
157
+ }
158
+ }
159
+ try {
160
+ spec.onDone?.(snapshotOf(record), outcome)
161
+ } catch {
162
+ // Completion observers must not break settlement.
163
+ }
164
+ return {
165
+ status: record.status === 'completed' ? 'completed' : 'failed',
166
+ ...(outcome?.ok ? {} : { detail: record.progress }),
167
+ }
168
+ } catch (error) {
169
+ const message = error instanceof Error ? error.message : String(error)
170
+ if (record.status === 'cancelled') {
171
+ try {
172
+ spec.onDone?.(snapshotOf(record), { ok: false, error: record.progress }, error)
173
+ } catch {
174
+ // Completion observers must not break settlement.
175
+ }
176
+ return { status: 'killed', detail: record.progress }
177
+ }
178
+ record.status = 'failed'
179
+ record.progress = message.slice(0, 180)
180
+ record.finishedAt = Date.now()
181
+ try {
182
+ spec.onDone?.(snapshotOf(record), { ok: false, error: message }, error)
183
+ } catch {
184
+ // Completion observers must not break settlement.
185
+ }
186
+ return { status: 'failed', detail: message }
187
+ } finally {
188
+ if (!record.finishedAt) record.finishedAt = Date.now()
189
+ this.#trim()
190
+ }
191
+ })()
192
+
193
+ return {
194
+ cancel: (reason) => {
195
+ if (record.status !== 'running' && record.status !== 'queued') return
196
+ record.status = 'cancelled'
197
+ record.progress = String(reason || 'cancelled').slice(0, 180)
198
+ record.finishedAt = Date.now()
199
+ emit()
200
+ try {
201
+ record.controller.abort(new Error(record.progress))
202
+ } catch {
203
+ // Aborting an already-settled signal is harmless.
204
+ }
205
+ },
206
+ done,
207
+ }
208
+ },
209
+ })
210
+
211
+ record.jobId = jobId
212
+ return snapshotOf(record)
213
+ }
214
+
215
+ get(runId) {
216
+ const record = this.records.get(runId)
217
+ if (record) return snapshotOf(record)
218
+ return this.fallback.get(runId)
219
+ }
220
+
221
+ listActive() {
222
+ const active = []
223
+ for (const record of this.records.values()) {
224
+ if (record.status === 'queued' || record.status === 'running') {
225
+ active.push(snapshotOf(record))
226
+ }
227
+ }
228
+ return [...active, ...this.fallback.listActive()]
229
+ }
230
+
231
+ cancel(runId, reason = 'cancelled by caller') {
232
+ const record = this.records.get(runId)
233
+ if (!record) return this.fallback.cancel(runId, reason)
234
+ if (record.status !== 'running' && record.status !== 'queued') {
235
+ return { found: true, cancelled: false, status: record.status }
236
+ }
237
+ const service = this.jobsService
238
+ if (record.jobId && typeof service?.kill === 'function') {
239
+ try {
240
+ service.kill(record.jobId, record.parentSessionId || undefined, reason)
241
+ } catch {
242
+ // Fall through to the local abort below.
243
+ }
244
+ }
245
+ record.status = 'cancelled'
246
+ record.progress = String(reason || 'cancelled').slice(0, 180)
247
+ record.finishedAt = Date.now()
248
+ try {
249
+ record.controller.abort(new Error(record.progress))
250
+ } catch {
251
+ // Aborting an already-settled signal is harmless.
252
+ }
253
+ return { found: true, cancelled: true, status: record.status }
254
+ }
255
+
256
+ cancelByParent(parentSessionId, reason = 'parent session disposed') {
257
+ if (!parentSessionId) return 0
258
+ let count = 0
259
+ for (const record of this.records.values()) {
260
+ if (record.parentSessionId === parentSessionId && (record.status === 'running' || record.status === 'queued')) {
261
+ if (this.cancel(record.runId, reason).cancelled) count++
262
+ }
263
+ }
264
+ count += this.fallback.cancelByParent(parentSessionId, reason)
265
+ return count
266
+ }
267
+
268
+ dispose() {
269
+ this.disposed = true
270
+ for (const record of [...this.records.values()]) {
271
+ if (record.status === 'running' || record.status === 'queued') {
272
+ this.cancel(record.runId, 'plugin unloaded')
273
+ }
274
+ }
275
+ this.fallback.dispose()
276
+ }
277
+
278
+ #trim() {
279
+ if (this.records.size <= 100) return
280
+ for (const [runId, record] of this.records) {
281
+ if (this.records.size <= 60) break
282
+ if (record.status !== 'queued' && record.status !== 'running') {
283
+ this.records.delete(runId)
284
+ }
285
+ }
286
+ }
287
+ }
package/lib/ledger.js ADDED
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Persistent run ledger and circuit-breaker cooldown state.
3
+ * Zero external dependencies; atomic file writes with graceful memory fallback.
4
+ * @module dsh-agent-router/lib/ledger
5
+ */
6
+
7
+ import { randomUUID } from 'node:crypto'
8
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
9
+ import { homedir } from 'node:os'
10
+ import { dirname, join } from 'node:path'
11
+
12
+ import { CONFIG_LIMITS, clampInt, normalizeLedgerFile } from './config-limits.js'
13
+
14
+ export const DEFAULT_COOLDOWN_MS = CONFIG_LIMITS.cooldownMs.default
15
+ export const DEFAULT_MAX_RUNS = CONFIG_LIMITS.maxRuns.default
16
+
17
+ export function defaultLedgerPath() {
18
+ const base = process.env.DSH_AGENT_ROUTER_DIR || join(homedir(), '.dsh', 'agent-router')
19
+ return join(base, 'state.json')
20
+ }
21
+
22
+ export function routeKey(candidate) {
23
+ if (!candidate) return 'unknown'
24
+ if (candidate.kind === 'dsh') {
25
+ return `dsh:${candidate.provider}/${candidate.model}`
26
+ }
27
+ if (candidate.kind === 'cli') {
28
+ return candidate.model ? `cli:${candidate.backend}:${candidate.model}` : `cli:${candidate.backend}`
29
+ }
30
+ return String(candidate)
31
+ }
32
+
33
+ export class RouterStore {
34
+ /**
35
+ * @param {{ filePath?: string, maxRuns?: number, cooldownMs?: number, logger?: { warn?: (m: string) => void } }} [options]
36
+ */
37
+ constructor(options = {}) {
38
+ this.filePath = options.filePath ?? defaultLedgerPath()
39
+ this.maxRuns = clampInt(options.maxRuns, CONFIG_LIMITS.maxRuns)
40
+ this.cooldownMs = clampInt(options.cooldownMs, CONFIG_LIMITS.cooldownMs)
41
+ this.logger = options.logger
42
+ this.state = { version: 1, cooldowns: {}, runs: [], config: null, routeMetrics: {} }
43
+ this.load()
44
+ }
45
+
46
+ load() {
47
+ if (!this.filePath) return
48
+ try {
49
+ const raw = readFileSync(this.filePath, 'utf8')
50
+ const parsed = JSON.parse(raw)
51
+ if (parsed && typeof parsed === 'object') {
52
+ this.state = {
53
+ version: 1,
54
+ cooldowns: parsed.cooldowns && typeof parsed.cooldowns === 'object' ? parsed.cooldowns : {},
55
+ runs: Array.isArray(parsed.runs) ? parsed.runs : [],
56
+ config: parsed.config && typeof parsed.config === 'object' ? parsed.config : null,
57
+ routeMetrics: parsed.routeMetrics && typeof parsed.routeMetrics === 'object' ? parsed.routeMetrics : {},
58
+ }
59
+ }
60
+ } catch {
61
+ // Fresh state or unreadable file: start empty without failing activation.
62
+ }
63
+ }
64
+
65
+ save() {
66
+ if (!this.filePath) return
67
+ try {
68
+ mkdirSync(dirname(this.filePath), { recursive: true })
69
+ const tmp = `${this.filePath}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`
70
+ writeFileSync(tmp, JSON.stringify(this.state, null, 2), 'utf8')
71
+ renameSync(tmp, this.filePath)
72
+ } catch (error) {
73
+ this.logger?.warn?.(`dsh-agent-router: could not persist ledger: ${error instanceof Error ? error.message : String(error)}`)
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Check whether a route key is healthy right now.
79
+ * @param {string} key
80
+ * @param {number} [now]
81
+ */
82
+ checkHealth(key, now = Date.now()) {
83
+ const entry = this.state.cooldowns[key]
84
+ if (!entry) return { available: true, remainingMs: 0, failures: 0 }
85
+ const until = Number(entry.until ?? 0)
86
+ if (until <= now) {
87
+ return { available: true, remainingMs: 0, failures: Number(entry.failures ?? 0) }
88
+ }
89
+ return {
90
+ available: false,
91
+ remainingMs: until - now,
92
+ failures: Number(entry.failures ?? 1),
93
+ reason: entry.reason || 'recent failure',
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Mark a route failed and place it in bounded exponential-backoff cooldown.
99
+ * @param {string} key
100
+ * @param {string} reason
101
+ * @param {number} [now]
102
+ */
103
+ recordFailure(key, reason, now = Date.now()) {
104
+ const prev = this.state.cooldowns[key]
105
+ const failures = Math.min(8, Number(prev?.failures ?? 0) + 1)
106
+ const multiplier = Math.min(4, 2 ** (failures - 1))
107
+ const duration = this.cooldownMs * multiplier
108
+ this.state.cooldowns[key] = {
109
+ failures,
110
+ until: now + duration,
111
+ reason: String(reason || 'failure').slice(0, 300),
112
+ updatedAt: now,
113
+ }
114
+ this.save()
115
+ return this.state.cooldowns[key]
116
+ }
117
+
118
+ /**
119
+ * Clear cooldown after a successful call on a route.
120
+ * @param {string} key
121
+ */
122
+ recordSuccess(key) {
123
+ if (this.state.cooldowns[key]) {
124
+ delete this.state.cooldowns[key]
125
+ this.save()
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Clear one or all cooldown entries.
131
+ * @param {string} [key]
132
+ * @returns {number}
133
+ */
134
+ clearCooldowns(key) {
135
+ if (key) {
136
+ if (!this.state.cooldowns[key]) return 0
137
+ delete this.state.cooldowns[key]
138
+ this.save()
139
+ return 1
140
+ }
141
+ const count = Object.keys(this.state.cooldowns).length
142
+ this.state.cooldowns = {}
143
+ if (count > 0) this.save()
144
+ return count
145
+ }
146
+
147
+ /**
148
+ * List active (non-expired) cooldowns.
149
+ * @param {number} [now]
150
+ */
151
+ activeCooldowns(now = Date.now()) {
152
+ const out = []
153
+ for (const [key, entry] of Object.entries(this.state.cooldowns)) {
154
+ const remainingMs = Number(entry?.until ?? 0) - now
155
+ if (remainingMs > 0) {
156
+ out.push({ key, remainingMs, failures: entry.failures ?? 1, reason: entry.reason ?? '' })
157
+ }
158
+ }
159
+ return out
160
+ }
161
+
162
+ /**
163
+ * Insert or update a dispatch run record.
164
+ * @param {Record<string, any>} run
165
+ */
166
+ upsertRun(run) {
167
+ const idx = this.state.runs.findIndex(r => r.runId === run.runId)
168
+ if (idx >= 0) {
169
+ this.state.runs[idx] = { ...this.state.runs[idx], ...run, updatedAt: Date.now() }
170
+ } else {
171
+ this.state.runs.unshift({ ...run, createdAt: run.createdAt ?? Date.now(), updatedAt: Date.now() })
172
+ if (this.state.runs.length > this.maxRuns) {
173
+ this.state.runs.length = this.maxRuns
174
+ }
175
+ }
176
+ this.save()
177
+ return this.findRun(run.runId)
178
+ }
179
+
180
+ /**
181
+ * Lookup by runId, DSH childName, or DSH childSessionId.
182
+ * @param {string} target
183
+ */
184
+ findRun(target) {
185
+ if (!target) return undefined
186
+ return this.state.runs.find(
187
+ r => r.runId === target || r.childName === target || r.childId === target,
188
+ )
189
+ }
190
+
191
+ /**
192
+ * Attach quality feedback to a run.
193
+ * @param {string} runId
194
+ * @param {{ rating?: number, comment?: string }} feedback
195
+ */
196
+ addFeedback(runId, feedback = {}) {
197
+ const run = this.findRun(runId)
198
+ if (!run) return null
199
+ const rating = Number(feedback.rating)
200
+ return this.upsertRun({
201
+ runId: run.runId,
202
+ quality: {
203
+ ...(Number.isFinite(rating) ? { rating } : {}),
204
+ ...(typeof feedback.comment === 'string' && feedback.comment.trim()
205
+ ? { comment: feedback.comment.trim().slice(0, 500) }
206
+ : {}),
207
+ at: Date.now(),
208
+ },
209
+ })
210
+ }
211
+
212
+ /**
213
+ * Replace the run ledger (used by session pruning).
214
+ * @param {Array<Record<string, any>>} runs
215
+ */
216
+ replaceRuns(runs) {
217
+ this.state.runs = Array.isArray(runs) ? runs : []
218
+ if (this.state.runs.length > this.maxRuns) this.state.runs.length = this.maxRuns
219
+ this.save()
220
+ return this.state.runs.length
221
+ }
222
+
223
+ /**
224
+ * @param {number} [limit]
225
+ */
226
+ listRuns(limit = 20) {
227
+ return this.state.runs.slice(0, Math.max(1, limit))
228
+ }
229
+
230
+ /**
231
+ * Apply a runtime maxRuns change and trim the in-memory ledger when needed.
232
+ * @param {number} value
233
+ */
234
+ setMaxRuns(value) {
235
+ const next = clampInt(value ?? this.maxRuns, CONFIG_LIMITS.maxRuns)
236
+ if (next === this.maxRuns) return
237
+ this.maxRuns = next
238
+ if (this.state.runs.length > next) this.state.runs.length = next
239
+ this.save()
240
+ }
241
+
242
+ /**
243
+ * Switch the ledger file at runtime, persisting current state to the new path.
244
+ * @param {string | undefined} value
245
+ */
246
+ setFilePath(value) {
247
+ const next = normalizeLedgerFile(value) || defaultLedgerPath()
248
+ if (next === this.filePath) return
249
+ this.filePath = next
250
+ this.save()
251
+ }
252
+
253
+ /**
254
+ * Record an execution outcome sample into EWMA latency/cost/reliability metrics.
255
+ * @param {string} key
256
+ * @param {{ ok: boolean, durationMs?: number, costUsd?: number|null }} sample
257
+ */
258
+ recordRouteMetric(key, sample) {
259
+ if (!key) return
260
+ const prev = this.state.routeMetrics[key] || {
261
+ successCount: 0,
262
+ failCount: 0,
263
+ ewmaLatencyMs: null,
264
+ ewmaCostUsd: null,
265
+ recentOutcomes: [],
266
+ updatedAt: 0,
267
+ }
268
+ const alpha = 0.35
269
+ const ok = sample?.ok === true
270
+ const dur = Number(sample?.durationMs)
271
+ const cost = Number(sample?.costUsd)
272
+ const recent = Array.isArray(prev.recentOutcomes) ? prev.recentOutcomes.slice(-9) : []
273
+ recent.push(ok)
274
+
275
+ const ewmaLatencyMs = Number.isFinite(dur) && dur > 0
276
+ ? (prev.ewmaLatencyMs === null ? Math.round(dur) : Math.round(prev.ewmaLatencyMs * (1 - alpha) + dur * alpha))
277
+ : prev.ewmaLatencyMs
278
+ const ewmaCostUsd = Number.isFinite(cost) && cost >= 0
279
+ ? (prev.ewmaCostUsd === null ? cost : Number((prev.ewmaCostUsd * (1 - alpha) + cost * alpha).toFixed(6)))
280
+ : prev.ewmaCostUsd
281
+
282
+ this.state.routeMetrics[key] = {
283
+ successCount: (prev.successCount || 0) + (ok ? 1 : 0),
284
+ failCount: (prev.failCount || 0) + (ok ? 0 : 1),
285
+ ewmaLatencyMs,
286
+ ewmaCostUsd,
287
+ recentOutcomes: recent,
288
+ updatedAt: Date.now(),
289
+ }
290
+ this.save()
291
+ return this.state.routeMetrics[key]
292
+ }
293
+
294
+ getRouteMetrics() {
295
+ return this.state.routeMetrics || {}
296
+ }
297
+
298
+ stats() {
299
+ const byTier = {}
300
+ const byBackend = {}
301
+ let total = 0
302
+ let succeeded = 0
303
+ let running = 0
304
+ let failed = 0
305
+ let escalated = 0
306
+ for (const r of this.state.runs) {
307
+ total++
308
+ if (r.status === 'completed') succeeded++
309
+ else if (r.status === 'dispatched' || r.status === 'running' || r.status === 'queued') running++
310
+ else if (r.status === 'failed' || r.status === 'cancelled') failed++
311
+ if (r.escalatedFrom) escalated++
312
+ byTier[r.tier || 'unknown'] = (byTier[r.tier || 'unknown'] ?? 0) + 1
313
+ byBackend[r.backend || 'unknown'] = (byBackend[r.backend || 'unknown'] ?? 0) + 1
314
+ }
315
+ return { total, succeeded, running, failed, escalated, byTier, byBackend }
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Re-rank candidates using historical EWMA latency and recent reliability while
321
+ * keeping user priority as the base anchor.
322
+ */
323
+ export function rankCandidatesWithMetrics(candidates, routeMetrics = {}, { tier = 'T2', band, enabled = true } = {}) {
324
+ if (!enabled || !Array.isArray(candidates) || candidates.length <= 1) {
325
+ return { candidates: candidates.slice(), adjustments: [] }
326
+ }
327
+ const bandKey = band || (tier === 'T1' ? 'light' : (tier === 'T3' ? 'heavy' : (tier === 'T4' ? 'review' : 'standard')))
328
+ const adjustments = []
329
+ const scored = candidates.map((c, idx) => {
330
+ const baseScore = (candidates.length - idx) * 10
331
+ const m = routeMetrics[c.key]
332
+ let delta = 0
333
+ if (m) {
334
+ const recent = Array.isArray(m.recentOutcomes) ? m.recentOutcomes : []
335
+ if (recent.length >= 3) {
336
+ const rate = recent.filter(Boolean).length / recent.length
337
+ if (rate < 0.6) {
338
+ delta -= 25
339
+ adjustments.push(`${c.key}: penalized for low recent success (${Math.round(rate * 100)}%)`)
340
+ } else if (rate >= 0.9 && recent.length >= 4) {
341
+ delta += 6
342
+ }
343
+ }
344
+ if (bandKey === 'light' && typeof m.ewmaLatencyMs === 'number') {
345
+ if (m.ewmaLatencyMs > 45_000) {
346
+ delta -= 15
347
+ adjustments.push(`${c.key}: deprioritized for light tier due to high latency (${Math.round(m.ewmaLatencyMs / 1000)}s)`)
348
+ } else if (m.ewmaLatencyMs < 8_000) {
349
+ delta += 5
350
+ }
351
+ }
352
+ }
353
+ return { candidate: c, score: baseScore + delta, idx }
354
+ })
355
+ scored.sort((a, b) => (b.score - a.score) || (a.idx - b.idx))
356
+ return {
357
+ candidates: scored.map(x => x.candidate),
358
+ adjustments,
359
+ }
360
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Legacy config override storage (pre-Profile `state.json` → `config` key).
3
+ *
4
+ * Kept separate from the run ledger so the ledger only owns runs, cooldowns,
5
+ * and route metrics. Writes still go through the ledger's atomic persister so
6
+ * existing `state.json` files remain readable and writable without migration.
7
+ *
8
+ * @module dsh-agent-router/lib/legacy-config
9
+ */
10
+
11
+ export class LegacyConfigStore {
12
+ /**
13
+ * @param {import('./ledger.js').RouterStore} store
14
+ */
15
+ constructor(store) {
16
+ this.store = store
17
+ }
18
+
19
+ getConfig() {
20
+ const config = this.store.state?.config
21
+ return config && typeof config === 'object' ? config : null
22
+ }
23
+
24
+ setConfig(config) {
25
+ this.store.state.config = config && typeof config === 'object' ? config : null
26
+ this.store.save()
27
+ return this.store.state.config
28
+ }
29
+
30
+ clearConfig() {
31
+ this.store.state.config = null
32
+ this.store.save()
33
+ }
34
+ }