@skathio/somi 4.1.0 → 5.0.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 (372) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +8 -3
  3. package/.claude-plugin/plugin.json +9 -10
  4. package/.copilot-extension/extension.json +32 -40
  5. package/.copilot-extension/marketplace.json +8 -3
  6. package/README.md +83 -228
  7. package/VERSION +1 -1
  8. package/agents/somi-reviewer.md +21 -40
  9. package/agents/somi-security-reviewer.md +16 -90
  10. package/agents/somi-worker-high.md +11 -0
  11. package/agents/somi-worker-low.md +11 -0
  12. package/agents/somi-worker-medium.md +11 -0
  13. package/agents/somi.md +8 -75
  14. package/commands/somi-config.md +5 -14
  15. package/commands/somi-deliver.md +11 -0
  16. package/commands/somi-quality.md +10 -0
  17. package/commands/somi-review.md +10 -0
  18. package/commands/somi-status.md +11 -0
  19. package/commands/somi.md +10 -0
  20. package/hooks/hooks.json +28 -23
  21. package/hooks/lib/common.mjs +45 -34
  22. package/hooks/pre-tool/apply-tier.mjs +31 -0
  23. package/hooks/pre-tool/block-dangerous-bash.mjs +15 -0
  24. package/hooks/pre-tool/gate-dep-install.mjs +2 -2
  25. package/hooks/pre-tool/guard-protected-paths.mjs +9 -16
  26. package/hooks/pre-tool/guard-tier-config.mjs +17 -0
  27. package/hooks/pre-tool/reviewers-read-only.mjs +11 -0
  28. package/hooks/session-start/inject-digest.mjs +51 -0
  29. package/hooks/stop/review-due.mjs +40 -0
  30. package/hooks/user-prompt/capture-prompt.mjs +17 -0
  31. package/library/lenses/architecture.md +1 -0
  32. package/library/lenses/test-strategy.md +1 -0
  33. package/library/roles/accessibility.md +1 -0
  34. package/library/roles/answer.md +1 -0
  35. package/library/roles/atlas.md +1 -0
  36. package/library/roles/build.md +1 -0
  37. package/library/roles/debug.md +6 -0
  38. package/library/roles/design.md +1 -0
  39. package/library/roles/discover.md +1 -0
  40. package/library/roles/incident.md +1 -0
  41. package/library/roles/migrate.md +1 -0
  42. package/library/roles/perf.md +1 -0
  43. package/library/roles/plan.md +1 -0
  44. package/library/roles/refactor.md +1 -0
  45. package/library/roles/review.md +1 -0
  46. package/library/roles/security-review.md +1 -0
  47. package/library/roles/upgrade.md +1 -0
  48. package/library/skills/accessibility.md +16 -0
  49. package/library/skills/ci-infra-gotchas.md +12 -0
  50. package/library/skills/perf-method.md +10 -0
  51. package/library/skills/secure-coding.md +18 -0
  52. package/library/skills/testing-checklist.md +16 -0
  53. package/library/skills/threat-modeling.md +10 -0
  54. package/package.json +12 -17
  55. package/profiles/claude.json +21 -0
  56. package/profiles/copilot.json +5 -0
  57. package/rules/digest.md +40 -0
  58. package/scripts/check-links.mjs +65 -76
  59. package/scripts/lib/advisor.mjs +207 -0
  60. package/scripts/lib/check.mjs +165 -0
  61. package/scripts/lib/copilot-workflow.mjs +41 -0
  62. package/scripts/lib/doctor.mjs +91 -0
  63. package/scripts/lib/gates.mjs +69 -0
  64. package/scripts/lib/git-tree.mjs +201 -0
  65. package/scripts/lib/init.mjs +23 -0
  66. package/scripts/lib/ledger.mjs +38 -0
  67. package/scripts/lib/mcp-project-root.mjs +63 -67
  68. package/scripts/lib/migrate.mjs +73 -0
  69. package/scripts/lib/path-facts.mjs +2 -2
  70. package/scripts/lib/path-safety.mjs +6 -134
  71. package/scripts/lib/plan.mjs +69 -0
  72. package/scripts/lib/policy.mjs +103 -0
  73. package/scripts/lib/pr.mjs +28 -0
  74. package/scripts/lib/prompt.mjs +72 -0
  75. package/scripts/lib/quality/clones.mjs +76 -0
  76. package/scripts/lib/quality/css.mjs +43 -0
  77. package/scripts/lib/quality/gate.mjs +230 -0
  78. package/scripts/lib/quality/limits.mjs +73 -0
  79. package/scripts/lib/quality/metrics.mjs +159 -0
  80. package/scripts/lib/quality/parse.mjs +73 -0
  81. package/scripts/lib/quality/repo.mjs +69 -0
  82. package/scripts/lib/quality/run.mjs +38 -0
  83. package/scripts/lib/reviews.mjs +132 -0
  84. package/scripts/lib/routes.mjs +108 -0
  85. package/scripts/lib/setup.mjs +34 -0
  86. package/scripts/lib/shards.mjs +166 -0
  87. package/scripts/lib/signals.mjs +110 -0
  88. package/scripts/lib/state.mjs +42 -0
  89. package/scripts/lib/tiers.mjs +42 -0
  90. package/scripts/lib/update-notice.mjs +48 -0
  91. package/scripts/lib/views.mjs +62 -0
  92. package/scripts/lib/workflows.mjs +56 -0
  93. package/scripts/somi-mcp.mjs +181 -323
  94. package/scripts/somi.mjs +208 -0
  95. package/scripts/vendor/tree-sitter/LICENSE.vscode-tree-sitter-wasm +21 -0
  96. package/scripts/vendor/tree-sitter/LICENSE.web-tree-sitter +21 -0
  97. package/scripts/vendor/tree-sitter/cgmanifest.vscode-tree-sitter-wasm.json +16 -0
  98. package/scripts/vendor/tree-sitter/manifest.json +59 -0
  99. package/scripts/vendor/tree-sitter/package.json +3 -0
  100. package/scripts/vendor/tree-sitter/tree-sitter-css.wasm +0 -0
  101. package/scripts/vendor/tree-sitter/tree-sitter-javascript.wasm +0 -0
  102. package/scripts/vendor/tree-sitter/tree-sitter-tsx.wasm +0 -0
  103. package/scripts/vendor/tree-sitter/tree-sitter-typescript.wasm +0 -0
  104. package/scripts/vendor/tree-sitter/web-tree-sitter.js +4081 -0
  105. package/scripts/vendor/tree-sitter/web-tree-sitter.wasm +0 -0
  106. package/skills/somi-expertise/SKILL.md +6 -0
  107. package/workflows/deliver-stages.js +81 -0
  108. package/.claude/settings.json +0 -131
  109. package/agents/somi-architecture-reviewer.md +0 -101
  110. package/agents/somi-atlas.md +0 -100
  111. package/agents/somi-coder.md +0 -60
  112. package/agents/somi-designer.md +0 -36
  113. package/agents/somi-discovery-analyst.md +0 -57
  114. package/agents/somi-flow.md +0 -47
  115. package/agents/somi-general.md +0 -36
  116. package/agents/somi-impact.md +0 -95
  117. package/agents/somi-incident.md +0 -94
  118. package/agents/somi-plan-reviewer.md +0 -68
  119. package/agents/somi-planner.md +0 -57
  120. package/agents/somi-pr.md +0 -99
  121. package/agents/somi-refactor-designer.md +0 -81
  122. package/agents/somi-refactorer.md +0 -99
  123. package/agents/somi-sdlc-reviewer.md +0 -67
  124. package/agents/somi-test-strategist.md +0 -87
  125. package/commands/adopt.md +0 -14
  126. package/commands/architecture-review.md +0 -19
  127. package/commands/atlas.md +0 -19
  128. package/commands/code-loop.md +0 -19
  129. package/commands/code-parallel.md +0 -19
  130. package/commands/code.md +0 -19
  131. package/commands/debug.md +0 -19
  132. package/commands/design.md +0 -19
  133. package/commands/discover.md +0 -19
  134. package/commands/impact.md +0 -19
  135. package/commands/incident.md +0 -19
  136. package/commands/plan-loop.md +0 -19
  137. package/commands/plan.md +0 -19
  138. package/commands/pr.md +0 -19
  139. package/commands/refactor-design.md +0 -19
  140. package/commands/refactor.md +0 -19
  141. package/commands/release-readiness.md +0 -19
  142. package/commands/review-panel.md +0 -19
  143. package/commands/review.md +0 -19
  144. package/commands/security-review.md +0 -19
  145. package/commands/ship-loop.md +0 -19
  146. package/commands/ship.md +0 -19
  147. package/commands/test-strategy.md +0 -19
  148. package/commands/upgrade.md +0 -19
  149. package/examples/README.md +0 -19
  150. package/examples/code-review-example.md +0 -88
  151. package/examples/discovery-example.md +0 -200
  152. package/examples/feature-plan-example.md +0 -377
  153. package/examples/full-pipeline-example.md +0 -188
  154. package/examples/sample-consumer/.claude/settings.json +0 -29
  155. package/examples/sample-consumer/CLAUDE.md +0 -78
  156. package/examples/sample-consumer/README.md +0 -102
  157. package/hooks/post-tool/lint-changed-files.mjs +0 -209
  158. package/hooks/pre-tool/guard-cost-lowering.mjs +0 -192
  159. package/hooks/session-start/detect-repo-instructions.mjs +0 -287
  160. package/hooks/session-start/ensure-default-config.mjs +0 -113
  161. package/hooks/user-prompt-submit/inject-workflow-context.mjs +0 -580
  162. package/rules/00-priorities.md +0 -48
  163. package/rules/10-solid.md +0 -87
  164. package/rules/20-clean-code.md +0 -62
  165. package/rules/30-security-owasp.md +0 -83
  166. package/rules/40-engineering-practices.md +0 -65
  167. package/rules/50-collaboration.md +0 -114
  168. package/rules/99-overrides.md +0 -52
  169. package/rules/CLAUDE.md +0 -200
  170. package/scripts/check-session-artefacts.mjs +0 -149
  171. package/scripts/check-size-budget.mjs +0 -137
  172. package/scripts/generate-digest.mjs +0 -176
  173. package/scripts/lib/agent-info.mjs +0 -85
  174. package/scripts/lib/agent-registry.mjs +0 -92
  175. package/scripts/lib/cost-ceiling.mjs +0 -328
  176. package/scripts/lib/cost-config-edit.mjs +0 -102
  177. package/scripts/lib/cost-config.mjs +0 -64
  178. package/scripts/lib/cost-defaults.mjs +0 -53
  179. package/scripts/lib/cost-lowering.mjs +0 -89
  180. package/scripts/lib/cost-model.mjs +0 -110
  181. package/scripts/lib/dispatch-resolver.mjs +0 -243
  182. package/scripts/lib/escalation-facts.mjs +0 -146
  183. package/scripts/lib/escalation.mjs +0 -129
  184. package/scripts/lib/findings-ledger.mjs +0 -241
  185. package/scripts/lib/install-text.mjs +0 -97
  186. package/scripts/lib/loop-caps.mjs +0 -140
  187. package/scripts/lib/loop-diff.mjs +0 -38
  188. package/scripts/lib/loop-dispatch.mjs +0 -19
  189. package/scripts/lib/loop-engine.mjs +0 -226
  190. package/scripts/lib/loop-escalate.mjs +0 -49
  191. package/scripts/lib/loop-exit.mjs +0 -47
  192. package/scripts/lib/loop-notes-compact.mjs +0 -72
  193. package/scripts/lib/loop-notes.mjs +0 -278
  194. package/scripts/lib/loop-review.mjs +0 -395
  195. package/scripts/lib/loop-state.mjs +0 -44
  196. package/scripts/lib/loop-step-close.mjs +0 -75
  197. package/scripts/lib/loop-step-kit.mjs +0 -179
  198. package/scripts/lib/loop-step-review.mjs +0 -140
  199. package/scripts/lib/loop-step-tool.mjs +0 -89
  200. package/scripts/lib/loop-step.mjs +0 -301
  201. package/scripts/lib/run-budget.mjs +0 -28
  202. package/scripts/lib/run-card.mjs +0 -73
  203. package/scripts/lib/size-tier.mjs +0 -184
  204. package/scripts/lib/tier-record.mjs +0 -82
  205. package/scripts/size-budget-overrides.json +0 -58
  206. package/scripts/somi-card.mjs +0 -39
  207. package/scripts/somi-check.mjs +0 -237
  208. package/scripts/somi-config.mjs +0 -421
  209. package/scripts/somi-dispatch.mjs +0 -141
  210. package/scripts/somi-findings.mjs +0 -100
  211. package/scripts/somi-loop.mjs +0 -128
  212. package/scripts/somi-tier.mjs +0 -393
  213. package/scripts/validate.sh +0 -653
  214. package/skills/api-design/SKILL.md +0 -147
  215. package/skills/clean-code/SKILL.md +0 -142
  216. package/skills/flow-adopt/SKILL.md +0 -92
  217. package/skills/flow-architecture-review/SKILL.md +0 -94
  218. package/skills/flow-atlas/SKILL.md +0 -34
  219. package/skills/flow-code/SKILL.md +0 -167
  220. package/skills/flow-code-loop/SKILL.md +0 -263
  221. package/skills/flow-code-parallel/SKILL.md +0 -160
  222. package/skills/flow-debug/SKILL.md +0 -141
  223. package/skills/flow-design/SKILL.md +0 -170
  224. package/skills/flow-discover/SKILL.md +0 -204
  225. package/skills/flow-impact/SKILL.md +0 -35
  226. package/skills/flow-incident/SKILL.md +0 -49
  227. package/skills/flow-plan/SKILL.md +0 -254
  228. package/skills/flow-plan-loop/SKILL.md +0 -254
  229. package/skills/flow-pr/SKILL.md +0 -34
  230. package/skills/flow-refactor/SKILL.md +0 -58
  231. package/skills/flow-refactor-design/SKILL.md +0 -97
  232. package/skills/flow-release-readiness/SKILL.md +0 -82
  233. package/skills/flow-review/SKILL.md +0 -193
  234. package/skills/flow-review-panel/SKILL.md +0 -154
  235. package/skills/flow-security-review/SKILL.md +0 -83
  236. package/skills/flow-ship/SKILL.md +0 -125
  237. package/skills/flow-ship-loop/SKILL.md +0 -274
  238. package/skills/flow-somi-config/SKILL.md +0 -142
  239. package/skills/flow-status/SKILL.md +0 -43
  240. package/skills/flow-test-strategy/SKILL.md +0 -83
  241. package/skills/flow-upgrade/SKILL.md +0 -82
  242. package/skills/market-research/SKILL.md +0 -125
  243. package/skills/observability/SKILL.md +0 -133
  244. package/skills/owasp-defense/SKILL.md +0 -141
  245. package/skills/plan-review/SKILL.md +0 -83
  246. package/skills/reasoning-craft/SKILL.md +0 -213
  247. package/skills/requirements-engineering/SKILL.md +0 -137
  248. package/skills/role-coder/SKILL.md +0 -247
  249. package/skills/role-designer/SKILL.md +0 -172
  250. package/skills/role-discovery-analyst/SKILL.md +0 -288
  251. package/skills/role-planner/SKILL.md +0 -353
  252. package/skills/role-reviewer/SKILL.md +0 -218
  253. package/skills/rules/SKILL.md +0 -47
  254. package/skills/sdlc-process/SKILL.md +0 -74
  255. package/skills/solid-principles/SKILL.md +0 -143
  256. package/skills/somi-checkpoint/SKILL.md +0 -95
  257. package/skills/somi-dispatch/SKILL.md +0 -259
  258. package/skills/somi-routing/SKILL.md +0 -158
  259. package/skills/testing-playbook/SKILL.md +0 -133
  260. package/skills/threat-modeling/SKILL.md +0 -117
  261. package/templates/ADR.md.tmpl +0 -73
  262. package/templates/ATLAS.md.tmpl +0 -75
  263. package/templates/BRD.md.tmpl +0 -68
  264. package/templates/BRIEF.md.tmpl +0 -119
  265. package/templates/CONTEXT.md.tmpl +0 -74
  266. package/templates/DECISIONS.md.tmpl +0 -105
  267. package/templates/DESIGN.md.tmpl +0 -83
  268. package/templates/DIARY.md.tmpl +0 -70
  269. package/templates/DOD.md.tmpl +0 -90
  270. package/templates/FRD.md.tmpl +0 -64
  271. package/templates/PHASE.md.tmpl +0 -80
  272. package/templates/PROGRESS.md.tmpl +0 -63
  273. package/templates/RCA.md.tmpl +0 -53
  274. package/templates/RD-README.md.tmpl +0 -70
  275. package/templates/RESEARCH.md.tmpl +0 -96
  276. package/templates/REVIEW.md.tmpl +0 -82
  277. package/templates/SDD.md.tmpl +0 -82
  278. package/templates/SOMI-README.md.tmpl +0 -83
  279. package/templates/SPEC.md.tmpl +0 -123
  280. package/templates/SRS.md.tmpl +0 -85
  281. package/templates/TDD.md.tmpl +0 -77
  282. package/tests/hooks/cases/audit-log.json +0 -21
  283. package/tests/hooks/cases/block-dangerous-bash.json +0 -166
  284. package/tests/hooks/cases/block-secret-writes.json +0 -140
  285. package/tests/hooks/cases/detect-repo-instructions.json +0 -105
  286. package/tests/hooks/cases/gate-dep-install.json +0 -42
  287. package/tests/hooks/cases/guard-protected-paths.json +0 -222
  288. package/tests/hooks/cases/inject-workflow-context.json +0 -239
  289. package/tests/hooks/cases/lint-changed-files.json +0 -120
  290. package/tests/hooks/run.sh +0 -392
  291. package/tests/scripts/agent-model-frontmatter.sh +0 -38
  292. package/tests/scripts/agent-names.sh +0 -77
  293. package/tests/scripts/check-frontmatter.sh +0 -37
  294. package/tests/scripts/check-links.sh +0 -105
  295. package/tests/scripts/check-session-artefacts.sh +0 -60
  296. package/tests/scripts/check-size-budget.sh +0 -71
  297. package/tests/scripts/checkpoint-gate.sh +0 -131
  298. package/tests/scripts/convergence-runner.sh +0 -1514
  299. package/tests/scripts/cost-ceiling.sh +0 -255
  300. package/tests/scripts/cost-defaults.sh +0 -130
  301. package/tests/scripts/cost-hardcap.sh +0 -338
  302. package/tests/scripts/cost-lowering.sh +0 -261
  303. package/tests/scripts/cost-model.sh +0 -196
  304. package/tests/scripts/dispatch-guard.sh +0 -108
  305. package/tests/scripts/dispatch-line-gate.sh +0 -61
  306. package/tests/scripts/dispatch-reference-gate.sh +0 -173
  307. package/tests/scripts/ensure-default-config.sh +0 -162
  308. package/tests/scripts/escalation.sh +0 -409
  309. package/tests/scripts/eval-runner.sh +0 -3692
  310. package/tests/scripts/evals-packaging.sh +0 -224
  311. package/tests/scripts/fact-sheet.sh +0 -296
  312. package/tests/scripts/fixtures/legacy-shard-no-schema.json +0 -50
  313. package/tests/scripts/fixtures/mock-stdin-read-throw.cjs +0 -18
  314. package/tests/scripts/fixtures/size-tier-cases.json +0 -87
  315. package/tests/scripts/generate-digest.sh +0 -180
  316. package/tests/scripts/global-config.sh +0 -167
  317. package/tests/scripts/goldens/loop-state-breach.json +0 -1
  318. package/tests/scripts/goldens/loop-state-done.json +0 -1
  319. package/tests/scripts/goldens/somi-findings.json +0 -336
  320. package/tests/scripts/goldens/somi-loop.json +0 -168
  321. package/tests/scripts/lib/adr-shape.mjs +0 -41
  322. package/tests/scripts/lib/agent-registry-tests.mjs +0 -95
  323. package/tests/scripts/lib/brief-only-guard.mjs +0 -27
  324. package/tests/scripts/lib/checkpoint-gate.mjs +0 -91
  325. package/tests/scripts/lib/digest-marker-coupling.mjs +0 -52
  326. package/tests/scripts/lib/dispatch-reference-gate.mjs +0 -121
  327. package/tests/scripts/lib/escalation-facts-tests.mjs +0 -140
  328. package/tests/scripts/lib/escalation-tests.mjs +0 -154
  329. package/tests/scripts/lib/findings-ledger-tests.mjs +0 -118
  330. package/tests/scripts/lib/loop-engine-tests.mjs +0 -287
  331. package/tests/scripts/lib/loop-escalate-tests.mjs +0 -356
  332. package/tests/scripts/lib/loop-flow-gate.mjs +0 -173
  333. package/tests/scripts/lib/loop-notes-tests.mjs +0 -371
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -141
  335. package/tests/scripts/lib/loop-step-close-tests.mjs +0 -351
  336. package/tests/scripts/lib/loop-step-lenient-tests.mjs +0 -114
  337. package/tests/scripts/lib/loop-step-state-tests.mjs +0 -127
  338. package/tests/scripts/lib/loop-step-tests.mjs +0 -499
  339. package/tests/scripts/lib/loop-step-unwritten-tests.mjs +0 -55
  340. package/tests/scripts/lib/multipass-dependence.mjs +0 -192
  341. package/tests/scripts/lib/multipass-source-identity.mjs +0 -243
  342. package/tests/scripts/lib/path-facts-tests.mjs +0 -198
  343. package/tests/scripts/lib/path-safety-tests.mjs +0 -201
  344. package/tests/scripts/lib/reference-pair.mjs +0 -61
  345. package/tests/scripts/lib/retirement-gate.mjs +0 -172
  346. package/tests/scripts/lib/run-suites.mjs +0 -139
  347. package/tests/scripts/lib/shell-embedded-js.mjs +0 -47
  348. package/tests/scripts/lib/ship-loop-sizing-guard.mjs +0 -52
  349. package/tests/scripts/lib/site-roadmap-gate.mjs +0 -64
  350. package/tests/scripts/lib/size-tier-drift.mjs +0 -74
  351. package/tests/scripts/lib/sizing-score-tests.mjs +0 -210
  352. package/tests/scripts/lib/sizing-set-tests.mjs +0 -131
  353. package/tests/scripts/lib/somi-mcp-client.mjs +0 -102
  354. package/tests/scripts/lib/somi-mcp-config-tests.mjs +0 -92
  355. package/tests/scripts/lib/somi-mcp-loop-tests.mjs +0 -226
  356. package/tests/scripts/lib/somi-mcp-tests.mjs +0 -491
  357. package/tests/scripts/lib/somi-mcp-tier-tests.mjs +0 -64
  358. package/tests/scripts/lib/somi-mcp-tool-schema.mjs +0 -38
  359. package/tests/scripts/loop-engine.sh +0 -22
  360. package/tests/scripts/loop-flow-gate.sh +0 -11
  361. package/tests/scripts/retirement-gate.sh +0 -306
  362. package/tests/scripts/review-panel-seats.sh +0 -32
  363. package/tests/scripts/run-card.sh +0 -57
  364. package/tests/scripts/run-suites.sh +0 -74
  365. package/tests/scripts/run.sh +0 -689
  366. package/tests/scripts/site-roadmap-gate.sh +0 -76
  367. package/tests/scripts/size-tier.sh +0 -562
  368. package/tests/scripts/somi-agent-dispatch-contract.sh +0 -224
  369. package/tests/scripts/somi-config.sh +0 -286
  370. package/tests/scripts/somi-dispatch.sh +0 -465
  371. package/tests/scripts/somi-mcp.sh +0 -15
  372. package/tests/scripts/suite-plan.json +0 -20
