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,524 @@
1
+ /**
2
+ * Read-only inspection of how `dsh-agent-router` is mounted in a DSH profile,
3
+ * plus one safe repair path for hand-written `- insert:` blocks.
4
+ *
5
+ * A standard install registers the package in `dsh.profile.bundles`; a manual
6
+ * mount copies the package's `- insert:` block into the profile (or home)
7
+ * `cordis.patch.yml`. Manual mounts make DSH refuse to uninstall the bundle
8
+ * with “其他配置仍在使用这个组合包的组件”. Everything here is local, synchronous,
9
+ * dependency-free, and never throws.
10
+ *
11
+ * @module dsh-agent-router/lib/profile-mount
12
+ */
13
+
14
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
15
+ import { homedir } from 'node:os'
16
+ import { basename, dirname, join, resolve } from 'node:path'
17
+
18
+ const DEFAULT_PLUGIN = 'dsh-agent-router'
19
+ const DEP_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies']
20
+ const INSERT_START = /^- insert:(?:\s|$)/
21
+ const TOP_LEVEL_ITEM = /^- /
22
+
23
+ function escapeRegExp(value) {
24
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
25
+ }
26
+
27
+ function readText(file) {
28
+ if (!file) return null
29
+ try {
30
+ return readFileSync(file, 'utf8')
31
+ } catch {
32
+ return null
33
+ }
34
+ }
35
+
36
+ function readJson(file) {
37
+ const text = readText(file)
38
+ if (text === null) return null
39
+ const clean = text.charCodeAt(0) === 0xFEFF ? text.slice(1) : text
40
+ try {
41
+ return JSON.parse(clean)
42
+ } catch {
43
+ return null
44
+ }
45
+ }
46
+
47
+ function isFile(file) {
48
+ try {
49
+ return statSync(file).isFile()
50
+ } catch {
51
+ return false
52
+ }
53
+ }
54
+
55
+ function isDirectory(file) {
56
+ try {
57
+ return statSync(file).isDirectory()
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
63
+ function stripEol(line) {
64
+ return line.replace(/\r?\n$/, '')
65
+ }
66
+
67
+ /** Split text into lines while keeping each line's own line ending. */
68
+ function splitLines(text) {
69
+ const lines = []
70
+ let start = 0
71
+ for (let i = 0; i < text.length; i += 1) {
72
+ if (text[i] === '\n') {
73
+ const end = i + 1
74
+ lines.push(text.slice(start, end))
75
+ start = end
76
+ }
77
+ }
78
+ if (start < text.length) lines.push(text.slice(start))
79
+ return lines
80
+ }
81
+
82
+ function dependencySpec(pkg, pluginName) {
83
+ if (!pkg || typeof pkg !== 'object') return null
84
+ for (const field of DEP_FIELDS) {
85
+ const deps = pkg[field]
86
+ if (deps && typeof deps === 'object' && typeof deps[pluginName] === 'string') {
87
+ return deps[pluginName]
88
+ }
89
+ }
90
+ return null
91
+ }
92
+
93
+ function bundlesOf(pkg) {
94
+ const bundles = pkg?.dsh?.profile?.bundles
95
+ return Array.isArray(bundles) ? bundles.filter(item => typeof item === 'string') : []
96
+ }
97
+
98
+ function profileFromArgv(argv) {
99
+ const args = Array.isArray(argv) ? argv.map(String) : []
100
+ for (let i = 0; i < args.length; i += 1) {
101
+ const arg = args[i]
102
+ if (arg === '--profile') {
103
+ const value = args[i + 1]
104
+ if (value && !value.startsWith('-')) return value
105
+ } else if (arg.startsWith('--profile=')) {
106
+ const value = arg.slice('--profile='.length)
107
+ if (value) return value
108
+ }
109
+ }
110
+ return null
111
+ }
112
+
113
+ function scanProfiles(homeRoot, pluginName) {
114
+ const profilesRoot = join(homeRoot, 'profiles')
115
+ let entries = []
116
+ try {
117
+ entries = readdirSync(profilesRoot, { withFileTypes: true })
118
+ } catch {
119
+ return []
120
+ }
121
+ const matches = []
122
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
123
+ if (!entry.isDirectory()) continue
124
+ const profileDir = join(profilesRoot, entry.name)
125
+ const pkg = readJson(join(profileDir, 'package.json'))
126
+ const dependency = dependencySpec(pkg, pluginName)
127
+ if (dependency !== null) matches.push({ profile: entry.name, profileDir, dependency })
128
+ }
129
+ return matches
130
+ }
131
+
132
+ function findInsertBlocks(text, pluginName) {
133
+ const lines = splitLines(text)
134
+ const nameRe = new RegExp(`name:\\s*['"]?${escapeRegExp(pluginName)}(?![\\w.-])`)
135
+ const blocks = []
136
+ let index = 0
137
+ while (index < lines.length) {
138
+ if (INSERT_START.test(stripEol(lines[index]))) {
139
+ let end = index + 1
140
+ while (end < lines.length && !TOP_LEVEL_ITEM.test(stripEol(lines[end]))) end += 1
141
+ const body = lines.slice(index, end).map(stripEol).join('\n')
142
+ if (nameRe.test(body)) {
143
+ blocks.push({ startLine: index + 1, endLine: end, startIndex: index, endIndex: end })
144
+ }
145
+ index = end
146
+ } else {
147
+ index += 1
148
+ }
149
+ }
150
+ return blocks
151
+ }
152
+
153
+ /**
154
+ * Remove every top-level `- insert:` block that references `pluginName`.
155
+ * Other content (comments, blank lines, `- id: agent-router` config rows, and
156
+ * other bundles' insert blocks) is preserved byte-for-byte.
157
+ *
158
+ * @param {string} text
159
+ * @param {string} [pluginName]
160
+ * @returns {{ text: string, removed: Array<{ startLine: number, endLine: number }> }}
161
+ */
162
+ export function removeManualInserts(text, pluginName = DEFAULT_PLUGIN) {
163
+ if (typeof text !== 'string' || text.length === 0) return { text: text ?? '', removed: [] }
164
+ const lines = splitLines(text)
165
+ const blocks = findInsertBlocks(text, pluginName)
166
+ if (blocks.length === 0) return { text, removed: [] }
167
+ const drop = new Set()
168
+ for (const block of blocks) {
169
+ for (let i = block.startIndex; i < block.endIndex; i += 1) drop.add(i)
170
+ }
171
+ const kept = lines.filter((_, index) => !drop.has(index))
172
+ return {
173
+ text: kept.join(''),
174
+ removed: blocks.map(block => ({ startLine: block.startLine, endLine: block.endLine })),
175
+ }
176
+ }
177
+
178
+ function unknownResult({ pluginName, homeRoot, files, reason, issues = [], guidance = [] }) {
179
+ return {
180
+ state: 'unknown',
181
+ profile: null,
182
+ profileDir: null,
183
+ home: homeRoot,
184
+ pluginName,
185
+ files,
186
+ bundleRegistered: false,
187
+ dependency: null,
188
+ manualInserts: [],
189
+ issues,
190
+ guidance,
191
+ reason,
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Inspect how the plugin is mounted in a DSH home.
197
+ *
198
+ * @param {{
199
+ * pluginName?: string,
200
+ * home?: string,
201
+ * argv?: string[],
202
+ * env?: Record<string, string|undefined>,
203
+ * }} [options]
204
+ * @returns {{
205
+ * state: 'ok'|'manual'|'duplicate'|'unknown',
206
+ * profile: string|null,
207
+ * profileDir: string|null,
208
+ * home: string,
209
+ * pluginName: string,
210
+ * files: { profilePatch: string|null, homePatch: string, profilePackage: string|null },
211
+ * bundleRegistered: boolean,
212
+ * dependency: string|null,
213
+ * manualInserts: Array<{ file: string, line: number }>,
214
+ * issues: Array<{ code: string, message: string, file?: string }>,
215
+ * guidance: string[],
216
+ * reason: string|null,
217
+ * }}
218
+ */
219
+ export function inspectMount({
220
+ pluginName = DEFAULT_PLUGIN,
221
+ home,
222
+ argv = process.argv.slice(2),
223
+ env = process.env,
224
+ } = {}) {
225
+ try {
226
+ const homeRoot = resolve(home || env?.DSH_HOME || join(homedir(), '.dsh'))
227
+ const homePatch = join(homeRoot, 'cordis.patch.yml')
228
+
229
+ let profile = null
230
+ let profileDir = null
231
+ let dependency = null
232
+ let ambiguous = []
233
+
234
+ const requested = profileFromArgv(argv)
235
+ if (requested) {
236
+ const candidate = join(homeRoot, 'profiles', requested)
237
+ if (isDirectory(candidate)) {
238
+ profile = requested
239
+ profileDir = candidate
240
+ }
241
+ }
242
+
243
+ if (!profileDir) {
244
+ const matches = scanProfiles(homeRoot, pluginName)
245
+ if (matches.length === 1) {
246
+ const match = matches[0]
247
+ profile = match.profile
248
+ profileDir = match.profileDir
249
+ dependency = match.dependency
250
+ } else if (matches.length > 1) {
251
+ ambiguous = matches
252
+ }
253
+ }
254
+
255
+ const profilePackage = profileDir ? join(profileDir, 'package.json') : null
256
+ const profilePatch = profileDir ? join(profileDir, 'cordis.patch.yml') : null
257
+ const files = { profilePatch, homePatch, profilePackage }
258
+
259
+ if (ambiguous.length > 0) {
260
+ const names = ambiguous.map(match => match.profile)
261
+ return unknownResult({
262
+ pluginName,
263
+ homeRoot,
264
+ files,
265
+ reason: `多个 profile 都声明了 ${pluginName} 依赖(${names.join(', ')})。`,
266
+ issues: [{
267
+ code: 'ambiguous-profile',
268
+ message: `多个 profile 同时声明了 ${pluginName} 依赖(${names.join(', ')})。请用 --profile <name> 指定要检查的 profile 后重试。`,
269
+ }],
270
+ guidance: ['使用 --profile <name> 指定目标 profile。'],
271
+ })
272
+ }
273
+
274
+ if (!profileDir) {
275
+ return unknownResult({
276
+ pluginName,
277
+ homeRoot,
278
+ files,
279
+ reason: `未在 ${join(homeRoot, 'profiles')} 下找到声明了 ${pluginName} 依赖的 profile。`,
280
+ guidance: [`请先在目标 profile 中安装 ${pluginName}。`],
281
+ })
282
+ }
283
+
284
+ const pkg = readJson(profilePackage)
285
+ if (dependency === null) dependency = dependencySpec(pkg, pluginName)
286
+ const bundleRegistered = bundlesOf(pkg).includes(pluginName)
287
+
288
+ const manualInserts = []
289
+ for (const file of [profilePatch, homePatch]) {
290
+ const text = readText(file)
291
+ if (text === null) continue
292
+ for (const block of findInsertBlocks(text, pluginName)) {
293
+ manualInserts.push({ file, line: block.startLine })
294
+ }
295
+ }
296
+
297
+ const issues = []
298
+ const guidance = []
299
+ const addGuidance = (line) => {
300
+ if (line && !guidance.includes(line)) guidance.push(line)
301
+ }
302
+ let state = 'unknown'
303
+ let reason = null
304
+
305
+ if (manualInserts.length > 0) {
306
+ state = bundleRegistered ? 'duplicate' : 'manual'
307
+ for (const insert of manualInserts) {
308
+ const message = state === 'duplicate'
309
+ ? `同时检测到标准 bundle 注册与手工 insert(${insert.file} 第 ${insert.line} 行)。这会让 DSH 卸载时提示“其他配置仍在使用这个组合包的组件”。请运行 profile-maintenance.mjs repair 移除手工块并重启 DSH。`
310
+ : `检测到手工挂载:${insert.file} 第 ${insert.line} 行的顶层 - insert: 块引用了 ${pluginName}。这会让 DSH 卸载时提示“其他配置仍在使用这个组合包的组件”。请删除该块,改用标准 bundle 安装,并运行 profile-maintenance.mjs repair 后重启 DSH。`
311
+ issues.push({ code: state === 'duplicate' ? 'duplicate-mount' : 'manual-mount', message, file: insert.file })
312
+ }
313
+ addGuidance('删除手写的 - insert: 挂载块(保留 - id: agent-router 配置行)。')
314
+ addGuidance('在 profile 目录执行 node node_modules/dsh-agent-router/scripts/profile-maintenance.mjs repair(仓库开发者可用 npm run profile:repair)。')
315
+ addGuidance('修复后完整重启 DSH。')
316
+ if (manualInserts.some(insert => insert.file === homePatch)) {
317
+ addGuidance('home 级 cordis.patch.yml 会作用于所有 profile,请确认只移除本插件的块。')
318
+ }
319
+ if (dependency === null) {
320
+ issues.push({
321
+ code: 'missing-dependency',
322
+ message: `${profilePackage} 未声明 ${pluginName} 依赖,无法自动修复。请先安装插件(DSH 插件页安装,或在仓库根执行 npm run profile:install -- --spec <版本>),再运行 repair。`,
323
+ file: profilePackage,
324
+ })
325
+ addGuidance('先安装插件:DSH 插件页,或在仓库根执行 npm run profile:install -- --spec <版本>。')
326
+ }
327
+ } else if (bundleRegistered) {
328
+ if (dependency === null) {
329
+ state = 'unknown'
330
+ reason = 'bundle 已注册,但 profile 的 package.json 未声明该依赖。'
331
+ issues.push({
332
+ code: 'missing-dependency',
333
+ message: `${profilePackage} 未声明 ${pluginName} 依赖;bundle 注册可能无法加载。请重新安装(DSH 插件页,或在仓库根执行 npm run profile:install -- --spec <版本>)。`,
334
+ file: profilePackage,
335
+ })
336
+ addGuidance('先安装插件:DSH 插件页,或在仓库根执行 npm run profile:install -- --spec <版本>。')
337
+ } else {
338
+ state = 'ok'
339
+ }
340
+ } else if (dependency !== null) {
341
+ state = 'unknown'
342
+ reason = `依赖已存在,但 ${pluginName} 未注册到 dsh.profile.bundles。`
343
+ addGuidance('重新安装以写入 dsh.profile.bundles:npm run profile:install -- --spec <版本>。')
344
+ } else {
345
+ state = 'unknown'
346
+ reason = `profile ${profile} 尚未安装 ${pluginName}。`
347
+ addGuidance(`请先在 profile 目录安装 ${pluginName}。`)
348
+ }
349
+
350
+ return {
351
+ state,
352
+ profile,
353
+ profileDir,
354
+ home: homeRoot,
355
+ pluginName,
356
+ files,
357
+ bundleRegistered,
358
+ dependency,
359
+ manualInserts,
360
+ issues,
361
+ guidance,
362
+ reason,
363
+ }
364
+ } catch (error) {
365
+ return unknownResult({
366
+ pluginName,
367
+ homeRoot: home || env?.DSH_HOME || '',
368
+ files: { profilePatch: null, homePatch: '', profilePackage: null },
369
+ reason: `检测安装方式失败:${error instanceof Error ? error.message : String(error)}`,
370
+ })
371
+ }
372
+ }
373
+
374
+ function timestamp(date) {
375
+ const pad = value => String(value).padStart(2, '0')
376
+ return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
377
+ }
378
+
379
+ function backupName(file, files) {
380
+ if (file === files.profilePatch) return 'profile-cordis.patch.yml'
381
+ if (file === files.homePatch) return 'home-cordis.patch.yml'
382
+ if (file === files.profilePackage) return 'profile-package.json'
383
+ return basename(file)
384
+ }
385
+
386
+ function ensureBundleEntry(packageFile, pluginName) {
387
+ const pkg = readJson(packageFile)
388
+ if (!pkg || typeof pkg !== 'object') return false
389
+ if (bundlesOf(pkg).includes(pluginName)) return false
390
+ if (!pkg.dsh || typeof pkg.dsh !== 'object') pkg.dsh = {}
391
+ if (!pkg.dsh.profile || typeof pkg.dsh.profile !== 'object') pkg.dsh.profile = {}
392
+ if (!Array.isArray(pkg.dsh.profile.bundles)) pkg.dsh.profile.bundles = []
393
+ pkg.dsh.profile.bundles.push(pluginName)
394
+ writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8')
395
+ return true
396
+ }
397
+
398
+ /**
399
+ * Repair a manual or duplicate mount: back up every file that changes, remove
400
+ * the hand-written insert blocks, and ensure the standard bundle entry exists.
401
+ *
402
+ * @param {ReturnType<typeof inspectMount>} inspection
403
+ * @param {{ now?: Date }} [options]
404
+ * @returns {{
405
+ * ok: boolean,
406
+ * changed: string[],
407
+ * backupDir: string|null,
408
+ * restartRequired: boolean,
409
+ * remainingIssues: Array<{ code: string, message: string, file?: string }>,
410
+ * guidance?: string[],
411
+ * error?: string,
412
+ * }}
413
+ */
414
+ export function applyMountRepair(inspection, { now = new Date() } = {}) {
415
+ const safe = inspection && typeof inspection === 'object' ? inspection : {}
416
+ const pluginName = safe.pluginName || DEFAULT_PLUGIN
417
+ const files = safe.files || {}
418
+ const issues = Array.isArray(safe.issues) ? safe.issues : []
419
+
420
+ if (safe.state !== 'manual' && safe.state !== 'duplicate') {
421
+ return {
422
+ ok: true,
423
+ changed: [],
424
+ backupDir: null,
425
+ restartRequired: false,
426
+ remainingIssues: issues,
427
+ }
428
+ }
429
+
430
+ if (!safe.dependency) {
431
+ return {
432
+ ok: false,
433
+ changed: [],
434
+ backupDir: null,
435
+ restartRequired: false,
436
+ remainingIssues: issues,
437
+ guidance: [`未检测到 ${pluginName} 依赖,未修改任何文件。请先安装插件(DSH 插件页,或在仓库根执行 npm run profile:install -- --spec <版本>)后再修复。`],
438
+ }
439
+ }
440
+
441
+ if (!safe.profileDir || !files.profilePackage) {
442
+ return {
443
+ ok: false,
444
+ changed: [],
445
+ backupDir: null,
446
+ restartRequired: false,
447
+ remainingIssues: issues,
448
+ guidance: ['无法定位 profile 目录,未修改任何文件。请用 --profile <name> 指定后重试。'],
449
+ }
450
+ }
451
+
452
+ const inserts = Array.isArray(safe.manualInserts) ? safe.manualInserts : []
453
+ const profileHasInsert = inserts.some(insert => insert.file === files.profilePatch)
454
+ const homeHasInsert = inserts.some(insert => insert.file === files.homePatch)
455
+ const bundleMissing = !safe.bundleRegistered
456
+
457
+ const backupTargets = []
458
+ if (profileHasInsert && isFile(files.profilePatch)) backupTargets.push(files.profilePatch)
459
+ if (homeHasInsert && isFile(files.homePatch)) backupTargets.push(files.homePatch)
460
+ if (bundleMissing && isFile(files.profilePackage)) backupTargets.push(files.profilePackage)
461
+
462
+ if (backupTargets.length === 0) {
463
+ return {
464
+ ok: true,
465
+ changed: [],
466
+ backupDir: null,
467
+ restartRequired: false,
468
+ remainingIssues: issues,
469
+ }
470
+ }
471
+
472
+ let backupDir = null
473
+ const changed = []
474
+ try {
475
+ backupDir = join(safe.home || dirname(dirname(safe.profileDir)), 'backups', `agent-router-mount-${timestamp(now)}`)
476
+ mkdirSync(backupDir, { recursive: true })
477
+ for (const file of backupTargets) {
478
+ copyFileSync(file, join(backupDir, backupName(file, {
479
+ profilePatch: files.profilePatch,
480
+ homePatch: files.homePatch,
481
+ profilePackage: files.profilePackage,
482
+ })))
483
+ }
484
+
485
+ for (const file of [files.profilePatch, files.homePatch]) {
486
+ if (!file || !isFile(file)) continue
487
+ const original = readText(file)
488
+ if (original === null) continue
489
+ const result = removeManualInserts(original, pluginName)
490
+ if (result.removed.length === 0) continue
491
+ writeFileSync(file, result.text, 'utf8')
492
+ changed.push(file)
493
+ }
494
+
495
+ if (bundleMissing && ensureBundleEntry(files.profilePackage, pluginName)) {
496
+ changed.push(files.profilePackage)
497
+ }
498
+ } catch (error) {
499
+ return {
500
+ ok: false,
501
+ changed,
502
+ backupDir,
503
+ restartRequired: changed.length > 0,
504
+ remainingIssues: issues,
505
+ error: error instanceof Error ? error.message : String(error),
506
+ }
507
+ }
508
+
509
+ let remainingIssues = []
510
+ try {
511
+ const argv = safe.profile ? ['--profile', safe.profile] : []
512
+ remainingIssues = inspectMount({ pluginName, home: safe.home, argv }).issues
513
+ } catch {
514
+ remainingIssues = []
515
+ }
516
+
517
+ return {
518
+ ok: changed.length > 0,
519
+ changed,
520
+ backupDir,
521
+ restartRequired: changed.length > 0,
522
+ remainingIssues,
523
+ }
524
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Pure route-editing helpers shared by the browser UI and unit tests.
3
+ *
4
+ * Keeping normalization, duplicate detection, and list movement outside the
5
+ * React component makes the "add DSH model route" flow easier to maintain and
6
+ * lets drag-and-drop reordering be tested without a DOM.
7
+ * @module dsh-agent-router/lib/route-edit
8
+ */
9
+
10
+ /** Empty DSH route draft used by the add form. */
11
+ export const EMPTY_DSH_ROUTE_INPUT = Object.freeze({
12
+ provider: '',
13
+ model: '',
14
+ reasoningEffort: '',
15
+ note: '',
16
+ })
17
+
18
+ /**
19
+ * Normalize a raw add-form value into a route entry.
20
+ * Returns null when provider or model is empty after trimming.
21
+ * @param {{ provider?: string, model?: string, reasoningEffort?: string, note?: string }} input
22
+ */
23
+ export function normalizeDshRouteInput(input) {
24
+ const provider = String(input?.provider ?? '').trim()
25
+ const model = String(input?.model ?? '').trim()
26
+ if (!provider || !model) return null
27
+ const reasoningEffort = String(input?.reasoningEffort ?? '').trim()
28
+ const note = String(input?.note ?? '').trim()
29
+ return {
30
+ provider,
31
+ model,
32
+ ...(reasoningEffort ? { reasoningEffort } : {}),
33
+ ...(note ? { note } : {}),
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Whether the same provider/model/effort route already exists in a tier chain.
39
+ * @param {Array<Record<string, any>>} list
40
+ * @param {{ provider: string, model: string, reasoningEffort?: string }} route
41
+ */
42
+ export function hasDshRoute(list, route) {
43
+ if (!Array.isArray(list) || !route) return false
44
+ return list.some(item => item
45
+ && item.provider === route.provider
46
+ && item.model === route.model
47
+ && (item.reasoningEffort || '') === (route.reasoningEffort || ''))
48
+ }
49
+
50
+ /**
51
+ * Append a normalized route unless an identical entry already exists.
52
+ * @param {Array<Record<string, any>>} list
53
+ * @param {{ provider: string, model: string, reasoningEffort?: string, note?: string } | null} route
54
+ * @returns {{ list: Array<Record<string, any>>, added: boolean }}
55
+ */
56
+ export function appendDshRoute(list, route) {
57
+ const current = Array.isArray(list) ? list : []
58
+ if (!route || hasDshRoute(current, route)) {
59
+ return { list: current, added: false }
60
+ }
61
+ return { list: [...current, route], added: true }
62
+ }
63
+
64
+ /**
65
+ * Move an item inside a list, clamping the target index. Returns a new array.
66
+ * @param {Array<any>} list
67
+ * @param {number} from
68
+ * @param {number} to
69
+ */
70
+ export function moveListItem(list, from, to) {
71
+ if (!Array.isArray(list)) return []
72
+ const source = Number(from)
73
+ const target = Number(to)
74
+ if (!Number.isInteger(source) || !Number.isInteger(target)) return list.slice()
75
+ if (source < 0 || source >= list.length) return list.slice()
76
+ const clamped = Math.max(0, Math.min(list.length - 1, target))
77
+ if (source === clamped) return list.slice()
78
+ const copy = list.slice()
79
+ const [item] = copy.splice(source, 1)
80
+ copy.splice(clamped, 0, item)
81
+ return copy
82
+ }