dsh-agent-router 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +304 -0
  3. package/README.md +304 -0
  4. package/client.js +3061 -0
  5. package/cordis.patch.yml +20 -0
  6. package/docs/ARCHITECTURE_DIAGNOSIS_AND_PLAN.md +414 -0
  7. package/docs/DETAIL.ja.md +1 -0
  8. package/docs/DETAIL.md +1 -0
  9. package/docs/DETAIL.zh.md +1 -0
  10. package/docs/IMPLEMENTATION_PLAN.md +99 -0
  11. package/docs/ITERATION_PLAN_2026-11.md +377 -0
  12. package/docs/RELEASE.md +133 -0
  13. package/docs/RELEASE_CHECKLIST.md +88 -0
  14. package/docs/preview.svg +69 -0
  15. package/docs/preview.zh.svg +63 -0
  16. package/icon.svg +16 -0
  17. package/index.js +24 -0
  18. package/lib/classifier.js +405 -0
  19. package/lib/cli/discover.js +187 -0
  20. package/lib/cli/invoke.js +294 -0
  21. package/lib/cli/parsers.js +234 -0
  22. package/lib/cli/shared.js +145 -0
  23. package/lib/cli-runners.js +39 -0
  24. package/lib/config-limits.js +67 -0
  25. package/lib/config-normalize.js +147 -0
  26. package/lib/config-presets.js +89 -0
  27. package/lib/config-schema.js +347 -0
  28. package/lib/defaults.js +117 -0
  29. package/lib/diagnose-fallback.js +96 -0
  30. package/lib/error-classify.js +160 -0
  31. package/lib/eval-routing.js +96 -0
  32. package/lib/guardrails.js +70 -0
  33. package/lib/integrations.js +173 -0
  34. package/lib/job-runner.js +287 -0
  35. package/lib/ledger.js +360 -0
  36. package/lib/legacy-config.js +34 -0
  37. package/lib/model-capabilities.js +135 -0
  38. package/lib/model-score.js +65 -0
  39. package/lib/plugin.js +184 -0
  40. package/lib/profile-mount.js +524 -0
  41. package/lib/route-edit.js +82 -0
  42. package/lib/router/candidates.js +194 -0
  43. package/lib/router/catalog.js +121 -0
  44. package/lib/router/cli-select.js +84 -0
  45. package/lib/router/config-manager.js +122 -0
  46. package/lib/router/doctor.js +159 -0
  47. package/lib/router/local-models.js +126 -0
  48. package/lib/router/policy.js +61 -0
  49. package/lib/router/rpc.js +263 -0
  50. package/lib/router/system-prompt.js +29 -0
  51. package/lib/router/tools.js +1028 -0
  52. package/lib/router/util.js +99 -0
  53. package/lib/rpc-contract.js +46 -0
  54. package/lib/sessions.js +59 -0
  55. package/lib/task-queue.js +201 -0
  56. package/lib/tier-presets.js +595 -0
  57. package/lib/typert.host.js +79 -0
  58. package/lib/update-check.js +205 -0
  59. package/lib/worktree-lock.js +86 -0
  60. package/lib/worktree.js +268 -0
  61. package/locale/en.json +7 -0
  62. package/locale/ja.json +7 -0
  63. package/locale/zh.json +7 -0
  64. package/package.json +136 -0
  65. package/scripts/profile-maintenance.mjs +287 -0