@@ -1,64 +0,0 @@
1
- // cost-config.mjs — the one validator for the `cost.*` block of .somi/config.json.
2
- //
3
- // The block is committed, cloned input (untrusted), so every consumer must agree on which keys
4
- // and values are legal; keeping that decision here stops readers from drifting apart. Errors keep
5
- // the `cost-ceiling:` prefix so existing callers' config-problem mapping is unchanged.
6
-
7
- import { VALID_COSTS } from './cost-model.mjs';
8
-
9
- export const COST_CONFIG_KEYS = Object.freeze(['ceiling', 'mapping', 'agents']);
10
-
11
- // The one agent-name pattern; dispatch-resolver.mjs re-exports it (that module imports this one, so
12
- // the dependency runs one way).
13
- export const AGENT_NAME_RE = /^[a-z][a-z0-9-]*$/;
14
-
15
- // "constructor" and "prototype" satisfy AGENT_NAME_RE, so the name pattern alone does not keep them
16
- // out of a map that later code may index with a plain lookup.
17
- const FORBIDDEN_KEYS = Object.freeze(['__proto__', 'constructor', 'prototype']);
18
-
19
- const where = 'cost in .somi/config.json';
20
-
21
- // Committed config reaches the model's context through these messages: quote every echoed value and
22
- // bound its length so a hostile key cannot inject lines or escape sequences.
23
- export const quote = (v) => {
24
- const q = JSON.stringify(v) ?? String(v);
25
- return q.length > 80 ? `${q.slice(0, 80)}...` : q;
26
- };
27
-
28
- // -> a frozen null-prototype copy, so a plain lookup of a missing name ("constructor") finds nothing.
29
- function validateAgents(agents) {
30
- if (agents === null || typeof agents !== 'object' || Array.isArray(agents)) {
31
- throw new Error(`cost-ceiling: cost.agents in .somi/config.json expected an object, got ${quote(agents)}`);
32
- }
33
- for (const [name, tier] of Object.entries(agents)) {
34
- if (FORBIDDEN_KEYS.includes(name)) {
35
- throw new Error(`cost-ceiling: cost.agents in .somi/config.json has a forbidden agent name ${quote(name)}`);
36
- }
37
- if (!AGENT_NAME_RE.test(name)) {
38
- throw new Error(`cost-ceiling: cost.agents in .somi/config.json has an invalid agent name ${quote(name)} (expected ${AGENT_NAME_RE})`);
39
- }
40
- if (!VALID_COSTS.includes(tier)) {
41
- throw new Error(`cost-ceiling: cost.agents.${name} expected one of ${VALID_COSTS.join('|')}, got ${quote(tier)}`);
42
- }
43
- }
44
- return Object.freeze(Object.assign(Object.create(null), agents));
45
- }
46
-
47
- /**
48
- * Validates a parsed `cost` value and returns it (with `agents` as a frozen null-prototype map). `undefined`/`null` mean unconfigured.
49
- * `ceiling` and `mapping` values are checked where they are used (validateCeiling, resolveModel);
50
- * this decides only which keys are legal and that `agents` is a name-to-tier map.
51
- */
52
- export function validateCostConfig(cost) {
53
- if (cost === undefined || cost === null) return {};
54
- if (typeof cost !== 'object' || Array.isArray(cost)) {
55
- throw new Error(`cost-ceiling: ${where} expected an object, got ${quote(cost)}`);
56
- }
57
- for (const key of Object.keys(cost)) {
58
- if (!COST_CONFIG_KEYS.includes(key)) {
59
- throw new Error(`cost-ceiling: ${where} has an unrecognized key ${quote(key)}`);
60
- }
61
- }
62
- if (cost.agents === undefined) return cost;
63
- return { ...cost, agents: validateAgents(cost.agents) };
64
- }
@@ -1,53 +0,0 @@
1
- // cost-defaults.mjs — the default .somi/config.json `cost` block a project with no config gets.
2
- //
3
- // The table is the one source of each agent's default tier (agent files carry no tier of their own).
4
- // It is literal data, not read from agents/ at runtime: the code that writes the file runs in a
5
- // consuming project where only the plugin install exists. tests/scripts/cost-defaults.sh keeps its
6
- // keys equal to agents/*.md minus the front-door `somi` agent, which is exempt from cost resolution
7
- // (the host binds its model).
8
- // Tier names only; which model a tier means is cost.mapping's job.
9
-
10
- import { DEFAULT_CEILING } from './cost-ceiling.mjs';
11
- import { validateCostConfig } from './cost-config.mjs';
12
-
13
- export const DEFAULT_CEILING_TIER = DEFAULT_CEILING;
14
-
15
- // Null-prototype and frozen: a plain lookup of "constructor" finds nothing, and nothing can edit it.
16
- export const AGENT_DEFAULT_TIERS = Object.freeze(Object.assign(Object.create(null), {
17
- 'somi-architecture-reviewer': 'high',
18
- 'somi-atlas': 'high',
19
- 'somi-coder': 'medium',
20
- 'somi-designer': 'high',
21
- 'somi-discovery-analyst': 'high',
22
- 'somi-flow': 'medium',
23
- 'somi-general': 'medium',
24
- 'somi-impact': 'medium',
25
- 'somi-incident': 'medium',
26
- 'somi-plan-reviewer': 'high',
27
- 'somi-planner': 'medium',
28
- 'somi-pr': 'medium',
29
- 'somi-refactor-designer': 'high',
30
- 'somi-refactorer': 'medium',
31
- 'somi-reviewer': 'high',
32
- 'somi-sdlc-reviewer': 'high',
33
- 'somi-security-reviewer': 'high',
34
- 'somi-test-strategist': 'high',
35
- }));
36
-
37
- /**
38
- * The exact object a fresh .somi/config.json holds: `{cost: {ceiling, agents}}`, agents sorted by
39
- * name so the bytes are stable. `table` is overridable for tests. Throws if the shared validator
40
- * rejects it.
41
- */
42
- export function buildDefaultConfig(table = AGENT_DEFAULT_TIERS) {
43
- const agents = {};
44
- for (const name of Object.keys(table).sort()) agents[name] = table[name];
45
- const cost = { ceiling: DEFAULT_CEILING_TIER, agents };
46
- validateCostConfig(cost);
47
- return { cost };
48
- }
49
-
50
- /** The file text: JSON, 2-space indent, trailing newline. The one serialization every writer uses. */
51
- export function serializeDefaultConfig(table = AGENT_DEFAULT_TIERS) {
52
- return `${JSON.stringify(buildDefaultConfig(table), null, 2)}\n`;
53
- }
@@ -1,89 +0,0 @@
1
- // cost-lowering.mjs — does moving from one config to another LOWER any agent's tier?
2
- //
3
- // Pure. Compares EFFECTIVE tiers (the agent's cost.agents entry, else the ceiling: the resolver's own
4
- // rule, via decideDispatch) for every agent in the default table and any named in either config. It
5
- // answers one question for the PreToolUse hook and the CLI's --refuse-lowering: does this change need
6
- // the user? Reasons are fixed strings; nothing from either config is ever echoed.
7
- //
8
- // A change lowers when any of these holds:
9
- // - security-reviewer would run below high (flagged even if unchanged from before, so an explicit low
10
- // pin is always flagged; an identical before and after is a no-op and never lowers)
11
- // - the ceiling is lower than before
12
- // - an agent's effective tier is lower than before; when that is a removed pin above the ceiling
13
- // the reason says so
14
- // - cost.mapping changes in any way (which model a tier means cannot be ranked here)
15
- // - the new config is not an object, or its cost block is not valid
16
- // Whether a state file appears later cannot change a verdict: a config that has NO cost.ceiling after the
17
- // change is judged against the worst case, so deleting cost.ceiling (or unpinning an agent in a config
18
- // without one) is a lowering unless the removed value was already `low`. Otherwise a model could delete the
19
- // ceiling first and plant a persisted low ceiling afterwards.
20
- // The ceiling an absent cost.ceiling falls back to is the resolver's: a ceiling an earlier --ceiling or
21
- // env call persisted (origin cli/env), else the default. `root` (the project) is needed to read that
22
- // state, read-only; it is applied on BOTH sides of the comparison, so deleting cost.ceiling is judged by
23
- // the value that takes over. SOMI_COST_CEILING of the session is not known here and is not considered.
24
- // Raises and no-ops never lower. Both arguments are parsed config objects ({} or null for an absent
25
- // file); `after` may also be anything unparsed (null, a string, an array), which counts as invalid.
26
-
27
- import { decideDispatch, DEFAULT_CEILING, loadState } from './cost-ceiling.mjs';
28
- import { VALID_COSTS } from './cost-model.mjs';
29
- import { AGENT_DEFAULT_TIERS } from './cost-defaults.mjs';
30
- import { validateCostBlock } from './cost-config-edit.mjs';
31
-
32
- export const REASONS = Object.freeze({
33
- security: 'security-reviewer would run below high',
34
- ceiling: 'the ceiling would be lowered',
35
- agent: 'an agent tier would be lowered',
36
- pin: 'a pin above the ceiling would be removed',
37
- invalid: 'the new config is not valid',
38
- mapping: 'a tier would be mapped to a different model',
39
- });
40
-
41
- const rank = (t) => VALID_COSTS.indexOf(t);
42
- const isObj = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
43
-
44
- // The persisted ceiling that would take over when cost.ceiling is absent, or undefined.
45
- function stateCeiling(root) {
46
- if (!root) return undefined;
47
- try {
48
- const st = loadState(root);
49
- return st && ['cli', 'env'].includes(st.ceiling_origin) ? st.ceiling : undefined;
50
- } catch {
51
- return undefined; // an unreadable state file is the resolver's error to report, not a reason here
52
- }
53
- }
54
-
55
- // Tolerant on purpose: a bad value in `before` must not make the comparison throw.
56
- function view(cfg, fallback) {
57
- const cost = isObj(cfg) && isObj(cfg.cost) ? cfg.cost : {};
58
- const ceiling = VALID_COSTS.includes(cost.ceiling) ? cost.ceiling : fallback;
59
- const agents = isObj(cost.agents) ? cost.agents : {};
60
- const pin = (name) => (Object.hasOwn(agents, name) && VALID_COSTS.includes(agents[name]) ? agents[name] : undefined);
61
- const tier = (name) => decideDispatch(AGENT_DEFAULT_TIERS[name] ?? ceiling, ceiling, pin(name)).selected;
62
- return { ceiling, pin, tier, names: Object.keys(agents), json: JSON.stringify(cost), mapping: JSON.stringify(cost.mapping ?? null) };
63
- }
64
-
65
- /** @returns {{lowers: boolean, reasons: string[]}}; `root` is the project directory (for the persisted ceiling). */
66
- export function lowers(before, after, root) {
67
- if (!isObj(after)) return { lowers: true, reasons: [REASONS.invalid] };
68
- try { validateCostBlock(after.cost); } catch { return { lowers: true, reasons: [REASONS.invalid] }; }
69
- const fallback = stateCeiling(root) ?? DEFAULT_CEILING;
70
- const b = view(before, fallback);
71
- const a = view(after, fallback);
72
- const ceilingGone = isObj(before?.cost) && VALID_COSTS.includes(before.cost.ceiling) && !(isObj(after.cost) && VALID_COSTS.includes(after.cost.ceiling));
73
- const worst = (name) => decideDispatch(AGENT_DEFAULT_TIERS[name] ?? 'low', 'low', undefined).selected;
74
- if (a.json === b.json) return { lowers: false, reasons: [] };
75
- const reasons = new Set();
76
- // Which model a tier means is not comparable here (no prices), so any mapping change needs the user:
77
- // pointing `high` at a cheap model is a lowering this function could not otherwise see.
78
- if (a.mapping !== b.mapping) reasons.add(REASONS.mapping);
79
- if (rank(a.tier('somi-security-reviewer')) < rank('high')) reasons.add(REASONS.security);
80
- if (rank(a.ceiling) < rank(b.ceiling) || (ceilingGone && rank(b.ceiling) > rank('low'))) reasons.add(REASONS.ceiling);
81
- const noCeiling = !(isObj(after.cost) && VALID_COSTS.includes(after.cost.ceiling));
82
- for (const name of new Set([...Object.keys(AGENT_DEFAULT_TIERS), ...b.names, ...a.names])) {
83
- const removedPin = b.pin(name) !== undefined && a.pin(name) === undefined;
84
- const aTier = removedPin && noCeiling ? worst(name) : a.tier(name);
85
- if (rank(aTier) >= rank(b.tier(name))) continue;
86
- reasons.add(removedPin ? REASONS.pin : REASONS.agent);
87
- }
88
- return { lowers: reasons.size > 0, reasons: [...reasons] };
89
- }
@@ -1,110 +0,0 @@
1
- // One shipped, user-overridable mapping instead of scattering model names across instruction
2
- // files: a repricing or a new model is an edit here. A host absent from the mapping gets no
3
- // override — the caller omits the model argument and that host's own default applies (today's
4
- // behavior, unchanged). A cost value outside the enum, or a mapped host missing that tier, throws
5
- // rather than silently routing to an unintended model.
6
-
7
- export const VALID_COSTS = Object.freeze(['low', 'medium', 'high']);
8
-
9
- // A mapped model can come from committed, cloned .somi/config.json -- untrusted input about to
10
- // reach a prompt and possibly a host CLI -- so it must look like a model identifier, not just be
11
- // a non-empty string.
12
- export const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@\[\]-]{0,127}$/;
13
-
14
- // Hosts with a verified model identifier for each tier. Add an entry to opt a new host into
15
- // explicit model selection; leave a host out to keep it on its own default.
16
- //
17
- // TODO(cost-model maintainer): add copilot-cli / vscode once a verified model identifier exists
18
- // for each tier; until then they return null and fall back to their own default.
19
- export const HOST_MODELS = Object.freeze({
20
- 'claude-code': Object.freeze({ low: 'haiku', medium: 'sonnet', high: 'opus' }),
21
- });
22
-
23
- export const MAX_MODEL_CANDIDATES = 8;
24
-
25
- /**
26
- * Resolves a declared cost tier to its ordered model candidates for the given host (#35). A mapping
27
- * entry is one model id, or a non-empty list of up to MAX_MODEL_CANDIDATES distinct ids in preference
28
- * order: plans and editors expose different model ids, so the caller passes the first one its host
29
- * actually offers. The resolver cannot see the host's model list; it only validates and orders.
30
- * @returns {string[]|null} the candidates (length >= 1), or null when the host is absent from the
31
- * mapping (no override for that host — the caller omits the model argument and its own default applies).
32
- */
33
- export function resolveModelCandidates(cost, host, mapping = HOST_MODELS) {
34
- if (!VALID_COSTS.includes(cost)) {
35
- throw new Error(`cost-model: unrecognized cost "${cost}" (expected one of ${VALID_COSTS.join('|')})`);
36
- }
37
- if (!Object.hasOwn(mapping, host)) return null; // unmapped host: no override, its own default applies
38
- const models = mapping[host];
39
- const entry = models[cost];
40
- if (entry === undefined) {
41
- throw new Error(`cost-model: host "${host}" has no "${cost}" entry in its mapping`);
42
- }
43
- // A user-supplied mapping (.somi/config.json's cost.mapping) can name a tier with a value of the
44
- // wrong shape -- that must die loudly here, at the one place every mapping (shipped or overridden)
45
- // is read, rather than hand a caller something that prints into JSON as a "model" no host can run.
46
- const list = Array.isArray(entry) ? entry : [entry];
47
- if (list.length === 0 || list.length > MAX_MODEL_CANDIDATES) {
48
- throw new Error(`cost-model: host "${host}"'s "${cost}" entry must be a model id or a list of 1 to ${MAX_MODEL_CANDIDATES} ids, got ${list.length}`);
49
- }
50
- for (const model of list) {
51
- if (typeof model !== 'string' || model === '') {
52
- throw new Error(`cost-model: host "${host}"'s "${cost}" entry must be a non-empty string, got ${JSON.stringify(model)}`);
53
- }
54
- if (!MODEL_ID_RE.test(model)) {
55
- throw new Error(`cost-model: host "${host}"'s "${cost}" entry "${model}" is not a valid model identifier`);
56
- }
57
- }
58
- if (new Set(list).size !== list.length) {
59
- throw new Error(`cost-model: host "${host}"'s "${cost}" list names the same model twice`);
60
- }
61
- return [...list];
62
- }
63
-
64
- /**
65
- * Resolves a declared cost tier to its preferred model for the given host: the first candidate.
66
- * @returns {string|null} the mapped model, or null when the host is absent from the mapping.
67
- */
68
- export function resolveModel(cost, host, mapping = HOST_MODELS) {
69
- return resolveModelCandidates(cost, host, mapping)?.[0] ?? null;
70
- }
71
-
72
- const FORBIDDEN_HOST_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
73
-
74
- /**
75
- * Merges a user-supplied per-host override (e.g. `.somi/config.json`'s `cost.mapping`) on top of
76
- * `defaults`, for use as resolveModel()'s third argument. A host present in `override` REPLACES
77
- * that host's whole tier map — never merged tier-by-tier — so mapping a host to `{}` makes every
78
- * tier for that host fail loudly via resolveModel() instead of silently falling back to the
79
- * shipped default. Throws on a disallowed or non-object override rather than absorbing it.
80
- */
81
- export function mergeHostMapping(defaults, override) {
82
- if (override === undefined || override === null) return defaults;
83
- if (typeof override !== 'object' || Array.isArray(override)) {
84
- throw new Error('cost-model: mapping override must be an object');
85
- }
86
- const merged = { ...defaults };
87
- for (const host of Object.keys(override)) {
88
- if (FORBIDDEN_HOST_KEYS.has(host)) {
89
- throw new Error(`cost-model: mapping override has a disallowed host key "${host}"`);
90
- }
91
- const tiers = override[host];
92
- if (typeof tiers !== 'object' || tiers === null || Array.isArray(tiers)) {
93
- throw new Error(`cost-model: mapping override for host "${host}" must be an object of cost -> model`);
94
- }
95
- // A tier key outside VALID_COSTS is either a typo (this repo's own "low"/"medium"/"high") or a
96
- // stale key from a renamed tier -- either way it would sit unused forever, unflagged, since
97
- // resolveModel() only ever looks up the tier it actually selected. Reject the whole per-host
98
- // object rather than silently keeping the junk key alongside the valid ones.
99
- for (const tier of Object.keys(tiers)) {
100
- if (!VALID_COSTS.includes(tier)) {
101
- throw new Error(
102
- `cost-model: mapping override for host "${host}" has an unrecognized tier key "${tier}" ` +
103
- `(expected one of ${VALID_COSTS.join('|')})`,
104
- );
105
- }
106
- }
107
- merged[host] = tiers;
108
- }
109
- return merged;
110
- }
@@ -1,243 +0,0 @@
1
- // dispatch-resolver.mjs — the resolve logic shared by scripts/somi-dispatch.mjs (the CLI) and
2
- // scripts/somi-mcp.mjs (the MCP server): for a given agent, right now, which tier and model
3
- // should run it? Factored out so the two surfaces share one validation order and one set of
4
- // error codes/messages rather than each re-deriving the composition and risking drift.
5
- //
6
- // Pure function over explicit inputs: no argv parsing, no process.exit, no stdout/stderr writes.
7
- // Each caller turns the returned {ok, ...} shape into its own surface — the CLI: exit code +
8
- // stdout JSON, or a stderr message; the MCP server: a tool result. Composition (never inline the
9
- // pieces yourself; this is the one sanctioned call site for it):
10
- // resolveCeiling(projectRoot, ceiling) -> decideDispatch([default tier], ceiling, cost.agents[agent])
11
- // -> modelForDispatch(decision, host, mergeHostMapping(HOST_MODELS, cost.mapping))
12
- //
13
- // `cost.mapping`, `cost.agents` and `cost.ceiling` are all read from the project's
14
- // .somi/config.json on EVERY call, so a mid-session config fix takes effect on the very next
15
- // dispatch (see cost-ceiling.mjs's header for the ceiling's precedence).
16
- //
17
- // `agent` is validated against a strict allowlist before any path is built — it may come from a
18
- // prompt carrying untrusted text (and, via the MCP server, from a model-supplied tool argument).
19
- //
20
- // Codes both surfaces reuse verbatim (see each caller for how it turns these into its own shape):
21
- // 64 usage error (bad/missing arguments, including an unrecognized ceiling/env-ceiling value) —
22
- // `validateDispatchArgs` below is the ONE place both surfaces run this family of checks, so
23
- // the same bad input produces the same code through either surface, checked before either
24
- // surface's own project-root lookup (the MCP server's own can be a 2s `roots/list` round trip)
25
- // 65 unknown agent (no agents/<name>.md at the install root)
26
- // 66 no tier source (the exempt `somi` agent, or an agent file with no default-tier-table entry) — OR the
27
- // merged mapping's own resolution for the selected tier failing WHEN the project's own
28
- // cost.mapping never named that host at all (a bug in the shipped HOST_MODELS table, not a
29
- // broken project file)
30
- // 67 project environment/config failure (corrupt .somi/somi-state/ceiling.json; an
31
- // unparsable/malformed .somi/config.json; a structurally invalid cost.mapping) — distinct
32
- // from 64 because the problem is the project's own persisted files, not this call's
33
- // arguments — ALSO when the mapping fails for a host the project's mapping DID name (a
34
- // partial override of a shipped host replaces its whole tier map, not per-tier) — ALSO the
35
- // code scripts/lib/mcp-project-root.mjs returns for "no project root could be established":
36
- // the MCP server's own environment failing to add up to a usable answer, same family.
37
- // A guessed model is never returned on any error path — only the ok:true result carries one.
38
-
39
- import fs from 'node:fs';
40
- import path from 'node:path';
41
- import { resolveCeiling, decideDispatch, modelForDispatch, readCostConfig, CEILING_ENV } from './cost-ceiling.mjs';
42
- import { AGENT_NAME_RE } from './cost-config.mjs';
43
- import { HOST_MODELS, mergeHostMapping, resolveModelCandidates, VALID_COSTS } from './cost-model.mjs';
44
- import { AGENT_DEFAULT_TIERS } from './cost-defaults.mjs';
45
- import { buildRegistry, agentTypeFor } from './agent-registry.mjs';
46
-
47
- // Built once: an alias collision fails the import, so no surface can start on an ambiguous registry.
48
- const REGISTRY = buildRegistry();
49
-
50
- export { AGENT_NAME_RE };
51
-
52
- export const EXIT_USAGE = 64;
53
- export const EXIT_UNKNOWN_AGENT = 65;
54
- export const EXIT_MALFORMED = 66;
55
- export const EXIT_PROJECT_ENV = 67;
56
-
57
- function err(code, message) {
58
- return { ok: false, code, message };
59
- }
60
-
61
- // The ONE validation order both surfaces run, over the SAME three fields, producing the SAME code
62
- // for the SAME bad input. scripts/somi-dispatch.mjs and scripts/somi-mcp.mjs each call this
63
- // directly before either does its own project-root lookup (the MCP server's can be a 2s
64
- // `roots/list` round trip); `resolveDispatch` below also calls it first thing, so a direct caller
65
- // of that alone still gets the same checks before any disk I/O.
66
- //
67
- // `undefined` means "not given" for `host`/`ceiling` (the CLI's own sentinel — requireValue()
68
- // already dies on an explicitly empty flag before assignment, so it never passes `''` here). A
69
- // DEFINED-but-wrong-shaped value (an empty string on purpose, an array, an object, a number) is a
70
- // caller mistake, not an omission, and must fail the same way — silently coercing it to "not
71
- // given", as an earlier shape of the MCP surface did, is the bug this function closes.
72
- //
73
- // `agent` has no "not given" reading — it is REQUIRED, so `undefined` fails like any non-string.
74
- export function validateDispatchArgs({ agent, host, ceiling } = {}) {
75
- // `JSON.stringify`, not a bare template-literal interpolation: an object-shaped `agent` (e.g.
76
- // `{toString: null}`, reachable as an MCP tool argument) throws INSIDE `${agent}` instead of
77
- // producing a string, surfacing as an unrelated internal error rather than this 64.
78
- if (typeof agent !== 'string' || !AGENT_NAME_RE.test(agent)) {
79
- return err(EXIT_USAGE, `invalid --agent ${JSON.stringify(agent)} (expected ${AGENT_NAME_RE})`);
80
- }
81
- // `host` has a real default ('claude-code', applied once validation passes) — only a
82
- // DEFINED-but-wrong-shaped value is rejected here.
83
- if (host !== undefined && (typeof host !== 'string' || host === '')) {
84
- return err(EXIT_USAGE, `--host requires a non-empty string, got ${JSON.stringify(host)}`);
85
- }
86
- // Validated here, before resolveCeiling() ever touches disk, so a rejected argument can never
87
- // leave a persisted state file behind.
88
- if (ceiling !== undefined) {
89
- if (typeof ceiling !== 'string' || ceiling === '') {
90
- return err(EXIT_USAGE, `--ceiling requires a non-empty string, got ${JSON.stringify(ceiling)}`);
91
- }
92
- if (!VALID_COSTS.includes(ceiling)) {
93
- return err(EXIT_USAGE, `--ceiling expected one of ${VALID_COSTS.join('|')}, got "${ceiling}"`);
94
- }
95
- }
96
- // Same reasoning for the env-var channel: SOMI_COST_CEILING is caller input like --ceiling, so a
97
- // bad value is 64 here, never routed into resolveCeiling() to surface as a project-env failure
98
- // (67) alongside a genuinely corrupt config/state file.
99
- const envCeiling = process.env[CEILING_ENV];
100
- if (envCeiling && !VALID_COSTS.includes(envCeiling)) {
101
- return err(EXIT_USAGE, `${CEILING_ENV} expected one of ${VALID_COSTS.join('|')}, got "${envCeiling}"`);
102
- }
103
- return { ok: true };
104
- }
105
-
106
- /**
107
- * Resolves one agent's dispatch tier + model. `host` defaults to `'claude-code'` when not given;
108
- * `ceiling`, when given, is this call's explicit override. Both, and `agent`, are validated by
109
- * `validateDispatchArgs` above. `projectRoot`/`installRoot` are plain strings the caller resolves
110
- * itself (the CLI's own convention differs from the MCP server's — see mcp-project-root.mjs).
111
- * `persist: false` makes the call read-only: an explicit or env ceiling is used but never remembered.
112
- * The result's `agent_type` is the id the host's subagent tool takes for this agent (`somi:<agent>`
113
- * on both shipped hosts), or null for a host with no registration (see agent-registry.mjs).
114
- *
115
- * @returns {{ok: true, result: object} | {ok: false, code: number, message: string}}
116
- */
117
- export function resolveDispatch({ agent, host, ceiling, projectRoot, installRoot, persist = true }) {
118
- const validated = validateDispatchArgs({ agent, host, ceiling });
119
- if (!validated.ok) return validated;
120
- const HOST = host || 'claude-code';
121
-
122
- const agentPath = path.join(installRoot, 'agents', `${agent}.md`);
123
- let content;
124
- try {
125
- content = fs.readFileSync(agentPath, 'utf8');
126
- } catch (e) {
127
- if (e.code === 'ENOENT') return err(EXIT_UNKNOWN_AGENT, `unknown agent "${agent}" (no ${agentPath})`);
128
- throw e;
129
- }
130
-
131
- // The agent's own tier comes from the shipped default table, never from the agent file: a
132
- // leftover `cost:` line in the file is ignored. `somi` is the one agent with no table entry on
133
- // purpose; any other agent file the table doesn't know is a gap in the plugin itself (66).
134
- if (agent === 'somi') {
135
- return err(
136
- EXIT_MALFORMED,
137
- `agent "somi" is exempt from cost: — the host binds its model when the user selects it ` +
138
- `in the host's own UI, so there is nothing for this resolver to compute`,
139
- );
140
- }
141
- const defaultTier = AGENT_DEFAULT_TIERS[agent];
142
- if (defaultTier === undefined) {
143
- return err(EXIT_MALFORMED, `agent "${agent}" has no entry in the default tier table (scripts/lib/cost-defaults.mjs)`);
144
- }
145
- const declaredCost = [defaultTier];
146
-
147
- // Both --ceiling and SOMI_COST_CEILING were already syntax-checked above, before any disk write —
148
- // so anything resolveCeiling() throws now is the PROJECT's own persisted state, not this call's
149
- // arguments: an unparsable .somi/config.json, or a corrupt .somi/somi-state/ceiling.json.
150
- let ceilingResult;
151
- try {
152
- ceilingResult = resolveCeiling(projectRoot, ceiling || undefined, { persist });
153
- } catch (e) {
154
- return err(EXIT_PROJECT_ENV, e.message);
155
- }
156
-
157
- // Read fresh per call (see this file's header): this is how a project on a
158
- // host SoMi doesn't ship a mapping for (e.g. Copilot) tells SoMi which of ITS models counts as
159
- // low/medium/high. Captured once, before the merge, and kept around past it: modelForDispatch's
160
- // own catch below needs to know whether the PROJECT's mapping named this specific host at all,
161
- // to attribute a later resolution failure correctly.
162
- let projectMapping;
163
- let override;
164
- try {
165
- const costConfig = readCostConfig(projectRoot);
166
- projectMapping = costConfig.mapping;
167
- // hasOwn, not a plain lookup: the map is null-prototype already, but this keeps "no entry"
168
- // meaning "follows the ceiling" for any name, including ones like "constructor".
169
- if (costConfig.agents && Object.hasOwn(costConfig.agents, agent)) override = costConfig.agents[agent];
170
- } catch (e) {
171
- return err(EXIT_PROJECT_ENV, e.message);
172
- }
173
- // readCostConfig already validated it; re-checked here so an invalid override can only ever be the
174
- // project's file (67), never reach decideDispatch's agent-declaration error path (66).
175
- if (override !== undefined && !VALID_COSTS.includes(override)) {
176
- return err(EXIT_PROJECT_ENV, `cost.agents.${agent} expected one of ${VALID_COSTS.join('|')}, got ${JSON.stringify(override)}`);
177
- }
178
-
179
- // mergeHostMapping rejects a __proto__/constructor/prototype key, a non-object per-host value,
180
- // and a tier key outside low|medium|high outright — kept in its own try/catch, distinct from
181
- // decideDispatch/modelForDispatch below: this fails only on the PROJECT's own persisted
182
- // .somi/config.json being structurally broken, never on this agent's own default tier.
183
- let mapping;
184
- try {
185
- mapping = mergeHostMapping(HOST_MODELS, projectMapping);
186
- } catch (e) {
187
- return err(EXIT_PROJECT_ENV, e.message);
188
- }
189
-
190
- // The override and ceiling are validated by now, so decideDispatch failing is this AGENT's own
191
- // default tier (66) -- unrelated to the mapping, so it stays in its own try/catch.
192
- let decision;
193
- try {
194
- decision = decideDispatch(declaredCost, ceilingResult.ceiling, override);
195
- } catch (e) {
196
- return err(EXIT_MALFORMED, e.message);
197
- }
198
-
199
- // modelForDispatch failing here means the MERGED mapping is shape-valid but incomplete or wrong
200
- // for the tier this call actually selected (the ceiling, or the agent's override). Whose fault that is turns on whether the project's
201
- // OWN cost.mapping named this host at all: if it did, the gap is the project's own file (67),
202
- // and the message says so explicitly. Only a host the project's mapping never mentioned failing
203
- // this way would point at a bug in the shipped HOST_MODELS table itself, which stays 66.
204
- let model;
205
- let candidates;
206
- try {
207
- model = modelForDispatch(decision, HOST, mapping);
208
- candidates = resolveModelCandidates(decision.selected, HOST, mapping);
209
- } catch (e) {
210
- if (projectMapping && Object.hasOwn(projectMapping, HOST)) {
211
- return err(EXIT_PROJECT_ENV, `${e.message} (in .somi/config.json cost.mapping)`);
212
- }
213
- return err(EXIT_MALFORMED, e.message);
214
- }
215
-
216
- // `enforced` is true only when a concrete model id came out of the merged mapping (shipped table
217
- // or the project's cost.mapping). A null model means nothing pins the tier on this host: the
218
- // agent runs on whatever the host picks, so a caller must not report the tier as "dispatched".
219
- const enforced = model !== null;
220
- const modelFields = enforced
221
- ? { enforced }
222
- : { enforced, reason: `no model mapping for host ${HOST} (set cost.mapping.${HOST} with low, medium and high in .somi/config.json)` };
223
-
224
- return {
225
- ok: true,
226
- result: {
227
- agent,
228
- agent_type: agentTypeFor(REGISTRY, agent, HOST),
229
- supported: decision.supported,
230
- declared: decision.supported,
231
- tier: decision.selected,
232
- degraded: decision.degraded,
233
- tier_source: decision.tier_source,
234
- model,
235
- // Only for a preference list (#35): pass the first candidate the host offers; `model` is the first.
236
- ...(candidates && candidates.length > 1 ? { model_candidates: candidates } : {}),
237
- ...modelFields,
238
- ceiling: ceilingResult.ceiling,
239
- ceiling_source: ceilingResult.source,
240
- ceiling_origin: ceilingResult.ceiling_origin,
241
- },
242
- };
243
- }