@skathio/somi 4.1.1 → 5.0.1

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 +88 -227
  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 +29 -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 +44 -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 +167 -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 +97 -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 +58 -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 +182 -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 -227
  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 -282
  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 -303
  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 -139
  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 -384
  334. package/tests/scripts/lib/loop-step-cli-tests.mjs +0 -156
  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,85 +0,0 @@
1
- // agent-info.mjs — the read-only somi_agent_info lookup: the agent catalog, or one identifier (a
2
- // canonical name or a registered alias) normalised through agent-registry.mjs and resolved through the
3
- // shared dispatch resolver with persist:false, so a lookup reports what a dispatch would get right now
4
- // and writes nothing (no ceiling argument is accepted, and an env ceiling is never remembered).
5
- //
6
- // Pure apart from the resolver's reads: the caller supplies the project root lookup (the MCP server's
7
- // can be a roots/list round trip) and the install root, and turns {ok, ...} into its own surface.
8
-
9
- import { buildRegistry, normalize, agentTypeFor, catalog, ORCHESTRATOR } from './agent-registry.mjs';
10
- import { resolveDispatch, EXIT_USAGE, EXIT_UNKNOWN_AGENT } from './dispatch-resolver.mjs';
11
-
12
- // Built once: an alias collision fails at import, before any lookup answers.
13
- const REGISTRY = buildRegistry();
14
- const HOST_RE = /^[a-z][a-z0-9-]{0,31}$/;
15
-
16
- export const AGENT_INFO_TOOL = {
17
- name: 'somi_agent_info',
18
- description:
19
- 'Read-only agent registry and dispatch lookup. Without `agent`: the catalog of every canonical ' +
20
- 'SoMi agent with the aliases hosts actually register for it and its default tier. With `agent` ' +
21
- '(a canonical name such as "somi-coder" or a registered alias such as "somi:somi-coder"): the ' +
22
- 'canonical agent, the alias that matched, `agent_type` (the id to pass as the host subagent ' +
23
- 'type), and the tier and model it would run at right now on `host` — from the same resolver as ' +
24
- 'somi_resolve, but nothing is written: no ceiling is set or remembered. Failures: 64 invalid ' +
25
- 'identifier or arguments, 65 unknown agent or alias (never routed to another agent), 67 ' +
26
- 'project environment failure (as somi_resolve).',
27
- inputSchema: {
28
- type: 'object',
29
- properties: {
30
- agent: { type: 'string', description: 'canonical name or registered alias; omit for the catalog' },
31
- host: { type: 'string', description: '"claude-code" or "copilot"; defaults to "claude-code"' },
32
- project_dir: { type: 'string', description: 'absolute path of the consuming project, as for somi_resolve (lookup only)' },
33
- },
34
- },
35
- };
36
-
37
- const fail = (code, message) => ({ ok: false, code, message });
38
-
39
- /**
40
- * @param {{agent?: unknown, host?: unknown}} args
41
- * @param {{resolveRoot: () => Promise<{ok: boolean, root?: string, code?: number, message?: string}>, installRoot: string}} env
42
- * @returns {Promise<{ok: true, result: object} | {ok: false, code: number, message: string}>}
43
- */
44
- export async function agentInfo(args, { resolveRoot, installRoot }) {
45
- const host = args?.host;
46
- if (host !== undefined && (typeof host !== 'string' || !HOST_RE.test(host))) {
47
- return fail(EXIT_USAGE, `host must be a lowercase host name, got ${JSON.stringify(host)}`);
48
- }
49
- if (args?.agent === undefined) return { ok: true, result: { agents: catalog(REGISTRY) } };
50
- const n = normalize(REGISTRY, args.agent);
51
- if (!n.ok) return fail(n.reason === 'invalid' ? EXIT_USAGE : EXIT_UNKNOWN_AGENT, n.message);
52
- const HOST = host || 'claude-code';
53
- const identity = {
54
- requested_as: args.agent,
55
- canonical_name: n.canonical,
56
- matched_alias: n.matched_alias,
57
- aliases: REGISTRY.aliasesOf.get(n.canonical).filter((a) => a !== n.matched_alias),
58
- agent_type: agentTypeFor(REGISTRY, n.canonical, HOST),
59
- host: HOST,
60
- };
61
- if (n.canonical === ORCHESTRATOR) {
62
- return { ok: true, result: { ...identity, role: 'orchestrator', dispatch: null, reason: 'the front door is selected by the user, never dispatched; the host binds its model' } };
63
- }
64
- const root = await resolveRoot();
65
- if (!root.ok) return fail(root.code, root.message);
66
- const outcome = resolveDispatch({ agent: n.canonical, host: HOST, projectRoot: root.root, installRoot, persist: false });
67
- if (!outcome.ok) return outcome;
68
- const r = outcome.result;
69
- return {
70
- ok: true,
71
- result: {
72
- ...identity,
73
- role: 'specialist',
74
- session_ceiling: { value: r.ceiling, source: r.ceiling_source, origin: r.ceiling_origin },
75
- default_tier: r.declared[0],
76
- dispatch_tier: r.tier,
77
- tier_source: r.tier_source,
78
- degraded: r.degraded,
79
- model: r.model,
80
- ...(r.model_candidates ? { model_candidates: r.model_candidates } : {}),
81
- enforced: r.enforced,
82
- ...(r.reason ? { reason: r.reason } : {}),
83
- },
84
- };
85
- }
@@ -1,92 +0,0 @@
1
- // agent-registry.mjs — the one source of SoMi agent identity: canonical names, the aliases hosts
2
- // actually register for them, and the normalisation from either one to the canonical name.
3
- //
4
- // Canonical names are the default tier table's keys (every specialist, `somi-` prefixed) plus the
5
- // front-door orchestrator `somi`, which is exempt from cost resolution. tests/scripts/agent-registry.sh
6
- // keeps this set equal to agents/*.md.
7
- //
8
- // Aliases are never guessed. A host that registers SoMi's plugin agents under ids of its own is
9
- // declared in HOST_REGISTRATIONS with the rule it applies; an alias exists only for a host listed
10
- // there. Both shipped hosts namespace a plugin agent as `<plugin>:<file stem>`:
11
- // - copilot: the loader in Copilot CLI 1.0.70 (configLoaderParsePluginAgentFile in its runtime.node),
12
- // run on this repo, returns ids such as `somi:somi-planner`; its task tool accepts any registered
13
- // id and rejects a bare stem with `Unknown agent_type`.
14
- // - claude-code: the Task tool lists plugin agents as `somi:<file stem>`.
15
- // So today every agent has exactly one alias, `somi:<canonical>`, registered on both hosts. The
16
- // pre-4.0.0 bare names (`coder`) are deliberately NOT aliases: they are unknown, with a derived hint.
17
-
18
- import { AGENT_DEFAULT_TIERS } from './cost-defaults.mjs';
19
-
20
- export const PLUGIN_NAME = 'somi';
21
- export const ORCHESTRATOR = 'somi';
22
-
23
- // host -> the id that host's subagent tool takes for a plugin agent's canonical name.
24
- export const HOST_REGISTRATIONS = Object.freeze({
25
- 'claude-code': (canonical) => `${PLUGIN_NAME}:${canonical}`,
26
- copilot: (canonical) => `${PLUGIN_NAME}:${canonical}`,
27
- });
28
-
29
- // An identifier as a caller may supply it: a canonical name, or `<plugin>:<name>`. Checked before
30
- // any lookup, so nothing downstream ever sees an unvalidated string.
31
- export const IDENTIFIER_RE = /^[a-z0-9][a-z0-9-]{0,63}(?::[a-z0-9][a-z0-9-]{0,63})?$/;
32
-
33
- export class RegistryError extends Error {}
34
-
35
- /**
36
- * Builds the registry from a tier table and host registrations (both overridable for tests).
37
- * Throws RegistryError when one alias would map to two agents or shadow a canonical name.
38
- */
39
- export function buildRegistry(table = AGENT_DEFAULT_TIERS, registrations = HOST_REGISTRATIONS) {
40
- const specialists = Object.keys(table).sort();
41
- const agents = [...specialists, ORCHESTRATOR];
42
- const canonical = new Set(agents);
43
- const aliasOwner = new Map();
44
- const aliasesOf = new Map(agents.map((n) => [n, []]));
45
- const agentTypes = new Map(agents.map((n) => [n, {}]));
46
- for (const host of Object.keys(registrations).sort()) {
47
- for (const name of agents) {
48
- const alias = registrations[host](name);
49
- agentTypes.get(name)[host] = alias;
50
- if (alias === name) continue;
51
- if (canonical.has(alias)) throw new RegistryError(`alias "${alias}" (host ${host}) shadows the canonical agent "${alias}"`);
52
- const owner = aliasOwner.get(alias);
53
- if (owner !== undefined && owner !== name) throw new RegistryError(`alias "${alias}" maps to both "${owner}" and "${name}"`);
54
- if (owner === undefined) {
55
- aliasOwner.set(alias, name);
56
- aliasesOf.get(name).push(alias);
57
- }
58
- }
59
- }
60
- return { specialists, canonical, aliasOwner, aliasesOf, agentTypes, table };
61
- }
62
-
63
- /**
64
- * -> {ok: true, canonical, matched_alias} | {ok: false, reason: 'invalid'|'unknown', message}.
65
- * An identifier that is a pre-4.0.0 bare name gets a hint, derived rather than stored.
66
- */
67
- export function normalize(registry, identifier) {
68
- if (typeof identifier !== 'string' || !IDENTIFIER_RE.test(identifier)) {
69
- return { ok: false, reason: 'invalid', message: `invalid agent identifier ${JSON.stringify(identifier)} (expected ${IDENTIFIER_RE})` };
70
- }
71
- if (registry.canonical.has(identifier)) return { ok: true, canonical: identifier, matched_alias: null };
72
- const owner = registry.aliasOwner.get(identifier);
73
- if (owner !== undefined) return { ok: true, canonical: owner, matched_alias: identifier };
74
- const renamed = `somi-${identifier}`;
75
- const hint = registry.canonical.has(renamed) ? ` (renamed in 4.0.0: use "${renamed}")` : '';
76
- return { ok: false, reason: 'unknown', message: `unknown agent "${identifier}"${hint}` };
77
- }
78
-
79
- /** The id `host`'s subagent tool takes for `canonical`, or null when the host registers none. */
80
- export function agentTypeFor(registry, canonical, host) {
81
- return registry.agentTypes.get(canonical)?.[host] ?? null;
82
- }
83
-
84
- /** The catalog: one entry per agent, specialists first, in name order. */
85
- export function catalog(registry) {
86
- return [...registry.specialists, ORCHESTRATOR].map((name) => ({
87
- canonical_name: name,
88
- role: name === ORCHESTRATOR ? 'orchestrator' : 'specialist',
89
- aliases: [...registry.aliasesOf.get(name)],
90
- default_tier: registry.table[name] ?? null,
91
- }));
92
- }
@@ -1,328 +0,0 @@
1
- // cost-ceiling.mjs — the session cost ceiling: the tier every dispatch runs at unless an agent has
2
- // its own override in .somi/config.json.
3
- //
4
- // "The config" below is the effective one: the global file with the project's .somi/config.json
5
- // merged over it (scripts/lib/config-files.mjs).
6
- //
7
- // The ceiling is re-resolved on every call, nothing is frozen once. Precedence, highest first:
8
- // 1. a value given THIS call: an argument the caller parsed itself (a CLI flag) or SOMI_COST_CEILING
9
- // 2. `cost.ceiling` in .somi/config.json, read live on every call
10
- // 3. a ceiling persisted by an earlier call, but only one that call took from a CLI flag or the env
11
- // var (a ceiling someone explicitly set), and only when the config sets none
12
- // 4. DEFAULT_CEILING
13
- // So a bare edit to .somi/config.json moves the ceiling on the very next dispatch. That reverses the
14
- // older rule (and the loop-cap precedent in scripts/somi-loop.mjs) under which a config edit could
15
- // not move a ceiling already in force. A persisted ceiling that was itself taken from the config,
16
- // the default, or from before origins were recorded never outranks 2 or 4 -- it yields, so it can
17
- // not pin a stale value after a config fix or a change of default.
18
- //
19
- // Only a CLI/env value is ever written to disk. Every value that reaches validateCeiling() is
20
- // rejected outright if it isn't one of VALID_COSTS -- never coerced -- so a malformed value dies
21
- // loudly instead of quietly disabling the ceiling.
22
- //
23
- // State is deliberately NOT keyed by slug (unlike loop state): the ceiling bounds an operator's
24
- // spend for the whole session, not one slice of work, so one file covers every dispatch.
25
- // Callers pass `root` explicitly rather than this module sniffing CLAUDE_PROJECT_DIR itself --
26
- // keeps the module a pure library over explicit inputs, testable without env-var setup.
27
- //
28
- // Every raise is appended to `ceiling_overrides`, shaped {field, from, to, source, at} -- the same
29
- // shape somi-loop.mjs's `cap_overrides` uses, so an override record looks the same wherever it's
30
- // read from. Created lazily, only on the first real override.
31
-
32
- import fs from 'node:fs';
33
- import path from 'node:path';
34
- import { resolveModel, VALID_COSTS } from './cost-model.mjs';
35
- import { validateCostConfig, quote } from './cost-config.mjs';
36
- import { loadConfig, ConfigFileError, MAX_CONFIG_BYTES as CONFIG_LIMIT } from './config-files.mjs';
37
-
38
- export const CEILING_ENV = 'SOMI_COST_CEILING';
39
- export const DEFAULT_CEILING = 'medium';
40
- export const ACTIONS = Object.freeze(['allow']);
41
-
42
- const ORDER = Object.freeze(Object.fromEntries(VALID_COSTS.map((c, i) => [c, i])));
43
-
44
- export function ceilingStatePath(root) {
45
- return path.join(root, '.somi', 'somi-state', 'ceiling.json');
46
- }
47
-
48
- function nowIso() {
49
- return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
50
- }
51
-
52
- // A file this large is neither a config nor a state file, so it is refused rather than parsed.
53
- export const MAX_CONFIG_BYTES = CONFIG_LIMIT;
54
-
55
- // The reader for SoMi's own state files (the persisted ceiling): opened with O_NOFOLLOW (a planted
56
- // symlink -- say to /dev/zero -- is refused, never followed) and O_NONBLOCK (a FIFO cannot hang the
57
- // open), then checked on the open descriptor, not the path, so there is no stat-then-read race. At
58
- // most MAX_CONFIG_BYTES+1 bytes are ever read. Config files are read by config-files.mjs instead,
59
- // which follows links (a junction or symlinked .somi, a linked config) under the same other checks.
60
- const OPEN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
61
-
62
- export function readTextFile(file) {
63
- let fd;
64
- try {
65
- fd = fs.openSync(file, OPEN_FLAGS);
66
- } catch (e) {
67
- if (e.code === 'ELOOP') throw new Error(`cost-ceiling: ${file} is a symlink; refusing to follow it`);
68
- throw e;
69
- }
70
- try {
71
- if (!fs.fstatSync(fd).isFile()) throw new Error(`cost-ceiling: ${file} is not a regular file`);
72
- const buf = Buffer.alloc(MAX_CONFIG_BYTES + 1);
73
- let n = 0;
74
- while (n < buf.length) {
75
- const got = fs.readSync(fd, buf, n, buf.length - n, null);
76
- if (got === 0) break;
77
- n += got;
78
- }
79
- if (n > MAX_CONFIG_BYTES) throw new Error(`cost-ceiling: ${file} is over the ${MAX_CONFIG_BYTES}-byte limit`);
80
- return buf.toString('utf8', 0, n);
81
- } finally {
82
- fs.closeSync(fd);
83
- }
84
- }
85
-
86
- // The parser's own message quotes file text (untrusted, and it reaches the model), so only its error
87
- // name and numeric position are reported.
88
- function parseFailure(file, e) {
89
- const pos = /position (\d+)/.exec(String(e.message))?.[1];
90
- return new Error(`cost-ceiling: ${file} is not valid JSON (${JSON.stringify(e.name)}${pos ? ` at position ${pos}` : ''})`);
91
- }
92
-
93
- // The effective config. A file that fails to PARSE is not "unconfigured" -- silently returning {}
94
- // would bootstrap DEFAULT_CEILING and PERSIST it, inverting a team's `low` policy until someone
95
- // notices, and outliving the typo once fixed. Dies loudly, naming the file.
96
- export function readConfig(root) {
97
- try {
98
- return loadConfig(root).config;
99
- } catch (e) {
100
- if (e instanceof ConfigFileError) throw new Error(`cost-ceiling: ${e.message}`);
101
- throw e;
102
- }
103
- }
104
-
105
- // A `cost` that isn't an object, has an unrecognized key (a typo), or a `ceiling` misplaced at
106
- // the top level all die loudly here instead of silently resolving to "not configured".
107
- //
108
- // Exported: this is also the one config reader scripts/somi-dispatch.mjs uses to pull `mapping`
109
- // (its `ceiling` sibling), so a project's cost config is never parsed by two independent readers
110
- // that could drift on what counts as malformed.
111
- // Each file's own cost block is validated first, so an error names the file it is in; then the merge.
112
- export function readCostConfig(root) {
113
- let files;
114
- try {
115
- files = loadConfig(root);
116
- } catch (e) {
117
- if (e instanceof ConfigFileError) throw new Error(`cost-ceiling: ${e.message}`);
118
- throw e;
119
- }
120
- for (const f of [files.global, files.project]) {
121
- if (!f.present) continue;
122
- if (f.config.ceiling !== undefined) throw new Error(`cost-ceiling: "ceiling" in ${f.path} belongs under "cost.ceiling"`);
123
- try { validateCostConfig(f.config.cost); } catch (e) { throw new Error(`${e.message} (in ${f.path})`); }
124
- }
125
- return validateCostConfig(files.config.cost);
126
- }
127
-
128
- function validateCeiling(raw, label) {
129
- if (!VALID_COSTS.includes(raw)) {
130
- throw new Error(`cost-ceiling: ${label} expected one of ${VALID_COSTS.join('|')}, got ${quote(raw)}`);
131
- }
132
- return raw;
133
- }
134
-
135
- // What produced a persisted ceiling. Only `cli` and `env` are ever written now; `config` and `default`
136
- // are what earlier versions wrote, and are accepted (never rewritten) so an old state file still
137
- // loads. A state file with no origin at all (one written before origins were recorded) is legacy: it yields.
138
- const VALID_ORIGINS = Object.freeze(['config', 'cli', 'env', 'default']);
139
- const EXPLICIT_ORIGINS = Object.freeze(['cli', 'env']);
140
-
141
- function validateOrigin(raw, label) {
142
- if (!VALID_ORIGINS.includes(raw)) {
143
- throw new Error(`cost-ceiling: ${label} expected one of ${VALID_ORIGINS.join('|')}, got ${quote(raw)}`);
144
- }
145
- return raw;
146
- }
147
-
148
- function saveState(root, state) {
149
- const file = ceilingStatePath(root);
150
- fs.mkdirSync(path.dirname(file), { recursive: true });
151
- // Written to a fresh exclusive temp file (O_NOFOLLOW) and renamed over the target: the rename
152
- // replaces a symlink planted at ceiling.json instead of writing through it, and a reader never
153
- // sees a half-written file.
154
- const tmp = `${file}.${process.pid}.tmp`;
155
- const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
156
- try {
157
- const fd = fs.openSync(tmp, flags, 0o666);
158
- try { fs.writeSync(fd, JSON.stringify(state)); } finally { fs.closeSync(fd); }
159
- fs.renameSync(tmp, file);
160
- } catch (e) {
161
- fs.rmSync(tmp, { force: true });
162
- throw e;
163
- }
164
- }
165
-
166
- // Returns the persisted state, or undefined when there is none. A PRESENT but corrupt file is not
167
- // silently treated as missing -- it throws, same "malformed dies loudly" discipline as a bad
168
- // CLI/env value. Read with the same no-follow, regular-file, size-bounded helper as the config.
169
- export function loadState(root) {
170
- const file = ceilingStatePath(root);
171
- let raw;
172
- try {
173
- raw = readTextFile(file);
174
- } catch (e) {
175
- if (e.code === 'ENOENT') return undefined;
176
- throw e;
177
- }
178
- // An unparsable state file must still name the file in its error -- a bare JSON.parse throw would
179
- // surface as an unattributed SyntaxError, leaving a caller no path to report which file is corrupt.
180
- let state;
181
- try {
182
- state = JSON.parse(raw);
183
- } catch (e) {
184
- throw parseFailure(file, e);
185
- }
186
- if (state === null || typeof state !== 'object' || Array.isArray(state)) {
187
- throw new Error(`cost-ceiling: ${file} is not a valid state object`);
188
- }
189
- state.ceiling = validateCeiling(state.ceiling, `ceiling in ${file}`);
190
- // Absent entirely is legacy (it yields), not corruption; present but wrong is rejected.
191
- if (state.ceiling_origin !== undefined) validateOrigin(state.ceiling_origin, `ceiling_origin in ${file}`);
192
- return state;
193
- }
194
-
195
- /**
196
- * Re-resolves the session ceiling for one dispatch. `explicitArg` is a value the caller already
197
- * extracted THIS invocation (e.g. a parsed CLI flag) -- distinct from SOMI_COST_CEILING, read here.
198
- * Precedence is in this file's header: explicit (arg, then env) > config > persisted CLI/env > default.
199
- * `source` names where THIS call's effective ceiling came from: `cli`, `env`, `config`, `state` (a
200
- * ceiling persisted by an earlier CLI/env call) or `default`. `ceiling_origin` is what produced the
201
- * value: the same, except a `state` ceiling reports the `cli`/`env` that originally set it.
202
- * A CLI/env value that differs from what is persisted is saved (with an override record); that is the
203
- * only write this function makes, and `{persist: false}` skips it (a read-only lookup such as
204
- * somi_agent_info reports the same answer without remembering anything).
205
- * @returns {{ceiling: string, overridden: boolean, source: string, ceiling_origin: string, override?: object}}
206
- */
207
- export function resolveCeiling(root, explicitArg, { persist = true } = {}) {
208
- const state = loadState(root);
209
- const configured = readCostConfig(root).ceiling;
210
- const isConfigured = !(configured === undefined || configured === null || configured === '');
211
- const isCli = explicitArg !== undefined && explicitArg !== '';
212
- const envVal = process.env[CEILING_ENV];
213
- const explicit = isCli ? explicitArg : (envVal === undefined || envVal === '' ? undefined : envVal);
214
-
215
- if (explicit === undefined) {
216
- if (isConfigured) {
217
- const ceiling = validateCeiling(configured, 'cost.ceiling in .somi/config.json');
218
- return { ceiling, overridden: false, source: 'config', ceiling_origin: 'config' };
219
- }
220
- if (state && EXPLICIT_ORIGINS.includes(state.ceiling_origin)) {
221
- return { ceiling: state.ceiling, overridden: false, source: 'state', ceiling_origin: state.ceiling_origin };
222
- }
223
- return { ceiling: DEFAULT_CEILING, overridden: false, source: 'default', ceiling_origin: 'default' };
224
- }
225
-
226
- // A config that sets a ceiling is validated even when a CLI/env value outranks it: a typo there
227
- // should surface now, not on the later call that lacks the flag.
228
- if (isConfigured) validateCeiling(configured, 'cost.ceiling in .somi/config.json');
229
- const source = isCli ? 'cli' : 'env';
230
- const validated = validateCeiling(explicit, isCli ? '--ceiling' : CEILING_ENV);
231
- const persisted = state && EXPLICIT_ORIGINS.includes(state.ceiling_origin) ? state : undefined;
232
- // Nothing to do only when the stored value already matches AND no differing config is being raised
233
- // over (then the effective ceiling changes and the raise is recorded below).
234
- const configDiffers = isConfigured && configured !== validated;
235
- if (persisted && persisted.ceiling === validated && persisted.ceiling_origin === source && !configDiffers) {
236
- return { ceiling: validated, overridden: false, source, ceiling_origin: source };
237
- }
238
- const next = state ?? {};
239
- // The override record's `from` is the ceiling that was in force before this call.
240
- const from = isConfigured ? configured : (persisted ? persisted.ceiling : DEFAULT_CEILING);
241
- next.ceiling = validated;
242
- next.ceiling_origin = source;
243
- if (from === validated) {
244
- if (persist) saveState(root, next);
245
- return { ceiling: validated, overridden: false, source, ceiling_origin: source };
246
- }
247
- const override = { field: 'ceiling', from, to: validated, source, at: nowIso() };
248
- if (!Array.isArray(next.ceiling_overrides)) next.ceiling_overrides = [];
249
- // A repeat of the identical raise (same flag every call, config unchanged) is not a new event.
250
- const last = next.ceiling_overrides[next.ceiling_overrides.length - 1];
251
- if (!(last && last.from === from && last.to === validated && last.source === source)) next.ceiling_overrides.push(override);
252
- if (persist) saveState(root, next);
253
- return { ceiling: validated, overridden: true, source, ceiling_origin: source, override };
254
- }
255
-
256
- // The `costs` argument is a tier set in ascending order; the resolver passes the agent's single
257
- // default tier. Accepts a bare string too, as a one-member set, so a single-tier caller needs no
258
- // special-casing. Always returns a frozen array in ascending order, re-checked here rather than
259
- // trusted: this is a library over
260
- // explicit inputs, and a malformed set must die loudly rather than be silently coerced into
261
- // something valid -- the same discipline validateCeiling() above applies to the ceiling value.
262
- function normalizeCostSet(costs, label) {
263
- const arr = Array.isArray(costs) ? costs : [costs];
264
- if (arr.length === 0) {
265
- throw new Error(`cost-ceiling: ${label} must declare at least one cost value`);
266
- }
267
- let prevRank = -1;
268
- for (const c of arr) {
269
- if (!VALID_COSTS.includes(c)) {
270
- throw new Error(`cost-ceiling: ${label} has an unrecognized value "${c}" (expected one of ${VALID_COSTS.join('|')})`);
271
- }
272
- const rank = ORDER[c];
273
- if (rank <= prevRank) {
274
- throw new Error(`cost-ceiling: ${label} must be strictly ascending with no duplicates, got "${arr.join(',')}"`);
275
- }
276
- prevRank = rank;
277
- }
278
- return Object.freeze([...arr]);
279
- }
280
-
281
- /**
282
- * Selects the tier a dispatch runs at. The ceiling is a HARD cap with one escape hatch:
283
- *
284
- * - `override` given (the agent's `cost.agents.<name>` from config) -> `selected` is the override,
285
- * even above the ceiling. `tier_source` is `"override"`.
286
- * - no override -> `selected` is the CEILING tier itself, whatever the unit's default tier is (not that
287
- * default, not a min() of the two). `tier_source` is `"ceiling"`.
288
- *
289
- * `costs` (the unit's default tier set, a string or an ascending duplicate-free array) is
290
- * read only to report: `supported` echoes it, and `degraded` is true when `selected` ranks below
291
- * its highest member. It never changes `selected`: declaring a tier never lowers or raises the run.
292
- *
293
- * Pure and deterministic; the result is frozen so a caller can't rewrite the selection.
294
- */
295
- export function decideDispatch(costs, ceiling, override) {
296
- const supported = normalizeCostSet(costs, 'default tier');
297
- if (!VALID_COSTS.includes(ceiling)) {
298
- throw new Error(`cost-ceiling: unrecognized ceiling "${ceiling}" (expected one of ${VALID_COSTS.join('|')})`);
299
- }
300
- if (override !== undefined && !VALID_COSTS.includes(override)) {
301
- throw new Error(`cost-ceiling: unrecognized override "${override}" (expected one of ${VALID_COSTS.join('|')})`);
302
- }
303
- const selected = override === undefined ? ceiling : override;
304
- const degraded = ORDER[selected] < ORDER[supported[supported.length - 1]];
305
- return Object.freeze({
306
- action: 'allow',
307
- selected,
308
- supported,
309
- ceiling,
310
- degraded,
311
- tier_source: override === undefined ? 'ceiling' : 'override',
312
- });
313
- }
314
-
315
- /**
316
- * The only sanctioned way to turn a decideDispatch() result into a model. `decideDispatch` always
317
- * returns "allow" now, so this guard is unreachable by construction -- kept anyway as the
318
- * structural closer: nothing can hand this function a decision that wasn't produced by
319
- * `decideDispatch`'s own selection and expect a model back.
320
- */
321
- export function modelForDispatch(decision, host, mapping) {
322
- if (!decision || decision.action !== 'allow') {
323
- throw new Error(
324
- `cost-ceiling: modelForDispatch requires an "allow" decision (one of ${ACTIONS.join('|')}), got "${decision?.action}"`
325
- );
326
- }
327
- return resolveModel(decision.selected, host, mapping);
328
- }
@@ -1,102 +0,0 @@
1
- // cost-config-edit.mjs — the pure edit step shared by scripts/somi-config.mjs, the cost-lowering
2
- // PreToolUse hook and the tests: parse a key, check a tier, and apply set/unset/init to an
3
- // already-parsed config. No I/O. Only cost.ceiling and cost.agents.<name> can be edited.
4
-
5
- import { validateCostConfig, quote } from './cost-config.mjs';
6
- import { VALID_COSTS, MODEL_ID_RE, MAX_MODEL_CANDIDATES, mergeHostMapping, resolveModelCandidates } from './cost-model.mjs';
7
- import { buildDefaultConfig } from './cost-defaults.mjs';
8
-
9
- // A caller mistake (bad key, tier or name), as opposed to a problem with the project's files.
10
- export class EditError extends Error {}
11
-
12
- const KEY_RE = /^cost\.(ceiling|agents\.([a-z][a-z0-9-]*)|mapping\.([a-z][a-z0-9-]{0,31})(?:\.(low|medium|high))?)$/;
13
-
14
- /**
15
- * -> {kind:'ceiling'} | {kind:'agent', name} | {kind:'mapping', host, tier?}; throws EditError for any
16
- * other key. `cost.mapping.<host>.<tier>` is set; `cost.mapping.<host>` (the whole host map) is unset.
17
- */
18
- export function parseKey(key) {
19
- const m = KEY_RE.exec(key);
20
- if (!m) throw new EditError(`only cost.ceiling, cost.agents.<name> and cost.mapping.<host>[.<tier>] can be used, not ${quote(key)}`);
21
- if (m[1] === 'ceiling') return { kind: 'ceiling' };
22
- if (m[2] !== undefined) return { kind: 'agent', name: m[2] };
23
- return { kind: 'mapping', host: m[3], tier: m[4] };
24
- }
25
-
26
- /** A model value: one id, or a comma-separated preference list (#35) -> a string or an array. */
27
- export function parseModels(v) {
28
- const list = typeof v === 'string' ? v.split(',').map((x) => x.trim()) : [];
29
- if (list.length === 0 || list.length > MAX_MODEL_CANDIDATES || list.some((x) => !MODEL_ID_RE.test(x)) || new Set(list).size !== list.length) {
30
- throw new EditError(`the value must be a model id or up to ${MAX_MODEL_CANDIDATES} distinct comma-separated ids, got ${quote(v)}`);
31
- }
32
- return list.length === 1 ? list[0] : list;
33
- }
34
-
35
- /** The tiers a named host's map still lacks (a host in cost.mapping replaces its whole tier map). */
36
- export function missingMappingTiers(cost, host) {
37
- const tiers = cost?.mapping?.[host];
38
- return tiers ? VALID_COSTS.filter((t) => !Object.hasOwn(tiers, t)) : [];
39
- }
40
-
41
- export function parseTier(v) {
42
- if (!VALID_COSTS.includes(v)) throw new EditError(`the tier must be one of ${VALID_COSTS.join('|')}, got ${quote(v)}`);
43
- return v;
44
- }
45
-
46
- /** Throws unless the whole cost block is legal (keys, agent names, tiers, ceiling value). */
47
- export function validateCostBlock(cost) {
48
- validateCostConfig(cost);
49
- if (cost && cost.mapping !== undefined) {
50
- const merged = mergeHostMapping({}, cost.mapping);
51
- for (const host of Object.keys(merged)) for (const tier of Object.keys(merged[host])) resolveModelCandidates(tier, host, merged);
52
- }
53
- if (cost && cost.ceiling !== undefined && !VALID_COSTS.includes(cost.ceiling)) {
54
- throw new Error(`cost-ceiling: cost.ceiling expected one of ${VALID_COSTS.join('|')}, got ${quote(cost.ceiling)}`);
55
- }
56
- }
57
-
58
- /**
59
- * Applies one edit to `cfg` (a parsed config object, or null for an absent file) IN PLACE where it
60
- * can, and returns {next, changed}. `action` is set|unset|init. A set or init on an absent file
61
- * starts from the default config; an unset of an absent file or entry changes nothing. The result is
62
- * not validated here: callers run validateCostBlock(next.cost) so each can report it its own way.
63
- */
64
- export function applyEdit(cfg, { action, key, value }) {
65
- const absent = cfg === null || cfg === undefined;
66
- if (action === 'init') return absent ? { next: buildDefaultConfig(), changed: true } : { next: cfg, changed: false };
67
- const k = parseKey(key);
68
- if (action === 'unset') {
69
- if (k.kind === 'mapping' && k.tier === undefined) {
70
- if (absent || !(cfg.cost?.mapping && Object.hasOwn(cfg.cost.mapping, k.host))) return { next: cfg ?? {}, changed: false };
71
- delete cfg.cost.mapping[k.host];
72
- if (Object.keys(cfg.cost.mapping).length === 0) delete cfg.cost.mapping;
73
- return { next: cfg, changed: true };
74
- }
75
- if (k.kind !== 'agent') throw new EditError('only cost.agents.<name> and cost.mapping.<host> can be unset');
76
- if (absent || !(cfg.cost?.agents && Object.hasOwn(cfg.cost.agents, k.name))) return { next: cfg ?? {}, changed: false };
77
- delete cfg.cost.agents[k.name];
78
- return { next: cfg, changed: true };
79
- }
80
- if (action !== 'set') throw new EditError('the action must be set, unset or init');
81
- if (k.kind === 'mapping') {
82
- if (k.tier === undefined) throw new EditError('set one tier at a time: cost.mapping.<host>.<low|medium|high>');
83
- const models = parseModels(value);
84
- const base = absent ? buildDefaultConfig() : cfg;
85
- const before = JSON.stringify(base.cost ?? null);
86
- if (base.cost === undefined || base.cost === null) base.cost = {};
87
- if (base.cost.mapping === undefined) base.cost.mapping = {};
88
- if (base.cost.mapping[k.host] === undefined) base.cost.mapping[k.host] = {};
89
- base.cost.mapping[k.host][k.tier] = models;
90
- return { next: base, changed: absent || JSON.stringify(base.cost) !== before };
91
- }
92
- const tier = parseTier(value);
93
- const next = absent ? buildDefaultConfig() : cfg;
94
- const before = JSON.stringify(next.cost ?? null);
95
- if (next.cost === undefined || next.cost === null) next.cost = {};
96
- if (k.kind === 'ceiling') next.cost.ceiling = tier;
97
- else {
98
- if (next.cost.agents === undefined) next.cost.agents = {};
99
- next.cost.agents[k.name] = tier;
100
- }
101
- return { next, changed: absent || JSON.stringify(next.cost) !== before };
102
- }