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,234 @@
1
+ /**
2
+ * Structured output parsers and permission-mode mappings for each local CLI backend.
3
+ * @module dsh-agent-router/lib/cli/parsers
4
+ */
5
+
6
+ /**
7
+ * Parse `claude -p --output-format json` output.
8
+ * @param {string} stdout
9
+ */
10
+ export function parseClaudeOutput(stdout) {
11
+ const trimmed = stdout.trim()
12
+ if (!trimmed) return { ok: false, error: 'empty claude output' }
13
+ try {
14
+ const parsed = JSON.parse(trimmed)
15
+ const item = Array.isArray(parsed)
16
+ ? parsed.findLast(x => x && x.type === 'result') ?? parsed.at(-1)
17
+ : parsed
18
+ if (!item || typeof item !== 'object') {
19
+ return { ok: false, error: 'unexpected claude JSON payload' }
20
+ }
21
+ const isErr = Boolean(item.is_error) || (item.subtype && item.subtype !== 'success')
22
+ const text = typeof item.result === 'string'
23
+ ? item.result
24
+ : (Array.isArray(item.errors) ? item.errors.join('; ') : trimmed)
25
+ const usedModels = item.modelUsage && typeof item.modelUsage === 'object' ? Object.keys(item.modelUsage) : []
26
+ return {
27
+ ok: !isErr && Boolean(text.trim()),
28
+ text,
29
+ sessionId: item.session_id || item.sessionId || null,
30
+ resolvedModel: usedModels[0] || item.model || null,
31
+ costUsd: typeof item.total_cost_usd === 'number' ? item.total_cost_usd : null,
32
+ usage: item.usage || null,
33
+ error: isErr ? (text || item.subtype || 'claude run failed') : null,
34
+ }
35
+ } catch {
36
+ return { ok: true, text: trimmed, sessionId: null, costUsd: null, usage: null, error: null }
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Parse `codex exec --json` JSONL events (with optional `-o` last-message file).
42
+ * @param {string} stdout
43
+ * @param {string|null} [lastMsgText]
44
+ */
45
+ export function parseCodexOutput(stdout, lastMsgText = null) {
46
+ let sessionId = null
47
+ const messages = []
48
+ let usage = null
49
+ let error = null
50
+ let resolvedModel = null
51
+ for (const rawLine of stdout.split(/\r?\n/)) {
52
+ const line = rawLine.trim()
53
+ if (!line.startsWith('{')) continue
54
+ try {
55
+ const ev = JSON.parse(line)
56
+ if (ev.type === 'thread.started' && ev.thread_id) {
57
+ sessionId = ev.thread_id
58
+ } else if (!resolvedModel && typeof ev.model === 'string') {
59
+ resolvedModel = ev.model
60
+ } else if (ev.type === 'item.completed' && ev.item) {
61
+ if ((ev.item.type === 'agent_message' || ev.item.type === 'message') && typeof ev.item.text === 'string') {
62
+ messages.push(ev.item.text)
63
+ }
64
+ } else if (ev.type === 'turn.completed' && ev.usage) {
65
+ usage = ev.usage
66
+ } else if (ev.type === 'turn.failed' || ev.type === 'error') {
67
+ error = ev.message || ev.error?.message || JSON.stringify(ev)
68
+ }
69
+ } catch {
70
+ // Ignore non-JSON lines (e.g. startup warnings)
71
+ }
72
+ }
73
+ const text = (lastMsgText && lastMsgText.trim()) || messages.at(-1) || ''
74
+ return {
75
+ ok: !error && Boolean(text.trim()),
76
+ text,
77
+ sessionId,
78
+ resolvedModel,
79
+ costUsd: null,
80
+ usage,
81
+ error: error || (!text.trim() ? 'empty codex response' : null),
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Parse `gemini -p ... --output-format json` output.
87
+ * @param {string} stdout
88
+ */
89
+ export function parseGeminiOutput(stdout) {
90
+ const idx = stdout.indexOf('{')
91
+ const candidate = idx >= 0 ? stdout.slice(idx).trim() : stdout.trim()
92
+ if (!candidate) return { ok: false, error: 'empty gemini output' }
93
+ try {
94
+ const parsed = JSON.parse(candidate)
95
+ if (parsed.error) {
96
+ return {
97
+ ok: false,
98
+ text: parsed.response || '',
99
+ sessionId: parsed.session_id || null,
100
+ costUsd: null,
101
+ usage: parsed.stats || null,
102
+ error: typeof parsed.error === 'string' ? parsed.error : (parsed.error.message || JSON.stringify(parsed.error)),
103
+ }
104
+ }
105
+ const text = typeof parsed.response === 'string' ? parsed.response : ''
106
+ const gemModels = parsed.stats?.models && typeof parsed.stats.models === 'object' ? Object.keys(parsed.stats.models) : []
107
+ return {
108
+ ok: Boolean(text.trim()),
109
+ text,
110
+ sessionId: parsed.session_id || null,
111
+ resolvedModel: gemModels[0] || null,
112
+ costUsd: null,
113
+ usage: parsed.stats || null,
114
+ error: text.trim() ? null : 'empty gemini response',
115
+ }
116
+ } catch {
117
+ return { ok: true, text: stdout.trim(), sessionId: null, costUsd: null, usage: null, error: null }
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Parse `agy -p ... --output-format json` single-envelope output.
123
+ * @param {string} stdout
124
+ */
125
+ export function parseAntigravityOutput(stdout) {
126
+ const trimmed = stdout.trim()
127
+ if (!trimmed) return { ok: false, error: 'empty antigravity output' }
128
+ const idx = trimmed.indexOf('{')
129
+ const candidate = idx >= 0 ? trimmed.slice(idx).trim() : trimmed
130
+ try {
131
+ const parsed = JSON.parse(candidate)
132
+ const status = typeof parsed.status === 'string' ? parsed.status.toUpperCase() : ''
133
+ const text = typeof parsed.response === 'string'
134
+ ? parsed.response
135
+ : (parsed.structured_output ? JSON.stringify(parsed.structured_output) : '')
136
+ const isErr = Boolean(parsed.error) || (status && status !== 'SUCCESS')
137
+ return {
138
+ ok: !isErr && Boolean(text.trim()),
139
+ text,
140
+ sessionId: parsed.conversation_id || null,
141
+ resolvedModel: parsed.model || null,
142
+ costUsd: null,
143
+ usage: parsed.usage || null,
144
+ error: isErr
145
+ ? (parsed.error || status || 'antigravity run failed')
146
+ : (text.trim() ? null : 'empty antigravity response'),
147
+ }
148
+ } catch {
149
+ return { ok: true, text: trimmed, sessionId: null, costUsd: null, usage: null, error: null }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Parse `opencode run --format json` JSONL events.
155
+ * @param {string} stdout
156
+ */
157
+ export function parseOpencodeOutput(stdout) {
158
+ let sessionId = null
159
+ const chunks = []
160
+ let error = null
161
+ let sawJsonEvent = false
162
+ for (const rawLine of stdout.split(/\r?\n/)) {
163
+ const line = rawLine.trim()
164
+ if (!line.startsWith('{')) continue
165
+ try {
166
+ const ev = JSON.parse(line)
167
+ sawJsonEvent = true
168
+ if (!sessionId && (ev.sessionID || ev.sessionId)) {
169
+ sessionId = ev.sessionID || ev.sessionId
170
+ }
171
+ if (ev.type === 'text' && ev.part && typeof ev.part.text === 'string') {
172
+ chunks.push(ev.part.text)
173
+ } else if (ev.type === 'message' && typeof ev.text === 'string') {
174
+ chunks.push(ev.text)
175
+ } else if (ev.type === 'error') {
176
+ error = ev.error?.message || ev.message || JSON.stringify(ev)
177
+ }
178
+ } catch {
179
+ // ignore non-JSON diagnostic lines
180
+ }
181
+ }
182
+ const text = chunks.join('') || (sawJsonEvent ? '' : stdout.trim())
183
+ return {
184
+ ok: !error && Boolean(text.trim()),
185
+ text,
186
+ sessionId,
187
+ costUsd: null,
188
+ usage: null,
189
+ error: error || (!text.trim() ? 'empty opencode response' : null),
190
+ }
191
+ }
192
+
193
+ export function mapClaudePermission(mode) {
194
+ if (mode === 'read-only') return 'plan'
195
+ if (mode === 'auto') return 'bypassPermissions'
196
+ return 'acceptEdits'
197
+ }
198
+
199
+ export function mapCodexSandbox(mode) {
200
+ if (mode === 'read-only') return 'read-only'
201
+ if (mode === 'auto') return 'danger-full-access'
202
+ return 'workspace-write'
203
+ }
204
+
205
+ export function mapGeminiApproval(mode) {
206
+ if (mode === 'read-only') return 'default'
207
+ if (mode === 'auto') return 'yolo'
208
+ return 'auto_edit'
209
+ }
210
+
211
+ export function extractProgressLine(backend, chunkText) {
212
+ const lines = chunkText.split(/\r?\n/)
213
+ for (let i = lines.length - 1; i >= 0; i--) {
214
+ const line = lines[i].trim()
215
+ if (!line) continue
216
+ if (line.startsWith('{')) {
217
+ try {
218
+ const ev = JSON.parse(line)
219
+ if (ev.type === 'item.completed' && ev.item?.type) {
220
+ return `${backend}: ${ev.item.type}`
221
+ }
222
+ if (ev.type === 'tool_use' || ev.type === 'step_start') {
223
+ return `${backend}: ${ev.type}${ev.name ? ` (${ev.name})` : ''}`
224
+ }
225
+ if (ev.type === 'text' && ev.part?.text) {
226
+ return ev.part.text.trim().slice(0, 120)
227
+ }
228
+ } catch {}
229
+ } else if (line.length > 3) {
230
+ return line.slice(0, 120)
231
+ }
232
+ }
233
+ return null
234
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Shared helpers for local agent CLI discovery and invocation:
3
+ * PATH lookup, Windows `.cmd` shim resolution, and tolerant config readers.
4
+ * @module dsh-agent-router/lib/cli/shared
5
+ */
6
+
7
+ import { existsSync, readFileSync } from 'node:fs'
8
+ import { dirname, extname, join, resolve } from 'node:path'
9
+
10
+ /**
11
+ * Find an executable on PATH without launching an interactive shell.
12
+ * @param {string} name
13
+ * @returns {string|null}
14
+ */
15
+ export function findOnPath(name) {
16
+ const pathEnv = process.env.PATH || process.env.Path || ''
17
+ const dirs = pathEnv.split(process.platform === 'win32' ? ';' : ':').filter(Boolean)
18
+ const exts = process.platform === 'win32'
19
+ ? ['.exe', '.cmd', '.bat', '']
20
+ : ['']
21
+ for (const dir of dirs) {
22
+ for (const ext of exts) {
23
+ const candidate = join(dir, name.endsWith(ext) ? name : `${name}${ext}`)
24
+ if (existsSync(candidate)) return candidate
25
+ }
26
+ }
27
+ return null
28
+ }
29
+
30
+ /**
31
+ * Resolve Windows npm `.cmd` wrapper scripts into direct binary/node spawns so
32
+ * prompts with newlines, quotes, or non-ASCII text never pass through cmd.exe.
33
+ * @param {string} binPath
34
+ * @param {string[]} args
35
+ * @returns {{ command: string, args: string[] }}
36
+ */
37
+ export function resolveWindowsCmdShim(binPath, args) {
38
+ if (process.platform !== 'win32' || !/\.(?:cmd|bat)$/i.test(binPath)) {
39
+ return { command: binPath, args }
40
+ }
41
+ try {
42
+ const dp0 = dirname(binPath)
43
+ const content = readFileSync(binPath, 'utf8')
44
+ // Pattern 1: "%dp0%\...\something.exe" %*
45
+ const exeMatch = content.match(/"%dp0%\\([^"]+\.exe)"\s+%\*/i)
46
+ if (exeMatch) {
47
+ const exePath = resolve(dp0, exeMatch[1])
48
+ if (existsSync(exePath)) return { command: exePath, args }
49
+ }
50
+ // Pattern 2: "%_prog%" "%dp0%\...\script.js" %*
51
+ const jsMatch = content.match(/"%dp0%\\([^"]+\.(?:m?js|cjs))"\s+%\*/i)
52
+ if (jsMatch) {
53
+ const scriptPath = resolve(dp0, jsMatch[1])
54
+ if (existsSync(scriptPath)) {
55
+ const siblingNode = join(dp0, 'node.exe')
56
+ const nodeBin = existsSync(siblingNode)
57
+ ? siblingNode
58
+ : (extname(process.execPath).toLowerCase() === '.exe' && /node\.exe$/i.test(process.execPath)
59
+ ? process.execPath
60
+ : (findOnPath('node') || 'node'))
61
+ return { command: nodeBin, args: [scriptPath, ...args] }
62
+ }
63
+ }
64
+ } catch {
65
+ // Fall back to cmd.exe wrapper below
66
+ }
67
+ const comspec = process.env.ComSpec || 'cmd.exe'
68
+ return { command: comspec, args: ['/d', '/s', '/c', binPath, ...args] }
69
+ }
70
+
71
+ export function safeReadJson(filePath) {
72
+ try {
73
+ return JSON.parse(readFileSync(filePath, 'utf8'))
74
+ } catch {
75
+ return null
76
+ }
77
+ }
78
+
79
+ export function stripJsonc(raw) {
80
+ let out = ''
81
+ let inString = false
82
+ let escaped = false
83
+ let inLineComment = false
84
+ let inBlockComment = false
85
+ for (let i = 0; i < raw.length; i++) {
86
+ const ch = raw[i]
87
+ const next = raw[i + 1]
88
+ if (inLineComment) {
89
+ if (ch === '\n' || ch === '\r') {
90
+ inLineComment = false
91
+ out += ch
92
+ }
93
+ continue
94
+ }
95
+ if (inBlockComment) {
96
+ if (ch === '*' && next === '/') {
97
+ inBlockComment = false
98
+ i++
99
+ }
100
+ continue
101
+ }
102
+ if (inString) {
103
+ out += ch
104
+ if (escaped) escaped = false
105
+ else if (ch === '\\') escaped = true
106
+ else if (ch === '"') inString = false
107
+ continue
108
+ }
109
+ if (ch === '"') {
110
+ inString = true
111
+ out += ch
112
+ continue
113
+ }
114
+ if (ch === '/' && next === '/') {
115
+ inLineComment = true
116
+ i++
117
+ continue
118
+ }
119
+ if (ch === '/' && next === '*') {
120
+ inBlockComment = true
121
+ i++
122
+ continue
123
+ }
124
+ out += ch
125
+ }
126
+ // Remove trailing commas before } or ]
127
+ return out.replace(/,\s*([}\]])/g, '$1')
128
+ }
129
+
130
+ export function safeReadJsonc(filePath) {
131
+ try {
132
+ const raw = readFileSync(filePath, 'utf8')
133
+ return JSON.parse(stripJsonc(raw))
134
+ } catch {
135
+ return null
136
+ }
137
+ }
138
+
139
+ export function safeReadText(filePath) {
140
+ try {
141
+ return readFileSync(filePath, 'utf8')
142
+ } catch {
143
+ return null
144
+ }
145
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Local agent CLI support barrel.
3
+ *
4
+ * Implementation lives in focused modules under `lib/cli/`; this file keeps the
5
+ * historical `lib/cli-runners.js` import surface stable for Host code, tests,
6
+ * and the CLI integration smoke suite.
7
+ *
8
+ * @module dsh-agent-router/lib/cli-runners
9
+ */
10
+
11
+ export {
12
+ findOnPath,
13
+ resolveWindowsCmdShim,
14
+ safeReadJson,
15
+ stripJsonc,
16
+ safeReadJsonc,
17
+ safeReadText,
18
+ } from './cli/shared.js'
19
+
20
+ export {
21
+ SUPPORTED_CLIS,
22
+ CLI_BINARIES,
23
+ cliBinaryName,
24
+ probeLocalClis,
25
+ discoverCliModels,
26
+ } from './cli/discover.js'
27
+
28
+ export {
29
+ parseClaudeOutput,
30
+ parseCodexOutput,
31
+ parseGeminiOutput,
32
+ parseOpencodeOutput,
33
+ parseAntigravityOutput,
34
+ } from './cli/parsers.js'
35
+
36
+ export {
37
+ executeCliAgent,
38
+ buildCliInvocation,
39
+ } from './cli/invoke.js'
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Single source of truth for config field limits and integer clamping.
3
+ * Shared by the Config schema and the runtime normalizer so the two cannot drift.
4
+ * @module dsh-agent-router/lib/config-limits
5
+ */
6
+
7
+ export const CONFIG_LIMITS = Object.freeze({
8
+ maxConcurrentCli: Object.freeze({ min: 1, max: 16, default: 3 }),
9
+ cooldownMs: Object.freeze({ min: 5000, max: 3_600_000, default: 180_000 }),
10
+ defaultTimeoutMs: Object.freeze({ min: 10_000, max: 1_800_000, default: 300_000 }),
11
+ maxRuns: Object.freeze({ min: 20, max: 2000, default: 200 }),
12
+ localProviders: 20,
13
+ })
14
+
15
+ /** Supported CLI selection strategies. */
16
+ export const CLI_SELECTION_MODES = Object.freeze(['static', 'adaptive'])
17
+
18
+ /**
19
+ * Clamp a numeric config value into the shared limits.
20
+ * Missing, empty, or non-finite input falls back to the field default.
21
+ * @param {unknown} value
22
+ * @param {{ min: number, max: number, default: number }} limits
23
+ */
24
+ export function clampInt(value, limits) {
25
+ if (value === undefined || value === null || value === '') return limits.default
26
+ const n = Number(value)
27
+ if (!Number.isFinite(n)) return limits.default
28
+ return Math.min(limits.max, Math.max(limits.min, Math.round(n)))
29
+ }
30
+
31
+ /**
32
+ * Normalize a ledger file path; empty or non-string input means "use the default path".
33
+ * @param {unknown} value
34
+ * @returns {string | undefined}
35
+ */
36
+ export function normalizeLedgerFile(value) {
37
+ if (typeof value !== 'string') return undefined
38
+ const trimmed = value.trim()
39
+ return trimmed || undefined
40
+ }
41
+
42
+ /**
43
+ * Normalize a list of provider ids: trim, drop empties/duplicates, and cap length.
44
+ * @param {unknown} value
45
+ * @returns {string[]}
46
+ */
47
+ export function normalizeProviderIds(value) {
48
+ if (!Array.isArray(value)) return []
49
+ const out = []
50
+ for (const item of value) {
51
+ if (typeof item !== 'string') continue
52
+ const trimmed = item.trim()
53
+ if (!trimmed || out.includes(trimmed)) continue
54
+ out.push(trimmed)
55
+ if (out.length >= CONFIG_LIMITS.localProviders) break
56
+ }
57
+ return out
58
+ }
59
+
60
+ /**
61
+ * Normalize the CLI selection strategy; unknown values fall back to `static`.
62
+ * @param {unknown} value
63
+ * @returns {'static' | 'adaptive'}
64
+ */
65
+ export function normalizeCliSelection(value) {
66
+ return value === 'adaptive' ? 'adaptive' : 'static'
67
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Runtime config normalization shared by initial activation, UI saves, and resets.
3
+ * Keeps defaults and clamping in one place instead of duplicating them in index.js.
4
+ * @module dsh-agent-router/lib/config-normalize
5
+ */
6
+
7
+ import {
8
+ CONFIG_LIMITS,
9
+ clampInt,
10
+ normalizeCliSelection,
11
+ normalizeLedgerFile,
12
+ normalizeProviderIds,
13
+ } from './config-limits.js'
14
+ import { CONFIG_VERSION, DEFAULT_ROUTING_CONFIG, DEFAULT_TIER_LAYOUT, DEFAULT_TIER_POLICIES } from './defaults.js'
15
+ import { normalizeTierEntries } from './tier-presets.js'
16
+
17
+ function isPlainObject(value) {
18
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
19
+ }
20
+
21
+ /**
22
+ * Migrate a persisted config object to the current schema version.
23
+ *
24
+ * v1 → v2 moves the fixed T1-T4 map onto the configurable tier model
25
+ * (`name`/`role`/`minScore`/`maxScore` + `tierLayout`). Unknown keys are
26
+ * preserved so a newer plugin build is never silently downgraded.
27
+ * @param {unknown} input
28
+ */
29
+ export function migrateConfig(input) {
30
+ const src = isPlainObject(input) ? { ...input } : {}
31
+ const version = Number(src.configVersion)
32
+ if (!Number.isInteger(version) || version < 1 || version < CONFIG_VERSION) {
33
+ if (!Number.isInteger(version) || version < 1) {
34
+ src.migratedFrom = 'legacy'
35
+ } else {
36
+ src.migratedFrom = version
37
+ }
38
+ src.configVersion = CONFIG_VERSION
39
+ if (src.tierLayout !== 'custom' && src.tierLayout !== DEFAULT_TIER_LAYOUT) {
40
+ src.tierLayout = DEFAULT_TIER_LAYOUT
41
+ }
42
+ src.tiers = normalizeTierEntries(src.tiers, {
43
+ authoritative: false,
44
+ baseTiers: DEFAULT_TIER_POLICIES,
45
+ }).tiers
46
+ } else {
47
+ src.configVersion = version
48
+ if (src.tiers !== undefined && src.tierLayout !== 'custom' && src.tierLayout !== DEFAULT_TIER_LAYOUT) {
49
+ src.tierLayout = 'custom'
50
+ }
51
+ }
52
+ return src
53
+ }
54
+
55
+ /**
56
+ * Build the effective config from raw/settings input with stable defaults.
57
+ * @param {Record<string, unknown>} [settings]
58
+ */
59
+ export function buildBaseConfig(settings = {}) {
60
+ const s = settings && typeof settings === 'object' ? migrateConfig(settings) : {}
61
+ const tierLayout = s.tierLayout === 'custom' ? 'custom' : DEFAULT_TIER_LAYOUT
62
+ const tiers = normalizeTierEntries(s.tiers, {
63
+ authoritative: tierLayout === 'custom',
64
+ baseTiers: DEFAULT_TIER_POLICIES,
65
+ }).tiers
66
+ return {
67
+ configVersion: CONFIG_VERSION,
68
+ preferBackend: typeof s.preferBackend === 'string' ? s.preferBackend : DEFAULT_ROUTING_CONFIG.preferBackend,
69
+ autoEscalate: typeof s.autoEscalate === 'boolean' ? s.autoEscalate : DEFAULT_ROUTING_CONFIG.autoEscalate,
70
+ budgetGuard: typeof s.budgetGuard === 'boolean' ? s.budgetGuard : DEFAULT_ROUTING_CONFIG.budgetGuard,
71
+ peakAvoidance: typeof s.peakAvoidance === 'boolean' ? s.peakAvoidance : DEFAULT_ROUTING_CONFIG.peakAvoidance,
72
+ adaptiveRanking: typeof s.adaptiveRanking === 'boolean' ? s.adaptiveRanking : DEFAULT_ROUTING_CONFIG.adaptiveRanking,
73
+ defaultBackground: typeof s.defaultBackground === 'boolean' ? s.defaultBackground : DEFAULT_ROUTING_CONFIG.defaultBackground,
74
+ useNativeJobs: typeof s.useNativeJobs === 'boolean' ? s.useNativeJobs : DEFAULT_ROUTING_CONFIG.useNativeJobs,
75
+ cliSelection: s.cliSelection === undefined ? DEFAULT_ROUTING_CONFIG.cliSelection : normalizeCliSelection(s.cliSelection),
76
+ allowLocalModels: typeof s.allowLocalModels === 'boolean' ? s.allowLocalModels : DEFAULT_ROUTING_CONFIG.allowLocalModels,
77
+ localProviders: s.localProviders === undefined ? [] : normalizeProviderIds(s.localProviders),
78
+ maxConcurrentCli: clampInt(s.maxConcurrentCli, CONFIG_LIMITS.maxConcurrentCli),
79
+ cooldownMs: clampInt(s.cooldownMs, CONFIG_LIMITS.cooldownMs),
80
+ defaultTimeoutMs: clampInt(s.defaultTimeoutMs, CONFIG_LIMITS.defaultTimeoutMs),
81
+ maxRuns: clampInt(s.maxRuns, CONFIG_LIMITS.maxRuns),
82
+ ledgerFile: normalizeLedgerFile(s.ledgerFile),
83
+ tierLayout,
84
+ tiers,
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Sanitize a config candidate submitted by the Plugin Detail UI before persistence.
90
+ * Never throws: invalid tier input falls back to the current base config.
91
+ * @param {unknown} input
92
+ * @param {ReturnType<typeof buildBaseConfig>} baseConfig
93
+ */
94
+ export function sanitizeConfigInput(input, baseConfig) {
95
+ const rawInput = isPlainObject(input) ? input : {}
96
+ const hasTiers = Object.prototype.hasOwnProperty.call(rawInput, 'tiers')
97
+ const hasLayout = Object.prototype.hasOwnProperty.call(rawInput, 'tierLayout')
98
+ const src = migrateConfig(rawInput)
99
+
100
+ const preferBackend = typeof src.preferBackend === 'string' ? src.preferBackend : baseConfig.preferBackend
101
+ const autoEscalate = typeof src.autoEscalate === 'boolean' ? src.autoEscalate : baseConfig.autoEscalate
102
+ const budgetGuard = typeof src.budgetGuard === 'boolean' ? src.budgetGuard : baseConfig.budgetGuard
103
+ const peakAvoidance = typeof src.peakAvoidance === 'boolean' ? src.peakAvoidance : baseConfig.peakAvoidance
104
+ const adaptiveRanking = typeof src.adaptiveRanking === 'boolean' ? src.adaptiveRanking : baseConfig.adaptiveRanking
105
+ const defaultBackground = typeof src.defaultBackground === 'boolean' ? src.defaultBackground : baseConfig.defaultBackground
106
+ const useNativeJobs = typeof src.useNativeJobs === 'boolean' ? src.useNativeJobs : baseConfig.useNativeJobs
107
+ const cliSelection = src.cliSelection === undefined ? baseConfig.cliSelection : normalizeCliSelection(src.cliSelection)
108
+ const allowLocalModels = typeof src.allowLocalModels === 'boolean' ? src.allowLocalModels : baseConfig.allowLocalModels
109
+ const localProviders = 'localProviders' in src ? normalizeProviderIds(src.localProviders) : (baseConfig.localProviders ?? [])
110
+ const maxConcurrentCli = clampInt(src.maxConcurrentCli ?? baseConfig.maxConcurrentCli, CONFIG_LIMITS.maxConcurrentCli)
111
+ const cooldownMs = clampInt(src.cooldownMs ?? baseConfig.cooldownMs, CONFIG_LIMITS.cooldownMs)
112
+ const defaultTimeoutMs = clampInt(src.defaultTimeoutMs ?? baseConfig.defaultTimeoutMs, CONFIG_LIMITS.defaultTimeoutMs)
113
+ const maxRuns = clampInt(src.maxRuns ?? baseConfig.maxRuns, CONFIG_LIMITS.maxRuns)
114
+ const ledgerFile = 'ledgerFile' in src ? normalizeLedgerFile(src.ledgerFile) : baseConfig.ledgerFile
115
+
116
+ const baseLayout = baseConfig.tierLayout === 'custom' ? 'custom' : DEFAULT_TIER_LAYOUT
117
+ const tierLayout = hasLayout && (src.tierLayout === 'custom' || src.tierLayout === DEFAULT_TIER_LAYOUT)
118
+ ? src.tierLayout
119
+ : baseLayout
120
+ const invalidTiers = hasTiers && !isPlainObject(rawInput.tiers)
121
+ const rawTiers = hasTiers && !invalidTiers ? src.tiers : baseConfig.tiers
122
+ const normalized = normalizeTierEntries(rawTiers, {
123
+ authoritative: tierLayout === 'custom' && !invalidTiers,
124
+ baseTiers: baseConfig.tiers || DEFAULT_TIER_POLICIES,
125
+ })
126
+
127
+ return {
128
+ configVersion: CONFIG_VERSION,
129
+ preferBackend,
130
+ autoEscalate,
131
+ budgetGuard,
132
+ peakAvoidance,
133
+ adaptiveRanking,
134
+ defaultBackground,
135
+ useNativeJobs,
136
+ cliSelection,
137
+ allowLocalModels,
138
+ localProviders,
139
+ maxConcurrentCli,
140
+ cooldownMs,
141
+ defaultTimeoutMs,
142
+ maxRuns,
143
+ ledgerFile,
144
+ tierLayout: invalidTiers ? DEFAULT_TIER_LAYOUT : tierLayout,
145
+ tiers: normalized.tiers,
146
+ }
147
+ }