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
package/client.js ADDED
@@ -0,0 +1,3061 @@
1
+ // client.js — browser UI for dsh-agent-router inside DSH Plugin Detail & Config views.
2
+ // Zero build dependencies: uses window.__ModuleLoader__, React, and DSH theme CSS tokens.
3
+
4
+ window.__ModuleLoader__.load({
5
+ id: 'dsh-agent-router',
6
+ factory(require) {
7
+ const React = require('react')
8
+ const h = React.createElement
9
+ const { useEffect, useState } = React
10
+
11
+ const PACKAGE = 'dsh-agent-router'
12
+ const ROW_ID = 'agent-router'
13
+ const SLOT_KEY = PACKAGE + '#' + ROW_ID
14
+ const PRESET_NAMES = ['safe', 'cost', 'quality']
15
+ const CLI_BACKENDS = ['claude', 'codex', 'gemini', 'opencode', 'antigravity']
16
+ const PREFER_OPTIONS = ['auto', 'dsh', 'cli', 'claude', 'codex', 'gemini', 'opencode', 'antigravity']
17
+
18
+ function describe(error) {
19
+ return error instanceof Error ? error.message : String(error)
20
+ }
21
+
22
+ function descriptorsFor(pkg, endpoints) {
23
+ const argsCodec = () => ({
24
+ mode: 'strict',
25
+ typeSymbol: pkg + '/typert#EndpointArgs',
26
+ create: () => ({
27
+ parse(value) {
28
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
29
+ throw new TypeError(pkg + ': endpoint args must be a plain object')
30
+ }
31
+ return value
32
+ },
33
+ }),
34
+ })
35
+ return endpoints.map((name) => ({
36
+ id: pkg + '#' + pkg + '/' + name,
37
+ service: pkg,
38
+ namespace: pkg,
39
+ method: name,
40
+ invocation: { kind: 'direct' },
41
+ parameters: [{ name: 'args', wire: 'args', source: 'json', codec: argsCodec() }],
42
+ result: { mode: 'src-json' },
43
+ }))
44
+ }
45
+
46
+ function unwrapRemoteResult(res) {
47
+ if (!res || typeof res !== 'object' || typeof res.ok !== 'boolean') return res
48
+ if (res.ok === true && 'value' in res) return res.value
49
+ if (res.ok === false && res.error && typeof res.error === 'object') {
50
+ const failure = res.error
51
+ const err = new Error('remote ' + (failure.code || 'unknown') + (failure.message ? ': ' + failure.message : ''))
52
+ err.code = failure.code
53
+ throw err
54
+ }
55
+ return res
56
+ }
57
+
58
+ const DICT_EN = {
59
+ section_title: 'Difficulty Routing & Multi-Agent Config',
60
+ section_subtitle: 'Configure difficulty tiers, their model routing chains, failure escalation, and local CLI priorities. Saves take effect immediately.',
61
+ refresh: 'Refresh',
62
+ loading: 'Loading router configuration…',
63
+ load_error: 'Failed to load router state: {error}',
64
+ remote_unavailable: 'Remote RPC service is unavailable in this deployment.',
65
+ endpoint_missing: 'Router RPC endpoint is not mounted yet. Restart DSH if you just installed this plugin.',
66
+ contract_mismatch: 'The running Host uses an older RPC contract ({host}) than this UI ({ui}). Restart DSH to enable the full API; existing endpoints still work.',
67
+ cli_status_title: 'Local Agent CLIs',
68
+ cli_installed: 'Installed',
69
+ cli_missing: 'Not found',
70
+ stats_title: 'Routing Ledger',
71
+ stats_line: 'Total: {total} · Succeeded: {succeeded} · Running: {running} · Failed: {failed} · Escalated: {escalated}',
72
+ subagent_sel_warn: 'DSH subagent-model-selection is disabled: native subagents are locked to the active session model. Enable subagent-model-selection-settings in DSH to let tiers switch DSH models freely (external CLIs are unaffected).',
73
+ mount_warn_title: 'Non-standard mount',
74
+ mount_warn_manual: 'This plugin is manually mounted in the profile patch; DSH will refuse to uninstall it until that hand-written block is removed.',
75
+ mount_warn_duplicate: 'This plugin is both bundle-installed and manually mounted; DSH treats it as still in use and blocks uninstall.',
76
+ mount_warn_profile: 'Profile path',
77
+ mount_warn_fix: 'Run this in the profile directory, then fully restart DSH:',
78
+ mount_repair_command: 'node node_modules/dsh-agent-router/scripts/profile-maintenance.mjs repair',
79
+ auto_fill_btn: 'Auto-Match Live Models',
80
+ auto_fill_ok: 'Matched live DSH & CLI models into draft — review and click Save Configuration.',
81
+ route_ok: 'Ready',
82
+ route_missing_llm: 'Not in ctx.llm',
83
+ route_blocked_allowlist: 'Not in allowlist',
84
+ route_cli_missing: 'CLI not found',
85
+ route_duplicate: 'This route already exists in the current tier.',
86
+ test_title: 'Dry-Run Route Preview',
87
+ test_placeholder: 'Enter a sample task (e.g. "Review auth diff for security issues")…',
88
+ test_btn: 'Test Route',
89
+ testing: 'Testing…',
90
+ doctor_title: 'Environment Diagnostics',
91
+ doctor_run: 'Run diagnostics',
92
+ doctor_running: 'Diagnosing…',
93
+ doctor_summary: '{ok} ok · {warn} warning(s) · {fail} error(s)',
94
+ doctor_host_outdated: 'The running Host has not loaded the diagnose endpoint yet. Showing limited diagnostics — fully quit and relaunch DSH for the full report.',
95
+ doctor_hint_label: 'Fix',
96
+ doctor_check_host_rpc: 'Host RPC contract',
97
+ doctor_check_dsh_catalog: 'DSH LLM catalog',
98
+ doctor_check_subagent_model_selection: 'Subagent model selection',
99
+ doctor_check_local_clis: 'Local agent CLIs',
100
+ doctor_check_cli_selection: 'CLI selection mode',
101
+ doctor_check_local_models: 'Local models',
102
+ doctor_check_native_jobs: 'Native jobs',
103
+ doctor_check_cost_meter: 'dsh-cost-meter',
104
+ doctor_check_ledger: 'Routing ledger',
105
+ doctor_check_mount: 'Install mount mode',
106
+ doctor_check_background_queue: 'Background queue',
107
+ recent_title: 'Recent Routed Runs ({count})',
108
+ recent_empty: 'No routed tasks recorded yet.',
109
+ recent_toggle_show: 'Show',
110
+ recent_toggle_hide: 'Hide',
111
+ summary_line: 'Tier routing · {prefer} · {clis}/{totalClis} CLIs ready · {total} runs',
112
+ cooldowns_title: 'Circuit-Breaker Cooldowns',
113
+ cooldowns_none: 'All routes healthy (no active cooldowns)',
114
+ clear_cooldowns: 'Clear cooldowns',
115
+ cooldown_item: '{key} ({sec}s left): {reason}',
116
+ global_title: 'Global Policy',
117
+ prefer_backend: 'Default backend preference',
118
+ auto_escalate: 'Auto-escalate to the configured next tier on failure',
119
+ budget_guard: 'Budget guard via dsh-cost-meter (prefer low-cost/CLI near limit)',
120
+ peak_avoidance: 'Avoid DeepSeek-family routes during 2x peak pricing hours',
121
+ adaptive_ranking: 'Adaptive routing via historical EWMA latency & success rates',
122
+ default_background: 'Run external CLI dispatches asynchronously in background queue by default',
123
+ native_jobs: 'Use the DSH native job registry (ctx.jobs) for background CLI runs when available',
124
+ cli_selection_label: 'CLI candidate selection',
125
+ cli_selection_static: 'static (configured chain only)',
126
+ cli_selection_adaptive: 'adaptive (auto-add installed CLIs + EWMA)',
127
+ local_models_enable: 'Allow local/self-hosted DSH models (Ollama, LM Studio, vLLM…)',
128
+ local_providers_label: 'Local provider ids (comma-separated, empty = auto-detect)',
129
+ local_providers_placeholder: 'e.g. ollama, lmstudio',
130
+ local_models_detected: 'Detected local providers: {providers}',
131
+ max_concurrent_cli: 'Max concurrent async CLI jobs',
132
+ config_src_profile: 'Saved in Profile (cordis.patch.yml)',
133
+ config_src_legacy: 'Legacy override (state.json)',
134
+ config_src_default: 'Using built-in defaults',
135
+ import_legacy_btn: 'Migrate Legacy Config to Profile',
136
+ config_version_badge: 'schema v{version}',
137
+ preset_label: 'Presets',
138
+ preset_safe: 'Safe',
139
+ preset_cost: 'Cost-saving',
140
+ preset_quality: 'Quality-first',
141
+ preset_applied: 'Applied {name} preset; tier routes were left unchanged.',
142
+ export_config: 'Export Config',
143
+ import_config: 'Import Config',
144
+ import_placeholder: 'Paste an exported config JSON here…',
145
+ export_ready: 'Config JSON is shown below; copy it to share.',
146
+ import_empty: 'Paste a config JSON first.',
147
+ import_applied: 'Config imported and applied immediately.',
148
+ auto_fixed: 'auto-fixed {count} item(s): {detail}',
149
+ import_legacy_ok: 'Migrated legacy state.json config into Profile cordis.patch.yml.',
150
+ active_jobs_title: 'Active Background CLI Jobs ({count})',
151
+ cancel_job: 'Cancel',
152
+ job_cancelled: 'Cancelled job {runId}',
153
+ worktree_badge: 'branch: {branch}',
154
+ merged_badge: 'merged',
155
+ cost_meter_title: 'dsh-cost-meter Link',
156
+ cost_today: 'Today: {sym}{today}',
157
+ cost_budget: 'Budget: {sym}{used} / {sym}{amount} ({pct}%)',
158
+ cost_peak_on: 'Peak 2x active',
159
+ cost_peak_off: 'Off-peak',
160
+ cooldown_sec: 'Cooldown duration (sec)',
161
+ timeout_sec: 'CLI timeout (sec)',
162
+ tier_section_title: 'Difficulty Tier Routing Matrix',
163
+ tier_T1_name: 'T1 · Light / Search',
164
+ tier_T2_name: 'T2 · Standard / Code',
165
+ tier_T3_name: 'T3 · Hard / Architecture',
166
+ tier_T4_name: 'T4 · Review / Audit',
167
+ tier_prefer: 'Tier backend preference',
168
+ tier_escalate: 'Escalate on failure to',
169
+ escalate_none: 'None (top tier)',
170
+ tier_layout_label: 'Tier layout',
171
+ tier_layout_default: '4 tiers',
172
+ tier_layout_compact: '3 tiers',
173
+ tier_layout_fast: '2 tiers',
174
+ tier_layout_confirm: 'Switch to the "{name}" layout? Tiers with the same id keep their model chains.',
175
+ tier_layout_applied: 'Applied the "{name}" layout — review and click Save Configuration.',
176
+ tier_layout_hint: 'Presets only change tier names and score ranges; model chains are kept when the tier id matches.',
177
+ tier_name_label: 'Tier name',
178
+ tier_desc_label: 'What this tier handles',
179
+ tier_desc_placeholder: 'e.g. search, summaries, small edits',
180
+ tier_review_badge: 'Review tier',
181
+ tier_advanced: 'Advanced: score range',
182
+ tier_range_min: 'Minimum score',
183
+ tier_range_max: 'Maximum score',
184
+ tier_unbounded: 'No upper limit',
185
+ tier_range_hint: 'Scores are internal difficulty numbers; most users never need to change them.',
186
+ tier_role_review_label: 'Use this tier for review/audit tasks',
187
+ tier_add_title: 'Add tier',
188
+ tier_add_name_placeholder: 'New tier name (e.g. Quick fixes)',
189
+ tier_template_blank: 'Blank normal tier',
190
+ tier_template_light: 'Light tasks',
191
+ tier_template_standard: 'Standard tasks',
192
+ tier_template_heavy: 'Hard tasks',
193
+ tier_template_review: 'Review tier',
194
+ tier_add_btn: 'Add tier',
195
+ tier_remove_btn: 'Delete tier',
196
+ tier_remove_confirm: 'Delete tier "{name}"? Its routes will be removed from the draft.',
197
+ tier_remove_last_error: 'Keep at least one normal (non-review) tier.',
198
+ tier_validation_failed: 'Please fix the tier settings first.',
199
+ dsh_routes_title: 'DSH Native Model Chain (ordered by priority)',
200
+ dsh_routes_hint: 'Tried top to bottom within this tier; drag the handle to reorder. If a route fails, the next healthy candidate is attempted.',
201
+ dsh_routes_empty: 'No DSH models configured for this tier.',
202
+ drag_handle: 'Drag to reorder',
203
+ cli_routes_title: 'Local CLI Chain (ordered by priority)',
204
+ cli_routes_hint: 'Tried top to bottom within this tier; drag the handle to reorder. Missing or cooling-down CLIs are skipped automatically.',
205
+ cli_routes_empty: 'No CLI backends configured for this tier.',
206
+ add_dsh_title: 'Add DSH model route',
207
+ add_cli_title: 'Add local CLI route',
208
+ cli_catalog_pick: 'Pick from local {backend} config (optional)…',
209
+ cli_inherits_default: 'inherits CLI default ({model})',
210
+ provider_placeholder: 'provider (e.g. open-design)',
211
+ model_placeholder: 'model id',
212
+ effort_placeholder: 'effort (optional)',
213
+ note_placeholder: 'purpose note (optional)',
214
+ catalog_pick: 'Pick from live DSH catalog…',
215
+ add_btn: 'Add',
216
+ move_up: '↑',
217
+ move_down: '↓',
218
+ remove: 'Remove',
219
+ save: 'Save Configuration',
220
+ saving: 'Saving…',
221
+ discard: 'Discard Changes',
222
+ reset_defaults: 'Reset to Defaults',
223
+ saved_ok: 'Saved & applied immediately ({at})',
224
+ reset_ok: 'Restored default routing rules ({at})',
225
+ save_err: 'Save failed: {error}',
226
+ override_badge: 'Custom UI override active',
227
+ default_badge: 'Using defaults / cordis.patch.yml',
228
+ prefer_auto: 'auto (smart balance)',
229
+ prefer_dsh: 'dsh (native subagents first)',
230
+ prefer_cli: 'cli (local CLIs first)',
231
+ prefer_named: '{name} (pin this CLI)',
232
+ update_title: 'Version & Updates',
233
+ update_subtitle: 'Checks the GitHub branch for a newer package version. Network failures never affect routing.',
234
+ update_check: 'Check for Updates',
235
+ update_checking: 'Checking…',
236
+ update_current: 'Current version {version}',
237
+ update_badge: 'Update {version} available',
238
+ update_available: 'New version {version} available (current {current})',
239
+ update_latest: 'Up to date ({version})',
240
+ update_ahead: 'This build is newer than the GitHub branch.',
241
+ update_failed: 'Unable to check for updates: {error}',
242
+ update_offline_hint: 'Offline or GitHub unreachable. Routing, settings, and diagnostics keep working.',
243
+ update_command_hint: 'Run in the DSH profile directory, then restart DSH:',
244
+ update_copy: 'Copy command',
245
+ update_copied: 'Update command copied to the clipboard.',
246
+ update_open: 'Open on GitHub',
247
+ update_npm_hint: 'Installed from npm instead? Run: {command}',
248
+ update_checked_at: 'Checked {at}',
249
+ update_idle: 'Update status has not been checked yet.',
250
+ }
251
+
252
+ const DICT_ZH = {
253
+ section_title: '难度分级与多智能体路由配置',
254
+ section_subtitle: '按任务难度维护档位、DSH 模型链、本地 CLI 优先级、熔断冷却与失败升阶,保存后立即生效。',
255
+ refresh: '刷新状态',
256
+ loading: '正在加载路由器配置…',
257
+ load_error: '加载路由状态失败:{error}',
258
+ remote_unavailable: '当前环境未挂载 Remote RPC 服务。',
259
+ endpoint_missing: '路由器 RPC 接口尚未挂载(若刚安装本插件,请重启 DSH 生效)。',
260
+ contract_mismatch: '运行中的 Host 使用的 RPC 契约({host})与当前面板({ui})不一致。请重启 DSH 以启用完整接口;现有端点仍可正常保存。',
261
+ cli_status_title: '本机 Agent CLI 探测',
262
+ cli_installed: '已安装',
263
+ cli_missing: '未检测到',
264
+ stats_title: '调度账本统计',
265
+ stats_line: '总计: {total} · 成功: {succeeded} · 运行中: {running} · 失败: {failed} · 自动升阶: {escalated}',
266
+ subagent_sel_warn: 'DSH 当前未开启 subagent-model-selection:原生子智能体仅能沿用主会话当前模型。如需让各档位自由切换不同 DSH 模型,请在 DSH 配置中开启 subagent-model-selection-settings(外部 CLI 不受此限制)。',
267
+ mount_warn_title: '非标准挂载',
268
+ mount_warn_manual: '检测到本插件被手工挂载到 profile 配置中;在删除这段手写内容前,DSH 会拒绝卸载。',
269
+ mount_warn_duplicate: '本插件同时通过 bundle 注册和手工挂载安装,DSH 会认为组件仍在使用并阻止卸载。',
270
+ mount_warn_profile: 'Profile 路径',
271
+ mount_warn_fix: '请在 profile 目录执行以下命令,然后完整重启 DSH:',
272
+ mount_repair_command: 'node node_modules/dsh-agent-router/scripts/profile-maintenance.mjs repair',
273
+ auto_fill_btn: '从本机已注册模型智能匹配',
274
+ auto_fill_ok: '已按本机可用模型与 CLI 自动生成草稿,请检查后点击「保存配置」。',
275
+ route_ok: '可用',
276
+ route_missing_llm: '未在 ctx.llm 注册',
277
+ route_blocked_allowlist: '不在子智能体白名单',
278
+ route_cli_missing: 'CLI 未安装',
279
+ route_duplicate: '当前档位已存在相同路由。',
280
+ test_title: '路由定级实时试算',
281
+ test_placeholder: '输入示例任务(如:"审查 auth 模块是否存在并发安全漏洞")…',
282
+ test_btn: '测试路由',
283
+ testing: '计算中…',
284
+ doctor_title: '环境诊断',
285
+ doctor_run: '运行诊断',
286
+ doctor_running: '诊断中…',
287
+ doctor_summary: '{ok} 项正常 · {warn} 项提示 · {fail} 项错误',
288
+ doctor_host_outdated: '运行中的 Host 尚未加载 diagnose 端点,当前展示降级诊断。请完整退出并重启 DSH 后再试。',
289
+ doctor_hint_label: '建议',
290
+ doctor_check_host_rpc: 'Host RPC 契约',
291
+ doctor_check_dsh_catalog: 'DSH 模型目录',
292
+ doctor_check_subagent_model_selection: '子智能体模型选择',
293
+ doctor_check_local_clis: '本机 Agent CLI',
294
+ doctor_check_cli_selection: 'CLI 选择模式',
295
+ doctor_check_local_models: '本地模型',
296
+ doctor_check_native_jobs: '原生后台任务',
297
+ doctor_check_cost_meter: 'dsh-cost-meter',
298
+ doctor_check_ledger: '调度账本',
299
+ doctor_check_mount: '安装挂载方式',
300
+ doctor_check_background_queue: '后台队列',
301
+ recent_title: '最近调度记录({count})',
302
+ recent_empty: '暂无调度记录。',
303
+ recent_toggle_show: '展开',
304
+ recent_toggle_hide: '收起',
305
+ summary_line: '多档位路由 · {prefer} · {clis}/{totalClis} 个 CLI 就绪 · 累计 {total} 次调度',
306
+ cooldowns_title: '熔断冷却状态',
307
+ cooldowns_none: '全部路由健康(当前无冷却项)',
308
+ clear_cooldowns: '清除全部冷却',
309
+ cooldown_item: '{key}(剩余 {sec}s):{reason}',
310
+ global_title: '全局策略',
311
+ prefer_backend: '默认执行端倾向',
312
+ auto_escalate: '同档全部失败时自动升到配置的下一档重试',
313
+ budget_guard: '联动 dsh-cost-meter 预算告警:接近或超预算时优先低价/本地 CLI 路由',
314
+ peak_avoidance: '联动峰谷计价:DeepSeek 2× 高峰时段优先非 DeepSeek / 本地 CLI',
315
+ adaptive_ranking: '自适应排序:依据历史 EWMA 延迟与成功率动态微调同档优先级',
316
+ default_background: '外部 CLI 任务默认走后台异步队列(不阻塞当前对话)',
317
+ native_jobs: '后台 CLI 任务优先使用 DSH 原生 Job 运行时(ctx.jobs)',
318
+ cli_selection_label: 'CLI 候选选择模式',
319
+ cli_selection_static: 'static(严格按本档配置链)',
320
+ cli_selection_adaptive: 'adaptive(自动补充已安装 CLI + EWMA 排序)',
321
+ local_models_enable: '允许本地/自托管 DSH 模型(Ollama、LM Studio、vLLM 等)',
322
+ local_providers_label: '本地 Provider ID(逗号分隔,留空自动识别)',
323
+ local_providers_placeholder: '例如 ollama, lmstudio',
324
+ local_models_detected: '已识别本地 Provider:{providers}',
325
+ max_concurrent_cli: '后台 CLI 最大并发数',
326
+ config_src_profile: '配置已托管至 Profile(cordis.patch.yml)',
327
+ config_src_legacy: '旧版 state.json 覆盖生效中',
328
+ config_src_default: '使用默认配置',
329
+ import_legacy_btn: '迁移旧配置到 Profile',
330
+ config_version_badge: '配置版本 v{version}',
331
+ preset_label: '预设',
332
+ preset_safe: '稳妥优先',
333
+ preset_cost: '成本优先',
334
+ preset_quality: '质量优先',
335
+ preset_applied: '已应用「{name}」预设;各档位路由保持不变。',
336
+ export_config: '导出配置',
337
+ import_config: '导入配置',
338
+ import_placeholder: '在此粘贴导出的配置 JSON…',
339
+ export_ready: '配置 JSON 已生成,可复制分享。',
340
+ import_empty: '请先粘贴配置 JSON。',
341
+ import_applied: '配置已导入并立即生效。',
342
+ auto_fixed: '已自动修复 {count} 项:{detail}',
343
+ import_legacy_ok: '已将旧版 state.json 配置迁移写入 Profile cordis.patch.yml。',
344
+ active_jobs_title: '运行中后台 CLI 队列({count})',
345
+ cancel_job: '取消任务',
346
+ job_cancelled: '已取消后台任务 {runId}',
347
+ worktree_badge: '分支: {branch}',
348
+ merged_badge: '已合入',
349
+ cost_meter_title: 'dsh-cost-meter 联动状态',
350
+ cost_today: '今日费用:{sym}{today}',
351
+ cost_budget: '预算进度:{sym}{used} / {sym}{amount}({pct}%)',
352
+ cost_peak_on: '当前高峰 2× 计费',
353
+ cost_peak_off: '当前非高峰',
354
+ cooldown_sec: '失败冷却时长(秒)',
355
+ timeout_sec: '外部 CLI 超时(秒)',
356
+ tier_section_title: '难度档位路由表',
357
+ tier_T1_name: 'T1 · 轻量检索/摘要',
358
+ tier_T2_name: 'T2 · 标准编码/单测',
359
+ tier_T3_name: 'T3 · 困难架构/排错',
360
+ tier_T4_name: 'T4 · 异构审查/验收',
361
+ tier_prefer: '本档执行端倾向',
362
+ tier_escalate: '失败后升阶目标',
363
+ escalate_none: '无(最高档)',
364
+ tier_layout_label: '档位方案',
365
+ tier_layout_default: '默认四档',
366
+ tier_layout_compact: '精简三档',
367
+ tier_layout_fast: '极速两档',
368
+ tier_layout_confirm: '切换到「{name}」?同 id 的档位会保留原有模型链。',
369
+ tier_layout_applied: '已切换到「{name}」方案,请检查后点击「保存配置」。',
370
+ tier_layout_hint: '方案只调整档位名称与分数区间;同 id 档位的模型链保持不变。',
371
+ tier_name_label: '档位名称',
372
+ tier_desc_label: '这档负责什么',
373
+ tier_desc_placeholder: '例如:搜索、摘要、小改动',
374
+ tier_review_badge: '审查类档位',
375
+ tier_advanced: '进阶设置:分数区间',
376
+ tier_range_min: '最低分',
377
+ tier_range_max: '最高分',
378
+ tier_unbounded: '无上限',
379
+ tier_range_hint: '分数是内部难度值,普通用户通常不需要修改。',
380
+ tier_role_review_label: '把这一档用于审查/验收任务',
381
+ tier_add_title: '新增档位',
382
+ tier_add_name_placeholder: '新档位名称(例如:快速修复)',
383
+ tier_template_blank: '空白普通档',
384
+ tier_template_light: '轻量任务',
385
+ tier_template_standard: '标准任务',
386
+ tier_template_heavy: '困难任务',
387
+ tier_template_review: '审查档',
388
+ tier_add_btn: '新增档位',
389
+ tier_remove_btn: '删除档位',
390
+ tier_remove_confirm: '删除档位「{name}」?该档的模型链会从草稿中移除。',
391
+ tier_remove_last_error: '至少需要保留一个普通(非审查)档位。',
392
+ tier_validation_failed: '请先修正档位配置。',
393
+ dsh_routes_title: 'DSH 原生模型优先级列表(自上而下依次尝试)',
394
+ dsh_routes_hint: '同档内自上而下依次尝试;拖拽左侧手柄可调整顺序,失败时自动顺延下一个健康候选。',
395
+ dsh_routes_empty: '本档尚未配置 DSH 原生模型。',
396
+ drag_handle: '拖拽排序',
397
+ cli_routes_title: '本机 CLI 优先级列表(自上而下依次尝试)',
398
+ cli_routes_hint: '同档内自上而下依次尝试;拖拽左侧手柄可调整顺序。未安装或冷却中的 CLI 会自动跳过。',
399
+ cli_routes_empty: '本档尚未配置外部 CLI。',
400
+ add_dsh_title: '添加 DSH 模型路由',
401
+ add_cli_title: '添加本机 CLI 路由',
402
+ cli_catalog_pick: '从本机 {backend} 配置中快速选模型(可空)…',
403
+ cli_inherits_default: '未指定模型(继承 CLI 默认:{model})',
404
+ provider_placeholder: '提供方 (如 open-design)',
405
+ model_placeholder: '模型 ID',
406
+ effort_placeholder: '推理档位 (如 low/high,可空)',
407
+ note_placeholder: '用途备注(可空)',
408
+ catalog_pick: '从当前 DSH 已注册模型中快速选择…',
409
+ add_btn: '添加',
410
+ move_up: '上移',
411
+ move_down: '下移',
412
+ remove: '删除',
413
+ save: '保存配置',
414
+ saving: '正在保存…',
415
+ discard: '放弃修改',
416
+ reset_defaults: '恢复默认策略',
417
+ saved_ok: '已保存并立即生效({at})',
418
+ reset_ok: '已恢复默认路由策略({at})',
419
+ save_err: '保存失败:{error}',
420
+ override_badge: '已启用面板自定义配置',
421
+ default_badge: '当前使用默认 / cordis.patch.yml 配置',
422
+ prefer_auto: 'auto(智能均衡)',
423
+ prefer_dsh: 'dsh(优先 DSH 原生子智能体)',
424
+ prefer_cli: 'cli(优先本机外部 CLI)',
425
+ prefer_named: '{name}(优先使用该 CLI)',
426
+ update_title: '版本与更新',
427
+ update_subtitle: '检查 GitHub 分支上是否有更新版本;离线或网络失败不影响路由与配置。',
428
+ update_check: '检测更新',
429
+ update_checking: '正在检测…',
430
+ update_current: '当前版本 {version}',
431
+ update_badge: '可更新至 {version}',
432
+ update_available: '发现新版本 {version}(当前 {current})',
433
+ update_latest: '已是最新版本({version})',
434
+ update_ahead: '当前本地版本高于 GitHub 分支。',
435
+ update_failed: '无法检测更新:{error}',
436
+ update_offline_hint: '离线或 GitHub 不可达;路由、设置与诊断仍可正常使用。',
437
+ update_command_hint: '在 DSH profile 目录执行以下命令,然后重启 DSH:',
438
+ update_copy: '复制命令',
439
+ update_copied: '更新命令已复制到剪贴板。',
440
+ update_open: '在 GitHub 查看',
441
+ update_npm_hint: '如果是从 npm 安装:{command}',
442
+ update_checked_at: '检测时间 {at}',
443
+ update_idle: '尚未检测更新状态。',
444
+ }
445
+
446
+ const CSS = `
447
+ .dar-wrap{display:flex;flex-direction:column;gap:12px;min-width:0;font-size:13px;color:var(--dsw-alias-label-primary);}
448
+ .dar-card{display:flex;flex-direction:column;gap:12px;padding:14px;border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-lg);background:var(--dsw-alias-bg-layer-2,transparent);}
449
+ .dar-head{display:flex;align-items:flex-start;justify-content:space-between;gap:10px;flex-wrap:wrap;}
450
+ .dar-title{margin:0;font-size:13px;font-weight:600;line-height:20px;color:var(--dsw-alias-label-primary);}
451
+ .dar-sub{margin:2px 0 0;font-size:12px;line-height:1.5;color:var(--dsw-alias-label-tertiary);}
452
+ .dar-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
453
+ .dar-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:10px;}
454
+ .dar-box{padding:10px 12px;border-radius:var(--dsw-radius-md);background:var(--dsw-alias-interactive-bg-hover);display:flex;flex-direction:column;gap:6px;min-width:0;}
455
+ .dar-box-title{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary);}
456
+ .dar-badges{display:flex;flex-wrap:wrap;gap:6px;}
457
+ .dar-badge{display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:999px;font-size:11px;border:.5px solid var(--dsw-alias-border-l3);background:var(--dsw-alias-bg-layer-3);}
458
+ .dar-badge.ok{color:var(--dsw-alias-state-success-primary);border-color:var(--dsw-alias-state-success-primary);}
459
+ .dar-badge.off{color:var(--dsw-alias-label-tertiary);}
460
+ .dar-badge.warn{color:var(--dsw-alias-state-warn-primary,#d97706);border-color:var(--dsw-alias-state-warn-primary,#d97706);}
461
+ .dar-field{display:flex;flex-direction:column;gap:4px;min-width:0;}
462
+ .dar-label{font-size:12px;color:var(--dsw-alias-label-secondary);}
463
+ .dar-input,.dar-select{box-sizing:border-box;width:100%;height:32px;padding:0 10px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;}
464
+ .dar-tabs{display:flex;gap:6px;flex-wrap:wrap;border-bottom:.5px solid var(--dsw-alias-border-l2);padding-bottom:8px;}
465
+ .dar-tab{appearance:none;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);padding:5px 12px;font:inherit;font-size:12px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;}
466
+ .dar-tab.active{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3);border-color:transparent;font-weight:600;}
467
+ .dar-list{display:flex;flex-direction:column;gap:6px;}
468
+ .dar-item{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px 10px;border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-3);}
469
+ .dar-item.dragging{opacity:.55;}
470
+ .dar-item.drag-over{border-color:var(--dsw-alias-label-primary);box-shadow:inset 0 2px 0 var(--dsw-alias-label-primary);}
471
+ .dar-drag-handle{display:inline-flex;align-items:center;justify-content:center;width:16px;flex:0 0 16px;color:var(--dsw-alias-label-tertiary);cursor:grab;font-size:12px;line-height:1;letter-spacing:-2px;user-select:none;}
472
+ .dar-drag-handle:active{cursor:grabbing;}
473
+ .dar-item-main{flex:1 1 220px;min-width:0;display:flex;flex-direction:column;gap:2px;}
474
+ .dar-item-name{font-size:12px;font-weight:600;overflow-wrap:anywhere;}
475
+ .dar-item-meta{font-size:11px;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere;}
476
+ .dar-add-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:6px;align-items:center;}
477
+ .dar-btn{appearance:none;height:30px;padding:0 12px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;cursor:pointer;}
478
+ .dar-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover);}
479
+ .dar-btn:disabled{opacity:.45;cursor:default;}
480
+ .dar-code{display:block;margin:4px 0;padding:8px 10px;border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-3);border:.5px solid var(--dsw-alias-border-l2);font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:11px;line-height:1.5;white-space:pre-wrap;overflow-wrap:anywhere;user-select:all;}
481
+ .dar-btn.primary{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-layer-3);border-color:transparent;font-weight:500;}
482
+ .dar-btn.small{height:26px;padding:0 8px;font-size:11px;}
483
+ .dar-btn.danger{color:var(--dsw-alias-state-error-primary);}
484
+ .dar-msg-ok{font-size:12px;color:var(--dsw-alias-state-success-primary);}
485
+ .dar-msg-err{font-size:12px;color:var(--dsw-alias-state-error-primary);}
486
+ .dar-check{display:inline-flex;align-items:center;gap:6px;font-size:12px;cursor:pointer;}
487
+ .dar-tv{display:flex;flex-direction:column;gap:6px;padding:8px 10px;border:.5px solid var(--dsw-alias-border-l2,var(--dsw-alias-border-l1));border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-layer-1));font-size:12px;}
488
+ .dar-tv-head{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;cursor:pointer;}
489
+ .dar-tv-pre{margin:0;padding:8px;border-radius:6px;background:var(--dsw-alias-bg-base,#111);color:var(--dsw-alias-label-primary);font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:11px;white-space:pre-wrap;overflow-wrap:anywhere;max-height:220px;overflow:auto;}
490
+ `
491
+
492
+ function cloneConfig(cfg) {
493
+ return JSON.parse(JSON.stringify(cfg))
494
+ }
495
+
496
+ function preferLabel(val, t) {
497
+ if (val === 'auto') return t('prefer_auto')
498
+ if (val === 'dsh') return t('prefer_dsh')
499
+ if (val === 'cli') return t('prefer_cli')
500
+ return t('prefer_named', { name: val })
501
+ }
502
+
503
+ /**
504
+ * Single source of truth for the Typert RPC endpoint surface.
505
+ *
506
+ * Consumed by the Host descriptor (`lib/typert.host.js`), the RPC mount
507
+ * (`lib/router/rpc.js`), and the browser client (inlined by
508
+ * `scripts/build-client.mjs`). Add a method to all three by editing this list.
509
+ *
510
+ * @module dsh-agent-router/lib/rpc-contract
511
+ */
512
+
513
+ const RPC_ENDPOINTS = Object.freeze([
514
+ 'getState',
515
+ 'saveConfig',
516
+ 'resetConfig',
517
+ 'clearCooldowns',
518
+ 'testPlan',
519
+ 'diagnose',
520
+ 'getRunStatus',
521
+ 'cancelRun',
522
+ 'importLegacyConfig',
523
+ 'applyPreset',
524
+ 'exportConfig',
525
+ 'importConfig',
526
+ 'exportMetrics',
527
+ 'checkUpdate',
528
+ ])
529
+
530
+ /**
531
+ * Stable short hash of the endpoint surface.
532
+ *
533
+ * Both the Host and the browser bundle compute this from the same list, so a
534
+ * running Host that predates a newly added endpoint is detectable at runtime
535
+ * instead of failing with a bare HTTP 404.
536
+ *
537
+ * @param {readonly string[]} [endpoints]
538
+ * @returns {string}
539
+ */
540
+ function contractVersion(endpoints = RPC_ENDPOINTS) {
541
+ const text = [...endpoints].sort().join('|')
542
+ let hash = 0x811c9dc5
543
+ for (let i = 0; i < text.length; i += 1) {
544
+ hash ^= text.charCodeAt(i)
545
+ hash = Math.imul(hash, 0x01000193) >>> 0
546
+ }
547
+ return `rpc-${hash.toString(16).padStart(8, '0')}`
548
+ }
549
+
550
+ /**
551
+ * Model suitability scoring shared by the Host router and the Browser auto-match UI.
552
+ * Pure functions only, so the client build can inline this module verbatim.
553
+ * @module dsh-agent-router/lib/model-score
554
+ */
555
+
556
+ /**
557
+ * Classify a model ID into a coarse family for heterogeneity checks.
558
+ * @param {string} modelId
559
+ */
560
+ function modelFamilyOf(modelId) {
561
+ const m = String(modelId || '').toLowerCase()
562
+ if (m.includes('deepseek')) return 'deepseek'
563
+ if (m.includes('claude')) return 'claude'
564
+ if (m.includes('gemini')) return 'gemini'
565
+ if (m.includes('gpt') || m.includes('codex') || /^o[134]/.test(m)) return 'openai'
566
+ if (m.includes('kimi') || m.includes('moonshot')) return 'moonshot'
567
+ if (m.includes('glm')) return 'zhipu'
568
+ if (m.includes('qwen')) return 'qwen'
569
+ if (m.includes('mimo')) return 'mimo'
570
+ return m.split(/[-_/]/)[0] || 'other'
571
+ }
572
+
573
+ /**
574
+ * Score a live DSH model ID for suitability in a tier.
575
+ * Accepts either a canonical T1-T4 key or a capability band
576
+ * (`light`/`standard`/`heavy`/`review`), so custom tier ids work unchanged.
577
+ * Enables zero-config out-of-the-box routing on any user's `ctx.llm` catalog.
578
+ * @param {string} modelId
579
+ * @param {'T1'|'T2'|'T3'|'T4'|'light'|'standard'|'heavy'|'review'} tier
580
+ * @param {string|null} [parentModel]
581
+ */
582
+ function scoreModelForTier(modelId, tier, parentModel = null) {
583
+ const m = String(modelId || '').toLowerCase()
584
+ if (/image|tts|whisper|embedding|moderation/.test(m)) return -100
585
+ const isLight = /flash|eco|mini|lite|nano|haiku|fast|small|low\b/.test(m)
586
+ const isCoding = /code|coder|codex|sonnet|chat|medium|dev/.test(m)
587
+ const isHeavy = /pro\b|opus|reasoner|thinking|xhigh|high\b|max\b|r1\b|o3\b|orchestrator|hydrogen/.test(m)
588
+ const band = tier === 'T1' || tier === 'light'
589
+ ? 'light'
590
+ : (tier === 'T3' || tier === 'heavy'
591
+ ? 'heavy'
592
+ : (tier === 'T4' || tier === 'review' ? 'review' : 'standard'))
593
+ let score = 0
594
+ if (band === 'light') {
595
+ if (isLight) score += 30
596
+ if (/eco|lite|mini|haiku|low\b/.test(m)) score += 10
597
+ if (m === 'deepseek-chat') score += 20
598
+ if (isHeavy) score -= 25
599
+ } else if (band === 'standard') {
600
+ if (isCoding) score += 25
601
+ if (isLight && !/lite|nano|low\b/.test(m)) score += 10
602
+ if (m === 'deepseek-chat') score += 20
603
+ if (/xhigh|opus/.test(m)) score -= 10
604
+ } else if (band === 'heavy') {
605
+ if (isHeavy) score += 30
606
+ if (isLight && !/high/.test(m)) score -= 20
607
+ } else if (band === 'review') {
608
+ if (isHeavy) score += 25
609
+ if (isCoding) score += 10
610
+ if (parentModel && modelFamilyOf(modelId) !== modelFamilyOf(parentModel)) score += 20
611
+ if (isLight && !/high/.test(m)) score -= 15
612
+ }
613
+ return score
614
+ }
615
+
616
+ /**
617
+ * Configurable difficulty tier metadata, layout presets, normalization, and
618
+ * helper lookups shared by the Host and the browser UI.
619
+ *
620
+ * Zero imports by design so `scripts/build-client.mjs` can inline this module
621
+ * verbatim into the committed `client.js` artifact.
622
+ *
623
+ * @module dsh-agent-router/lib/tier-presets
624
+ */
625
+
626
+ const TIER_ID_RE = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/
627
+ const MAX_TIERS = 10
628
+ const MAX_TIER_NAME = 40
629
+ const DEFAULT_TIER_LAYOUT = 'default'
630
+ const TIER_ROLES = Object.freeze(['normal', 'review'])
631
+ const PREFER_BACKENDS = Object.freeze(['auto', 'dsh', 'cli', 'claude', 'codex', 'gemini', 'opencode', 'antigravity'])
632
+ const TIER_CLI_BACKENDS = Object.freeze(['claude', 'codex', 'gemini', 'opencode', 'antigravity'])
633
+
634
+ const BAND_SCORE_KEY = Object.freeze({ light: 'T1', standard: 'T2', heavy: 'T3', review: 'T4' })
635
+
636
+ function round(value, digits = 2) {
637
+ const factor = 10 ** digits
638
+ return Math.round(value * factor) / factor
639
+ }
640
+
641
+ function clone(value) {
642
+ if (Array.isArray(value)) return value.map(clone)
643
+ if (value && typeof value === 'object') {
644
+ const out = {}
645
+ for (const [k, v] of Object.entries(value)) out[k] = clone(v)
646
+ return out
647
+ }
648
+ return value
649
+ }
650
+
651
+ function cleanText(value, limit = Infinity) {
652
+ if (typeof value !== 'string') return ''
653
+ const text = value.trim()
654
+ return text.length > limit ? text.slice(0, limit) : text
655
+ }
656
+
657
+ /** Default four-tier skeleton. Route chains are attached by `lib/defaults.js`. */
658
+ const DEFAULT_TIER_SKELETON = Object.freeze([
659
+ Object.freeze({
660
+ id: 'T1',
661
+ name: '轻量检索',
662
+ description: '搜索、总结、格式转换等小任务',
663
+ role: 'normal',
664
+ minScore: 0,
665
+ maxScore: 1.5,
666
+ }),
667
+ Object.freeze({
668
+ id: 'T2',
669
+ name: '标准开发',
670
+ description: '常规编码、单元测试、普通修复',
671
+ role: 'normal',
672
+ minScore: 1.5,
673
+ maxScore: 3,
674
+ }),
675
+ Object.freeze({
676
+ id: 'T3',
677
+ name: '复杂攻坚',
678
+ description: '架构设计、跨模块重构、疑难排错',
679
+ role: 'normal',
680
+ minScore: 3,
681
+ maxScore: null,
682
+ }),
683
+ Object.freeze({
684
+ id: 'T4',
685
+ name: '审查验收',
686
+ description: '代码审查、安全审计、交叉验证',
687
+ role: 'review',
688
+ minScore: null,
689
+ maxScore: null,
690
+ }),
691
+ ])
692
+
693
+ /** Ready-made tier layouts offered to non-technical users. */
694
+ const TIER_LAYOUT_PRESETS = Object.freeze({
695
+ default: Object.freeze({
696
+ label: '默认四档',
697
+ description: '轻量 / 标准 / 复杂 / 审查',
698
+ tiers: Object.freeze(DEFAULT_TIER_SKELETON.map(entry => ({ ...entry }))),
699
+ }),
700
+ compact: Object.freeze({
701
+ label: '精简三档',
702
+ description: '轻量 / 标准 / 审查',
703
+ tiers: Object.freeze([
704
+ { id: 'T1', name: '快速处理', description: '搜索、总结、格式转换等小任务', role: 'normal', minScore: 0, maxScore: 2 },
705
+ { id: 'T2', name: '标准开发', description: '常规编码、单测、普通修复与较复杂任务', role: 'normal', minScore: 2, maxScore: null },
706
+ { id: 'T4', name: '审查验收', description: '代码审查、安全审计、交叉验证', role: 'review', minScore: null, maxScore: null },
707
+ ]),
708
+ }),
709
+ fast: Object.freeze({
710
+ label: '极速两档',
711
+ description: '快速 / 深度(审查任务走最高档)',
712
+ tiers: Object.freeze([
713
+ { id: 'T1', name: '快速处理', description: '日常小任务,优先低成本快速模型', role: 'normal', minScore: 0, maxScore: 2.5 },
714
+ { id: 'T3', name: '深度攻坚', description: '复杂实现、架构设计、疑难排错', role: 'normal', minScore: 2.5, maxScore: null },
715
+ ]),
716
+ }),
717
+ })
718
+
719
+ const SKELETON_BY_ID = Object.freeze(Object.fromEntries(DEFAULT_TIER_SKELETON.map(entry => [entry.id, entry])))
720
+
721
+ function coerceScore(value, fallback = null) {
722
+ if (value === null || value === undefined || value === '') return fallback
723
+ const n = Number(value)
724
+ if (!Number.isFinite(n) || n < 0) return fallback
725
+ return round(n)
726
+ }
727
+
728
+ function coerceMaxScore(value, minScore, fallback = null) {
729
+ // `undefined`/`''` mean "not provided" (v1 tier maps, partial overrides) and
730
+ // fall back to the inherited bound. `null` is an explicit "no upper limit"
731
+ // and must not be replaced by the inherited bound.
732
+ if (value === undefined || value === '') return fallback
733
+ if (value === null) return null
734
+ const n = Number(value)
735
+ if (!Number.isFinite(n) || n <= minScore) return fallback
736
+ return round(n)
737
+ }
738
+
739
+ /**
740
+ * Filter and normalize a DSH route array. Invalid entries are dropped.
741
+ * @param {unknown} list
742
+ * @param {Array<Record<string, any>>} [fallback]
743
+ */
744
+ function sanitizeDshRoutes(list, fallback = []) {
745
+ if (!Array.isArray(list)) return fallback.map(route => ({ ...route }))
746
+ const out = []
747
+ for (const item of list) {
748
+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue
749
+ const provider = cleanText(item.provider)
750
+ const model = cleanText(item.model)
751
+ if (!provider || !model) continue
752
+ const route = { provider, model }
753
+ const effort = cleanText(item.reasoningEffort)
754
+ if (effort) route.reasoningEffort = effort
755
+ const note = cleanText(item.note)
756
+ if (note) route.note = note
757
+ out.push(route)
758
+ }
759
+ return out
760
+ }
761
+
762
+ /**
763
+ * Filter and normalize a local CLI route array. Unknown backends are dropped.
764
+ * @param {unknown} list
765
+ * @param {Array<Record<string, any>>} [fallback]
766
+ */
767
+ function sanitizeCliRoutes(list, fallback = []) {
768
+ if (!Array.isArray(list)) return fallback.map(route => ({ ...route }))
769
+ const out = []
770
+ for (const item of list) {
771
+ if (!item || typeof item !== 'object' || Array.isArray(item)) continue
772
+ const backend = cleanText(item.backend)
773
+ if (!TIER_CLI_BACKENDS.includes(backend)) continue
774
+ const route = { backend }
775
+ const model = cleanText(item.model)
776
+ if (model) route.model = model
777
+ const effort = cleanText(item.effort)
778
+ if (effort) route.effort = effort
779
+ const note = cleanText(item.note)
780
+ if (note) route.note = note
781
+ out.push(route)
782
+ }
783
+ return out
784
+ }
785
+
786
+ function entryName(entry, id) {
787
+ return cleanText(entry?.name, MAX_TIER_NAME) || cleanText(entry?.label, MAX_TIER_NAME) || id
788
+ }
789
+
790
+ const KNOWN_TIER_KEYS = new Set([
791
+ 'name', 'label', 'description', 'role', 'minScore', 'maxScore',
792
+ 'preferBackend', 'escalateTo', 'dsh', 'cli',
793
+ ])
794
+ const UNSAFE_OBJECT_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
795
+
796
+ /**
797
+ * Keep forward-compatible fields that this build does not know about, so a
798
+ * newer config saved by a newer build is not silently downgraded. `label` is a
799
+ * v1 alias that is migrated into `name` and therefore not preserved.
800
+ * @param {unknown} raw
801
+ * @returns {Record<string, unknown>}
802
+ */
803
+ function pickTierExtras(raw) {
804
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
805
+ const extras = {}
806
+ for (const [key, value] of Object.entries(raw)) {
807
+ if (KNOWN_TIER_KEYS.has(key) || UNSAFE_OBJECT_KEYS.has(key)) continue
808
+ extras[key] = value
809
+ }
810
+ return extras
811
+ }
812
+
813
+ function normalizeOne(id, raw, fallback, warnings) {
814
+ const base = (fallback && fallback[id]) || SKELETON_BY_ID[id] || {}
815
+ const src = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
816
+ const extras = pickTierExtras(src)
817
+ const roleRaw = src.role === 'review' ? 'review' : (src.role === 'normal' ? 'normal' : base.role)
818
+ const role = roleRaw === 'review' ? 'review' : 'normal'
819
+ const name = entryName({ name: src.name ?? src.label ?? base.name }, id)
820
+ const description = cleanText(src.description ?? base.description, 160)
821
+ const minScore = role === 'review' ? null : coerceScore(src.minScore, coerceScore(base.minScore, 0))
822
+ const maxScore = role === 'review'
823
+ ? null
824
+ : coerceMaxScore(src.maxScore, minScore, coerceMaxScore(base.maxScore, minScore, null))
825
+ const preferBackend = PREFER_BACKENDS.includes(src.preferBackend)
826
+ ? src.preferBackend
827
+ : (PREFER_BACKENDS.includes(base.preferBackend) ? base.preferBackend : 'auto')
828
+ const dshRaw = src.dsh !== undefined ? src.dsh : base.dsh
829
+ const cliRaw = src.cli !== undefined ? src.cli : base.cli
830
+ const dsh = sanitizeDshRoutes(dshRaw, [])
831
+ const cli = sanitizeCliRoutes(cliRaw, [])
832
+ if (Array.isArray(dshRaw) && dsh.length < dshRaw.length) {
833
+ warnings.push(`档位「${name}」有 ${dshRaw.length - dsh.length} 条 DSH 路由缺少 provider/model,已忽略`)
834
+ }
835
+ if (Array.isArray(cliRaw) && cli.length < cliRaw.length) {
836
+ warnings.push(`档位「${name}」有 ${cliRaw.length - cli.length} 条 CLI 路由后端无效,已忽略`)
837
+ }
838
+ const escalateTo = src.escalateTo !== undefined ? src.escalateTo : base.escalateTo
839
+ return {
840
+ ...extras,
841
+ name,
842
+ description,
843
+ role,
844
+ minScore,
845
+ maxScore,
846
+ preferBackend,
847
+ escalateTo: escalateTo === null ? null : (typeof escalateTo === 'string' ? escalateTo : undefined),
848
+ dsh,
849
+ cli,
850
+ }
851
+ }
852
+
853
+ /**
854
+ * Sort tier entries by score: normal tiers ascending, review tiers last.
855
+ * @param {Record<string, any>} tiers
856
+ * @returns {Array<[string, any]>}
857
+ */
858
+ function sortTierEntries(tiers) {
859
+ const entries = Object.entries(tiers && typeof tiers === 'object' ? tiers : {})
860
+ .filter(([, entry]) => entry && typeof entry === 'object')
861
+ entries.sort((a, b) => {
862
+ const aReview = a[1].role === 'review'
863
+ const bReview = b[1].role === 'review'
864
+ if (aReview !== bReview) return aReview ? 1 : -1
865
+ if (aReview && bReview) return a[0].localeCompare(b[0])
866
+ const aMin = Number.isFinite(a[1].minScore) ? a[1].minScore : Number.POSITIVE_INFINITY
867
+ const bMin = Number.isFinite(b[1].minScore) ? b[1].minScore : Number.POSITIVE_INFINITY
868
+ if (aMin !== bMin) return aMin - bMin
869
+ return a[0].localeCompare(b[0])
870
+ })
871
+ return entries
872
+ }
873
+
874
+ /** @param {Record<string, any>} tiers */
875
+ function sortedNormalTiers(tiers) {
876
+ return sortTierEntries(tiers).filter(([, entry]) => entry.role !== 'review')
877
+ }
878
+
879
+ /** @param {Record<string, any>} tiers */
880
+ function tierCount(tiers) {
881
+ return Object.keys(tiers && typeof tiers === 'object' ? tiers : {}).length
882
+ }
883
+
884
+ /** @param {string} id @param {Record<string, any>} tiers */
885
+ function isReviewTier(id, tiers) {
886
+ return tiers?.[id]?.role === 'review'
887
+ }
888
+
889
+ /**
890
+ * Coarse capability band used by model scoring and CLI ordering.
891
+ * @param {string} id
892
+ * @param {Record<string, any>} tiers
893
+ * @returns {'light'|'standard'|'heavy'|'review'}
894
+ */
895
+ function tierBand(id, tiers) {
896
+ if (isReviewTier(id, tiers)) return 'review'
897
+ const normals = sortedNormalTiers(tiers)
898
+ const index = normals.findIndex(([tierId]) => tierId === id)
899
+ if (index < 0) return 'standard'
900
+ // A single normal tier is both the lowest and the highest tier; score the
901
+ // catch-all as balanced instead of arbitrarily picking the 'light' path.
902
+ if (normals.length === 1) return 'standard'
903
+ if (index === 0) return 'light'
904
+ if (index === normals.length - 1) return 'heavy'
905
+ return 'standard'
906
+ }
907
+
908
+ /**
909
+ * Map an arbitrary tier id to the legacy T1-T4 key used by `model-score`.
910
+ * @param {string} id
911
+ * @param {Record<string, any>} tiers
912
+ */
913
+ function tierKeyForScoring(id, tiers) {
914
+ if (tiers && typeof tiers === 'object' && tiers[id]) return BAND_SCORE_KEY[tierBand(id, tiers)]
915
+ return BAND_SCORE_KEY[id] ? id : 'T2'
916
+ }
917
+
918
+ /**
919
+ * Next normal tier by score order, or null at the top.
920
+ * @param {string} id
921
+ * @param {Record<string, any>} tiers
922
+ */
923
+ function nextNormalTier(id, tiers) {
924
+ const normals = sortedNormalTiers(tiers)
925
+ const index = normals.findIndex(([tierId]) => tierId === id)
926
+ if (index < 0) return null
927
+ return normals[index + 1]?.[0] ?? null
928
+ }
929
+
930
+ /**
931
+ * Compute the score range for a normal tier placed after the current highest
932
+ * normal tier. When that tier is unbounded it must be narrowed to make room;
933
+ * the returned `narrowLastTo` tells the caller which upper bound to write.
934
+ * The caller is responsible for inserting the new tier.
935
+ * @param {Record<string, any>} tiers
936
+ * @param {string|null} [excludeId] tier being moved to the top
937
+ * @returns {{ minScore: number, lastId: string|null, narrowLastTo: number|null }}
938
+ */
939
+ function nextTopRange(tiers, excludeId = null) {
940
+ const others = { ...(tiers && typeof tiers === 'object' ? tiers : {}) }
941
+ if (excludeId) delete others[excludeId]
942
+ const normals = sortedNormalTiers(others)
943
+ const lastId = normals[normals.length - 1]?.[0] || null
944
+ const last = lastId ? others[lastId] : null
945
+ if (!last) return { minScore: 0, lastId: null, narrowLastTo: null }
946
+ if (Number.isFinite(last.maxScore)) {
947
+ return { minScore: last.maxScore, lastId, narrowLastTo: null }
948
+ }
949
+ const minScore = round((Number(last.minScore) || 0) + 1)
950
+ return { minScore, lastId, narrowLastTo: minScore }
951
+ }
952
+
953
+ /**
954
+ * Resolve a tier reference by id or display name (case-insensitive).
955
+ * @param {unknown} ref
956
+ * @param {Record<string, any>} tiers
957
+ * @returns {string|null}
958
+ */
959
+ function resolveTierRef(ref, tiers) {
960
+ const key = cleanText(ref)
961
+ if (!key || !tiers || typeof tiers !== 'object') return null
962
+ if (tiers[key]) return key
963
+ const needle = key.toLowerCase()
964
+ for (const [id, entry] of Object.entries(tiers)) {
965
+ if (id.toLowerCase() === needle) return id
966
+ if (entryName(entry, id).toLowerCase() === needle) return id
967
+ }
968
+ return null
969
+ }
970
+
971
+ function repairRanges(entries, warnings) {
972
+ const normals = sortedNormalTiers(entries)
973
+ for (let i = 1; i < normals.length; i += 1) {
974
+ const prev = normals[i - 1][1]
975
+ const current = normals[i][1]
976
+ if (prev.maxScore !== null && current.minScore >= prev.maxScore) continue
977
+ warnings.push(`档位「${prev.name}」与「${current.name}」的分数区间重叠,已自动收窄`)
978
+ // A bounded previous tier already has a usable boundary. An unbounded one
979
+ // must be narrowed here as well, otherwise it keeps swallowing the current
980
+ // tier's range and the overlap is never actually repaired.
981
+ const boundary = prev.maxScore !== null
982
+ ? prev.maxScore
983
+ : (current.minScore > prev.minScore ? current.minScore : round(prev.minScore + 1))
984
+ prev.maxScore = boundary
985
+ current.minScore = boundary
986
+ if (current.maxScore !== null && current.maxScore <= boundary) current.maxScore = null
987
+ }
988
+ }
989
+
990
+ function uniqueNames(entries, warnings) {
991
+ const seen = new Map()
992
+ for (const [id, entry] of sortTierEntries(entries)) {
993
+ const key = entry.name.toLowerCase()
994
+ if (!key) {
995
+ warnings.push(`档位 ${id} 的名称不能为空,已使用 id 代替`)
996
+ entry.name = id
997
+ continue
998
+ }
999
+ if (seen.has(key)) {
1000
+ warnings.push(`档位名称重复:「${entry.name}」,已自动改为「${entry.name}(${id})」`)
1001
+ entry.name = `${entry.name}(${id})`.slice(0, MAX_TIER_NAME)
1002
+ }
1003
+ seen.set(entry.name.toLowerCase(), id)
1004
+ }
1005
+ }
1006
+
1007
+ function resolveEscalations(entries, warnings) {
1008
+ const normals = sortedNormalTiers(entries)
1009
+ for (const [id, entry] of sortTierEntries(entries)) {
1010
+ if (entry.role === 'review') {
1011
+ if (entry.escalateTo !== undefined && entry.escalateTo !== null) {
1012
+ if (!entries[entry.escalateTo] || entry.escalateTo === id) {
1013
+ warnings.push(`档位「${entry.name}」的升阶目标不存在,已清除`)
1014
+ entry.escalateTo = null
1015
+ }
1016
+ } else {
1017
+ entry.escalateTo = null
1018
+ }
1019
+ continue
1020
+ }
1021
+ const nextId = normals.findIndex(([tierId]) => tierId === id) >= 0
1022
+ ? nextNormalTier(id, entries)
1023
+ : null
1024
+ if (entry.escalateTo === undefined) {
1025
+ entry.escalateTo = nextId
1026
+ continue
1027
+ }
1028
+ if (entry.escalateTo === null) continue
1029
+ if (!entries[entry.escalateTo] || entry.escalateTo === id) {
1030
+ warnings.push(`档位「${entry.name}」的升阶目标不存在,已改为${nextId ? `「${entries[nextId].name}」` : '无'}`)
1031
+ entry.escalateTo = nextId
1032
+ }
1033
+ }
1034
+ }
1035
+
1036
+ /**
1037
+ * Normalize a tier map into the current schema.
1038
+ *
1039
+ * - `authoritative: true` uses exactly the supplied ids (removed tiers stay removed).
1040
+ * - `authoritative: false` merges supplied overrides over `baseTiers` by id.
1041
+ * - Invalid input falls back to `baseTiers`, then to the built-in skeleton.
1042
+ *
1043
+ * `issues` are blocking problems that cannot be repaired safely (for example a
1044
+ * map without any normal tier). `warnings` describe problems that were already
1045
+ * repaired automatically (overlaps, duplicate names, dropped routes, ...).
1046
+ *
1047
+ * @param {unknown} input
1048
+ * @param {{ authoritative?: boolean, baseTiers?: Record<string, any> }} [options]
1049
+ * @returns {{ tiers: Record<string, any>, issues: string[], warnings: string[] }}
1050
+ */
1051
+ function normalizeTierEntries(input, { authoritative = false, baseTiers = null } = {}) {
1052
+ const issues = []
1053
+ const warnings = []
1054
+ const fallback = baseTiers && typeof baseTiers === 'object'
1055
+ ? baseTiers
1056
+ : Object.fromEntries(DEFAULT_TIER_SKELETON.map(entry => [entry.id, { ...entry }]))
1057
+ const source = input && typeof input === 'object' && !Array.isArray(input) ? input : null
1058
+
1059
+ let ids = []
1060
+ if (!source) {
1061
+ if (input !== undefined) warnings.push('档位配置无效,已恢复默认档位')
1062
+ ids = Object.keys(fallback)
1063
+ } else if (authoritative) {
1064
+ ids = Object.keys(source)
1065
+ } else {
1066
+ ids = [...new Set([...Object.keys(fallback), ...Object.keys(source)])]
1067
+ }
1068
+
1069
+ if (ids.length === 0) {
1070
+ warnings.push('档位配置为空,已使用默认档位')
1071
+ ids = Object.keys(fallback)
1072
+ }
1073
+ if (ids.length > MAX_TIERS) {
1074
+ warnings.push(`档位数量不能超过 ${MAX_TIERS} 个,多余的档位已忽略`)
1075
+ ids = ids.slice(0, MAX_TIERS)
1076
+ }
1077
+
1078
+ const entries = {}
1079
+ for (const id of ids) {
1080
+ if (!TIER_ID_RE.test(id)) {
1081
+ warnings.push(`档位 id「${id}」无效:需以字母开头,仅含字母、数字、- 或 _,已忽略`)
1082
+ continue
1083
+ }
1084
+ const raw = source && Object.prototype.hasOwnProperty.call(source, id) ? source[id] : undefined
1085
+ const base = fallback[id]
1086
+ entries[id] = normalizeOne(id, raw ?? base ?? {}, fallback, warnings)
1087
+ }
1088
+
1089
+ if (Object.keys(entries).length === 0) {
1090
+ warnings.push('档位配置为空,已恢复默认档位')
1091
+ for (const [id, entry] of Object.entries(fallback)) entries[id] = normalizeOne(id, entry, fallback, warnings)
1092
+ }
1093
+
1094
+ uniqueNames(entries, warnings)
1095
+ repairRanges(entries, warnings)
1096
+ resolveEscalations(entries, warnings)
1097
+
1098
+ const normalCount = Object.values(entries).filter(entry => entry.role !== 'review').length
1099
+ if (normalCount === 0) {
1100
+ issues.push('至少需要保留一个普通(非审查)档位')
1101
+ const replacement = Object.fromEntries(
1102
+ Object.entries(fallback).map(([id, entry]) => [id, normalizeOne(id, entry, fallback, [])]),
1103
+ )
1104
+ uniqueNames(replacement, [])
1105
+ repairRanges(replacement, [])
1106
+ resolveEscalations(replacement, [])
1107
+ return { tiers: replacement, issues, warnings }
1108
+ }
1109
+
1110
+ return { tiers: entries, issues, warnings }
1111
+ }
1112
+
1113
+ /**
1114
+ * Strict structural validation over an already-normalized tier map.
1115
+ * @param {Record<string, any>} tiers
1116
+ * @returns {string[]}
1117
+ */
1118
+ function validateTierEntries(tiers) {
1119
+ const issues = []
1120
+ if (!tiers || typeof tiers !== 'object' || Array.isArray(tiers)) {
1121
+ return ['档位配置必须是对象(键为档位 id)']
1122
+ }
1123
+ const entries = Object.entries(tiers)
1124
+ if (entries.length === 0) return ['至少需要保留一个普通档位']
1125
+ if (entries.length > MAX_TIERS) issues.push(`档位数量不能超过 ${MAX_TIERS} 个`)
1126
+
1127
+ const names = new Set()
1128
+ let normalCount = 0
1129
+ for (const [id, entry] of entries) {
1130
+ if (!TIER_ID_RE.test(id)) issues.push(`档位 id「${id}」无效`)
1131
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
1132
+ issues.push(`档位 ${id} 的配置无效`)
1133
+ continue
1134
+ }
1135
+ const name = cleanText(entry.name, MAX_TIER_NAME)
1136
+ if (!name) issues.push(`档位 ${id} 的名称不能为空`)
1137
+ const nameKey = name.toLowerCase()
1138
+ if (nameKey && names.has(nameKey)) issues.push(`档位名称重复:「${name}」`)
1139
+ names.add(nameKey)
1140
+ if (entry.role !== 'review') {
1141
+ normalCount += 1
1142
+ if (!Number.isFinite(entry.minScore) || entry.minScore < 0) {
1143
+ issues.push(`档位「${name || id}」的分数下限无效`)
1144
+ }
1145
+ if (entry.maxScore !== null && (!Number.isFinite(entry.maxScore) || entry.maxScore <= entry.minScore)) {
1146
+ issues.push(`档位「${name || id}」的分数上限必须大于下限`)
1147
+ }
1148
+ }
1149
+ if (!PREFER_BACKENDS.includes(entry.preferBackend)) {
1150
+ issues.push(`档位「${name || id}」的执行端倾向无效`)
1151
+ }
1152
+ if (entry.escalateTo !== null && entry.escalateTo !== undefined) {
1153
+ if (!tiers[entry.escalateTo] || entry.escalateTo === id) {
1154
+ issues.push(`档位「${name || id}」的升阶目标无效`)
1155
+ }
1156
+ }
1157
+ if (!Array.isArray(entry.dsh) || !Array.isArray(entry.cli)) {
1158
+ issues.push(`档位「${name || id}」的路由链格式无效`)
1159
+ }
1160
+ }
1161
+ if (normalCount === 0) issues.push('至少需要保留一个普通(非审查)档位')
1162
+
1163
+ const normals = sortedNormalTiers(tiers)
1164
+ for (let i = 1; i < normals.length; i += 1) {
1165
+ const prev = normals[i - 1][1]
1166
+ const current = normals[i][1]
1167
+ if (prev.maxScore === null || current.minScore < prev.maxScore) {
1168
+ issues.push(`档位「${prev.name}」与「${current.name}」的分数区间重叠`)
1169
+ }
1170
+ }
1171
+ return issues
1172
+ }
1173
+
1174
+ /**
1175
+ * Apply a layout preset while preserving routes for tiers with the same id.
1176
+ * New ids clone the closest existing tier's routing chain.
1177
+ * @param {Record<string, any>} tiers
1178
+ * @param {'default'|'compact'|'fast'|string} key
1179
+ * @returns {Record<string, any>}
1180
+ */
1181
+ function applyTierLayoutPreset(tiers, key) {
1182
+ const preset = TIER_LAYOUT_PRESETS[key]
1183
+ if (!preset) return clone(tiers || {})
1184
+ const current = tiers && typeof tiers === 'object' ? tiers : {}
1185
+ const currentEntries = sortTierEntries(current)
1186
+ const fallbackSeed = currentEntries.find(([, entry]) => entry.role !== 'review')?.[1] || currentEntries[0]?.[1] || null
1187
+ const next = {}
1188
+ for (const meta of preset.tiers) {
1189
+ const existing = current[meta.id]
1190
+ const seed = existing || fallbackSeed
1191
+ next[meta.id] = {
1192
+ ...(existing ? pickTierExtras(existing) : {}),
1193
+ ...meta,
1194
+ ...(seed ? {
1195
+ preferBackend: seed.preferBackend,
1196
+ dsh: clone(seed.dsh || []),
1197
+ cli: clone(seed.cli || []),
1198
+ } : { preferBackend: 'auto', dsh: [], cli: [] }),
1199
+ escalateTo: undefined,
1200
+ }
1201
+ }
1202
+ const normals = sortedNormalTiers(next)
1203
+ normals.forEach(([id], index) => {
1204
+ next[id].escalateTo = normals[index + 1]?.[0] ?? null
1205
+ })
1206
+ for (const entry of Object.values(next)) {
1207
+ if (entry.role === 'review') entry.escalateTo = null
1208
+ }
1209
+ return next
1210
+ }
1211
+
1212
+ /**
1213
+ * Pure route-editing helpers shared by the browser UI and unit tests.
1214
+ *
1215
+ * Keeping normalization, duplicate detection, and list movement outside the
1216
+ * React component makes the "add DSH model route" flow easier to maintain and
1217
+ * lets drag-and-drop reordering be tested without a DOM.
1218
+ * @module dsh-agent-router/lib/route-edit
1219
+ */
1220
+
1221
+ /** Empty DSH route draft used by the add form. */
1222
+ const EMPTY_DSH_ROUTE_INPUT = Object.freeze({
1223
+ provider: '',
1224
+ model: '',
1225
+ reasoningEffort: '',
1226
+ note: '',
1227
+ })
1228
+
1229
+ /**
1230
+ * Normalize a raw add-form value into a route entry.
1231
+ * Returns null when provider or model is empty after trimming.
1232
+ * @param {{ provider?: string, model?: string, reasoningEffort?: string, note?: string }} input
1233
+ */
1234
+ function normalizeDshRouteInput(input) {
1235
+ const provider = String(input?.provider ?? '').trim()
1236
+ const model = String(input?.model ?? '').trim()
1237
+ if (!provider || !model) return null
1238
+ const reasoningEffort = String(input?.reasoningEffort ?? '').trim()
1239
+ const note = String(input?.note ?? '').trim()
1240
+ return {
1241
+ provider,
1242
+ model,
1243
+ ...(reasoningEffort ? { reasoningEffort } : {}),
1244
+ ...(note ? { note } : {}),
1245
+ }
1246
+ }
1247
+
1248
+ /**
1249
+ * Whether the same provider/model/effort route already exists in a tier chain.
1250
+ * @param {Array<Record<string, any>>} list
1251
+ * @param {{ provider: string, model: string, reasoningEffort?: string }} route
1252
+ */
1253
+ function hasDshRoute(list, route) {
1254
+ if (!Array.isArray(list) || !route) return false
1255
+ return list.some(item => item
1256
+ && item.provider === route.provider
1257
+ && item.model === route.model
1258
+ && (item.reasoningEffort || '') === (route.reasoningEffort || ''))
1259
+ }
1260
+
1261
+ /**
1262
+ * Append a normalized route unless an identical entry already exists.
1263
+ * @param {Array<Record<string, any>>} list
1264
+ * @param {{ provider: string, model: string, reasoningEffort?: string, note?: string } | null} route
1265
+ * @returns {{ list: Array<Record<string, any>>, added: boolean }}
1266
+ */
1267
+ function appendDshRoute(list, route) {
1268
+ const current = Array.isArray(list) ? list : []
1269
+ if (!route || hasDshRoute(current, route)) {
1270
+ return { list: current, added: false }
1271
+ }
1272
+ return { list: [...current, route], added: true }
1273
+ }
1274
+
1275
+ /**
1276
+ * Move an item inside a list, clamping the target index. Returns a new array.
1277
+ * @param {Array<any>} list
1278
+ * @param {number} from
1279
+ * @param {number} to
1280
+ */
1281
+ function moveListItem(list, from, to) {
1282
+ if (!Array.isArray(list)) return []
1283
+ const source = Number(from)
1284
+ const target = Number(to)
1285
+ if (!Number.isInteger(source) || !Number.isInteger(target)) return list.slice()
1286
+ if (source < 0 || source >= list.length) return list.slice()
1287
+ const clamped = Math.max(0, Math.min(list.length - 1, target))
1288
+ if (source === clamped) return list.slice()
1289
+ const copy = list.slice()
1290
+ const [item] = copy.splice(source, 1)
1291
+ copy.splice(clamped, 0, item)
1292
+ return copy
1293
+ }
1294
+
1295
+ /**
1296
+ * Limited diagnostics built from the older `getState` endpoint.
1297
+ *
1298
+ * A link-installed plugin can ship a newer browser bundle while the DSH Host
1299
+ * process still runs an older RPC contract. Instead of surfacing a raw
1300
+ * `HTTP 404` for `diagnose`, the UI shows this degraded report plus a clear
1301
+ * "restart DSH" instruction.
1302
+ * @module dsh-agent-router/lib/diagnose-fallback
1303
+ */
1304
+
1305
+ function check(id, status, message, hint) {
1306
+ return { id, status, message, ...(hint ? { hint } : {}) }
1307
+ }
1308
+
1309
+ /**
1310
+ * @param {Record<string, any>} state Result of the legacy `getState` RPC.
1311
+ * @returns {{
1312
+ * ok: boolean,
1313
+ * status: 'warn',
1314
+ * checks: Array<{ id: string, status: 'ok'|'warn'|'fail', message: string, hint?: string }>,
1315
+ * summary: { ok: number, warn: number, fail: number },
1316
+ * suggestions: string[],
1317
+ * degraded: true,
1318
+ * }}
1319
+ */
1320
+ function buildLegacyDoctorReport(state) {
1321
+ const checks = []
1322
+ const catalog = Array.isArray(state?.catalog) ? state.catalog : []
1323
+ const config = state?.config || {}
1324
+ const subagent = state?.subagentModelSelection || {}
1325
+ const localClis = state?.localClis && typeof state.localClis === 'object' ? state.localClis : {}
1326
+
1327
+ checks.push(check(
1328
+ 'host-rpc',
1329
+ 'warn',
1330
+ 'The running Host has not loaded the diagnose endpoint (HTTP 404).',
1331
+ 'Fully quit and relaunch DSH so the Host loads the current RPC contract, then run diagnostics again.',
1332
+ ))
1333
+
1334
+ checks.push(check(
1335
+ 'dsh-catalog',
1336
+ catalog.length > 0 ? 'ok' : 'fail',
1337
+ catalog.length > 0 ? `${catalog.length} DSH provider(s) reachable.` : 'No DSH LLM providers are registered.',
1338
+ catalog.length > 0 ? undefined : 'Register at least one provider in DSH, or use local CLI routes only.',
1339
+ ))
1340
+
1341
+ if (subagent.available === false) {
1342
+ checks.push(check('subagent-model-selection', 'warn', 'DSH subagent-model-selection is not exposed in this build.'))
1343
+ } else if (subagent.enabled === false) {
1344
+ checks.push(check('subagent-model-selection', 'warn', 'subagent-model-selection-settings is disabled.', 'Enable it and add tier models to allowedModels.'))
1345
+ } else {
1346
+ const allowed = Array.isArray(subagent.allowedModels) ? subagent.allowedModels.length : 0
1347
+ checks.push(check('subagent-model-selection', 'ok', `Enabled with ${allowed} allowed model(s).`))
1348
+ }
1349
+
1350
+ const installed = Object.keys(localClis).filter(name => localClis[name]?.installed)
1351
+ checks.push(check(
1352
+ 'local-clis',
1353
+ installed.length > 0 ? 'ok' : 'warn',
1354
+ installed.length > 0 ? `Installed: ${installed.join(', ')}.` : 'No supported local agent CLI was found on PATH.',
1355
+ installed.length > 0 ? undefined : 'Install claude, codex, gemini, opencode, or antigravity (agy), or keep DSH routes in each tier.',
1356
+ ))
1357
+
1358
+ checks.push(check(
1359
+ 'cli-selection',
1360
+ 'ok',
1361
+ config.cliSelection === 'adaptive'
1362
+ ? 'CLI selection is adaptive.'
1363
+ : 'CLI selection is static.',
1364
+ ))
1365
+
1366
+ checks.push(check(
1367
+ 'local-models',
1368
+ 'ok',
1369
+ config.allowLocalModels === true
1370
+ ? 'Local models are enabled; route details need the full diagnose endpoint.'
1371
+ : 'Local/self-hosted models are disabled (default).',
1372
+ ))
1373
+
1374
+ checks.push(check(
1375
+ 'cost-meter',
1376
+ 'ok',
1377
+ state?.costMeter?.available ? 'dsh-cost-meter linked.' : 'dsh-cost-meter is not installed (optional).',
1378
+ ))
1379
+
1380
+ const summary = { ok: 0, warn: 0, fail: 0 }
1381
+ for (const item of checks) summary[item.status] = (summary[item.status] ?? 0) + 1
1382
+ return {
1383
+ ok: summary.fail === 0,
1384
+ status: 'warn',
1385
+ checks,
1386
+ summary,
1387
+ suggestions: checks.filter(item => item.hint && item.status !== 'ok').map(item => item.hint),
1388
+ degraded: true,
1389
+ }
1390
+ }
1391
+
1392
+ return {
1393
+ inject: ['slots', 'locale'],
1394
+ apply(ctx) {
1395
+ const disposeLocale = ctx.locale.register(PACKAGE, {
1396
+ zh: DICT_ZH,
1397
+ en: DICT_EN,
1398
+ ja: DICT_EN,
1399
+ de: DICT_EN,
1400
+ es: DICT_EN,
1401
+ fr: DICT_EN,
1402
+ pt: DICT_EN,
1403
+ ru: DICT_EN,
1404
+ })
1405
+ const t = ctx.locale.bind(PACKAGE)
1406
+
1407
+ let mounting = null
1408
+ let mountDisposer = null
1409
+ let disposed = false
1410
+ async function callRemote(method, args = {}) {
1411
+ const remote = ctx.get('remote')
1412
+ if (!remote || typeof remote.$mount !== 'function') {
1413
+ throw new Error(t('remote_unavailable'))
1414
+ }
1415
+ if (mounting === null) {
1416
+ mounting = remote.$mount({
1417
+ package: PACKAGE,
1418
+ descriptors: descriptorsFor(PACKAGE, RPC_ENDPOINTS),
1419
+ }).then((dispose) => {
1420
+ if (disposed) {
1421
+ if (typeof dispose === 'function') void dispose()
1422
+ return null
1423
+ }
1424
+ mountDisposer = typeof dispose === 'function' ? dispose : null
1425
+ return mountDisposer
1426
+ }).catch((err) => {
1427
+ mounting = null
1428
+ throw err
1429
+ })
1430
+ }
1431
+ await mounting
1432
+ const ns = ctx.get('remote.' + PACKAGE) || remote[PACKAGE]
1433
+ if (!ns || typeof ns[method] !== 'function') {
1434
+ throw new Error(t('endpoint_missing'))
1435
+ }
1436
+ return unwrapRemoteResult(await ns[method](args))
1437
+ }
1438
+
1439
+ function buildSmartDraftFromLive(baseDraft, state) {
1440
+ const next = cloneConfig(baseDraft)
1441
+ const catalog = Array.isArray(state?.catalog) ? state.catalog : []
1442
+ const clis = state?.localClis || {}
1443
+ const cliModels = state?.cliModels || {}
1444
+
1445
+ for (const tier of Object.keys(next.tiers || {})) {
1446
+ if (!next.tiers[tier]) continue
1447
+ const band = tierBand(tier, next.tiers)
1448
+ const scoringTier = tierKeyForScoring(tier, next.tiers)
1449
+ const scored = []
1450
+ for (const p of catalog) {
1451
+ for (const m of p.models || []) {
1452
+ const s = scoreModelForTier(m.id, scoringTier)
1453
+ if (s > -50) scored.push({ provider: p.id, model: m.id, score: s })
1454
+ }
1455
+ }
1456
+ scored.sort((a, b) => b.score - a.score)
1457
+ if (scored.length > 0) {
1458
+ next.tiers[tier].dsh = scored.slice(0, 4).map((x) => ({
1459
+ provider: x.provider,
1460
+ model: x.model,
1461
+ note: 'Auto-matched (' + tier + ')',
1462
+ }))
1463
+ }
1464
+
1465
+ const matchedCli = []
1466
+ const order = band === 'light'
1467
+ ? ['gemini', 'antigravity', 'claude', 'opencode', 'codex']
1468
+ : (band === 'standard'
1469
+ ? ['codex', 'antigravity', 'opencode', 'claude', 'gemini']
1470
+ : ['claude', 'antigravity', 'codex', 'gemini', 'opencode'])
1471
+ for (const b of order) {
1472
+ if (!clis[b]?.installed) continue
1473
+ const avail = Array.isArray(cliModels[b]?.models) ? cliModels[b].models : []
1474
+ let pickedModel = ''
1475
+ if (avail.length > 0) {
1476
+ const ranked = avail
1477
+ .map((mid) => ({ mid, score: scoreModelForTier(mid, scoringTier) }))
1478
+ .sort((a, b2) => b2.score - a.score)
1479
+ pickedModel = ranked[0]?.mid || ''
1480
+ }
1481
+ matchedCli.push({
1482
+ backend: b,
1483
+ ...(pickedModel ? { model: pickedModel } : {}),
1484
+ ...(b === 'claude' && band === 'light' ? { effort: 'low' } : {}),
1485
+ ...(b === 'claude' && (band === 'heavy' || band === 'review') ? { effort: 'high' } : {}),
1486
+ })
1487
+ }
1488
+ if (matchedCli.length > 0) {
1489
+ next.tiers[tier].cli = matchedCli
1490
+ }
1491
+ }
1492
+ return next
1493
+ }
1494
+
1495
+ function noticeWithWarnings(base, warnings) {
1496
+ if (!Array.isArray(warnings) || warnings.length === 0) return base
1497
+ const detail = warnings.slice(0, 3).join(';')
1498
+ return `${base} · ${t('auto_fixed', { count: warnings.length, detail })}`
1499
+ }
1500
+
1501
+ function BundleConfigSection(props) {
1502
+ if (props?.view === 'summary') {
1503
+ return h(RouterSummary, null)
1504
+ }
1505
+ return h(RouterEditor, null)
1506
+ }
1507
+
1508
+ function RouterSummary() {
1509
+ const [summary, setSummary] = useState(null)
1510
+ useEffect(() => {
1511
+ let alive = true
1512
+ callRemote('getState', {}).then((data) => {
1513
+ if (!alive || !data) return
1514
+ const clis = Object.values(data.localClis || {}).filter((x) => x?.installed).length
1515
+ setSummary(t('summary_line', {
1516
+ prefer: data.config?.preferBackend || 'auto',
1517
+ clis,
1518
+ totalClis: CLI_BACKENDS.length,
1519
+ total: data.stats?.total || 0,
1520
+ }))
1521
+ }).catch(() => {})
1522
+ return () => { alive = false }
1523
+ }, [])
1524
+ return summary ? h('span', { style: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary)' } }, summary) : null
1525
+ }
1526
+
1527
+ function RouterEditor() {
1528
+ const [state, setState] = useState(null)
1529
+ const [draft, setDraft] = useState(null)
1530
+ const [loading, setLoading] = useState(true)
1531
+ const [saving, setSaving] = useState(false)
1532
+ const [error, setError] = useState(null)
1533
+ const [notice, setNotice] = useState(null)
1534
+ const [activeTier, setActiveTier] = useState('T1')
1535
+
1536
+ // Add-form temporary states
1537
+ const [newDsh, setNewDsh] = useState({ ...EMPTY_DSH_ROUTE_INPUT })
1538
+ const [newCli, setNewCli] = useState({ backend: 'claude', model: '', effort: '', note: '' })
1539
+ const [newTier, setNewTier] = useState({ name: '', template: 'blank' })
1540
+ const [testTask, setTestTask] = useState('')
1541
+ const [testing, setTesting] = useState(false)
1542
+ const [testResult, setTestResult] = useState(null)
1543
+ const [doctor, setDoctor] = useState(null)
1544
+ const [doctorLoading, setDoctorLoading] = useState(false)
1545
+ const [showRuns, setShowRuns] = useState(false)
1546
+ const [dragState, setDragState] = useState(null)
1547
+ const [importText, setImportText] = useState('')
1548
+ const [exportJson, setExportJson] = useState(null)
1549
+ const [updateInfo, setUpdateInfo] = useState(null)
1550
+ const [updateLoading, setUpdateLoading] = useState(false)
1551
+
1552
+ async function loadState(preserveDraft = false) {
1553
+ setLoading(true)
1554
+ setError(null)
1555
+ try {
1556
+ const data = await callRemote('getState', {})
1557
+ setState(data)
1558
+ if (!preserveDraft) setDraft(cloneConfig(data.config))
1559
+ } catch (err) {
1560
+ setError(t('load_error', { error: describe(err) }))
1561
+ } finally {
1562
+ setLoading(false)
1563
+ }
1564
+ }
1565
+
1566
+ useEffect(() => {
1567
+ void loadState(false)
1568
+ }, [])
1569
+
1570
+ const activeJobCount = Array.isArray(state?.activeJobs) ? state.activeJobs.length : 0
1571
+ useEffect(() => {
1572
+ if (!activeJobCount) return undefined
1573
+ let alive = true
1574
+ const timer = setInterval(() => {
1575
+ callRemote('getState', {}).then((data) => {
1576
+ if (alive && data) setState(data)
1577
+ }).catch(() => {})
1578
+ }, 1500)
1579
+ return () => {
1580
+ alive = false
1581
+ clearInterval(timer)
1582
+ }
1583
+ }, [activeJobCount])
1584
+
1585
+ const dirty = state && draft && JSON.stringify(state.config) !== JSON.stringify(draft)
1586
+ const contractMatches = Boolean(state?.contract?.version) && state.contract.version === contractVersion()
1587
+
1588
+ // Non-blocking update probe: only after the Host/Client contract matches.
1589
+ // Failures are kept inside the update panel and never block routing.
1590
+ useEffect(() => {
1591
+ if (!contractMatches) return undefined
1592
+ let alive = true
1593
+ setUpdateLoading(true)
1594
+ callRemote('checkUpdate', {})
1595
+ .then((res) => { if (alive) setUpdateInfo(res) })
1596
+ .catch((err) => { if (alive) setUpdateInfo({ ok: false, error: describe(err) }) })
1597
+ .finally(() => { if (alive) setUpdateLoading(false) })
1598
+ return () => { alive = false }
1599
+ }, [contractMatches])
1600
+
1601
+ function updateTier(tier, updater) {
1602
+ setNotice(null)
1603
+ setDraft((prev) => {
1604
+ const next = cloneConfig(prev)
1605
+ next.tiers[tier] = updater(next.tiers[tier])
1606
+ return next
1607
+ })
1608
+ }
1609
+
1610
+ function resetDrag() {
1611
+ setDragState(null)
1612
+ }
1613
+
1614
+ function handleDragStart(list, event, index) {
1615
+ setDragState({ list, from: index, over: index })
1616
+ if (event?.dataTransfer) {
1617
+ event.dataTransfer.effectAllowed = 'move'
1618
+ try {
1619
+ event.dataTransfer.setData('text/plain', String(index))
1620
+ } catch {}
1621
+ }
1622
+ }
1623
+
1624
+ function handleDragOver(list, event, index) {
1625
+ event.preventDefault()
1626
+ if (event?.dataTransfer) event.dataTransfer.dropEffect = 'move'
1627
+ setDragState((prev) => (
1628
+ prev && prev.list === list && prev.over !== index ? { ...prev, over: index } : prev
1629
+ ))
1630
+ }
1631
+
1632
+ function handleDrop(list, event, index) {
1633
+ event.preventDefault()
1634
+ const current = dragState
1635
+ resetDrag()
1636
+ if (!current || current.list !== list || current.from === index) return
1637
+ updateTier(activeTierId, (cur) => ({
1638
+ ...cur,
1639
+ [list]: moveListItem(cur[list], current.from, index),
1640
+ }))
1641
+ }
1642
+
1643
+ function handleAddDshRoute() {
1644
+ const route = normalizeDshRouteInput(newDsh)
1645
+ if (!route) return
1646
+ if (hasDshRoute(tierCfg.dsh, route)) {
1647
+ setError(t('route_duplicate'))
1648
+ return
1649
+ }
1650
+ setError(null)
1651
+ updateTier(activeTierId, (cur) => ({ ...cur, dsh: appendDshRoute(cur.dsh, route).list }))
1652
+ setNewDsh({ ...EMPTY_DSH_ROUTE_INPUT })
1653
+ }
1654
+
1655
+ async function handleSave() {
1656
+ if (!draft) return
1657
+ const normalized = normalizeTierEntries(draft.tiers, { authoritative: true, baseTiers: draft.tiers })
1658
+ const tierProblems = [...normalized.issues, ...validateTierEntries(normalized.tiers)]
1659
+ if (tierProblems.length > 0) {
1660
+ setSaving(false)
1661
+ setNotice(null)
1662
+ setError(t('tier_validation_failed') + ' ' + tierProblems.join(';'))
1663
+ return
1664
+ }
1665
+ setSaving(true)
1666
+ setError(null)
1667
+ setNotice(null)
1668
+ try {
1669
+ const res = await callRemote('saveConfig', {
1670
+ config: { ...draft, tierLayout: 'custom', tiers: normalized.tiers },
1671
+ })
1672
+ setState((prev) => ({ ...prev, config: res.config, hasCustomOverride: true }))
1673
+ setDraft(cloneConfig(res.config))
1674
+ setNotice(noticeWithWarnings(t('saved_ok', { at: new Date().toLocaleTimeString() }), res.warnings))
1675
+ } catch (err) {
1676
+ setError(t('save_err', { error: describe(err) }))
1677
+ } finally {
1678
+ setSaving(false)
1679
+ }
1680
+ }
1681
+
1682
+ async function handleResetDefaults() {
1683
+ setSaving(true)
1684
+ setError(null)
1685
+ setNotice(null)
1686
+ try {
1687
+ const res = await callRemote('resetConfig', {})
1688
+ setState((prev) => ({ ...prev, config: res.config, hasCustomOverride: false }))
1689
+ setDraft(cloneConfig(res.config))
1690
+ setNotice(t('reset_ok', { at: new Date().toLocaleTimeString() }))
1691
+ } catch (err) {
1692
+ setError(t('save_err', { error: describe(err) }))
1693
+ } finally {
1694
+ setSaving(false)
1695
+ }
1696
+ }
1697
+
1698
+ async function handleClearCooldowns() {
1699
+ try {
1700
+ await callRemote('clearCooldowns', {})
1701
+ await loadState(true)
1702
+ } catch (err) {
1703
+ setError(describe(err))
1704
+ }
1705
+ }
1706
+
1707
+ async function handleCancelRun(runId) {
1708
+ try {
1709
+ await callRemote('cancelRun', { runId })
1710
+ setNotice(t('job_cancelled', { runId }))
1711
+ await loadState(true)
1712
+ } catch (err) {
1713
+ setError(describe(err))
1714
+ }
1715
+ }
1716
+
1717
+ async function handleImportLegacy() {
1718
+ setSaving(true)
1719
+ setError(null)
1720
+ try {
1721
+ const res = await callRemote('importLegacyConfig', {})
1722
+ if (res?.ok) {
1723
+ setNotice(noticeWithWarnings(t('import_legacy_ok'), res.warnings))
1724
+ await loadState(false)
1725
+ }
1726
+ } catch (err) {
1727
+ setError(describe(err))
1728
+ } finally {
1729
+ setSaving(false)
1730
+ }
1731
+ }
1732
+
1733
+ async function handleApplyPreset(name) {
1734
+ setSaving(true)
1735
+ setError(null)
1736
+ setNotice(null)
1737
+ try {
1738
+ const res = await callRemote('applyPreset', { preset: name })
1739
+ if (res?.ok) {
1740
+ setNotice(noticeWithWarnings(t('preset_applied', { name: t('preset_' + name) }), res.warnings))
1741
+ await loadState(false)
1742
+ }
1743
+ } catch (err) {
1744
+ setError(describe(err))
1745
+ } finally {
1746
+ setSaving(false)
1747
+ }
1748
+ }
1749
+
1750
+ async function handleExportConfig() {
1751
+ setError(null)
1752
+ setNotice(null)
1753
+ try {
1754
+ const payload = await callRemote('exportConfig', {})
1755
+ setExportJson(JSON.stringify(payload, null, 2))
1756
+ setNotice(t('export_ready'))
1757
+ } catch (err) {
1758
+ setError(describe(err))
1759
+ }
1760
+ }
1761
+
1762
+ async function handleImportConfig() {
1763
+ const text = importText.trim()
1764
+ if (!text) {
1765
+ setError(t('import_empty'))
1766
+ return
1767
+ }
1768
+ setSaving(true)
1769
+ setError(null)
1770
+ setNotice(null)
1771
+ try {
1772
+ const parsed = JSON.parse(text)
1773
+ const res = await callRemote('importConfig', { payload: parsed })
1774
+ if (res?.ok) {
1775
+ setImportText('')
1776
+ setExportJson(null)
1777
+ setNotice(noticeWithWarnings(t('import_applied'), res.warnings))
1778
+ await loadState(false)
1779
+ }
1780
+ } catch (err) {
1781
+ setError(describe(err))
1782
+ } finally {
1783
+ setSaving(false)
1784
+ }
1785
+ }
1786
+
1787
+ function tierDisplayName(tiers, id) {
1788
+ const entry = tiers?.[id]
1789
+ return entry?.name || entry?.label || t('tier_' + id + '_name') || id
1790
+ }
1791
+
1792
+ function handleApplyTierLayout(key) {
1793
+ if (!draft) return
1794
+ const preset = TIER_LAYOUT_PRESETS[key]
1795
+ if (!preset) return
1796
+ const label = t('tier_layout_' + key)
1797
+ if (typeof window !== 'undefined' && typeof window.confirm === 'function'
1798
+ && !window.confirm(t('tier_layout_confirm', { name: label }))) return
1799
+ setDraft((prev) => {
1800
+ const next = cloneConfig(prev)
1801
+ next.tiers = applyTierLayoutPreset(next.tiers, key)
1802
+ next.tierLayout = 'custom'
1803
+ return next
1804
+ })
1805
+ setActiveTier(preset.tiers[0]?.id || '')
1806
+ setNotice(t('tier_layout_applied', { name: label }))
1807
+ setError(null)
1808
+ }
1809
+
1810
+ function nextTierDraftId(tiers) {
1811
+ let index = 1
1812
+ while (tiers && tiers['T' + index]) index += 1
1813
+ return 'T' + index
1814
+ }
1815
+
1816
+ function handleAddTier() {
1817
+ if (!draft) return
1818
+ const name = newTier.name.trim()
1819
+ if (!name) {
1820
+ setError(t('tier_validation_failed'))
1821
+ return
1822
+ }
1823
+ const newId = nextTierDraftId(draft.tiers)
1824
+ setDraft((prev) => {
1825
+ const next = cloneConfig(prev)
1826
+ const tiers = next.tiers || {}
1827
+ const id = newId
1828
+ const review = newTier.template === 'review'
1829
+ const normals = sortedNormalTiers(tiers)
1830
+ const seedId = newTier.template === 'light'
1831
+ ? normals[0]?.[0]
1832
+ : (newTier.template === 'standard'
1833
+ ? normals[Math.floor(normals.length / 2)]?.[0]
1834
+ : normals[normals.length - 1]?.[0])
1835
+ const seed = (seedId && tiers[seedId]) || normals[normals.length - 1]?.[1] || null
1836
+ const top = review ? { minScore: null, lastId: null, narrowLastTo: null } : nextTopRange(tiers)
1837
+ if (top.narrowLastTo !== null) {
1838
+ tiers[top.lastId].maxScore = top.narrowLastTo
1839
+ }
1840
+ const minScore = top.minScore
1841
+ const lastId = top.lastId
1842
+ tiers[id] = {
1843
+ name,
1844
+ description: '',
1845
+ role: review ? 'review' : 'normal',
1846
+ minScore,
1847
+ maxScore: null,
1848
+ preferBackend: seed?.preferBackend || 'auto',
1849
+ escalateTo: null,
1850
+ dsh: seed ? JSON.parse(JSON.stringify(seed.dsh || [])) : [],
1851
+ cli: seed ? JSON.parse(JSON.stringify(seed.cli || [])) : [],
1852
+ }
1853
+ if (!review && lastId) {
1854
+ tiers[lastId].escalateTo = id
1855
+ }
1856
+ next.tierLayout = 'custom'
1857
+ return next
1858
+ })
1859
+ setActiveTier(newId)
1860
+ setNewTier({ name: '', template: 'blank' })
1861
+ setError(null)
1862
+ }
1863
+
1864
+ function handleRemoveTier(id) {
1865
+ if (!draft || !draft.tiers?.[id]) return
1866
+ const name = tierDisplayName(draft.tiers, id)
1867
+ if (typeof window !== 'undefined' && typeof window.confirm === 'function'
1868
+ && !window.confirm(t('tier_remove_confirm', { name }))) return
1869
+ const entry = draft.tiers[id]
1870
+ if (entry.role !== 'review' && sortedNormalTiers(draft.tiers).filter(([tierId]) => tierId !== id).length === 0) {
1871
+ setError(t('tier_remove_last_error'))
1872
+ return
1873
+ }
1874
+ setDraft((prev) => {
1875
+ const next = cloneConfig(prev)
1876
+ const fallback = entry.escalateTo && entry.escalateTo !== id && next.tiers[entry.escalateTo]
1877
+ ? entry.escalateTo
1878
+ : null
1879
+ delete next.tiers[id]
1880
+ for (const [tierId, tier] of Object.entries(next.tiers)) {
1881
+ if (tier.escalateTo === id) {
1882
+ tier.escalateTo = fallback && fallback !== tierId ? fallback : nextNormalTier(tierId, next.tiers)
1883
+ }
1884
+ }
1885
+ next.tierLayout = 'custom'
1886
+ return next
1887
+ })
1888
+ if (activeTierId === id) setActiveTier('')
1889
+ setError(null)
1890
+ }
1891
+
1892
+ function handleToggleReview(checked) {
1893
+ if (!draft || !activeTierId) return
1894
+ setDraft((prev) => {
1895
+ const next = cloneConfig(prev)
1896
+ const tier = next.tiers?.[activeTierId]
1897
+ if (!tier) return prev
1898
+ if (checked) {
1899
+ Object.assign(tier, { role: 'review', minScore: null, maxScore: null, escalateTo: null })
1900
+ } else {
1901
+ // A review tier has no score range. Give it the range after the
1902
+ // current highest normal tier instead of [0, ∞), which would
1903
+ // overlap every other tier and block saving.
1904
+ const top = nextTopRange(next.tiers, activeTierId)
1905
+ if (top.narrowLastTo !== null) next.tiers[top.lastId].maxScore = top.narrowLastTo
1906
+ Object.assign(tier, {
1907
+ role: 'normal',
1908
+ minScore: top.minScore,
1909
+ maxScore: null,
1910
+ escalateTo: null,
1911
+ })
1912
+ if (top.lastId) next.tiers[top.lastId].escalateTo = activeTierId
1913
+ }
1914
+ next.tierLayout = 'custom'
1915
+ return next
1916
+ })
1917
+ setError(null)
1918
+ }
1919
+
1920
+ async function handleTestPlan() {
1921
+ if (!testTask.trim()) return
1922
+ setTesting(true)
1923
+ setError(null)
1924
+ try {
1925
+ const res = await callRemote('testPlan', { task: testTask.trim() })
1926
+ setTestResult(res)
1927
+ } catch (err) {
1928
+ setError(describe(err))
1929
+ } finally {
1930
+ setTesting(false)
1931
+ }
1932
+ }
1933
+
1934
+ async function handleDiagnose() {
1935
+ setDoctorLoading(true)
1936
+ setError(null)
1937
+ setNotice(null)
1938
+ try {
1939
+ // Contract handshake: when the running Host predates this bundle,
1940
+ // skip the doomed `diagnose` call and use the getState fallback.
1941
+ if (contractOutdated) {
1942
+ const snapshot = await callRemote('getState', {})
1943
+ setDoctor(buildLegacyDoctorReport(snapshot))
1944
+ setNotice(t('doctor_host_outdated'))
1945
+ return
1946
+ }
1947
+ setDoctor(await callRemote('diagnose', {}))
1948
+ } catch (err) {
1949
+ const message = describe(err)
1950
+ const staleHost = /HTTP 404/.test(message) && message.includes('/diagnose')
1951
+ if (!staleHost) {
1952
+ setError(message)
1953
+ return
1954
+ }
1955
+ // The browser bundle can be newer than the running Host process.
1956
+ // Fall back to the legacy getState snapshot with an explicit hint.
1957
+ try {
1958
+ const snapshot = await callRemote('getState', {})
1959
+ setDoctor(buildLegacyDoctorReport(snapshot))
1960
+ setNotice(t('doctor_host_outdated'))
1961
+ } catch {
1962
+ setError(message)
1963
+ }
1964
+ } finally {
1965
+ setDoctorLoading(false)
1966
+ }
1967
+ }
1968
+
1969
+ async function handleCheckUpdate(force) {
1970
+ setUpdateLoading(true)
1971
+ try {
1972
+ setUpdateInfo(await callRemote('checkUpdate', force ? { force: true } : {}))
1973
+ } catch (err) {
1974
+ setUpdateInfo({ ok: false, error: describe(err) })
1975
+ } finally {
1976
+ setUpdateLoading(false)
1977
+ }
1978
+ }
1979
+
1980
+ async function handleCopyUpdateCommand() {
1981
+ const command = updateInfo?.updateCommand
1982
+ if (!command) return
1983
+ try {
1984
+ if (typeof navigator === 'undefined' || !navigator.clipboard?.writeText) {
1985
+ throw new Error('clipboard unavailable')
1986
+ }
1987
+ await navigator.clipboard.writeText(command)
1988
+ setError(null)
1989
+ setNotice(t('update_copied'))
1990
+ } catch (err) {
1991
+ setNotice(null)
1992
+ setError(describe(err))
1993
+ }
1994
+ }
1995
+
1996
+ if (loading && !state) {
1997
+ return h('div', { className: 'dar-wrap' },
1998
+ h('style', null, CSS),
1999
+ h('div', { className: 'dar-card' }, h('p', { className: 'dar-sub' }, t('loading'))))
2000
+ }
2001
+
2002
+ if (error && !state) {
2003
+ return h('div', { className: 'dar-wrap' },
2004
+ h('style', null, CSS),
2005
+ h('div', { className: 'dar-card' },
2006
+ h('div', { className: 'dar-head' },
2007
+ h('h3', { className: 'dar-title' }, t('section_title')),
2008
+ h('button', { type: 'button', className: 'dar-btn small', onClick: () => void loadState(false) }, t('refresh'))),
2009
+ h('p', { className: 'dar-msg-err' }, error)))
2010
+ }
2011
+
2012
+ const tierEntries = draft ? sortTierEntries(draft.tiers) : []
2013
+ const activeTierId = tierEntries.some(([tierId]) => tierId === activeTier)
2014
+ ? activeTier
2015
+ : (tierEntries[0]?.[0] || '')
2016
+ const tierCfg = draft?.tiers?.[activeTierId] || { dsh: [], cli: [], preferBackend: 'auto', escalateTo: null }
2017
+ const expectedContract = contractVersion()
2018
+ const hostContract = state?.contract?.version || null
2019
+ const contractOutdated = Boolean(state) && hostContract !== expectedContract
2020
+ const catalog = Array.isArray(state?.catalog) ? state.catalog : []
2021
+ const clis = state?.localClis || {}
2022
+ const cliModels = state?.cliModels || {}
2023
+ const cooldowns = Array.isArray(state?.cooldowns) ? state.cooldowns : []
2024
+ const stats = state?.stats || { total: 0, succeeded: 0, running: 0, failed: 0, escalated: 0 }
2025
+ const recentRuns = Array.isArray(state?.recentRuns) ? state.recentRuns : []
2026
+ const activeJobs = Array.isArray(state?.activeJobs) ? state.activeJobs : []
2027
+ const subSel = state?.subagentModelSelection || { available: false, enabled: false, allowedModels: [] }
2028
+ const mountInfo = state?.mount || null
2029
+ const mountWarning = Boolean(mountInfo && (mountInfo.state === 'manual' || mountInfo.state === 'duplicate'))
2030
+ const detectedLocalProviders = Array.isArray(state?.localProvidersDetected) ? state.localProvidersDetected : []
2031
+ const configSource = state?.configSource || (state?.hasCustomOverride ? 'legacy-state' : 'default')
2032
+ const sourceLabel = configSource === 'profile-patch'
2033
+ ? t('config_src_profile')
2034
+ : (configSource === 'legacy-state' ? t('config_src_legacy') : t('config_src_default'))
2035
+
2036
+ const catalogLookup = new Map()
2037
+ const catalogOptions = []
2038
+ for (const p of catalog) {
2039
+ const mset = new Set()
2040
+ for (const m of p.models || []) {
2041
+ mset.add(m.id)
2042
+ catalogOptions.push({
2043
+ key: p.id + '/' + m.id,
2044
+ provider: p.id,
2045
+ model: m.id,
2046
+ efforts: m.efforts || [],
2047
+ })
2048
+ }
2049
+ catalogLookup.set(p.id, mset)
2050
+ }
2051
+
2052
+ function dshRouteStatus(item) {
2053
+ if (catalog.length > 0) {
2054
+ const provSet = catalogLookup.get(item.provider)
2055
+ if (!provSet || !provSet.has(item.model)) {
2056
+ return { kind: 'warn', text: t('route_missing_llm') }
2057
+ }
2058
+ }
2059
+ if (subSel.enabled) {
2060
+ const inList = (subSel.allowedModels || []).some((a) => a.provider === item.provider && a.model === item.model)
2061
+ if (!inList) return { kind: 'warn', text: t('route_blocked_allowlist') }
2062
+ }
2063
+ return { kind: 'ok', text: t('route_ok') }
2064
+ }
2065
+
2066
+ const selectedCatalogModel = catalogOptions.find((x) => x.provider === newDsh.provider && x.model === newDsh.model)
2067
+
2068
+ return h('section', { className: 'dar-wrap' },
2069
+ h('style', null, CSS),
2070
+ h('div', { className: 'dar-card' },
2071
+ // Header
2072
+ h('div', { className: 'dar-head' },
2073
+ h('div', null,
2074
+ h('h3', { className: 'dar-title' }, t('section_title')),
2075
+ h('p', { className: 'dar-sub' }, t('section_subtitle'))),
2076
+ h('div', { className: 'dar-row' },
2077
+ h('span', { className: 'dar-badge ' + (configSource !== 'default' ? 'ok' : 'off') }, sourceLabel),
2078
+ h('span', { className: 'dar-badge off' },
2079
+ t('config_version_badge', { version: state?.config?.configVersion ?? 1 })),
2080
+ updateInfo?.hasUpdate
2081
+ ? h('span', { className: 'dar-badge warn' }, t('update_badge', { version: updateInfo.latestVersion }))
2082
+ : null,
2083
+ state?.hasLegacyOverride
2084
+ ? h('button', {
2085
+ type: 'button',
2086
+ className: 'dar-btn small',
2087
+ disabled: saving,
2088
+ onClick: () => void handleImportLegacy(),
2089
+ }, t('import_legacy_btn'))
2090
+ : null,
2091
+ h('button', {
2092
+ type: 'button',
2093
+ className: 'dar-btn small',
2094
+ onClick: () => {
2095
+ setDraft(buildSmartDraftFromLive(draft, state))
2096
+ setNotice(t('auto_fill_ok'))
2097
+ setError(null)
2098
+ },
2099
+ }, t('auto_fill_btn')),
2100
+ h('button', { type: 'button', className: 'dar-btn small', onClick: () => void loadState(Boolean(dirty)), disabled: loading }, t('refresh')))),
2101
+
2102
+ contractOutdated
2103
+ ? h('div', { className: 'dar-box' },
2104
+ h('span', { className: 'dar-badge warn' },
2105
+ t('contract_mismatch', { host: hostContract || 'legacy', ui: expectedContract })))
2106
+ : null,
2107
+
2108
+ subSel.available && !subSel.enabled
2109
+ ? h('div', { className: 'dar-box' },
2110
+ h('span', { className: 'dar-badge warn' }, t('subagent_sel_warn')))
2111
+ : null,
2112
+
2113
+ // Health & Overview
2114
+ h('div', { className: 'dar-grid' },
2115
+ h('div', { className: 'dar-box' },
2116
+ h('div', { className: 'dar-box-title' }, t('cli_status_title')),
2117
+ h('div', { className: 'dar-badges' },
2118
+ CLI_BACKENDS.map((name) => {
2119
+ const info = clis[name]
2120
+ const defM = cliModels[name]?.defaultModel
2121
+ return h('span', { key: name, className: 'dar-badge ' + (info?.installed ? 'ok' : 'off') },
2122
+ name + ': ' + (info?.installed ? t('cli_installed') : t('cli_missing')) + (defM ? ' · ' + defM : ''))
2123
+ }))),
2124
+ h('div', { className: 'dar-box' },
2125
+ h('div', { className: 'dar-box-title' }, t('stats_title')),
2126
+ h('div', { className: 'dar-sub' }, t('stats_line', { running: 0, ...stats })),
2127
+ h('div', { className: 'dar-row' },
2128
+ h('span', { className: 'dar-box-title' }, t('cooldowns_title') + ':'),
2129
+ cooldowns.length === 0
2130
+ ? h('span', { className: 'dar-sub' }, t('cooldowns_none'))
2131
+ : h('button', { type: 'button', className: 'dar-btn small', onClick: () => void handleClearCooldowns() }, t('clear_cooldowns'))),
2132
+ cooldowns.length > 0
2133
+ ? h('div', { className: 'dar-badges' },
2134
+ cooldowns.map((c) => h('span', { key: c.key, className: 'dar-badge warn' },
2135
+ t('cooldown_item', { key: c.key, sec: Math.ceil((c.remainingMs || 0) / 1000), reason: c.reason || '' }))))
2136
+ : null,
2137
+ state?.costMeter?.available
2138
+ ? h('div', { className: 'dar-badges', style: { marginTop: '4px' } },
2139
+ h('span', { className: 'dar-badge off' },
2140
+ t('cost_today', { sym: state.costMeter.symbol || '$', today: Number(state.costMeter.todayCost || 0).toFixed(2) })),
2141
+ state.costMeter.budget?.enabled
2142
+ ? h('span', { className: 'dar-badge ' + (state.costMeter.budget.exhausted || state.costMeter.budget.nearLimit ? 'warn' : 'ok') },
2143
+ t('cost_budget', {
2144
+ sym: state.costMeter.symbol || '$',
2145
+ used: Number(state.costMeter.budget.used || 0).toFixed(2),
2146
+ amount: Number(state.costMeter.budget.amount || 0).toFixed(2),
2147
+ pct: Math.round((state.costMeter.budget.ratio || 0) * 100),
2148
+ }))
2149
+ : null,
2150
+ state.costMeter.peak?.enabled
2151
+ ? h('span', { className: 'dar-badge ' + (state.costMeter.peak.isPeak ? 'warn' : 'ok') },
2152
+ state.costMeter.peak.isPeak ? t('cost_peak_on') : t('cost_peak_off'))
2153
+ : null)
2154
+ : null)),
2155
+
2156
+ // Global policy controls
2157
+ h('div', { className: 'dar-box' },
2158
+ h('div', { className: 'dar-box-title' }, t('global_title')),
2159
+ h('div', { className: 'dar-grid' },
2160
+ h('label', { className: 'dar-field' },
2161
+ h('span', { className: 'dar-label' }, t('prefer_backend')),
2162
+ h('select', {
2163
+ className: 'dar-select',
2164
+ value: draft.preferBackend || 'auto',
2165
+ onChange: (e) => {
2166
+ setNotice(null)
2167
+ setDraft({ ...draft, preferBackend: e.target.value })
2168
+ },
2169
+ }, PREFER_OPTIONS.map((opt) => h('option', { key: opt, value: opt }, preferLabel(opt, t))))),
2170
+ h('label', { className: 'dar-field' },
2171
+ h('span', { className: 'dar-label' }, t('cooldown_sec')),
2172
+ h('input', {
2173
+ className: 'dar-input',
2174
+ type: 'number',
2175
+ min: 5,
2176
+ max: 3600,
2177
+ value: Math.round((draft.cooldownMs || 180000) / 1000),
2178
+ onChange: (e) => {
2179
+ setNotice(null)
2180
+ setDraft({ ...draft, cooldownMs: Math.max(5, Number(e.target.value || 180)) * 1000 })
2181
+ },
2182
+ })),
2183
+ h('label', { className: 'dar-field' },
2184
+ h('span', { className: 'dar-label' }, t('timeout_sec')),
2185
+ h('input', {
2186
+ className: 'dar-input',
2187
+ type: 'number',
2188
+ min: 10,
2189
+ max: 1800,
2190
+ value: Math.round((draft.defaultTimeoutMs || 300000) / 1000),
2191
+ onChange: (e) => {
2192
+ setNotice(null)
2193
+ setDraft({ ...draft, defaultTimeoutMs: Math.max(10, Number(e.target.value || 300)) * 1000 })
2194
+ },
2195
+ })),
2196
+ h('label', { className: 'dar-field' },
2197
+ h('span', { className: 'dar-label' }, t('max_concurrent_cli')),
2198
+ h('input', {
2199
+ className: 'dar-input',
2200
+ type: 'number',
2201
+ min: 1,
2202
+ max: 16,
2203
+ value: Number(draft.maxConcurrentCli || 3),
2204
+ onChange: (e) => {
2205
+ setNotice(null)
2206
+ setDraft({ ...draft, maxConcurrentCli: Math.max(1, Math.min(16, Number(e.target.value || 3))) })
2207
+ },
2208
+ }))),
2209
+ h('label', { className: 'dar-check' },
2210
+ h('input', {
2211
+ type: 'checkbox',
2212
+ checked: draft.autoEscalate !== false,
2213
+ onChange: (e) => {
2214
+ setNotice(null)
2215
+ setDraft({ ...draft, autoEscalate: e.target.checked })
2216
+ },
2217
+ }),
2218
+ t('auto_escalate')),
2219
+ h('label', { className: 'dar-check' },
2220
+ h('input', {
2221
+ type: 'checkbox',
2222
+ checked: draft.adaptiveRanking !== false,
2223
+ onChange: (e) => {
2224
+ setNotice(null)
2225
+ setDraft({ ...draft, adaptiveRanking: e.target.checked })
2226
+ },
2227
+ }),
2228
+ t('adaptive_ranking')),
2229
+ h('label', { className: 'dar-check' },
2230
+ h('input', {
2231
+ type: 'checkbox',
2232
+ checked: draft.defaultBackground === true,
2233
+ onChange: (e) => {
2234
+ setNotice(null)
2235
+ setDraft({ ...draft, defaultBackground: e.target.checked })
2236
+ },
2237
+ }),
2238
+ t('default_background')),
2239
+ h('label', { className: 'dar-check' },
2240
+ h('input', {
2241
+ type: 'checkbox',
2242
+ checked: draft.useNativeJobs !== false,
2243
+ onChange: (e) => {
2244
+ setNotice(null)
2245
+ setDraft({ ...draft, useNativeJobs: e.target.checked })
2246
+ },
2247
+ }),
2248
+ t('native_jobs')),
2249
+ h('label', { className: 'dar-check' },
2250
+ h('input', {
2251
+ type: 'checkbox',
2252
+ checked: draft.budgetGuard !== false,
2253
+ onChange: (e) => {
2254
+ setNotice(null)
2255
+ setDraft({ ...draft, budgetGuard: e.target.checked })
2256
+ },
2257
+ }),
2258
+ t('budget_guard')),
2259
+ h('label', { className: 'dar-check' },
2260
+ h('input', {
2261
+ type: 'checkbox',
2262
+ checked: draft.peakAvoidance === true,
2263
+ onChange: (e) => {
2264
+ setNotice(null)
2265
+ setDraft({ ...draft, peakAvoidance: e.target.checked })
2266
+ },
2267
+ }),
2268
+ t('peak_avoidance')),
2269
+ h('div', { className: 'dar-grid' },
2270
+ h('label', { className: 'dar-field' },
2271
+ h('span', { className: 'dar-label' }, t('cli_selection_label')),
2272
+ h('select', {
2273
+ className: 'dar-select',
2274
+ value: draft.cliSelection || 'static',
2275
+ onChange: (e) => {
2276
+ setNotice(null)
2277
+ setDraft({ ...draft, cliSelection: e.target.value })
2278
+ },
2279
+ }, [
2280
+ h('option', { key: 'static', value: 'static' }, t('cli_selection_static')),
2281
+ h('option', { key: 'adaptive', value: 'adaptive' }, t('cli_selection_adaptive')),
2282
+ ]))),
2283
+ h('label', { className: 'dar-check' },
2284
+ h('input', {
2285
+ type: 'checkbox',
2286
+ checked: draft.allowLocalModels === true,
2287
+ onChange: (e) => {
2288
+ setNotice(null)
2289
+ setDraft({ ...draft, allowLocalModels: e.target.checked })
2290
+ },
2291
+ }),
2292
+ t('local_models_enable')),
2293
+ draft.allowLocalModels === true
2294
+ ? h('label', { className: 'dar-field' },
2295
+ h('span', { className: 'dar-label' }, t('local_providers_label')),
2296
+ h('input', {
2297
+ className: 'dar-input',
2298
+ placeholder: t('local_providers_placeholder'),
2299
+ value: (draft.localProviders || []).join(', '),
2300
+ onChange: (e) => {
2301
+ setNotice(null)
2302
+ setDraft({
2303
+ ...draft,
2304
+ localProviders: e.target.value.split(',').map((x) => x.trim()).filter(Boolean),
2305
+ })
2306
+ },
2307
+ }),
2308
+ detectedLocalProviders.length > 0
2309
+ ? h('span', { className: 'dar-item-meta' },
2310
+ t('local_models_detected', { providers: detectedLocalProviders.join(', ') }))
2311
+ : null)
2312
+ : null),
2313
+
2314
+ // Presets & config portability
2315
+ h('div', { className: 'dar-box' },
2316
+ h('div', { className: 'dar-box-title' }, t('preset_label')),
2317
+ h('div', { className: 'dar-row' },
2318
+ ...PRESET_NAMES.map((name) => h('button', {
2319
+ key: name,
2320
+ type: 'button',
2321
+ className: 'dar-btn small',
2322
+ disabled: saving,
2323
+ onClick: () => void handleApplyPreset(name),
2324
+ }, t('preset_' + name))),
2325
+ h('button', {
2326
+ type: 'button',
2327
+ className: 'dar-btn small',
2328
+ disabled: saving,
2329
+ onClick: () => void handleExportConfig(),
2330
+ }, t('export_config')),
2331
+ h('button', {
2332
+ type: 'button',
2333
+ className: 'dar-btn small',
2334
+ disabled: saving || !importText.trim(),
2335
+ onClick: () => void handleImportConfig(),
2336
+ }, t('import_config'))),
2337
+ h('textarea', {
2338
+ className: 'dar-input',
2339
+ style: { width: '100%', minHeight: '72px', padding: '6px 10px', boxSizing: 'border-box' },
2340
+ placeholder: t('import_placeholder'),
2341
+ value: importText,
2342
+ onChange: (e) => setImportText(e.target.value),
2343
+ }),
2344
+ exportJson
2345
+ ? h('pre', { className: 'dar-tv-pre' }, exportJson)
2346
+ : null),
2347
+
2348
+ mountWarning
2349
+ ? h('div', { className: 'dar-box' },
2350
+ h('div', { className: 'dar-row' },
2351
+ h('span', { className: 'dar-badge warn' }, t('mount_warn_title')),
2352
+ h('span', { className: 'dar-sub' },
2353
+ t(mountInfo.state === 'duplicate' ? 'mount_warn_duplicate' : 'mount_warn_manual'))),
2354
+ h('div', { className: 'dar-row' },
2355
+ h('span', { className: 'dar-label' }, t('mount_warn_profile')),
2356
+ h('code', { className: 'dar-code' }, mountInfo.profileDir || mountInfo.files?.homePatch || '')),
2357
+ h('span', { className: 'dar-sub' }, t('mount_warn_fix')),
2358
+ h('code', { className: 'dar-code' }, t('mount_repair_command')))
2359
+ : null,
2360
+
2361
+ // Tier layout presets, tabs & editor
2362
+ h('div', { className: 'dar-box' },
2363
+ h('div', { className: 'dar-box-title' }, t('tier_section_title')),
2364
+ h('div', { className: 'dar-row' },
2365
+ h('span', { className: 'dar-label' }, t('tier_layout_label')),
2366
+ ...['default', 'compact', 'fast'].map((key) => h('button', {
2367
+ key,
2368
+ type: 'button',
2369
+ className: 'dar-btn small',
2370
+ disabled: saving,
2371
+ onClick: () => handleApplyTierLayout(key),
2372
+ }, t('tier_layout_' + key)))),
2373
+ h('p', { className: 'dar-sub' }, t('tier_layout_hint')),
2374
+ h('div', { className: 'dar-tabs' },
2375
+ tierEntries.map(([tierId, entry]) => h('button', {
2376
+ key: tierId,
2377
+ type: 'button',
2378
+ className: 'dar-tab' + (activeTierId === tierId ? ' active' : ''),
2379
+ onClick: () => {
2380
+ setActiveTier(tierId)
2381
+ resetDrag()
2382
+ },
2383
+ }, entry.name || tierDisplayName(draft?.tiers, tierId)))),
2384
+
2385
+ h('div', { className: 'dar-grid' },
2386
+ h('label', { className: 'dar-field' },
2387
+ h('span', { className: 'dar-label' }, t('tier_name_label')),
2388
+ h('input', {
2389
+ className: 'dar-input',
2390
+ maxLength: 40,
2391
+ value: tierCfg.name || '',
2392
+ onChange: (e) => updateTier(activeTierId, (cur) => ({ ...cur, name: e.target.value })),
2393
+ })),
2394
+ h('label', { className: 'dar-field' },
2395
+ h('span', { className: 'dar-label' }, t('tier_desc_label')),
2396
+ h('input', {
2397
+ className: 'dar-input',
2398
+ placeholder: t('tier_desc_placeholder'),
2399
+ value: tierCfg.description || '',
2400
+ onChange: (e) => updateTier(activeTierId, (cur) => ({ ...cur, description: e.target.value })),
2401
+ }))),
2402
+ tierCfg.role === 'review'
2403
+ ? h('span', { className: 'dar-badge warn' }, t('tier_review_badge'))
2404
+ : null,
2405
+
2406
+ h('div', { className: 'dar-grid' },
2407
+ h('label', { className: 'dar-field' },
2408
+ h('span', { className: 'dar-label' }, t('tier_prefer')),
2409
+ h('select', {
2410
+ className: 'dar-select',
2411
+ value: tierCfg.preferBackend || 'auto',
2412
+ onChange: (e) => updateTier(activeTierId, (cur) => ({ ...cur, preferBackend: e.target.value })),
2413
+ }, PREFER_OPTIONS.map((opt) => h('option', { key: opt, value: opt }, preferLabel(opt, t))))),
2414
+ h('label', { className: 'dar-field' },
2415
+ h('span', { className: 'dar-label' }, t('tier_escalate')),
2416
+ h('select', {
2417
+ className: 'dar-select',
2418
+ value: tierCfg.escalateTo || '',
2419
+ onChange: (e) => updateTier(activeTierId, (cur) => ({ ...cur, escalateTo: e.target.value || null })),
2420
+ }, [
2421
+ h('option', { key: 'none', value: '' }, t('escalate_none')),
2422
+ ...tierEntries
2423
+ .filter(([tierId]) => tierId !== activeTierId)
2424
+ .map(([tierId]) => h('option', { key: tierId, value: tierId }, tierDisplayName(draft?.tiers, tierId))),
2425
+ ]))),
2426
+
2427
+ h('details', { className: 'dar-box' },
2428
+ h('summary', { className: 'dar-box-title' }, t('tier_advanced')),
2429
+ h('div', { className: 'dar-grid' },
2430
+ h('label', { className: 'dar-field' },
2431
+ h('span', { className: 'dar-label' }, t('tier_range_min')),
2432
+ h('input', {
2433
+ className: 'dar-input',
2434
+ type: 'number',
2435
+ step: '0.1',
2436
+ min: '0',
2437
+ disabled: tierCfg.role === 'review',
2438
+ value: Number.isFinite(tierCfg.minScore) ? tierCfg.minScore : '',
2439
+ onChange: (e) => updateTier(activeTierId, (cur) => ({
2440
+ ...cur,
2441
+ minScore: e.target.value === '' ? 0 : Number(e.target.value),
2442
+ })),
2443
+ })),
2444
+ h('label', { className: 'dar-field' },
2445
+ h('span', { className: 'dar-label' }, t('tier_range_max')),
2446
+ h('input', {
2447
+ className: 'dar-input',
2448
+ type: 'number',
2449
+ step: '0.1',
2450
+ min: '0',
2451
+ disabled: tierCfg.role === 'review',
2452
+ placeholder: t('tier_unbounded'),
2453
+ value: tierCfg.maxScore === null || tierCfg.maxScore === undefined ? '' : tierCfg.maxScore,
2454
+ onChange: (e) => updateTier(activeTierId, (cur) => ({
2455
+ ...cur,
2456
+ maxScore: e.target.value === '' ? null : Number(e.target.value),
2457
+ })),
2458
+ }))),
2459
+ h('p', { className: 'dar-sub' }, t('tier_range_hint')),
2460
+ h('label', { className: 'dar-check' },
2461
+ h('input', {
2462
+ type: 'checkbox',
2463
+ checked: tierCfg.role === 'review',
2464
+ onChange: (e) => handleToggleReview(e.target.checked),
2465
+ }),
2466
+ t('tier_role_review_label'))),
2467
+ h('div', { className: 'dar-row' },
2468
+ h('button', {
2469
+ type: 'button',
2470
+ className: 'dar-btn small danger',
2471
+ disabled: saving,
2472
+ onClick: () => handleRemoveTier(activeTierId),
2473
+ }, t('tier_remove_btn'))),
2474
+
2475
+ // DSH routes list
2476
+ h('div', { className: 'dar-box-title' }, t('dsh_routes_title')),
2477
+ h('p', { className: 'dar-sub' }, t('dsh_routes_hint')),
2478
+ tierCfg.dsh.length === 0
2479
+ ? h('p', { className: 'dar-sub' }, t('dsh_routes_empty'))
2480
+ : h('div', { className: 'dar-list' },
2481
+ tierCfg.dsh.map((item, idx) => {
2482
+ const st = dshRouteStatus(item)
2483
+ const itemKey = item.provider + '/' + item.model + (item.reasoningEffort ? ':' + item.reasoningEffort : '')
2484
+ return h('div', {
2485
+ key: itemKey,
2486
+ className: 'dar-item'
2487
+ + (dragState?.list === 'dsh' && dragState.from === idx ? ' dragging' : '')
2488
+ + (dragState?.list === 'dsh' && dragState.over === idx && dragState.from !== idx ? ' drag-over' : ''),
2489
+ onDragOver: (event) => handleDragOver('dsh', event, idx),
2490
+ onDrop: (event) => handleDrop('dsh', event, idx),
2491
+ onDragEnd: resetDrag,
2492
+ },
2493
+ h('span', {
2494
+ className: 'dar-drag-handle',
2495
+ draggable: true,
2496
+ title: t('drag_handle'),
2497
+ 'aria-label': t('drag_handle'),
2498
+ onDragStart: (event) => handleDragStart('dsh', event, idx),
2499
+ onDragEnd: resetDrag,
2500
+ }, '⋮⋮'),
2501
+ h('div', { className: 'dar-item-main' },
2502
+ h('div', { className: 'dar-row' },
2503
+ h('span', { className: 'dar-item-name' }, (idx + 1) + '. ' + item.provider + '/' + item.model + (item.reasoningEffort ? ' · ' + item.reasoningEffort : '')),
2504
+ h('span', { className: 'dar-badge ' + st.kind }, st.text)),
2505
+ item.note ? h('span', { className: 'dar-item-meta' }, item.note) : null),
2506
+ h('div', { className: 'dar-row' },
2507
+ h('button', {
2508
+ type: 'button',
2509
+ className: 'dar-btn small',
2510
+ disabled: idx === 0,
2511
+ onClick: () => updateTier(activeTierId, (cur) => ({ ...cur, dsh: moveListItem(cur.dsh, idx, idx - 1) })),
2512
+ }, t('move_up')),
2513
+ h('button', {
2514
+ type: 'button',
2515
+ className: 'dar-btn small',
2516
+ disabled: idx === tierCfg.dsh.length - 1,
2517
+ onClick: () => updateTier(activeTierId, (cur) => ({ ...cur, dsh: moveListItem(cur.dsh, idx, idx + 1) })),
2518
+ }, t('move_down')),
2519
+ h('button', {
2520
+ type: 'button',
2521
+ className: 'dar-btn small danger',
2522
+ onClick: () => updateTier(activeTierId, (cur) => ({ ...cur, dsh: cur.dsh.filter((_, i) => i !== idx) })),
2523
+ }, t('remove'))))
2524
+ })),
2525
+
2526
+ // Add DSH model form
2527
+ h('div', { className: 'dar-label' }, t('add_dsh_title')),
2528
+ catalogOptions.length > 0
2529
+ ? h('select', {
2530
+ className: 'dar-select',
2531
+ value: selectedCatalogModel ? selectedCatalogModel.key : '',
2532
+ onChange: (e) => {
2533
+ const hit = catalogOptions.find((x) => x.key === e.target.value)
2534
+ if (hit) {
2535
+ setNewDsh({
2536
+ ...EMPTY_DSH_ROUTE_INPUT,
2537
+ provider: hit.provider,
2538
+ model: hit.model,
2539
+ })
2540
+ }
2541
+ },
2542
+ }, [
2543
+ h('option', { key: 'pick', value: '' }, t('catalog_pick')),
2544
+ ...catalogOptions.map((opt) => h('option', { key: opt.key, value: opt.key }, opt.key)),
2545
+ ])
2546
+ : null,
2547
+ h('div', { className: 'dar-add-row' },
2548
+ h('input', {
2549
+ className: 'dar-input',
2550
+ placeholder: t('provider_placeholder'),
2551
+ value: newDsh.provider,
2552
+ onChange: (e) => setNewDsh({ ...newDsh, provider: e.target.value }),
2553
+ }),
2554
+ h('input', {
2555
+ className: 'dar-input',
2556
+ placeholder: t('model_placeholder'),
2557
+ value: newDsh.model,
2558
+ onChange: (e) => setNewDsh({ ...newDsh, model: e.target.value }),
2559
+ }),
2560
+ selectedCatalogModel && selectedCatalogModel.efforts.length > 0
2561
+ ? h('select', {
2562
+ className: 'dar-select',
2563
+ value: newDsh.reasoningEffort,
2564
+ onChange: (e) => setNewDsh({ ...newDsh, reasoningEffort: e.target.value }),
2565
+ }, [
2566
+ h('option', { key: 'def', value: '' }, t('effort_placeholder')),
2567
+ ...selectedCatalogModel.efforts.map((ef) => h('option', { key: ef, value: ef }, ef)),
2568
+ ])
2569
+ : h('input', {
2570
+ className: 'dar-input',
2571
+ placeholder: t('effort_placeholder'),
2572
+ value: newDsh.reasoningEffort,
2573
+ onChange: (e) => setNewDsh({ ...newDsh, reasoningEffort: e.target.value }),
2574
+ }),
2575
+ h('input', {
2576
+ className: 'dar-input',
2577
+ placeholder: t('note_placeholder'),
2578
+ value: newDsh.note,
2579
+ onChange: (e) => setNewDsh({ ...newDsh, note: e.target.value }),
2580
+ }),
2581
+ h('button', {
2582
+ type: 'button',
2583
+ className: 'dar-btn',
2584
+ disabled: !normalizeDshRouteInput(newDsh),
2585
+ onClick: handleAddDshRoute,
2586
+ }, t('add_btn'))),
2587
+
2588
+ // CLI routes list
2589
+ h('div', { className: 'dar-box-title', style: { marginTop: '6px' } }, t('cli_routes_title')),
2590
+ h('p', { className: 'dar-sub' }, t('cli_routes_hint')),
2591
+ tierCfg.cli.length === 0
2592
+ ? h('p', { className: 'dar-sub' }, t('cli_routes_empty'))
2593
+ : h('div', { className: 'dar-list' },
2594
+ tierCfg.cli.map((item, idx) => {
2595
+ const installed = Boolean(clis[item.backend]?.installed)
2596
+ const itemKey = item.backend + ':' + (item.model || '') + ':' + (item.effort || '')
2597
+ return h('div', {
2598
+ key: itemKey,
2599
+ className: 'dar-item'
2600
+ + (dragState?.list === 'cli' && dragState.from === idx ? ' dragging' : '')
2601
+ + (dragState?.list === 'cli' && dragState.over === idx && dragState.from !== idx ? ' drag-over' : ''),
2602
+ onDragOver: (event) => handleDragOver('cli', event, idx),
2603
+ onDrop: (event) => handleDrop('cli', event, idx),
2604
+ onDragEnd: resetDrag,
2605
+ },
2606
+ h('span', {
2607
+ className: 'dar-drag-handle',
2608
+ draggable: true,
2609
+ title: t('drag_handle'),
2610
+ 'aria-label': t('drag_handle'),
2611
+ onDragStart: (event) => handleDragStart('cli', event, idx),
2612
+ onDragEnd: resetDrag,
2613
+ }, '⋮⋮'),
2614
+ h('div', { className: 'dar-item-main' },
2615
+ h('div', { className: 'dar-row' },
2616
+ h('span', { className: 'dar-item-name' },
2617
+ (idx + 1) + '. ' + item.backend + (item.model ? ' / ' + item.model : '') + (item.effort ? ' · ' + item.effort : '')),
2618
+ h('span', { className: 'dar-badge ' + (installed ? 'ok' : 'off') },
2619
+ installed ? t('cli_installed') : t('route_cli_missing'))),
2620
+ !item.model && cliModels[item.backend]?.defaultModel
2621
+ ? h('span', { className: 'dar-item-meta' }, t('cli_inherits_default', { model: cliModels[item.backend].defaultModel }))
2622
+ : null,
2623
+ item.note ? h('span', { className: 'dar-item-meta' }, item.note) : null),
2624
+ h('div', { className: 'dar-row' },
2625
+ h('button', {
2626
+ type: 'button',
2627
+ className: 'dar-btn small',
2628
+ disabled: idx === 0,
2629
+ onClick: () => updateTier(activeTierId, (cur) => ({ ...cur, cli: moveListItem(cur.cli, idx, idx - 1) })),
2630
+ }, t('move_up')),
2631
+ h('button', {
2632
+ type: 'button',
2633
+ className: 'dar-btn small',
2634
+ disabled: idx === tierCfg.cli.length - 1,
2635
+ onClick: () => updateTier(activeTierId, (cur) => ({ ...cur, cli: moveListItem(cur.cli, idx, idx + 1) })),
2636
+ }, t('move_down')),
2637
+ h('button', {
2638
+ type: 'button',
2639
+ className: 'dar-btn small danger',
2640
+ onClick: () => updateTier(activeTierId, (cur) => ({ ...cur, cli: cur.cli.filter((_, i) => i !== idx) })),
2641
+ }, t('remove'))))
2642
+ })),
2643
+
2644
+ // Add CLI route form
2645
+ h('div', { className: 'dar-label' }, t('add_cli_title')),
2646
+ Array.isArray(cliModels[newCli.backend]?.models) && cliModels[newCli.backend].models.length > 0
2647
+ ? h('select', {
2648
+ className: 'dar-select',
2649
+ value: cliModels[newCli.backend].models.includes(newCli.model) ? newCli.model : '',
2650
+ onChange: (e) => setNewCli({ ...newCli, model: e.target.value }),
2651
+ }, [
2652
+ h('option', { key: 'pick-cli', value: '' }, t('cli_catalog_pick', { backend: newCli.backend })),
2653
+ ...cliModels[newCli.backend].models.map((m) => h('option', { key: m, value: m }, m)),
2654
+ ])
2655
+ : null,
2656
+ h('div', { className: 'dar-add-row' },
2657
+ h('select', {
2658
+ className: 'dar-select',
2659
+ value: newCli.backend,
2660
+ onChange: (e) => setNewCli({ ...newCli, backend: e.target.value, model: '' }),
2661
+ }, CLI_BACKENDS.map((b) => h('option', { key: b, value: b }, b))),
2662
+ h('input', {
2663
+ className: 'dar-input',
2664
+ placeholder: t('model_placeholder'),
2665
+ value: newCli.model,
2666
+ onChange: (e) => setNewCli({ ...newCli, model: e.target.value }),
2667
+ }),
2668
+ h('input', {
2669
+ className: 'dar-input',
2670
+ placeholder: t('effort_placeholder'),
2671
+ value: newCli.effort,
2672
+ onChange: (e) => setNewCli({ ...newCli, effort: e.target.value }),
2673
+ }),
2674
+ h('input', {
2675
+ className: 'dar-input',
2676
+ placeholder: t('note_placeholder'),
2677
+ value: newCli.note,
2678
+ onChange: (e) => setNewCli({ ...newCli, note: e.target.value }),
2679
+ }),
2680
+ h('button', {
2681
+ type: 'button',
2682
+ className: 'dar-btn',
2683
+ onClick: () => {
2684
+ const mod = newCli.model.trim()
2685
+ const eff = newCli.effort.trim()
2686
+ if (tierCfg.cli.some((x) => x.backend === newCli.backend && (x.model || '') === mod && (x.effort || '') === eff)) {
2687
+ setError(t('route_duplicate'))
2688
+ return
2689
+ }
2690
+ setError(null)
2691
+ const entry = {
2692
+ backend: newCli.backend,
2693
+ ...(mod ? { model: mod } : {}),
2694
+ ...(eff ? { effort: eff } : {}),
2695
+ ...(newCli.note.trim() ? { note: newCli.note.trim() } : {}),
2696
+ }
2697
+ updateTier(activeTierId, (cur) => ({ ...cur, cli: [...cur.cli, entry] }))
2698
+ setNewCli({ backend: newCli.backend, model: '', effort: '', note: '' })
2699
+ },
2700
+ }, t('add_btn')))),
2701
+
2702
+ // Add tier (draft-only, saved together with the rest)
2703
+ h('div', { className: 'dar-box' },
2704
+ h('div', { className: 'dar-box-title' }, t('tier_add_title')),
2705
+ h('div', { className: 'dar-add-row' },
2706
+ h('input', {
2707
+ className: 'dar-input',
2708
+ maxLength: 40,
2709
+ placeholder: t('tier_add_name_placeholder'),
2710
+ value: newTier.name,
2711
+ onChange: (e) => setNewTier({ ...newTier, name: e.target.value }),
2712
+ }),
2713
+ h('select', {
2714
+ className: 'dar-select',
2715
+ value: newTier.template,
2716
+ onChange: (e) => setNewTier({ ...newTier, template: e.target.value }),
2717
+ }, ['blank', 'light', 'standard', 'heavy', 'review'].map((key) => (
2718
+ h('option', { key, value: key }, t('tier_template_' + key))
2719
+ ))),
2720
+ h('button', {
2721
+ type: 'button',
2722
+ className: 'dar-btn',
2723
+ disabled: saving || !newTier.name.trim(),
2724
+ onClick: handleAddTier,
2725
+ }, t('tier_add_btn')))),
2726
+
2727
+ // Save / Reset actions
2728
+ h('div', { className: 'dar-row' },
2729
+ h('button', {
2730
+ type: 'button',
2731
+ className: 'dar-btn primary',
2732
+ disabled: saving || !dirty,
2733
+ onClick: () => void handleSave(),
2734
+ }, saving ? t('saving') : t('save')),
2735
+ h('button', {
2736
+ type: 'button',
2737
+ className: 'dar-btn',
2738
+ disabled: saving || !dirty,
2739
+ onClick: () => {
2740
+ setDraft(cloneConfig(state.config))
2741
+ setNotice(null)
2742
+ setError(null)
2743
+ },
2744
+ }, t('discard')),
2745
+ h('button', {
2746
+ type: 'button',
2747
+ className: 'dar-btn danger',
2748
+ disabled: saving,
2749
+ onClick: () => void handleResetDefaults(),
2750
+ }, t('reset_defaults')),
2751
+ notice ? h('span', { className: 'dar-msg-ok' }, notice) : null,
2752
+ error ? h('span', { className: 'dar-msg-err' }, error) : null),
2753
+
2754
+ // Dry-run classifier & route preview
2755
+ h('div', { className: 'dar-box' },
2756
+ h('div', { className: 'dar-box-title' }, t('test_title')),
2757
+ h('div', { className: 'dar-row' },
2758
+ h('input', {
2759
+ className: 'dar-input',
2760
+ style: { flex: '1 1 260px' },
2761
+ placeholder: t('test_placeholder'),
2762
+ value: testTask,
2763
+ onChange: (e) => setTestTask(e.target.value),
2764
+ onKeyDown: (e) => { if (e.key === 'Enter') void handleTestPlan() },
2765
+ }),
2766
+ h('button', {
2767
+ type: 'button',
2768
+ className: 'dar-btn',
2769
+ disabled: testing || !testTask.trim(),
2770
+ onClick: () => void handleTestPlan(),
2771
+ }, testing ? t('testing') : t('test_btn'))),
2772
+ testResult
2773
+ ? h('div', { className: 'dar-list' },
2774
+ h('div', { className: 'dar-sub' },
2775
+ testResult.classification?.tier + ' (' + (testResult.classification?.tierName || testResult.policyLabel || '') + ') · '
2776
+ + (testResult.classification?.domain || '') + ' · score=' + (testResult.classification?.score ?? '?')
2777
+ + ' · confidence=' + (testResult.classification?.confidence || '?')
2778
+ + ' — ' + (testResult.classification?.reasons || []).join('; ')),
2779
+ h('div', { className: 'dar-badges' },
2780
+ (testResult.candidates || []).map((c, idx) => h('span', { key: idx + ':' + c.key, className: 'dar-badge ' + (idx === 0 ? 'ok' : 'off') },
2781
+ (idx + 1) + '. ' + c.key))))
2782
+ : null),
2783
+
2784
+ // Environment diagnostics (read-only)
2785
+ h('div', { className: 'dar-box' },
2786
+ h('div', { className: 'dar-row' },
2787
+ h('span', { className: 'dar-box-title' }, t('doctor_title')),
2788
+ h('button', {
2789
+ type: 'button',
2790
+ className: 'dar-btn small',
2791
+ disabled: doctorLoading,
2792
+ onClick: () => void handleDiagnose(),
2793
+ }, doctorLoading ? t('doctor_running') : t('doctor_run'))),
2794
+ doctor
2795
+ ? h('div', null,
2796
+ h('div', { className: 'dar-badges' },
2797
+ h('span', { className: 'dar-badge ' + (doctor.status === 'ok' ? 'ok' : 'warn') },
2798
+ t('doctor_summary', doctor.summary || { ok: 0, warn: 0, fail: 0 }))),
2799
+ h('div', { className: 'dar-list' },
2800
+ (doctor.checks || []).map((check) => h('div', { key: check.id, className: 'dar-item' },
2801
+ h('div', { className: 'dar-item-main' },
2802
+ h('div', { className: 'dar-row' },
2803
+ h('span', { className: 'dar-item-name' }, t('doctor_check_' + String(check.id).replace(/-/g, '_'))),
2804
+ h('span', { className: 'dar-badge ' + (check.status === 'ok' ? 'ok' : check.status === 'info' ? 'off' : 'warn') }, check.status)),
2805
+ h('span', { className: 'dar-item-meta' }, check.message),
2806
+ check.hint
2807
+ ? h('span', { className: 'dar-item-meta' }, t('doctor_hint_label') + ': ' + check.hint)
2808
+ : null)))))
2809
+ : null),
2810
+
2811
+ // Version & update status (read-only, network failures are contained)
2812
+ h('div', { className: 'dar-box' },
2813
+ h('div', { className: 'dar-head' },
2814
+ h('div', null,
2815
+ h('div', { className: 'dar-box-title' }, t('update_title')),
2816
+ h('p', { className: 'dar-sub' }, t('update_subtitle'))),
2817
+ h('button', {
2818
+ type: 'button',
2819
+ className: 'dar-btn small',
2820
+ disabled: updateLoading,
2821
+ onClick: () => void handleCheckUpdate(true),
2822
+ }, updateLoading ? t('update_checking') : t('update_check'))),
2823
+ updateInfo
2824
+ ? h('div', { className: 'dar-list' },
2825
+ h('div', { className: 'dar-row' },
2826
+ h('span', {
2827
+ className: 'dar-badge ' + (updateInfo.ok ? (updateInfo.hasUpdate ? 'warn' : 'ok') : 'off'),
2828
+ }, updateInfo.ok
2829
+ ? (updateInfo.hasUpdate
2830
+ ? t('update_available', { version: updateInfo.latestVersion, current: updateInfo.currentVersion })
2831
+ : t('update_latest', { version: updateInfo.currentVersion }))
2832
+ : t('update_failed', { error: updateInfo.error || 'unknown' })),
2833
+ updateInfo.currentVersion
2834
+ ? h('span', { className: 'dar-sub' }, t('update_current', { version: updateInfo.currentVersion }))
2835
+ : null),
2836
+ updateInfo.ok && updateInfo.ahead
2837
+ ? h('span', { className: 'dar-sub' }, t('update_ahead'))
2838
+ : null,
2839
+ updateInfo.ok && updateInfo.hasUpdate
2840
+ ? h('div', null,
2841
+ h('span', { className: 'dar-sub' }, t('update_command_hint')),
2842
+ h('code', { className: 'dar-code' }, updateInfo.updateCommand),
2843
+ h('div', { className: 'dar-row' },
2844
+ h('button', {
2845
+ type: 'button',
2846
+ className: 'dar-btn small',
2847
+ onClick: () => void handleCopyUpdateCommand(),
2848
+ }, t('update_copy')),
2849
+ updateInfo.releasesUrl
2850
+ ? h('a', {
2851
+ className: 'dar-btn small',
2852
+ href: updateInfo.releasesUrl,
2853
+ target: '_blank',
2854
+ rel: 'noreferrer',
2855
+ style: { display: 'inline-flex', alignItems: 'center', textDecoration: 'none' },
2856
+ }, t('update_open'))
2857
+ : null),
2858
+ h('span', { className: 'dar-sub' }, t('update_npm_hint', { command: updateInfo.npmCommand || 'pnpm add dsh-agent-router@latest' })))
2859
+ : null,
2860
+ !updateInfo.ok
2861
+ ? h('span', { className: 'dar-sub' }, t('update_offline_hint'))
2862
+ : null,
2863
+ updateInfo.checkedAt
2864
+ ? h('span', { className: 'dar-sub' }, t('update_checked_at', { at: new Date(updateInfo.checkedAt).toLocaleTimeString() }))
2865
+ : null)
2866
+ : h('p', { className: 'dar-sub' }, t('update_idle'))),
2867
+
2868
+ // Active background CLI jobs
2869
+ activeJobs.length > 0
2870
+ ? h('div', { className: 'dar-box' },
2871
+ h('div', { className: 'dar-box-title' }, t('active_jobs_title', { count: activeJobs.length })),
2872
+ h('div', { className: 'dar-list' },
2873
+ activeJobs.map((job) => h('div', { key: job.runId, className: 'dar-item' },
2874
+ h('div', { className: 'dar-item-main' },
2875
+ h('div', { className: 'dar-row' },
2876
+ h('span', { className: 'dar-item-name' }, job.runId + ' · ' + job.tier + ' · ' + job.backend),
2877
+ h('span', { className: 'dar-badge warn' }, job.status + ' · ' + Math.round((job.elapsedMs || 0) / 1000) + 's')),
2878
+ job.progress ? h('span', { className: 'dar-item-meta' }, job.progress) : null),
2879
+ h('button', {
2880
+ type: 'button',
2881
+ className: 'dar-btn small danger',
2882
+ onClick: () => void handleCancelRun(job.runId),
2883
+ }, t('cancel_job'))))))
2884
+ : null,
2885
+
2886
+ // Recent routed runs
2887
+ h('div', { className: 'dar-box' },
2888
+ h('div', { className: 'dar-head' },
2889
+ h('div', { className: 'dar-box-title' }, t('recent_title', { count: recentRuns.length })),
2890
+ recentRuns.length > 0
2891
+ ? h('button', {
2892
+ type: 'button',
2893
+ className: 'dar-btn small',
2894
+ onClick: () => setShowRuns(!showRuns),
2895
+ }, showRuns ? t('recent_toggle_hide') : t('recent_toggle_show'))
2896
+ : null),
2897
+ recentRuns.length === 0
2898
+ ? h('p', { className: 'dar-sub' }, t('recent_empty'))
2899
+ : (showRuns
2900
+ ? h('div', { className: 'dar-list' },
2901
+ recentRuns.map((r) => h('div', { key: r.runId, className: 'dar-item' },
2902
+ h('div', { className: 'dar-item-main' },
2903
+ h('div', { className: 'dar-row' },
2904
+ h('span', { className: 'dar-item-name' }, r.runId + ' · ' + (r.tier || '?') + ' · ' + (r.route || r.backend || '?') + (r.model ? ' (' + r.model + ')' : '')),
2905
+ h('span', { className: 'dar-badge ' + (r.status === 'completed' ? 'ok' : (r.status === 'failed' || r.status === 'cancelled' ? 'warn' : 'off')) }, r.status || 'unknown'),
2906
+ r.worktree?.branch && !r.worktreeCleaned
2907
+ ? h('span', { className: 'dar-badge off' }, t('worktree_badge', { branch: r.worktree.branch }))
2908
+ : null,
2909
+ r.mergeCommit ? h('span', { className: 'dar-badge ok' }, t('merged_badge') + ' ' + r.mergeCommit) : null),
2910
+ r.description ? h('span', { className: 'dar-item-meta' }, r.description + (r.durationMs ? ' · ' + r.durationMs + 'ms' : '') + (typeof r.costUsd === 'number' ? ' · $' + r.costUsd.toFixed(4) : '')) : null,
2911
+ r.error ? h('span', { className: 'dar-msg-err' }, r.error) : null))))
2912
+ : null))))
2913
+ }
2914
+
2915
+ function RowConfigSection(props) {
2916
+ if (props?.view === 'summary') {
2917
+ return h(RouterSummary, null)
2918
+ }
2919
+ return h(RouterEditor, null)
2920
+ }
2921
+
2922
+ function safeJsonParse(raw) {
2923
+ if (!raw) return null
2924
+ if (typeof raw === 'object') return raw
2925
+ try { return JSON.parse(String(raw)) } catch { return null }
2926
+ }
2927
+
2928
+ function RouterGenericToolView(toolName) {
2929
+ return function GenericRouterToolView(props) {
2930
+ const [open, setOpen] = typeof props?.useDisclosure === 'function'
2931
+ ? props.useDisclosure(false)
2932
+ : useState(false)
2933
+ const phase = props?.phase
2934
+ const block = props?.block || {}
2935
+ const callObj = phase === 'result' ? (block.call || {}) : block
2936
+ const args = safeJsonParse(callObj.args?.object || callObj.args) || {}
2937
+ const resultVal = phase === 'result' ? safeJsonParse(block.value ?? block.result) : null
2938
+ const status = phase === 'preparing' || phase === 'start'
2939
+ ? 'running'
2940
+ : (resultVal?.ok === false ? 'failed' : 'completed')
2941
+ const tier = resultVal?.classification?.tier || resultVal?.tier || args.tier || 'auto'
2942
+ const title = toolName === 'router_plan'
2943
+ ? (args.task || 'router_plan')
2944
+ : (toolName === 'router_status'
2945
+ ? (args.action || 'router_status')
2946
+ : (args.run_id || args.message || 'router_continue'))
2947
+ const summary = toolName === 'router_plan'
2948
+ ? (Array.isArray(resultVal?.candidates) ? resultVal.candidates.length + ' candidates' : '')
2949
+ : (toolName === 'router_status'
2950
+ ? (resultVal?.status || '')
2951
+ : (resultVal?.targetId || resultVal?.sessionId || ''))
2952
+
2953
+ return h('div', { className: 'dar-tv' },
2954
+ h('style', null, CSS),
2955
+ h('div', { className: 'dar-tv-head', onClick: () => setOpen(!open) },
2956
+ h('div', { className: 'dar-row' },
2957
+ h('span', { className: 'dar-badge ' + (status === 'completed' ? 'ok' : (status === 'failed' ? 'warn' : 'off')) }, tier),
2958
+ h('strong', { style: { fontSize: '12px' } }, String(title).slice(0, 80)),
2959
+ summary ? h('span', { className: 'dar-sub' }, String(summary)) : null),
2960
+ h('div', { className: 'dar-row' },
2961
+ h('span', { className: 'dar-badge off' }, toolName),
2962
+ h('span', { className: 'dar-badge ' + (status === 'completed' ? 'ok' : (status === 'failed' ? 'warn' : 'off')) }, status))),
2963
+ open && resultVal
2964
+ ? h('pre', { className: 'dar-tv-pre' },
2965
+ resultVal.ok === false
2966
+ ? (resultVal.error || JSON.stringify(resultVal, null, 2))
2967
+ : JSON.stringify(resultVal, null, 2))
2968
+ : null)
2969
+ }
2970
+ }
2971
+
2972
+ const RouterPlanToolView = RouterGenericToolView('router_plan')
2973
+ const RouterContinueToolView = RouterGenericToolView('router_continue')
2974
+ const RouterStatusToolView = RouterGenericToolView('router_status')
2975
+
2976
+ function RouterDispatchToolView(props) {
2977
+ const [open, setOpen] = typeof props?.useDisclosure === 'function'
2978
+ ? props.useDisclosure(false)
2979
+ : useState(false)
2980
+ const phase = props?.phase
2981
+ const block = props?.block || {}
2982
+ const callObj = phase === 'result' ? (block.call || {}) : block
2983
+ const args = safeJsonParse(callObj.args?.object || callObj.args) || {}
2984
+ const resultVal = phase === 'result' ? safeJsonParse(block.value ?? block.result) : null
2985
+ const tier = resultVal?.tier || args.tier || 'auto'
2986
+ const routeLabel = resultVal?.route
2987
+ || (resultVal?.backend ? resultVal.backend + (resultVal.model ? '/' + resultVal.model : '') : (args.backend || 'auto'))
2988
+ const status = phase === 'preparing' || phase === 'start'
2989
+ ? 'running'
2990
+ : (resultVal?.mode === 'cli-async' || resultVal?.mode === 'dsh-subagent'
2991
+ ? (resultVal.status || 'dispatched')
2992
+ : (resultVal?.ok === false ? 'failed' : 'completed'))
2993
+
2994
+ return h('div', { className: 'dar-tv' },
2995
+ h('style', null, CSS),
2996
+ h('div', { className: 'dar-tv-head', onClick: () => setOpen(!open) },
2997
+ h('div', { className: 'dar-row' },
2998
+ h('span', { className: 'dar-badge ' + (status === 'completed' ? 'ok' : (status === 'failed' ? 'warn' : 'off')) }, tier),
2999
+ h('strong', { style: { fontSize: '12px' } }, args.description || 'router_dispatch'),
3000
+ h('span', { className: 'dar-sub' }, routeLabel + (resultVal?.durationMs ? ' · ' + resultVal.durationMs + 'ms' : ''))),
3001
+ h('div', { className: 'dar-row' },
3002
+ resultVal?.worktreeDiff?.branch
3003
+ ? h('span', { className: 'dar-badge off' }, resultVal.worktreeDiff.branch)
3004
+ : null,
3005
+ h('span', { className: 'dar-badge ' + (status === 'completed' ? 'ok' : (status === 'failed' ? 'warn' : 'off')) }, status))),
3006
+ open && resultVal
3007
+ ? h('pre', { className: 'dar-tv-pre' },
3008
+ resultVal.ok === false
3009
+ ? (resultVal.error || JSON.stringify(resultVal, null, 2))
3010
+ : (resultVal.output ? String(resultVal.output).slice(0, 2500) : JSON.stringify(resultVal, null, 2)))
3011
+ : null)
3012
+ }
3013
+
3014
+ ctx.effect(() => disposeLocale, 'dsh-agent-router: client locale')
3015
+ ctx.effect(() => {
3016
+ const disposers = [
3017
+ ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
3018
+ name: 'plugins.bundle.config',
3019
+ key: PACKAGE,
3020
+ locale: PACKAGE,
3021
+ }, BundleConfigSection)),
3022
+ ctx.slots.inject('plugins.row.config', () => ctx.slots.register({
3023
+ name: 'plugins.row.config',
3024
+ key: SLOT_KEY,
3025
+ locale: PACKAGE,
3026
+ }, RowConfigSection)),
3027
+ ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
3028
+ name: 'tool.call.toolview',
3029
+ key: 'router_dispatch',
3030
+ locale: PACKAGE,
3031
+ }, RouterDispatchToolView)),
3032
+ ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
3033
+ name: 'tool.call.toolview',
3034
+ key: 'router_plan',
3035
+ locale: PACKAGE,
3036
+ }, RouterPlanToolView)),
3037
+ ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
3038
+ name: 'tool.call.toolview',
3039
+ key: 'router_continue',
3040
+ locale: PACKAGE,
3041
+ }, RouterContinueToolView)),
3042
+ ctx.slots.inject('tool.call.toolview', () => ctx.slots.register({
3043
+ name: 'tool.call.toolview',
3044
+ key: 'router_status',
3045
+ locale: PACKAGE,
3046
+ }, RouterStatusToolView)),
3047
+ ]
3048
+ return () => {
3049
+ disposed = true
3050
+ if (typeof mountDisposer === 'function') {
3051
+ void mountDisposer()
3052
+ mountDisposer = null
3053
+ }
3054
+ for (const dispose of disposers) dispose?.()
3055
+ }
3056
+ }, 'dsh-agent-router: plugin detail routing editor')
3057
+
3058
+ },
3059
+ }
3060
+ },
3061
+ })