@@ -0,0 +1,69 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="760" height="340" viewBox="0 0 760 340">
2
+ <defs>
3
+ <linearGradient id="darBg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0%" stop-color="#0f172a"/>
5
+ <stop offset="100%" stop-color="#1e293b"/>
6
+ </linearGradient>
7
+ <linearGradient id="darAccent" x1="0" y1="0" x2="1" y2="0">
8
+ <stop offset="0%" stop-color="#3b82f6"/>
9
+ <stop offset="100%" stop-color="#10b981"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect width="760" height="340" rx="16" fill="url(#darBg)"/>
13
+ <rect x="20" y="20" width="720" height="300" rx="12" fill="none" stroke="#334155" stroke-width="1"/>
14
+
15
+ <!-- Header -->
16
+ <circle cx="48" cy="48" r="10" fill="#3b82f6" opacity="0.25"/>
17
+ <circle cx="48" cy="48" r="4" fill="#60a5fa"/>
18
+ <text x="68" y="53" fill="#f8fafc" font-family="system-ui,-apple-system,sans-serif" font-size="16" font-weight="600">dsh-agent-router · T1–T4 Difficulty Router</text>
19
+ <rect x="572" y="34" width="144" height="26" rx="13" fill="#1e3a8a" opacity="0.7"/>
20
+ <text x="644" y="51" text-anchor="middle" fill="#93c5fd" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">DSH + Local CLIs</text>
21
+
22
+ <!-- Left: Classifier -->
23
+ <rect x="36" y="88" width="166" height="196" rx="10" fill="#1e293b" stroke="#475569" stroke-width="1"/>
24
+ <text x="119" y="114" text-anchor="middle" fill="#94a3b8" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">TASK CLASSIFIER</text>
25
+ <rect x="52" y="128" width="134" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
26
+ <text x="119" y="147" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">Signals + Scope</text>
27
+ <rect x="52" y="168" width="134" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
28
+ <text x="119" y="187" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">Budget &amp; Peak 2x</text>
29
+ <rect x="52" y="208" width="134" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
30
+ <text x="119" y="227" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">EWMA Latency</text>
31
+ <text x="119" y="266" text-anchor="middle" fill="#38bdf8" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">Auto T1 → T4</text>
32
+
33
+ <!-- Connectors -->
34
+ <path d="M202 186 H238" stroke="url(#darAccent)" stroke-width="2.5"/>
35
+ <path d="M238 112 V260" stroke="#475569" stroke-width="1.5"/>
36
+ <path d="M238 112 H268 M238 161 H268 M238 211 H268 M238 260 H268" stroke="#60a5fa" stroke-width="1.5"/>
37
+
38
+ <!-- Center: Tiers -->
39
+ <rect x="268" y="92" width="212" height="40" rx="8" fill="#064e3b" stroke="#10b981"/>
40
+ <text x="284" y="116" fill="#6ee7b7" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T1</text>
41
+ <text x="312" y="116" fill="#ecfdf5" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">Light · Flash / Eco</text>
42
+
43
+ <rect x="268" y="141" width="212" height="40" rx="8" fill="#1e3a8a" stroke="#3b82f6"/>
44
+ <text x="284" y="165" fill="#93c5fd" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T2</text>
45
+ <text x="312" y="165" fill="#eff6ff" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">Code · Codex / Standard</text>
46
+
47
+ <rect x="268" y="191" width="212" height="40" rx="8" fill="#4c1d95" stroke="#8b5cf6"/>
48
+ <text x="284" y="215" fill="#c4b5fd" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T3</text>
49
+ <text x="312" y="215" fill="#f5f3ff" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">Hard · Reasoner / Opus</text>
50
+
51
+ <rect x="268" y="240" width="212" height="40" rx="8" fill="#78350f" stroke="#f59e0b"/>
52
+ <text x="284" y="264" fill="#fcd34d" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T4</text>
53
+ <text x="312" y="264" fill="#fffbeb" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">Review · Cross-Family</text>
54
+
55
+ <!-- Right Connectors -->
56
+ <path d="M480 112 H514 M480 161 H514 M480 211 H514 M480 260 H514" stroke="#64748b" stroke-width="1.5"/>
57
+ <path d="M514 112 V260 M514 186 H542" stroke="#10b981" stroke-width="1.8"/>
58
+
59
+ <!-- Right: Execution & Safety -->
60
+ <rect x="542" y="88" width="182" height="196" rx="10" fill="#1e293b" stroke="#475569" stroke-width="1"/>
61
+ <text x="633" y="114" text-anchor="middle" fill="#94a3b8" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">ORCHESTRATION</text>
62
+ <rect x="558" y="128" width="150" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
63
+ <text x="633" y="147" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">Cooldown Failover</text>
64
+ <rect x="558" y="168" width="150" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
65
+ <text x="633" y="187" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">Async Queue + Resume</text>
66
+ <rect x="558" y="208" width="150" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
67
+ <text x="633" y="227" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">Git Worktree Merge</text>
68
+ <text x="633" y="266" text-anchor="middle" fill="#34d399" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">Profile Config Sync</text>
69
+ </svg>
@@ -0,0 +1,63 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="760" height="340" viewBox="0 0 760 340">
2
+ <defs>
3
+ <linearGradient id="darBgZh" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0%" stop-color="#0f172a"/>
5
+ <stop offset="100%" stop-color="#1e293b"/>
6
+ </linearGradient>
7
+ <linearGradient id="darAccentZh" x1="0" y1="0" x2="1" y2="0">
8
+ <stop offset="0%" stop-color="#3b82f6"/>
9
+ <stop offset="100%" stop-color="#10b981"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect width="760" height="340" rx="16" fill="url(#darBgZh)"/>
13
+ <rect x="20" y="20" width="720" height="300" rx="12" fill="none" stroke="#334155" stroke-width="1"/>
14
+
15
+ <circle cx="48" cy="48" r="10" fill="#3b82f6" opacity="0.25"/>
16
+ <circle cx="48" cy="48" r="4" fill="#60a5fa"/>
17
+ <text x="68" y="53" fill="#f8fafc" font-family="system-ui,-apple-system,sans-serif" font-size="16" font-weight="600">dsh-agent-router · 多智能体难度路由器</text>
18
+ <rect x="564" y="34" width="152" height="26" rx="13" fill="#1e3a8a" opacity="0.7"/>
19
+ <text x="640" y="51" text-anchor="middle" fill="#93c5fd" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">DSH 原生 + 本机 CLI</text>
20
+
21
+ <rect x="36" y="88" width="166" height="196" rx="10" fill="#1e293b" stroke="#475569" stroke-width="1"/>
22
+ <text x="119" y="114" text-anchor="middle" fill="#94a3b8" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">智能定级与感知</text>
23
+ <rect x="52" y="128" width="134" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
24
+ <text x="119" y="147" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">复杂度与路径信号</text>
25
+ <rect x="52" y="168" width="134" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
26
+ <text x="119" y="187" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">预算与峰谷 2×避让</text>
27
+ <rect x="52" y="208" width="134" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
28
+ <text x="119" y="227" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">EWMA 延迟自适应</text>
29
+ <text x="119" y="266" text-anchor="middle" fill="#38bdf8" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">自动定级 T1 → T4</text>
30
+
31
+ <path d="M202 186 H238" stroke="url(#darAccentZh)" stroke-width="2.5"/>
32
+ <path d="M238 112 V260" stroke="#475569" stroke-width="1.5"/>
33
+ <path d="M238 112 H268 M238 161 H268 M238 211 H268 M238 260 H268" stroke="#60a5fa" stroke-width="1.5"/>
34
+
35
+ <rect x="268" y="92" width="212" height="40" rx="8" fill="#064e3b" stroke="#10b981"/>
36
+ <text x="284" y="116" fill="#6ee7b7" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T1</text>
37
+ <text x="312" y="116" fill="#ecfdf5" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">轻量检索 · Flash / Eco</text>
38
+
39
+ <rect x="268" y="141" width="212" height="40" rx="8" fill="#1e3a8a" stroke="#3b82f6"/>
40
+ <text x="284" y="165" fill="#93c5fd" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T2</text>
41
+ <text x="312" y="165" fill="#eff6ff" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">标准编码 · Codex / 单测</text>
42
+
43
+ <rect x="268" y="191" width="212" height="40" rx="8" fill="#4c1d95" stroke="#8b5cf6"/>
44
+ <text x="284" y="215" fill="#c4b5fd" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T3</text>
45
+ <text x="312" y="215" fill="#f5f3ff" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">困难架构 · Reasoner / Opus</text>
46
+
47
+ <rect x="268" y="240" width="212" height="40" rx="8" fill="#78350f" stroke="#f59e0b"/>
48
+ <text x="284" y="264" fill="#fcd34d" font-family="system-ui,-apple-system,sans-serif" font-size="12" font-weight="700">T4</text>
49
+ <text x="312" y="264" fill="#fffbeb" font-family="system-ui,-apple-system,sans-serif" font-size="11.5">交叉审查 · 异构独立验收</text>
50
+
51
+ <path d="M480 112 H514 M480 161 H514 M480 211 H514 M480 260 H514" stroke="#64748b" stroke-width="1.5"/>
52
+ <path d="M514 112 V260 M514 186 H542" stroke="#10b981" stroke-width="1.8"/>
53
+
54
+ <rect x="542" y="88" width="182" height="196" rx="10" fill="#1e293b" stroke="#475569" stroke-width="1"/>
55
+ <text x="633" y="114" text-anchor="middle" fill="#94a3b8" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">可靠执行与闭环</text>
56
+ <rect x="558" y="128" width="150" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
57
+ <text x="633" y="147" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">熔断冷却 + 失败升阶</text>
58
+ <rect x="558" y="168" width="150" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
59
+ <text x="633" y="187" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">异步队列 + 会话续接</text>
60
+ <rect x="558" y="208" width="150" height="30" rx="6" fill="#0f172a" stroke="#334155"/>
61
+ <text x="633" y="227" text-anchor="middle" fill="#e2e8f0" font-family="system-ui,-apple-system,sans-serif" font-size="11">Worktree 审查与合入</text>
62
+ <text x="633" y="266" text-anchor="middle" fill="#34d399" font-family="system-ui,-apple-system,sans-serif" font-size="11" font-weight="600">Profile 原生配置同步</text>
63
+ </svg>
package/icon.svg ADDED
@@ -0,0 +1,16 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
2
+ <title>DSH Agent Router</title>
3
+ <g fill="none" stroke="#3b6ef5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
4
+ <circle cx="8" cy="18" r="3.5"/>
5
+ <rect x="24.5" y="5.5" width="7" height="5.5" rx="1.5"/>
6
+ <rect x="24.5" y="15.25" width="7" height="5.5" rx="1.5"/>
7
+ <rect x="24.5" y="25" width="7" height="5.5" rx="1.5"/>
8
+ <path d="M11.5 18h4.5c2 0 3-9.75 5-9.75h3.5"/>
9
+ <path d="M11.5 18h13"/>
10
+ <path d="M11.5 18h4.5c2 0 3 9.75 5 9.75h3.5"/>
11
+ </g>
12
+ <circle cx="8" cy="18" r="1.4" fill="#3b6ef5"/>
13
+ <circle cx="28" cy="8.25" r="1.1" fill="#10b981"/>
14
+ <circle cx="28" cy="18" r="1.1" fill="#3b6ef5"/>
15
+ <circle cx="28" cy="27.75" r="1.1" fill="#f59e0b"/>
16
+ </svg>
package/index.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Multi-agent orchestration and difficulty-based model router for DeepSeek Harness.
3
+ *
4
+ * This module is intentionally thin: it only declares the plugin surface
5
+ * (`name`, `Config`, `inject`, `apply`). Composition lives in `lib/plugin.js`
6
+ * and the route/catalog/policy/tool/RPC domains in `lib/router/*`.
7
+ *
8
+ * Zero external npm imports by design so `link:` workspace installs resolve cleanly.
9
+ * @module dsh-agent-router
10
+ */
11
+
12
+ import { Config as RouterConfigSchema } from './lib/config-schema.js'
13
+ import { install } from './lib/plugin.js'
14
+ import { toLosslessJson } from './lib/router/util.js'
15
+
16
+ export const name = 'dsh-agent-router'
17
+ export const Config = RouterConfigSchema
18
+ export const inject = ['tools', 'systemPrompt', 'subagents', 'agents']
19
+
20
+ export { toLosslessJson }
21
+
22
+ export function apply(ctx, raw) {
23
+ install(ctx, raw)
24
+ }
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Task difficulty classifier and default multi-agent routing policies.
3
+ * Tiers are configurable; T1-T4 remain the default presets.
4
+ * @module dsh-agent-router/lib/classifier
5
+ */
6
+
7
+ export const TIERS = ['T1', 'T2', 'T3', 'T4']
8
+ export const DOMAINS = ['general', 'code', 'research', 'review']
9
+
10
+ import { DEFAULT_TIER_POLICIES } from './defaults.js'
11
+ import { scoreModelForTier } from './model-score.js'
12
+ import {
13
+ normalizeTierEntries,
14
+ nextNormalTier,
15
+ resolveTierRef,
16
+ sortTierEntries,
17
+ sortedNormalTiers,
18
+ tierKeyForScoring,
19
+ } from './tier-presets.js'
20
+
21
+ export { DEFAULT_TIER_POLICIES }
22
+
23
+ const REVIEW_RE = /\b(review|audit|critique|verify|inspect|second opinion|security check|diff check|penetration|pentest)\b|代码审查|评审|复核|审计|验收|挑刺|第二意见|交叉验证|安全检查/iu
24
+ // Mutating action verbs. A task that asks for changes must not be routed to a
25
+ // read-only review tier just because it mentions "review" (e.g. "fix the bug
26
+ // found in review"). Noun forms ("changes", "updated") are intentionally not
27
+ // matched, so a pure review of recent changes still counts as review intent.
28
+ const ACTION_RE = /\b(fix|implement|add|create|build|refactor|rename|rewrite|write|patch|apply|update|change|remove|delete|drop|migrate|upgrade|merge|commit|deploy|install|generate|repair|resolve|address|modify)\b|修复|实现|新增|添加|创建|重构|改名|重命名|改写|编写|修改|更新|更换|删除|移除|合并|提交|部署|安装|生成|补上|加上|改成|调整为/iu
29
+ const RESEARCH_RE = /\b(search|summarize|summary|extract|scan|grep|find|list|overview|explain|translate|read)\b|搜索|检索|查找|总结|摘要|梳理|扫描|翻译|整理|统计/iu
30
+ const CODE_RE = /\b(implement|fix|bug|test|refactor|write|build|create|patch|script|endpoint|plugin|module|migrate)\b|实现|修复|编写|测试|重构|开发|脚本|接口|插件|模块|迁移|调试/iu
31
+ const HARD_RE = /\b(architect|architecture|cross[-\s]?module|multi[-\s]?file|system design|concurrency|race condition|deadlock|reverse|deobfuscate|security|vulnerability|root cause|distributed|kernel|compiler|migration plan|deep debug|memory leak|stack overflow|segfault)\b|架构|跨模块|多模块|并发|竞态|死锁|逆向|混淆|安全|漏洞|根因|疑难|复杂|全链路|迁移方案|大型重构|内存泄漏/iu
32
+ const LOCAL_REFACTOR_RE = /\b(extract helper|extract function|rename variable|clean up|simplify function|split helper)\b|局部重构|提取函数|简化函数|拆分辅助/iu
33
+ const EASY_RE = /\b(typo|rename|format|lint|readme|comment|docstring|list files|count|simple|quick|trivial|one[-\s]?liner)\b|拼写|重命名|格式化|注释|简单|快速|列出|统计行数|摘要|翻译/iu
34
+ const FILE_PATH_RE = /(?:[A-Za-z]:\\|\/|\b[\w.-]+\/)+[\w.-]+\.(?:[cm]?[jt]sx?|py|rs|go|java|jsonc?|ya?ml|md|css|html|sh|ps1|toml)\b/gi
35
+ const NEGATION_RE = /\b(no|not|without|never|don't|dont|avoid)\b|无需|不需要|不要|不用|避免|排除/iu
36
+ const FENCED_CODE_RE = /```[\s\S]*?```|`[^`\n]*`/g
37
+
38
+ /**
39
+ * Per-domain signal weights. Review is handled before scoring; the table keeps
40
+ * code/general slightly more sensitive to hard signals than read-only research.
41
+ */
42
+ const DOMAIN_WEIGHTS = Object.freeze({
43
+ code: { hard: 1.5, easy: 1.0, length: 0.4, bullets: 0.35, paths: 0.35, short: 0.5, structuralCap: 0.9 },
44
+ research: { hard: 1.1, easy: 1.2, length: 0.3, bullets: 0.25, paths: 0.2, short: 0.6, structuralCap: 0.7 },
45
+ general: { hard: 1.4, easy: 1.0, length: 0.4, bullets: 0.35, paths: 0.35, short: 0.5, structuralCap: 0.9 },
46
+ review: { hard: 1.5, easy: 1.0, length: 0.4, bullets: 0.35, paths: 0.35, short: 0.5, structuralCap: 0.9 },
47
+ })
48
+
49
+ function round(value, digits = 2) {
50
+ const factor = 10 ** digits
51
+ return Math.round(value * factor) / factor
52
+ }
53
+
54
+ function unique(values) {
55
+ return [...new Set(values)]
56
+ }
57
+
58
+ /**
59
+ * Drop fenced/inline code from the semantic scan. A pasted stack trace or log
60
+ * should not classify a task as hard merely because it mentions "deadlock".
61
+ */
62
+ function stripCodeBlocks(text) {
63
+ return text.replace(FENCED_CODE_RE, ' ')
64
+ }
65
+
66
+ function keywordMatches(regex, text, { negation = false } = {}) {
67
+ const flags = regex.flags.includes('g') ? regex.flags : regex.flags + 'g'
68
+ const matches = []
69
+ for (const match of text.matchAll(new RegExp(regex.source, flags))) {
70
+ const index = match.index ?? 0
71
+ if (negation) {
72
+ const before = text.slice(Math.max(0, index - 28), index)
73
+ if (NEGATION_RE.test(before)) continue
74
+ }
75
+ matches.push({ value: match[0], index })
76
+ }
77
+ return matches
78
+ }
79
+
80
+ function detectDomainFrom(text) {
81
+ const semanticText = stripCodeBlocks(text)
82
+ const reviewHit = keywordMatches(REVIEW_RE, semanticText, { negation: true }).length > 0
83
+ const actionHit = keywordMatches(ACTION_RE, semanticText, { negation: true }).length > 0
84
+ if (reviewHit && !actionHit) return 'review'
85
+ if (keywordMatches(CODE_RE, semanticText).length > 0 || keywordMatches(LOCAL_REFACTOR_RE, semanticText).length > 0) return 'code'
86
+ if (keywordMatches(RESEARCH_RE, semanticText).length > 0) return 'research'
87
+ return 'general'
88
+ }
89
+
90
+ /**
91
+ * Detect domain from task text when omitted.
92
+ * @param {string} text
93
+ * @returns {'general'|'code'|'research'|'review'}
94
+ */
95
+ export function detectDomain(text) {
96
+ return detectDomainFrom(String(text ?? ''))
97
+ }
98
+
99
+ function resolveTierMap(tiers) {
100
+ if (tiers && typeof tiers === 'object' && !Array.isArray(tiers) && Object.keys(tiers).length > 0) {
101
+ return tiers
102
+ }
103
+ return DEFAULT_TIER_POLICIES
104
+ }
105
+
106
+ function tierNameOf(entry, id) {
107
+ return entry?.name || entry?.label || id
108
+ }
109
+
110
+ function boundsOf(normalEntries) {
111
+ return normalEntries.map(([id, entry]) => ({
112
+ id,
113
+ name: tierNameOf(entry, id),
114
+ minScore: entry.minScore,
115
+ maxScore: entry.maxScore,
116
+ }))
117
+ }
118
+
119
+ function thresholdsOf(normalEntries) {
120
+ return {
121
+ t1Max: normalEntries[0]?.[1]?.maxScore ?? null,
122
+ t3Min: normalEntries[1]?.[1]?.minScore ?? null,
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Classify task difficulty into the configured tiers with weighted, explainable signals.
128
+ *
129
+ * Rules are deterministic and local: intent keywords are matched outside code
130
+ * fences, negated hard signals are skipped, and structural signals are capped.
131
+ * Low confidence near the next tier boundary promotes when several complexity
132
+ * signals agree, so confidence is part of the decision rather than a label.
133
+ *
134
+ * @param {{ task: string, tier?: string, domain?: string, tiers?: Record<string, any> }} input
135
+ * @returns {{
136
+ * tier: string, tierName: string, domain: string, score: number,
137
+ * confidence: 'high'|'medium'|'low', confidenceScore: number,
138
+ * boundaryMargin: number, promoted: boolean, tierBeforePromotion?: string,
139
+ * signals: Array<{ id: string, delta: number, detail: string }>,
140
+ * reasons: string[], source: 'explicit'|'auto',
141
+ * thresholds: { t1Max: number|null, t3Min: number|null },
142
+ * bounds: Array<{ id: string, name: string, minScore: number, maxScore: number|null }>,
143
+ * }}
144
+ */
145
+ export function classifyTask(input) {
146
+ const text = String(input?.task ?? '').trim()
147
+ const semanticText = stripCodeBlocks(text)
148
+ const domain = DOMAINS.includes(input?.domain) ? input.domain : detectDomainFrom(text)
149
+ let tiers = resolveTierMap(input?.tiers)
150
+ let normalEntries = sortedNormalTiers(tiers)
151
+ if (normalEntries.length === 0) {
152
+ tiers = DEFAULT_TIER_POLICIES
153
+ normalEntries = sortedNormalTiers(tiers)
154
+ }
155
+ const thresholds = thresholdsOf(normalEntries)
156
+ const bounds = boundsOf(normalEntries)
157
+
158
+ const explicitId = resolveTierRef(input?.tier, tiers)
159
+ if (explicitId) {
160
+ const entry = tiers[explicitId]
161
+ const name = tierNameOf(entry, explicitId)
162
+ return {
163
+ tier: explicitId,
164
+ tierName: name,
165
+ domain,
166
+ score: Number.isFinite(entry.minScore) ? entry.minScore : normalEntries.length + 1,
167
+ confidence: 'high',
168
+ confidenceScore: 1,
169
+ boundaryMargin: 1.5,
170
+ promoted: false,
171
+ signals: [{ id: 'explicit_tier', delta: 0, detail: `explicitly requested ${name} (${explicitId})` }],
172
+ reasons: [`explicitly requested ${name} (${explicitId})`],
173
+ source: 'explicit',
174
+ thresholds,
175
+ bounds,
176
+ }
177
+ }
178
+
179
+ if (domain === 'review') {
180
+ // Several review tiers are allowed; pick the first in sorted (id) order so
181
+ // the result never depends on object key order.
182
+ const reviewId = sortTierEntries(tiers).find(([, entry]) => entry?.role === 'review')?.[0]
183
+ || normalEntries[normalEntries.length - 1]?.[0]
184
+ const reviewEntry = tiers[reviewId]
185
+ const name = tierNameOf(reviewEntry, reviewId)
186
+ return {
187
+ tier: reviewId,
188
+ tierName: name,
189
+ domain,
190
+ score: Number.isFinite(reviewEntry?.minScore) ? reviewEntry.minScore : normalEntries.length + 1,
191
+ confidence: 'high',
192
+ confidenceScore: 1,
193
+ boundaryMargin: 1.5,
194
+ promoted: false,
195
+ signals: [{ id: 'review_intent', delta: 4, detail: 'review/audit intent' }],
196
+ reasons: ['review/audit intent detected'],
197
+ source: 'auto',
198
+ thresholds,
199
+ bounds,
200
+ }
201
+ }
202
+
203
+ const hardHits = keywordMatches(HARD_RE, semanticText, { negation: true })
204
+ const easyHits = keywordMatches(EASY_RE, semanticText)
205
+ const codeHits = keywordMatches(CODE_RE, semanticText)
206
+ const localHits = keywordMatches(LOCAL_REFACTOR_RE, semanticText)
207
+ const weights = DOMAIN_WEIGHTS[domain] || DOMAIN_WEIGHTS.general
208
+ const signals = []
209
+ const reasons = []
210
+
211
+ if (hardHits.length > 0) {
212
+ let delta = weights.hard
213
+ let detail = unique(hardHits.map(hit => hit.value.toLowerCase())).slice(0, 4).join(', ')
214
+ if (domain === 'research' && codeHits.length === 0) {
215
+ delta *= 0.75
216
+ detail += ' (damped for read-only research intent)'
217
+ }
218
+ signals.push({ id: 'hard', delta: round(delta), detail })
219
+ reasons.push('high-complexity engineering signals matched')
220
+ }
221
+
222
+ const isLocalRefactor = localHits.length > 0 && hardHits.length === 0
223
+ if (isLocalRefactor) {
224
+ signals.push({
225
+ id: 'local_refactor',
226
+ delta: 0,
227
+ detail: unique(localHits.map(hit => hit.value.toLowerCase())).join(', '),
228
+ })
229
+ reasons.push('scoped local refactor signal matched')
230
+ }
231
+
232
+ if (easyHits.length > 0 || (domain === 'research' && hardHits.length === 0)) {
233
+ signals.push({
234
+ id: 'easy',
235
+ delta: -weights.easy,
236
+ detail: easyHits.length > 0
237
+ ? unique(easyHits.map(hit => hit.value.toLowerCase())).slice(0, 4).join(', ')
238
+ : 'research/summary intent',
239
+ })
240
+ reasons.push('lightweight reconnaissance/summary signals matched')
241
+ }
242
+
243
+ if (semanticText.length > 1500) {
244
+ signals.push({ id: 'length', delta: weights.length, detail: `${semanticText.length} chars` })
245
+ reasons.push('long detailed specification (>1500 chars)')
246
+ } else if (semanticText.length < 180 && hardHits.length === 0 && codeHits.length === 0 && !isLocalRefactor) {
247
+ signals.push({ id: 'short', delta: -weights.short, detail: `${semanticText.length} chars` })
248
+ reasons.push('short bounded prompt')
249
+ }
250
+
251
+ const bulletCount = (semanticText.match(/(?:^|\n)\s*(?:[-*]|\d+\.)\s+/g) || []).length
252
+ if (bulletCount >= 5) {
253
+ signals.push({ id: 'bullets', delta: weights.bullets, detail: `${bulletCount} items` })
254
+ reasons.push(`multi-requirement checklist (${bulletCount} items)`)
255
+ }
256
+
257
+ const uniquePaths = new Set((semanticText.match(new RegExp(FILE_PATH_RE.source, 'gi')) || []).map(path => path.toLowerCase()))
258
+ if (uniquePaths.size >= 4) {
259
+ signals.push({ id: 'paths', delta: weights.paths, detail: `${uniquePaths.size} files` })
260
+ reasons.push(`multi-file scope (${uniquePaths.size} paths referenced)`)
261
+ }
262
+
263
+ if (text.includes('```')) {
264
+ signals.push({ id: 'code_block', delta: 0, detail: 'fenced code/log content ignored for intent keywords' })
265
+ }
266
+
267
+ const structuralTotal = signals
268
+ .filter(signal => signal.id === 'length' || signal.id === 'bullets' || signal.id === 'paths')
269
+ .reduce((sum, signal) => sum + signal.delta, 0)
270
+ if (structuralTotal > weights.structuralCap) {
271
+ signals.push({
272
+ id: 'structural_cap',
273
+ delta: round(weights.structuralCap - structuralTotal),
274
+ detail: `structural signals capped at ${weights.structuralCap}`,
275
+ })
276
+ reasons.push(`structural signals capped at ${weights.structuralCap}`)
277
+ }
278
+
279
+ if (hardHits.length > 0 && easyHits.length > 0) {
280
+ reasons.push('conflicting lightweight and high-complexity signals')
281
+ }
282
+
283
+ const score = round(2 + signals.reduce((sum, signal) => sum + signal.delta, 0))
284
+ let chosen = normalEntries[0]
285
+ for (const entry of normalEntries) {
286
+ if (score >= (entry[1].minScore ?? 0)) chosen = entry
287
+ }
288
+ let tier = chosen[0]
289
+ let tierName = tierNameOf(chosen[1], tier)
290
+
291
+ const boundaries = unique(normalEntries.flatMap(([, entry]) => {
292
+ const values = []
293
+ if (Number.isFinite(entry.maxScore)) values.push(entry.maxScore)
294
+ if (Number.isFinite(entry.minScore) && entry.minScore > 0) values.push(entry.minScore)
295
+ return values
296
+ }))
297
+ const margin = boundaries.length > 0
298
+ ? Math.min(...boundaries.map(boundary => Math.abs(score - boundary)))
299
+ : 1.5
300
+ const confidence = margin >= 0.75 ? 'high' : (margin >= 0.35 ? 'medium' : 'low')
301
+ const confidenceScore = round(Math.min(1, margin / 1.5))
302
+ const positiveSignals = signals.filter(signal => signal.delta > 0).length
303
+ let promoted = false
304
+ let tierBeforePromotion
305
+ const tierIndex = normalEntries.findIndex(([id]) => id === tier)
306
+ const nextTier = tierIndex >= 0 ? normalEntries[tierIndex + 1] : null
307
+ if (
308
+ tierIndex >= 1
309
+ && nextTier
310
+ && confidence === 'low'
311
+ && score >= (nextTier[1].minScore ?? 0) - 0.35
312
+ && score < (nextTier[1].minScore ?? 0)
313
+ && positiveSignals >= 2
314
+ && (domain === 'code' || domain === 'general')
315
+ ) {
316
+ tierBeforePromotion = tier
317
+ tier = nextTier[0]
318
+ tierName = tierNameOf(nextTier[1], tier)
319
+ promoted = true
320
+ reasons.push(`low confidence near the ${tierName} boundary with multiple complexity signals; promoted to ${tier} (${tierName})`)
321
+ }
322
+
323
+ if (reasons.length === 0) reasons.push('standard single-scope task baseline')
324
+ return {
325
+ tier,
326
+ tierName,
327
+ domain,
328
+ score,
329
+ confidence,
330
+ confidenceScore,
331
+ boundaryMargin: round(margin),
332
+ promoted,
333
+ ...(promoted ? { tierBeforePromotion } : {}),
334
+ signals,
335
+ reasons,
336
+ source: 'auto',
337
+ thresholds,
338
+ bounds,
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Return the next tier for failure escalation, or null when already top-tier.
344
+ *
345
+ * With a tier map, an explicit valid `escalateTo` wins; otherwise the next
346
+ * normal tier by score order is used. The legacy two-argument-free call keeps
347
+ * the original T1 → T2 → T3 behavior.
348
+ *
349
+ * @param {string} tier
350
+ * @param {Record<string, any>} [tiers]
351
+ * @returns {string|null}
352
+ */
353
+ export function nextEscalationTier(tier, tiers) {
354
+ if (!tiers || typeof tiers !== 'object') {
355
+ if (tier === 'T1') return 'T2'
356
+ if (tier === 'T2') return 'T3'
357
+ return null
358
+ }
359
+ const entry = tiers[tier]
360
+ if (!entry) return null
361
+ if (entry.escalateTo === null) return null
362
+ if (typeof entry.escalateTo === 'string' && entry.escalateTo !== tier && tiers[entry.escalateTo]) {
363
+ return entry.escalateTo
364
+ }
365
+ return nextNormalTier(tier, tiers)
366
+ }
367
+
368
+ /**
369
+ * Merge user-configured tier overrides over defaults.
370
+ * @param {Record<string, any>} [override]
371
+ * @returns {typeof DEFAULT_TIER_POLICIES}
372
+ */
373
+ export function mergeTierPolicies(override) {
374
+ return normalizeTierEntries(override, {
375
+ authoritative: false,
376
+ baseTiers: DEFAULT_TIER_POLICIES,
377
+ }).tiers
378
+ }
379
+
380
+ /**
381
+ * Recommend ordered DSH routes for a given tier from a live catalog array
382
+ * (`[{ id: providerId, models: [{ id: modelId, efforts?: string[] }] }]`).
383
+ */
384
+ export function recommendCatalogRoutes(catalog, { tier, tiers, parentRoute = null, limit = 4 } = {}) {
385
+ if (!Array.isArray(catalog) || catalog.length === 0) return []
386
+ const scoreTier = tiers ? tierKeyForScoring(tier, tiers) : tier
387
+ const candidates = []
388
+ for (const prov of catalog) {
389
+ if (!prov?.id || !Array.isArray(prov.models)) continue
390
+ for (const m of prov.models) {
391
+ if (!m?.id) continue
392
+ const score = scoreModelForTier(m.id, scoreTier, parentRoute?.model)
393
+ if (score <= -50) continue
394
+ candidates.push({
395
+ kind: 'dsh',
396
+ provider: prov.id,
397
+ model: m.id,
398
+ score,
399
+ note: `Auto-matched from live catalog (${tier})`,
400
+ })
401
+ }
402
+ }
403
+ candidates.sort((a, b) => b.score - a.score)
404
+ return candidates.slice(0, limit).map(({ score: _score, ...rest }) => rest)
405
+ }