@fantasticit/sumi 0.13.0 → 0.14.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 (452) hide show
  1. package/README.md +7 -7
  2. package/dist/adapters.d.ts +3 -27
  3. package/dist/adapters.js +75 -134
  4. package/dist/adapters.js.map +1 -1
  5. package/dist/agent-hooks.d.ts +32 -11
  6. package/dist/agent-hooks.js +546 -194
  7. package/dist/agent-hooks.js.map +1 -1
  8. package/dist/agents.d.ts +1 -3
  9. package/dist/agents.js +12 -15
  10. package/dist/agents.js.map +1 -1
  11. package/dist/bin.js +14 -10
  12. package/dist/bin.js.map +1 -1
  13. package/dist/cli.d.ts +1 -1
  14. package/dist/cli.js +122 -7
  15. package/dist/cli.js.map +1 -1
  16. package/dist/compaction-marker.d.ts +4 -0
  17. package/dist/compaction-marker.js +37 -0
  18. package/dist/compaction-marker.js.map +1 -0
  19. package/dist/config-text.d.ts +1 -1
  20. package/dist/config-text.js +21 -13
  21. package/dist/config-text.js.map +1 -1
  22. package/dist/constraint-list.js +1 -1
  23. package/dist/constraint-list.js.map +1 -1
  24. package/dist/context-providers.js +12 -0
  25. package/dist/context-providers.js.map +1 -0
  26. package/dist/context.js +49 -51
  27. package/dist/context.js.map +1 -1
  28. package/dist/declared-hooks.d.ts +29 -0
  29. package/dist/declared-hooks.js +99 -0
  30. package/dist/declared-hooks.js.map +1 -0
  31. package/dist/hook-output.d.ts +3 -0
  32. package/dist/hook-output.js +5 -0
  33. package/dist/hook-output.js.map +1 -0
  34. package/dist/hook-routing.d.ts +29 -1
  35. package/dist/hook-routing.js +88 -13
  36. package/dist/hook-routing.js.map +1 -1
  37. package/dist/host-adapters.d.ts +32 -0
  38. package/dist/host-adapters.js +97 -0
  39. package/dist/host-adapters.js.map +1 -0
  40. package/dist/instructions.js +7 -5
  41. package/dist/instructions.js.map +1 -1
  42. package/dist/run-stats.d.ts +6 -0
  43. package/dist/run-stats.js +44 -3
  44. package/dist/run-stats.js.map +1 -1
  45. package/dist/scaffold-commands.js +18 -7
  46. package/dist/scaffold-commands.js.map +1 -1
  47. package/dist/stop-hint.d.ts +4 -0
  48. package/dist/stop-hint.js +29 -0
  49. package/dist/stop-hint.js.map +1 -0
  50. package/dist/subagent-history.d.ts +2 -0
  51. package/dist/subagent-history.js +35 -0
  52. package/dist/subagent-history.js.map +1 -0
  53. package/dist/task.js +45 -37
  54. package/dist/task.js.map +1 -1
  55. package/dist/vendor.js +10 -4
  56. package/dist/vendor.js.map +1 -1
  57. package/dist/visualize-page.js +2 -25
  58. package/dist/visualize-page.js.map +1 -1
  59. package/node_modules/@sumi/create/dist/scaffold.js +5 -4
  60. package/node_modules/@sumi/create/dist/scaffold.js.map +1 -1
  61. package/node_modules/@sumi/create/package.json +2 -2
  62. package/node_modules/@sumi/create/template/AGENTS.md +1 -1
  63. package/node_modules/@sumi/create/template/control/config.yaml +3 -0
  64. package/node_modules/@sumi/create/template/control/flows/change.flow.yaml +8 -5
  65. package/node_modules/@sumi/create/template/control/flows/check.flow.yaml +7 -21
  66. package/node_modules/@sumi/create/template/control/rubrics/behavior.yaml +14 -1
  67. package/node_modules/@sumi/create/template/control/rubrics/omission.yaml +1 -1
  68. package/node_modules/@sumi/create/template/control/rubrics/{clean-code.yaml → quality.yaml} +12 -4
  69. package/node_modules/@sumi/create/template/control/rules/boundaries.md +25 -0
  70. package/node_modules/@sumi/create/template/control/rules/codecheck.md +1 -1
  71. package/node_modules/@sumi/create/template/control/rules/development.md +7 -2
  72. package/node_modules/@sumi/create/template/init/AGENTS.md +1 -1
  73. package/node_modules/@sumi/create/template/init/control/flows/change.flow.yaml +7 -4
  74. package/node_modules/@sumi/create/template/init/control/flows/check.flow.yaml +3 -0
  75. package/node_modules/@sumi/create/template/init/control/rubrics/behavior.yaml +30 -0
  76. package/node_modules/@sumi/create/template/init/control/rubrics/omission.yaml +13 -0
  77. package/node_modules/@sumi/create/template/init/control/rubrics/quality.yaml +22 -0
  78. package/node_modules/@sumi/create/template/init/control/rubrics/security.yaml +20 -0
  79. package/node_modules/@sumi/create/template/init/openspec/config.yaml +6 -0
  80. package/node_modules/@sumi/create/template/openspec/config.yaml +6 -0
  81. package/node_modules/@sumi/kernel/dist/config.d.ts +13 -0
  82. package/node_modules/@sumi/kernel/dist/config.js +23 -2
  83. package/node_modules/@sumi/kernel/dist/config.js.map +1 -1
  84. package/node_modules/@sumi/kernel/dist/context-providers.d.ts +17 -0
  85. package/node_modules/@sumi/kernel/dist/context-providers.js +74 -0
  86. package/node_modules/@sumi/kernel/dist/context-providers.js.map +1 -0
  87. package/node_modules/@sumi/kernel/dist/engine.js +119 -71
  88. package/node_modules/@sumi/kernel/dist/engine.js.map +1 -1
  89. package/node_modules/@sumi/kernel/dist/flow.d.ts +7 -0
  90. package/node_modules/@sumi/kernel/dist/flow.js +16 -0
  91. package/node_modules/@sumi/kernel/dist/flow.js.map +1 -1
  92. package/node_modules/@sumi/kernel/dist/index.d.ts +3 -0
  93. package/node_modules/@sumi/kernel/dist/index.js +3 -0
  94. package/node_modules/@sumi/kernel/dist/index.js.map +1 -1
  95. package/node_modules/@sumi/kernel/dist/plan.d.ts +12 -0
  96. package/node_modules/@sumi/kernel/dist/plan.js.map +1 -1
  97. package/node_modules/@sumi/kernel/dist/record.d.ts +10 -1
  98. package/node_modules/@sumi/kernel/dist/record.js +133 -3
  99. package/node_modules/@sumi/kernel/dist/record.js.map +1 -1
  100. package/node_modules/@sumi/kernel/dist/resume.d.ts +3 -1
  101. package/node_modules/@sumi/kernel/dist/resume.js +35 -27
  102. package/node_modules/@sumi/kernel/dist/resume.js.map +1 -1
  103. package/node_modules/@sumi/kernel/dist/runtime.d.ts +2 -0
  104. package/node_modules/@sumi/kernel/dist/runtime.js +30 -0
  105. package/node_modules/@sumi/kernel/dist/runtime.js.map +1 -0
  106. package/node_modules/@sumi/kernel/dist/scope.d.ts +2 -1
  107. package/node_modules/@sumi/kernel/dist/scope.js +2 -2
  108. package/node_modules/@sumi/kernel/dist/scope.js.map +1 -1
  109. package/node_modules/@sumi/kernel/dist/source-monitor.d.ts +20 -0
  110. package/node_modules/@sumi/kernel/dist/source-monitor.js +105 -0
  111. package/node_modules/@sumi/kernel/dist/source-monitor.js.map +1 -0
  112. package/node_modules/@sumi/kernel/dist/step-cache.d.ts +1 -1
  113. package/node_modules/@sumi/kernel/dist/step-cache.js +62 -51
  114. package/node_modules/@sumi/kernel/dist/step-cache.js.map +1 -1
  115. package/node_modules/@sumi/kernel/dist/step.d.ts +61 -0
  116. package/node_modules/@sumi/kernel/dist/step.js +55 -0
  117. package/node_modules/@sumi/kernel/dist/step.js.map +1 -0
  118. package/node_modules/@sumi/kernel/package.json +2 -2
  119. package/node_modules/@sumi/plugin-sdk/README.md +3 -3
  120. package/node_modules/@sumi/plugin-sdk/dist/context-delivery.d.ts +15 -0
  121. package/node_modules/@sumi/plugin-sdk/dist/context-delivery.js +28 -0
  122. package/node_modules/@sumi/plugin-sdk/dist/context-delivery.js.map +1 -0
  123. package/node_modules/@sumi/plugin-sdk/dist/context-scope.d.ts +2 -0
  124. package/node_modules/@sumi/plugin-sdk/dist/context-scope.js +49 -0
  125. package/node_modules/@sumi/plugin-sdk/dist/context-scope.js.map +1 -0
  126. package/node_modules/@sumi/plugin-sdk/dist/edit-paths.d.ts +2 -0
  127. package/node_modules/@sumi/plugin-sdk/dist/edit-paths.js +54 -0
  128. package/node_modules/@sumi/plugin-sdk/dist/edit-paths.js.map +1 -0
  129. package/node_modules/@sumi/plugin-sdk/dist/files.d.ts +1 -1
  130. package/node_modules/@sumi/plugin-sdk/dist/files.js +64 -13
  131. package/node_modules/@sumi/plugin-sdk/dist/files.js.map +1 -1
  132. package/node_modules/@sumi/plugin-sdk/dist/host-event.d.ts +9 -2
  133. package/node_modules/@sumi/plugin-sdk/dist/host-event.js +41 -16
  134. package/node_modules/@sumi/plugin-sdk/dist/host-event.js.map +1 -1
  135. package/node_modules/@sumi/plugin-sdk/dist/html-page.d.ts +5 -0
  136. package/node_modules/@sumi/plugin-sdk/dist/html-page.js +93 -0
  137. package/node_modules/@sumi/plugin-sdk/dist/html-page.js.map +1 -0
  138. package/node_modules/@sumi/plugin-sdk/dist/html-style.d.ts +1 -0
  139. package/node_modules/@sumi/plugin-sdk/dist/html-style.js +27 -0
  140. package/node_modules/@sumi/plugin-sdk/dist/html-style.js.map +1 -0
  141. package/node_modules/@sumi/plugin-sdk/dist/index.d.ts +7 -0
  142. package/node_modules/@sumi/plugin-sdk/dist/index.js +7 -0
  143. package/node_modules/@sumi/plugin-sdk/dist/index.js.map +1 -1
  144. package/node_modules/@sumi/plugin-sdk/dist/permissions.d.ts +7 -0
  145. package/node_modules/@sumi/plugin-sdk/dist/permissions.js +41 -0
  146. package/node_modules/@sumi/plugin-sdk/dist/permissions.js.map +1 -0
  147. package/node_modules/@sumi/plugin-sdk/dist/project.d.ts +2 -0
  148. package/node_modules/@sumi/plugin-sdk/dist/project.js +2 -0
  149. package/node_modules/@sumi/plugin-sdk/dist/project.js.map +1 -1
  150. package/node_modules/@sumi/plugin-sdk/dist/protocol.d.ts +39 -4
  151. package/node_modules/@sumi/plugin-sdk/dist/protocol.js +12 -4
  152. package/node_modules/@sumi/plugin-sdk/dist/protocol.js.map +1 -1
  153. package/node_modules/@sumi/plugin-sdk/dist/sdk.js +3 -1
  154. package/node_modules/@sumi/plugin-sdk/dist/sdk.js.map +1 -1
  155. package/node_modules/@sumi/plugin-sdk/dist/session-context.d.ts +26 -1
  156. package/node_modules/@sumi/plugin-sdk/dist/session-context.js +98 -17
  157. package/node_modules/@sumi/plugin-sdk/dist/session-context.js.map +1 -1
  158. package/node_modules/@sumi/plugin-sdk/dist/shell.js +2 -1
  159. package/node_modules/@sumi/plugin-sdk/dist/shell.js.map +1 -1
  160. package/node_modules/@sumi/plugin-sdk/dist/snapshot.d.ts +12 -0
  161. package/node_modules/@sumi/plugin-sdk/dist/snapshot.js +29 -5
  162. package/node_modules/@sumi/plugin-sdk/dist/snapshot.js.map +1 -1
  163. package/node_modules/@sumi/plugin-sdk/dist/trace.d.ts +7 -2
  164. package/node_modules/@sumi/plugin-sdk/dist/trace.js +21 -1
  165. package/node_modules/@sumi/plugin-sdk/dist/trace.js.map +1 -1
  166. package/node_modules/@sumi/plugin-sdk/dist/validate.js +25 -1
  167. package/node_modules/@sumi/plugin-sdk/dist/validate.js.map +1 -1
  168. package/node_modules/@sumi/plugin-sdk/dist/yaml-text.d.ts +7 -0
  169. package/node_modules/@sumi/plugin-sdk/dist/yaml-text.js +116 -0
  170. package/node_modules/@sumi/plugin-sdk/dist/yaml-text.js.map +1 -0
  171. package/node_modules/@sumi/plugin-sdk/package.json +3 -2
  172. package/node_modules/@sumi/plugins-core/dist/agent-rules.js +2 -2
  173. package/node_modules/@sumi/plugins-core/dist/agent-rules.js.map +1 -1
  174. package/node_modules/@sumi/plugins-core/dist/commands/adopt.js +7 -5
  175. package/node_modules/@sumi/plugins-core/dist/commands/adopt.js.map +1 -1
  176. package/node_modules/@sumi/plugins-core/dist/commands/context-impact.js +9 -21
  177. package/node_modules/@sumi/plugins-core/dist/commands/context-impact.js.map +1 -1
  178. package/node_modules/@sumi/plugins-core/dist/context-provider.d.ts +3 -0
  179. package/node_modules/@sumi/plugins-core/dist/context-provider.js +45 -0
  180. package/node_modules/@sumi/plugins-core/dist/context-provider.js.map +1 -0
  181. package/node_modules/@sumi/plugins-core/dist/plugins/coverage.js +110 -15
  182. package/node_modules/@sumi/plugins-core/dist/plugins/coverage.js.map +1 -1
  183. package/node_modules/@sumi/plugins-core/dist/plugins/test-affected.js +32 -5
  184. package/node_modules/@sumi/plugins-core/dist/plugins/test-affected.js.map +1 -1
  185. package/node_modules/@sumi/plugins-core/dist/vitest-runner.js +1 -0
  186. package/node_modules/@sumi/plugins-core/dist/vitest-runner.js.map +1 -1
  187. package/node_modules/@sumi/plugins-core/instructions/bugfix.md +4 -0
  188. package/node_modules/@sumi/plugins-core/instructions/feature.md +2 -0
  189. package/node_modules/@sumi/plugins-core/package.json +2 -2
  190. package/node_modules/@sumi/plugins-core/sumi-plugins.yaml +1 -0
  191. package/node_modules/@sumi/plugins-governance/assets/hook-bootstrap.cjs +167 -0
  192. package/node_modules/@sumi/plugins-governance/dist/boundary-hooks.d.ts +12 -0
  193. package/node_modules/@sumi/plugins-governance/dist/boundary-hooks.js +76 -0
  194. package/node_modules/@sumi/plugins-governance/dist/boundary-hooks.js.map +1 -0
  195. package/node_modules/@sumi/plugins-governance/dist/boundary.d.ts +42 -0
  196. package/node_modules/@sumi/plugins-governance/dist/boundary.js +206 -0
  197. package/node_modules/@sumi/plugins-governance/dist/boundary.js.map +1 -0
  198. package/node_modules/@sumi/plugins-governance/dist/checkout.d.ts +1 -0
  199. package/node_modules/@sumi/plugins-governance/dist/checkout.js +16 -6
  200. package/node_modules/@sumi/plugins-governance/dist/checkout.js.map +1 -1
  201. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-after-edit.js +14 -0
  202. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-after-edit.js.map +1 -0
  203. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-before-edit.js +22 -0
  204. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-before-edit.js.map +1 -0
  205. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-prompt.js +12 -0
  206. package/node_modules/@sumi/plugins-governance/dist/commands/boundary-prompt.js.map +1 -0
  207. package/node_modules/@sumi/plugins-governance/dist/commands/boundary.d.ts +1 -0
  208. package/node_modules/@sumi/plugins-governance/dist/commands/boundary.js +48 -0
  209. package/node_modules/@sumi/plugins-governance/dist/commands/boundary.js.map +1 -0
  210. package/node_modules/@sumi/plugins-governance/dist/commands/context-state.d.ts +1 -0
  211. package/node_modules/@sumi/plugins-governance/dist/commands/context-state.js +4 -0
  212. package/node_modules/@sumi/plugins-governance/dist/commands/context-state.js.map +1 -0
  213. package/node_modules/@sumi/plugins-governance/dist/commands/gate.js +162 -24
  214. package/node_modules/@sumi/plugins-governance/dist/commands/gate.js.map +1 -1
  215. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report-check.js +5 -2
  216. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report-check.js.map +1 -1
  217. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report.js +5 -1
  218. package/node_modules/@sumi/plugins-governance/dist/commands/pr-report.js.map +1 -1
  219. package/node_modules/@sumi/plugins-governance/dist/commands/resume-work.d.ts +1 -0
  220. package/node_modules/@sumi/plugins-governance/dist/commands/resume-work.js +6 -0
  221. package/node_modules/@sumi/plugins-governance/dist/commands/resume-work.js.map +1 -0
  222. package/node_modules/@sumi/plugins-governance/dist/commands/run-policy.d.ts +1 -0
  223. package/node_modules/@sumi/plugins-governance/dist/commands/run-policy.js +19 -0
  224. package/node_modules/@sumi/plugins-governance/dist/commands/run-policy.js.map +1 -0
  225. package/node_modules/@sumi/plugins-governance/dist/commands/stop-work.d.ts +1 -0
  226. package/node_modules/@sumi/plugins-governance/dist/commands/stop-work.js +12 -0
  227. package/node_modules/@sumi/plugins-governance/dist/commands/stop-work.js.map +1 -0
  228. package/node_modules/@sumi/plugins-governance/dist/commands/view.d.ts +1 -0
  229. package/node_modules/@sumi/plugins-governance/dist/commands/view.js +45 -0
  230. package/node_modules/@sumi/plugins-governance/dist/commands/view.js.map +1 -0
  231. package/node_modules/@sumi/plugins-governance/dist/context-provider.d.ts +2 -0
  232. package/node_modules/@sumi/plugins-governance/dist/context-provider.js +22 -0
  233. package/node_modules/@sumi/plugins-governance/dist/context-provider.js.map +1 -0
  234. package/node_modules/@sumi/plugins-governance/dist/gate-cache.js +10 -2
  235. package/node_modules/@sumi/plugins-governance/dist/gate-cache.js.map +1 -1
  236. package/node_modules/@sumi/plugins-governance/dist/guard.js +4 -4
  237. package/node_modules/@sumi/plugins-governance/dist/guard.js.map +1 -1
  238. package/node_modules/@sumi/plugins-governance/dist/human-stop.d.ts +4 -0
  239. package/node_modules/@sumi/plugins-governance/dist/human-stop.js +39 -0
  240. package/node_modules/@sumi/plugins-governance/dist/human-stop.js.map +1 -0
  241. package/node_modules/@sumi/plugins-governance/dist/index.d.ts +4 -1
  242. package/node_modules/@sumi/plugins-governance/dist/index.js +4 -1
  243. package/node_modules/@sumi/plugins-governance/dist/index.js.map +1 -1
  244. package/node_modules/@sumi/plugins-governance/dist/plugins/state-writable.d.ts +1 -0
  245. package/node_modules/@sumi/plugins-governance/dist/plugins/state-writable.js +4 -0
  246. package/node_modules/@sumi/plugins-governance/dist/plugins/state-writable.js.map +1 -0
  247. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.d.ts +1 -1
  248. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.js +2 -1
  249. package/node_modules/@sumi/plugins-governance/dist/pr-report-compose.js.map +1 -1
  250. package/node_modules/@sumi/plugins-governance/dist/pr-report-markers.d.ts +1 -0
  251. package/node_modules/@sumi/plugins-governance/dist/pr-report-markers.js +1 -0
  252. package/node_modules/@sumi/plugins-governance/dist/pr-report-markers.js.map +1 -1
  253. package/node_modules/@sumi/plugins-governance/dist/pr-report-sections.js +4 -1
  254. package/node_modules/@sumi/plugins-governance/dist/pr-report-sections.js.map +1 -1
  255. package/node_modules/@sumi/plugins-governance/dist/pr-report-status.d.ts +1 -1
  256. package/node_modules/@sumi/plugins-governance/dist/pr-report-status.js +22 -3
  257. package/node_modules/@sumi/plugins-governance/dist/pr-report-status.js.map +1 -1
  258. package/node_modules/@sumi/plugins-governance/dist/preflight.d.ts +14 -0
  259. package/node_modules/@sumi/plugins-governance/dist/preflight.js +110 -0
  260. package/node_modules/@sumi/plugins-governance/dist/preflight.js.map +1 -0
  261. package/node_modules/@sumi/plugins-governance/dist/protected.d.ts +1 -0
  262. package/node_modules/@sumi/plugins-governance/dist/protected.js +1 -0
  263. package/node_modules/@sumi/plugins-governance/dist/protected.js.map +1 -1
  264. package/node_modules/@sumi/plugins-governance/dist/report-view.d.ts +12 -0
  265. package/node_modules/@sumi/plugins-governance/dist/report-view.js +59 -0
  266. package/node_modules/@sumi/plugins-governance/dist/report-view.js.map +1 -0
  267. package/node_modules/@sumi/plugins-governance/dist/state-access.d.ts +3 -0
  268. package/node_modules/@sumi/plugins-governance/dist/state-access.js +35 -0
  269. package/node_modules/@sumi/plugins-governance/dist/state-access.js.map +1 -0
  270. package/node_modules/@sumi/plugins-governance/dist/state.js +1 -4
  271. package/node_modules/@sumi/plugins-governance/dist/state.js.map +1 -1
  272. package/node_modules/@sumi/plugins-governance/dist/upgrade-command.d.ts +1 -0
  273. package/node_modules/@sumi/plugins-governance/dist/upgrade-command.js +30 -0
  274. package/node_modules/@sumi/plugins-governance/dist/upgrade-command.js.map +1 -0
  275. package/node_modules/@sumi/plugins-governance/dist/view-page.d.ts +4 -0
  276. package/node_modules/@sumi/plugins-governance/dist/view-page.js +51 -0
  277. package/node_modules/@sumi/plugins-governance/dist/view-page.js.map +1 -0
  278. package/node_modules/@sumi/plugins-governance/instructions/boundary.md +35 -0
  279. package/node_modules/@sumi/plugins-governance/instructions/push.md +11 -8
  280. package/node_modules/@sumi/plugins-governance/package.json +6 -3
  281. package/node_modules/@sumi/plugins-governance/sumi-plugins.yaml +30 -1
  282. package/node_modules/@sumi/plugins-openspec/package.json +4 -4
  283. package/node_modules/@sumi/plugins-precedent/README.md +6 -4
  284. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.d.ts +6 -23
  285. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.js +48 -156
  286. package/node_modules/@sumi/plugins-precedent/dist/after-edit-context.js.map +1 -1
  287. package/node_modules/@sumi/plugins-precedent/dist/commands/before-edit-context.js +16 -13
  288. package/node_modules/@sumi/plugins-precedent/dist/commands/before-edit-context.js.map +1 -1
  289. package/node_modules/@sumi/plugins-precedent/dist/commands/context.js +3 -44
  290. package/node_modules/@sumi/plugins-precedent/dist/commands/context.js.map +1 -1
  291. package/node_modules/@sumi/plugins-precedent/dist/commands/impact-submit.js +2 -1
  292. package/node_modules/@sumi/plugins-precedent/dist/commands/impact-submit.js.map +1 -1
  293. package/node_modules/@sumi/plugins-precedent/dist/context-output.d.ts +65 -0
  294. package/node_modules/@sumi/plugins-precedent/dist/context-output.js +186 -0
  295. package/node_modules/@sumi/plugins-precedent/dist/context-output.js.map +1 -0
  296. package/node_modules/@sumi/plugins-precedent/dist/context-provider.d.ts +3 -0
  297. package/node_modules/@sumi/plugins-precedent/dist/context-provider.js +48 -0
  298. package/node_modules/@sumi/plugins-precedent/dist/context-provider.js.map +1 -0
  299. package/node_modules/@sumi/plugins-precedent/dist/impact-state.js +4 -6
  300. package/node_modules/@sumi/plugins-precedent/dist/impact-state.js.map +1 -1
  301. package/node_modules/@sumi/plugins-precedent/dist/impact.js +1 -2
  302. package/node_modules/@sumi/plugins-precedent/dist/impact.js.map +1 -1
  303. package/node_modules/@sumi/plugins-precedent/dist/index.d.ts +1 -0
  304. package/node_modules/@sumi/plugins-precedent/dist/index.js +1 -0
  305. package/node_modules/@sumi/plugins-precedent/dist/index.js.map +1 -1
  306. package/node_modules/@sumi/plugins-precedent/dist/model.d.ts +1 -0
  307. package/node_modules/@sumi/plugins-precedent/dist/model.js.map +1 -1
  308. package/node_modules/@sumi/plugins-precedent/dist/plugins/context-read.js +2 -1
  309. package/node_modules/@sumi/plugins-precedent/dist/plugins/context-read.js.map +1 -1
  310. package/node_modules/@sumi/plugins-precedent/package.json +3 -3
  311. package/node_modules/@sumi/plugins-precedent/sumi-plugins.yaml +3 -2
  312. package/node_modules/@sumi/plugins-review/README.md +17 -4
  313. package/node_modules/@sumi/plugins-review/dist/batch-request.d.ts +22 -0
  314. package/node_modules/@sumi/plugins-review/dist/batch-request.js +30 -0
  315. package/node_modules/@sumi/plugins-review/dist/batch-request.js.map +1 -0
  316. package/node_modules/@sumi/plugins-review/dist/claude-review-agent.d.ts +8 -0
  317. package/node_modules/@sumi/plugins-review/dist/claude-review-agent.js +51 -0
  318. package/node_modules/@sumi/plugins-review/dist/claude-review-agent.js.map +1 -0
  319. package/node_modules/@sumi/plugins-review/dist/command-hint.d.ts +7 -0
  320. package/node_modules/@sumi/plugins-review/dist/command-hint.js +21 -0
  321. package/node_modules/@sumi/plugins-review/dist/command-hint.js.map +1 -1
  322. package/node_modules/@sumi/plugins-review/dist/command-input.d.ts +3 -0
  323. package/node_modules/@sumi/plugins-review/dist/command-input.js +32 -0
  324. package/node_modules/@sumi/plugins-review/dist/command-input.js.map +1 -0
  325. package/node_modules/@sumi/plugins-review/dist/commands/context.js +3 -69
  326. package/node_modules/@sumi/plugins-review/dist/commands/context.js.map +1 -1
  327. package/node_modules/@sumi/plugins-review/dist/commands/host-model-hook.js +4 -3
  328. package/node_modules/@sumi/plugins-review/dist/commands/host-model-hook.js.map +1 -1
  329. package/node_modules/@sumi/plugins-review/dist/commands/model-recheck.js +37 -25
  330. package/node_modules/@sumi/plugins-review/dist/commands/model-recheck.js.map +1 -1
  331. package/node_modules/@sumi/plugins-review/dist/commands/preflight.d.ts +1 -0
  332. package/node_modules/@sumi/plugins-review/dist/commands/preflight.js +13 -0
  333. package/node_modules/@sumi/plugins-review/dist/commands/preflight.js.map +1 -0
  334. package/node_modules/@sumi/plugins-review/dist/commands/request-read.d.ts +1 -0
  335. package/node_modules/@sumi/plugins-review/dist/commands/request-read.js +6 -0
  336. package/node_modules/@sumi/plugins-review/dist/commands/request-read.js.map +1 -0
  337. package/node_modules/@sumi/plugins-review/dist/commands/review-batch.d.ts +1 -0
  338. package/node_modules/@sumi/plugins-review/dist/commands/review-batch.js +8 -0
  339. package/node_modules/@sumi/plugins-review/dist/commands/review-batch.js.map +1 -0
  340. package/node_modules/@sumi/plugins-review/dist/commands/startup-context.d.ts +1 -0
  341. package/node_modules/@sumi/plugins-review/dist/commands/startup-context.js +6 -0
  342. package/node_modules/@sumi/plugins-review/dist/commands/startup-context.js.map +1 -0
  343. package/node_modules/@sumi/plugins-review/dist/commands/stats.d.ts +1 -0
  344. package/node_modules/@sumi/plugins-review/dist/commands/stats.js +10 -0
  345. package/node_modules/@sumi/plugins-review/dist/commands/stats.js.map +1 -0
  346. package/node_modules/@sumi/plugins-review/dist/commands/submit.js +79 -32
  347. package/node_modules/@sumi/plugins-review/dist/commands/submit.js.map +1 -1
  348. package/node_modules/@sumi/plugins-review/dist/context-provider.d.ts +3 -0
  349. package/node_modules/@sumi/plugins-review/dist/context-provider.js +84 -0
  350. package/node_modules/@sumi/plugins-review/dist/context-provider.js.map +1 -0
  351. package/node_modules/@sumi/plugins-review/dist/convergence.d.ts +17 -0
  352. package/node_modules/@sumi/plugins-review/dist/convergence.js +114 -0
  353. package/node_modules/@sumi/plugins-review/dist/convergence.js.map +1 -0
  354. package/node_modules/@sumi/plugins-review/dist/cost-advice.d.ts +2 -0
  355. package/node_modules/@sumi/plugins-review/dist/cost-advice.js +35 -0
  356. package/node_modules/@sumi/plugins-review/dist/cost-advice.js.map +1 -0
  357. package/node_modules/@sumi/plugins-review/dist/dispatch.d.ts +38 -0
  358. package/node_modules/@sumi/plugins-review/dist/dispatch.js +235 -0
  359. package/node_modules/@sumi/plugins-review/dist/dispatch.js.map +1 -0
  360. package/node_modules/@sumi/plugins-review/dist/dispute.d.ts +4 -0
  361. package/node_modules/@sumi/plugins-review/dist/dispute.js +38 -4
  362. package/node_modules/@sumi/plugins-review/dist/dispute.js.map +1 -1
  363. package/node_modules/@sumi/plugins-review/dist/instructions.d.ts +1 -0
  364. package/node_modules/@sumi/plugins-review/dist/instructions.js +2 -0
  365. package/node_modules/@sumi/plugins-review/dist/instructions.js.map +1 -0
  366. package/node_modules/@sumi/plugins-review/dist/model-execution.d.ts +1 -0
  367. package/node_modules/@sumi/plugins-review/dist/model-execution.js +51 -46
  368. package/node_modules/@sumi/plugins-review/dist/model-execution.js.map +1 -1
  369. package/node_modules/@sumi/plugins-review/dist/plugins/dispatch.d.ts +1 -0
  370. package/node_modules/@sumi/plugins-review/dist/plugins/dispatch.js +41 -0
  371. package/node_modules/@sumi/plugins-review/dist/plugins/dispatch.js.map +1 -0
  372. package/node_modules/@sumi/plugins-review/dist/plugins/independent-recheck.js +62 -39
  373. package/node_modules/@sumi/plugins-review/dist/plugins/independent-recheck.js.map +1 -1
  374. package/node_modules/@sumi/plugins-review/dist/plugins/rubric.js +3 -337
  375. package/node_modules/@sumi/plugins-review/dist/plugins/rubric.js.map +1 -1
  376. package/node_modules/@sumi/plugins-review/dist/preflight.d.ts +18 -0
  377. package/node_modules/@sumi/plugins-review/dist/preflight.js +170 -0
  378. package/node_modules/@sumi/plugins-review/dist/preflight.js.map +1 -0
  379. package/node_modules/@sumi/plugins-review/dist/recheck-tickets.d.ts +26 -0
  380. package/node_modules/@sumi/plugins-review/dist/recheck-tickets.js +48 -0
  381. package/node_modules/@sumi/plugins-review/dist/recheck-tickets.js.map +1 -0
  382. package/node_modules/@sumi/plugins-review/dist/recheck.d.ts +15 -0
  383. package/node_modules/@sumi/plugins-review/dist/recheck.js +33 -16
  384. package/node_modules/@sumi/plugins-review/dist/recheck.js.map +1 -1
  385. package/node_modules/@sumi/plugins-review/dist/report.d.ts +5 -1
  386. package/node_modules/@sumi/plugins-review/dist/report.js +25 -5
  387. package/node_modules/@sumi/plugins-review/dist/report.js.map +1 -1
  388. package/node_modules/@sumi/plugins-review/dist/review-evidence.js +2 -2
  389. package/node_modules/@sumi/plugins-review/dist/review-evidence.js.map +1 -1
  390. package/node_modules/@sumi/plugins-review/dist/review.d.ts +53 -7
  391. package/node_modules/@sumi/plugins-review/dist/review.js +100 -38
  392. package/node_modules/@sumi/plugins-review/dist/review.js.map +1 -1
  393. package/node_modules/@sumi/plugins-review/dist/rubric-check.d.ts +4 -0
  394. package/node_modules/@sumi/plugins-review/dist/rubric-check.js +382 -0
  395. package/node_modules/@sumi/plugins-review/dist/rubric-check.js.map +1 -0
  396. package/node_modules/@sumi/plugins-review/dist/startup-context.d.ts +21 -0
  397. package/node_modules/@sumi/plugins-review/dist/startup-context.js +94 -0
  398. package/node_modules/@sumi/plugins-review/dist/startup-context.js.map +1 -0
  399. package/node_modules/@sumi/plugins-review/dist/stats.d.ts +19 -0
  400. package/node_modules/@sumi/plugins-review/dist/stats.js +99 -0
  401. package/node_modules/@sumi/plugins-review/dist/stats.js.map +1 -0
  402. package/node_modules/@sumi/plugins-review/dist/submission.js +34 -18
  403. package/node_modules/@sumi/plugins-review/dist/submission.js.map +1 -1
  404. package/node_modules/@sumi/plugins-review/dist/support-scope.d.ts +4 -0
  405. package/node_modules/@sumi/plugins-review/dist/support-scope.js +9 -0
  406. package/node_modules/@sumi/plugins-review/dist/support-scope.js.map +1 -0
  407. package/node_modules/@sumi/plugins-review/dist/tickets.d.ts +12 -0
  408. package/node_modules/@sumi/plugins-review/dist/tickets.js +98 -0
  409. package/node_modules/@sumi/plugins-review/dist/tickets.js.map +1 -0
  410. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-plan.js +34 -9
  411. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-plan.js.map +1 -1
  412. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-render.js +2 -3
  413. package/node_modules/@sumi/plugins-review/dist/upgrade-flow-render.js.map +1 -1
  414. package/node_modules/@sumi/plugins-review/dist/upgrade.d.ts +2 -0
  415. package/node_modules/@sumi/plugins-review/dist/upgrade.js +12 -83
  416. package/node_modules/@sumi/plugins-review/dist/upgrade.js.map +1 -1
  417. package/node_modules/@sumi/plugins-review/package.json +6 -5
  418. package/node_modules/@sumi/plugins-review/sumi-plugins.yaml +22 -1
  419. package/package.json +10 -10
  420. package/dist/trace.d.ts +0 -16
  421. package/dist/trace.js +0 -30
  422. package/dist/trace.js.map +0 -1
  423. package/node_modules/@sumi/create/dist/bin.d.ts +0 -2
  424. package/node_modules/@sumi/create/dist/bin.js +0 -52
  425. package/node_modules/@sumi/create/dist/bin.js.map +0 -1
  426. package/node_modules/@sumi/create/template/control/rubrics/architecture.yaml +0 -15
  427. package/node_modules/@sumi/create/template/control/rubrics/business-impact.yaml +0 -6
  428. package/node_modules/@sumi/create/template/control/rubrics/device-acceptance.yaml +0 -10
  429. package/node_modules/@sumi/create/template/control/rubrics/domain.yaml +0 -9
  430. package/node_modules/@sumi/create/template/init/control/rubrics/architecture.yaml +0 -15
  431. package/node_modules/@sumi/create/template/init/control/rubrics/business-impact.yaml +0 -6
  432. package/node_modules/@sumi/plugins-core/dist/tool-batches.d.ts +0 -11
  433. package/node_modules/@sumi/plugins-core/dist/tool-batches.js +0 -41
  434. package/node_modules/@sumi/plugins-core/dist/tool-batches.js.map +0 -1
  435. package/node_modules/@sumi/plugins-governance/dist/commands/approve.js +0 -29
  436. package/node_modules/@sumi/plugins-governance/dist/commands/approve.js.map +0 -1
  437. package/node_modules/@sumi/plugins-governance/dist/commands/protected-after-shell.js +0 -20
  438. package/node_modules/@sumi/plugins-governance/dist/commands/protected-after-shell.js.map +0 -1
  439. package/node_modules/@sumi/plugins-governance/dist/commands/unlock.js +0 -23
  440. package/node_modules/@sumi/plugins-governance/dist/commands/unlock.js.map +0 -1
  441. package/node_modules/@sumi/plugins-governance/dist/hooks.d.ts +0 -2
  442. package/node_modules/@sumi/plugins-governance/dist/hooks.js +0 -4
  443. package/node_modules/@sumi/plugins-governance/dist/hooks.js.map +0 -1
  444. package/node_modules/@sumi/plugins-governance/dist/protected-shell.d.ts +0 -12
  445. package/node_modules/@sumi/plugins-governance/dist/protected-shell.js +0 -152
  446. package/node_modules/@sumi/plugins-governance/dist/protected-shell.js.map +0 -1
  447. package/node_modules/@sumi/plugins-precedent/dist/commands/session-start-context.js +0 -6
  448. package/node_modules/@sumi/plugins-precedent/dist/commands/session-start-context.js.map +0 -1
  449. /package/{node_modules/@sumi/plugins-governance/dist/commands/approve.d.ts → dist/context-providers.d.ts} +0 -0
  450. /package/node_modules/@sumi/plugins-governance/dist/commands/{protected-after-shell.d.ts → boundary-after-edit.d.ts} +0 -0
  451. /package/node_modules/@sumi/plugins-governance/dist/commands/{unlock.d.ts → boundary-before-edit.d.ts} +0 -0
  452. /package/node_modules/@sumi/{plugins-precedent/dist/commands/session-start-context.d.ts → plugins-governance/dist/commands/boundary-prompt.d.ts} +0 -0
@@ -1,11 +1,165 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { spawn } from 'node:child_process';
2
3
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
4
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
4
5
  import { loadConfig, loadRegistry, resolveArgv } from '@sumi/kernel';
5
- import { cleanEnv, contextSession, hostEvent, parseAfterEditResult, readHookInput, recordDelivery, recordTrace, resetContextSession, spawnCommandSync, traceFields, } from '@sumi/plugin-sdk';
6
+ import { cleanEnv, isContextScope, saveContextScope, contextSession, firstHostString, hostEvent, parseAfterEditResult, readHookInput, recordDelivery, recordTrace, resetContextSession, spawnCommandSync, traceFields, } from '@sumi/plugin-sdk';
6
7
  import { registerCommand, requireRoot } from './cli.js';
7
8
  import { declaredHooks } from './adapters.js';
8
- import { routeToOwners } from './hook-routing.js';
9
+ import { acknowledgeRouted, editTool, ROUTED_ENV, routeToOwners, withReceipt, } from './hook-routing.js';
10
+ import { inheritedSubagentHistory } from './subagent-history.js';
11
+ import { clearCompaction, markCompaction, takeCompaction } from './compaction-marker.js';
12
+ import { HOST_ADAPTERS, parseBeforeToolResponse } from './host-adapters.js';
13
+ import { writeHookOutput } from './hook-output.js';
14
+ import { stopHintMessages } from './stop-hint.js';
15
+ /** 约束正文几乎都是中文,上下文接近预算时也要远低于这个上限。 */
16
+ const MAX_COMMAND_OUTPUT = 1024 * 1024;
17
+ function runHookCommand(root, input, name, registry, timeout) {
18
+ const command = registry.commands.get(name);
19
+ if (!command)
20
+ return Promise.resolve({ code: null, stdout: '', stderr: `hook 命令 ${name} 未注册` });
21
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
22
+ return new Promise((resolveResult) => {
23
+ const child = spawn(bin, argv, {
24
+ cwd: root,
25
+ env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
26
+ windowsHide: true,
27
+ stdio: ['pipe', 'pipe', 'pipe'],
28
+ });
29
+ let stdout = '';
30
+ let stderr = '';
31
+ let truncated = false;
32
+ let settled = false;
33
+ const finish = (code, diagnostic = '') => {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ if (timer)
38
+ clearTimeout(timer);
39
+ const notice = truncated ? `hook 命令 ${name} 的输出超过上限,已截断` : '';
40
+ resolveResult({ code, stdout, stderr: [stderr, diagnostic, notice].filter(Boolean).join('\n') });
41
+ };
42
+ const capped = (text, chunk) => {
43
+ truncated ||= text.length + chunk.length > MAX_COMMAND_OUTPUT;
44
+ return (text + chunk).slice(0, MAX_COMMAND_OUTPUT);
45
+ };
46
+ const timer = timeout === undefined
47
+ ? null
48
+ : setTimeout(() => {
49
+ child.kill();
50
+ finish(null, 'hook 命令超时');
51
+ }, timeout);
52
+ // 按流解码:多字节字符可能落在两个数据块之间,逐块转字符串会变成乱码
53
+ child.stdout.setEncoding('utf8').on('data', (chunk) => {
54
+ stdout = capped(stdout, chunk);
55
+ });
56
+ child.stderr.setEncoding('utf8').on('data', (chunk) => {
57
+ stderr = capped(stderr, chunk);
58
+ });
59
+ child.on('error', (error) => finish(null, error.message));
60
+ child.on('close', (code) => finish(code));
61
+ child.stdin.on('error', () => { });
62
+ child.stdin.end(input);
63
+ });
64
+ }
65
+ /** 插件命令并发运行,结果按声明顺序合并;宿主只见一个原生响应。 */
66
+ export async function runBeforeToolChecks(root, input, host) {
67
+ const config = loadConfig(root);
68
+ const registry = loadRegistry(root, config);
69
+ const event = HOST_ADAPTERS[host].normalizeInput('PreToolUse', input);
70
+ // 没有工具名说明负载损坏:不能当作无关工具放行,要让闭合命令判断
71
+ const ignored = event.tool !== null && event.tool !== 'Bash' && !editTool(event.tool);
72
+ if (ignored)
73
+ return { contexts: [], ownContexts: [], denied: null, diagnostics: [], deliveries: [], evidence: {}, receipts: [] };
74
+ const hooks = declaredHooks(registry, config).beforeTool.filter((hook) => hook.tools === 'all' || event.tool === null || editTool(event.tool));
75
+ const results = await Promise.all(hooks.map((hook) => runHookCommand(root, event.pluginInput, hook.command, registry, 10000)));
76
+ const contexts = [];
77
+ const diagnostics = [];
78
+ const denials = [];
79
+ const deliveries = [];
80
+ const evidence = {};
81
+ results.forEach((result, index) => {
82
+ const hook = hooks[index];
83
+ const reason = result.stderr.trim() || `前置命令 ${hook.command} 未正常完成`;
84
+ if (result.code === 2)
85
+ denials.push(reason);
86
+ else if (result.code !== 0 && hook.failure === 'closed')
87
+ denials.push(reason);
88
+ else if (result.code !== 0)
89
+ diagnostics.push(reason);
90
+ if (result.code !== 0 || !result.stdout.trim())
91
+ return;
92
+ try {
93
+ const native = parseBeforeToolResponse(result.stdout, reason);
94
+ if (native.context)
95
+ contexts.push(native.context);
96
+ const parsed = parseAfterEditResult(result.stdout);
97
+ if (parsed) {
98
+ if (parsed.warning)
99
+ diagnostics.push(parsed.warning);
100
+ mergeEvidence(evidence, parsed);
101
+ const command = registry.commands.get(hook.command);
102
+ if (command && parsed.deliveryKeys?.length) {
103
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
104
+ deliveries.push({
105
+ argv: [bin, ...argv],
106
+ dir: command.dir,
107
+ keys: parsed.deliveryKeys,
108
+ scopes: parsed.deliveryScopes,
109
+ records: parsed.deliveryRecords,
110
+ });
111
+ }
112
+ }
113
+ if (native.denied)
114
+ denials.push(native.denied);
115
+ }
116
+ catch {
117
+ if (hook.failure === 'closed')
118
+ denials.push(`前置命令 ${hook.command} 输出无效 JSON`);
119
+ else
120
+ diagnostics.push(`前置命令 ${hook.command} 输出无效 JSON`);
121
+ }
122
+ });
123
+ const ownContexts = [...contexts];
124
+ const routed = denials.length
125
+ ? { denied: false, stderr: [], stdout: [], receipts: [] }
126
+ : routeToOwners(root, ['hook', 'before-tool', host], event.pluginInput);
127
+ if (routed.denied)
128
+ denials.push(...routed.stderr);
129
+ else
130
+ diagnostics.push(...routed.stderr);
131
+ for (const output of routed.stdout) {
132
+ try {
133
+ const value = JSON.parse(output);
134
+ const context = firstHostString([value.hookSpecificOutput?.additionalContext, value.additional_context]);
135
+ if (context && !routed.denied)
136
+ contexts.push(context);
137
+ }
138
+ catch {
139
+ diagnostics.push('转交的前置 hook 输出无效 JSON');
140
+ }
141
+ }
142
+ return {
143
+ contexts,
144
+ ownContexts,
145
+ denied: denials.length ? denials.join('\n') : null,
146
+ diagnostics,
147
+ deliveries,
148
+ evidence,
149
+ receipts: routed.receipts,
150
+ };
151
+ }
152
+ function acknowledgeBeforeTool(root, input, decision) {
153
+ for (const delivery of decision.deliveries) {
154
+ spawnCommandSync(delivery.argv[0], delivery.argv.slice(1), {
155
+ cwd: root,
156
+ input: JSON.stringify({ originalInput: input, keys: delivery.keys, scopes: delivery.scopes, records: delivery.records }),
157
+ encoding: 'utf8',
158
+ env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BEFORE_EDIT_DELIVERED: '1' },
159
+ windowsHide: true,
160
+ });
161
+ }
162
+ }
9
163
  function mergeEvidence(evidence, result) {
10
164
  const items = result.items ?? (result.deliveryKeys ?? []).map((key) => ({ key }));
11
165
  if (items.length)
@@ -30,87 +184,78 @@ function afterEditCommands(registry, shell = false) {
30
184
  return commands;
31
185
  }
32
186
  /** 提示词阶段只接受插件成功返回的上下文;失败不影响用户输入。 */
33
- export function runPromptChecks(root, input, registry = loadRegistry(root, loadConfig(root))) {
187
+ export async function runPromptChecks(root, input, registry) {
188
+ const config = loadConfig(root);
189
+ const activeRegistry = registry ?? loadRegistry(root, config);
190
+ const names = declaredHooks(activeRegistry, config).onPrompt;
191
+ const results = await Promise.all(names.map((name) => runHookCommand(root, input, name, activeRegistry, 10000)));
34
192
  const contexts = [];
35
193
  const deliveries = [];
36
194
  const evidence = {};
37
- // 只运行条件成立的声明:开始事件在提示词接线关闭时也会到这里
38
- for (const name of declaredHooks(registry, loadConfig(root)).onPrompt) {
39
- const command = registry.commands.get(name);
40
- if (!command)
41
- continue;
42
- const [bin, ...argv] = resolveArgv(command.argv, command.dir);
43
- const child = spawnCommandSync(bin, argv, {
44
- cwd: root,
45
- input,
46
- encoding: 'utf8',
47
- timeout: 10000,
48
- env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
49
- windowsHide: true,
50
- });
51
- if (child.status !== 0 || child.error)
52
- continue;
53
- const result = parseAfterEditResult(child.stdout ?? '');
54
- if (result) {
55
- contexts.push(result.additionalContext);
56
- mergeEvidence(evidence, result);
57
- if (result.deliveryKeys?.length)
58
- deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys });
195
+ results.forEach((child, index) => {
196
+ if (child.code !== 0)
197
+ return;
198
+ const result = parseAfterEditResult(child.stdout);
199
+ if (!result)
200
+ return;
201
+ contexts.push(result.additionalContext);
202
+ mergeEvidence(evidence, result);
203
+ const command = activeRegistry.commands.get(names[index]);
204
+ if (command && result.deliveryKeys?.length) {
205
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
206
+ deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys, records: result.deliveryRecords });
59
207
  }
60
- }
208
+ });
61
209
  return { contexts, deliveries, evidence };
62
210
  }
63
211
  export function acknowledgePrompt(root, input, decision) {
64
212
  for (const delivery of decision.deliveries ?? []) {
65
213
  spawnCommandSync(delivery.argv[0], delivery.argv.slice(1), {
66
214
  cwd: root,
67
- input: JSON.stringify({ originalInput: input, keys: delivery.keys }),
215
+ input: JSON.stringify({ originalInput: input, keys: delivery.keys, records: delivery.records }),
68
216
  encoding: 'utf8',
69
217
  env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_PROMPT_DELIVERED: '1' },
70
218
  windowsHide: true,
71
219
  });
72
220
  }
73
221
  }
74
- /** 插件成功结果可以补充上下文;只有显式退出码 2 才转为编辑后阻断反馈。 */
75
- export function runAfterEditChecks(root, input, registry = loadRegistry(root, loadConfig(root))) {
222
+ /** 编辑后插件并发执行;显式退出码 2 阻断。 */
223
+ export async function runAfterEditChecks(root, input) {
224
+ const registry = loadRegistry(root, loadConfig(root));
225
+ const commands = afterEditCommands(registry, hostEvent(input)?.tool === 'Bash');
226
+ const results = await Promise.all(commands.map((command) => runHookCommand(root, input, command.name, registry)));
76
227
  const contexts = [];
77
228
  const deliveries = [];
78
229
  const evidence = {};
79
230
  const errors = [];
80
231
  let code = 0;
81
- for (const command of afterEditCommands(registry, toolName(input) === 'Bash')) {
82
- const [bin, ...argv] = resolveArgv(command.argv, command.dir);
83
- const child = spawnCommandSync(bin, argv, {
84
- cwd: root,
85
- input,
86
- encoding: 'utf8',
87
- env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
88
- windowsHide: true,
89
- });
90
- if (child.status !== 0) {
91
- const detail = child.stderr || child.error?.message || `编辑后命令 ${command.name} 被信号终止或未正常退出`;
92
- errors.push(detail);
93
- if (child.status === 2)
232
+ results.forEach((child, index) => {
233
+ const command = commands[index];
234
+ if (child.code !== 0) {
235
+ errors.push(child.stderr || `编辑后命令 ${command.name} 被信号终止或未正常退出`);
236
+ if (child.code === 2)
94
237
  code = 2;
95
- else if (code !== 2 && code === 0)
96
- code = child.status ?? 1;
97
- continue;
238
+ else if (code === 0)
239
+ code = child.code ?? 1;
240
+ return;
98
241
  }
99
- const result = parseAfterEditResult(child.stdout ?? '');
100
- if (result) {
101
- contexts.push(result.additionalContext);
102
- mergeEvidence(evidence, result);
103
- if (result.deliveryKeys?.length)
104
- deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys });
242
+ const result = parseAfterEditResult(child.stdout);
243
+ if (!result)
244
+ return;
245
+ contexts.push(result.additionalContext);
246
+ mergeEvidence(evidence, result);
247
+ if (result.deliveryKeys?.length) {
248
+ const [bin, ...argv] = resolveArgv(command.argv, command.dir);
249
+ deliveries.push({ argv: [bin, ...argv], dir: command.dir, keys: result.deliveryKeys, records: result.deliveryRecords });
105
250
  }
106
- }
107
- const decision = {
251
+ });
252
+ return {
108
253
  code,
109
254
  contexts,
110
- ...(Object.keys(evidence).length ? { evidence } : {}),
111
255
  stderr: errors.reduce((all, detail) => `${all}${all && !all.endsWith('\n') ? '\n' : ''}${detail}`, ''),
256
+ ...(deliveries.length ? { deliveries } : {}),
257
+ ...(Object.keys(evidence).length ? { evidence } : {}),
112
258
  };
113
- return deliveries.length ? { ...decision, deliveries } : decision;
114
259
  }
115
260
  export function renderAfterEditResponse(agent, decision) {
116
261
  if (decision.code !== 0) {
@@ -121,20 +266,17 @@ export function renderAfterEditResponse(agent, decision) {
121
266
  stderr: context ? `${decision.stderr}${decision.stderr.endsWith('\n') ? '' : '\n'}${context}` : decision.stderr,
122
267
  };
123
268
  }
124
- if (!decision.contexts.length || agent === 'cursor')
269
+ if (!decision.contexts.length)
125
270
  return { code: 0, stdout: '', stderr: '' };
126
- return {
127
- code: 0,
128
- stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: decision.contexts.join('\n\n') } }),
129
- stderr: '',
130
- };
271
+ const event = agent === 'cursor' ? 'postToolUse' : 'PostToolUse';
272
+ return { code: 0, stdout: HOST_ADAPTERS[agent].formatOutput(event, { contexts: decision.contexts }), stderr: '' };
131
273
  }
132
274
  /** 只有输出已交给适配层,才通知插件记录本次实际送达的键。 */
133
275
  export function acknowledgeAfterEdit(root, input, decision) {
134
276
  for (const delivery of decision.deliveries ?? []) {
135
277
  spawnCommandSync(delivery.argv[0], delivery.argv.slice(1), {
136
278
  cwd: root,
137
- input: JSON.stringify({ originalInput: input, keys: delivery.keys }),
279
+ input: JSON.stringify({ originalInput: input, keys: delivery.keys, records: delivery.records }),
138
280
  encoding: 'utf8',
139
281
  env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_AFTER_EDIT_DELIVERED: '1' },
140
282
  windowsHide: true,
@@ -155,31 +297,24 @@ function stopCommands(registry) {
155
297
  }
156
298
  return commands;
157
299
  }
158
- /** 依次运行插件停止检查;仅显式退出码 2 请求阻断,命令故障作为诊断。 */
159
- export function runStopChecks(root, input, registry = loadRegistry(root, loadConfig(root))) {
300
+ /** 停止检查并发运行;没有固定超时,显式退出码 2 阻断。 */
301
+ export async function runStopChecks(root, input) {
302
+ const registry = loadRegistry(root, loadConfig(root));
303
+ const commands = stopCommands(registry);
304
+ const results = await Promise.all(commands.map((command) => runHookCommand(root, input, command.name, registry)));
160
305
  const reasons = [];
161
306
  const warnings = [];
162
- for (const command of stopCommands(registry)) {
163
- const [bin, ...argv] = resolveArgv(command.argv, command.dir);
164
- const child = spawnCommandSync(bin, argv, {
165
- cwd: root,
166
- input,
167
- encoding: 'utf8',
168
- env: { ...cleanEnv(), SUMI_ROOT: root, SUMI_BIN: process.env.SUMI_BIN ?? process.argv[1] ?? '' },
169
- windowsHide: true,
170
- });
171
- const detail = `${child.stderr ?? ''}${child.stdout ?? ''}`.trim();
172
- if (child.status === 0) {
307
+ results.forEach((child, index) => {
308
+ const detail = `${child.stderr}${child.stdout}`.trim();
309
+ if (child.code === 0) {
173
310
  if (detail)
174
311
  warnings.push(detail);
175
312
  }
176
- else if (child.status === 2) {
177
- reasons.push(detail || `停止检查 ${command.name} 请求继续处理`);
178
- }
179
- else {
180
- warnings.push(detail || `停止检查 ${command.name} 无法完成(退出码 ${child.status ?? '未知'})`);
181
- }
182
- }
313
+ else if (child.code === 2)
314
+ reasons.push(detail || `停止检查 ${commands[index].name} 请求继续处理`);
315
+ else
316
+ warnings.push(detail || `停止检查 ${commands[index].name} 无法完成(退出码 ${child.code ?? '未知'})`);
317
+ });
183
318
  return { blocked: reasons.length > 0, reasons, ...(warnings.length ? { warnings } : {}) };
184
319
  }
185
320
  function stopPayload(input) {
@@ -196,7 +331,8 @@ function retryFile(root, agent, session) {
196
331
  const common = spawnCommandSync('git', ['rev-parse', '--git-common-dir'], { cwd: root, encoding: 'utf8', windowsHide: true });
197
332
  const oid = head.stdout?.trim();
198
333
  const dir = common.stdout?.trim();
199
- if (head.status !== 0 || common.status !== 0 || !oid || !/^[0-9a-f]{40,64}$/i.test(oid) || !dir)
334
+ const validHead = head.status === 0 && Boolean(oid) && /^[0-9a-f]{40,64}$/i.test(oid ?? '');
335
+ if (!validHead || common.status !== 0 || !dir)
200
336
  return null;
201
337
  const key = createHash('sha256')
202
338
  .update(JSON.stringify([agent, session, oid.toLowerCase()]))
@@ -204,14 +340,14 @@ function retryFile(root, agent, session) {
204
340
  return join(resolve(root, dir), 'sumi', 'agent-stop-retries', key);
205
341
  }
206
342
  /** 跨进程 Stop 续跑熔断:稳定会话和同一 HEAD 最多阻断一次。 */
207
- export function runAgentStop(root, agent, input) {
343
+ export async function runAgentStop(root, agent, input, checks) {
208
344
  const payload = stopPayload(input);
209
345
  if (payload?.stop_hook_active === true || (typeof payload?.loop_count === 'number' && payload.loop_count > 0)) {
210
346
  return { blocked: false, reasons: [] };
211
347
  }
212
- const session = [payload?.session_id, payload?.thread_id, payload?.conversation_id].find((value) => typeof value === 'string' && value.length > 0 && value.length <= 512);
348
+ const session = firstHostString([payload?.session_id, payload?.thread_id, payload?.conversation_id], 512);
213
349
  const file = session ? retryFile(root, agent, session) : null;
214
- const decision = runStopChecks(root, input);
350
+ const decision = checks ?? (await runStopChecks(root, input));
215
351
  if (!decision.blocked)
216
352
  return decision;
217
353
  if (file && existsSync(file)) {
@@ -251,136 +387,352 @@ export function runAgentStop(root, agent, input) {
251
387
  }
252
388
  /** 把策略中立的阻断结论转换为各工具的原生 Stop 响应。 */
253
389
  export function renderStopResponse(agent, decision) {
254
- const reason = decision.reasons.join('\n\n');
255
- if (agent === 'cursor') {
256
- return { code: 0, stdout: JSON.stringify(decision.blocked ? { followup_message: reason } : {}), stderr: '' };
257
- }
258
- const warning = decision.warnings?.length ? { systemMessage: `Sumi Stop 提醒:${decision.warnings.join('\n')}` } : {};
259
- return { code: 0, stdout: JSON.stringify(decision.blocked ? { decision: 'block', reason, ...warning } : warning), stderr: '' };
260
- }
261
- const START_EVENTS = { 'agent-session-start': 'SessionStart', 'agent-subagent-start': 'SubagentStart' };
262
- /** 开始事件的注入输出。Cursor 的 `sessionStart` 用自己的字段,且没有子代理注入。 */
263
- export function renderStartContext(agent, event, context) {
264
- if (agent === 'cursor')
265
- return JSON.stringify({ additional_context: context });
266
- return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: context } });
267
- }
268
- /**
269
- * 开始事件主动注入:和提示词 hook 是同一批内容、同一套去重键,所以第一条提示不会重复。
270
- * 压缩或清空后模型上下文已不含此前送达的内容,先清记录;恢复会话上下文还在,不注入。
271
- */
272
- function deliverStart(root, agent, operation, input, out) {
273
- const source = hostEvent(input)?.source;
274
- if (source === 'resume')
275
- return;
276
- const session = contextSession(input);
277
- if (session && (source === 'compact' || source === 'clear'))
278
- resetContextSession(root, session);
279
- const decision = runPromptChecks(root, input);
390
+ const denied = decision.blocked ? decision.reasons.join('\n\n') : undefined;
391
+ const warning = decision.warnings?.length ? `Sumi Stop 提醒:${decision.warnings.join('\n')}` : undefined;
392
+ return { code: 0, stdout: HOST_ADAPTERS[agent].formatOutput(agent === 'cursor' ? 'stop' : 'Stop', { denied, warning }), stderr: '' };
393
+ }
394
+ const NEW_EVENTS = {
395
+ 'before-tool': { claude: 'PreToolUse', codex: 'PreToolUse', cursor: 'preToolUse' },
396
+ 'after-tool': { claude: 'PostToolUse', codex: 'PostToolUse', cursor: 'postToolUse' },
397
+ 'session-start': { claude: 'SessionStart', codex: 'SessionStart', cursor: 'sessionStart' },
398
+ 'subagent-start': { claude: 'SubagentStart', codex: 'SubagentStart', cursor: 'subagentStart' },
399
+ 'post-compact': { claude: 'PostCompact', codex: 'PostCompact', cursor: 'postCompact' },
400
+ 'model-switch': { claude: 'PostModelSwitch', codex: 'PostModelSwitch', cursor: 'postModelSwitch' },
401
+ 'user-prompt': { claude: 'UserPromptSubmit', codex: 'UserPromptSubmit', cursor: 'beforeSubmitPrompt' },
402
+ stop: { claude: 'Stop', codex: 'Stop', cursor: 'stop' },
403
+ };
404
+ const HOOK_OPERATIONS = [
405
+ 'agent-stop',
406
+ 'agent-after-edit',
407
+ 'agent-after-read',
408
+ 'agent-user-prompt',
409
+ 'agent-session-start',
410
+ 'agent-subagent-start',
411
+ 'context-before-edit',
412
+ ...Object.keys(NEW_EVENTS),
413
+ ];
414
+ const HOOK_USAGE = `sumi hook <${HOOK_OPERATIONS.join('|')}> <claude|codex|cursor>`;
415
+ function recordContexts(ctx, channel, decision) {
280
416
  if (!decision.contexts.length)
281
417
  return;
282
- const context = decision.contexts.join('\n\n');
283
- out(renderStartContext(agent, START_EVENTS[operation], context));
284
- const channel = operation === 'agent-subagent-start' ? 'subagent-start' : (source ?? 'session-start');
285
- recordDelivery(root, input, { channel, method: 'additional-context', content: context, host: agent, ...decision.evidence });
286
- acknowledgePrompt(root, input, decision);
418
+ recordDelivery(ctx.root, ctx.raw, {
419
+ channel,
420
+ method: 'additional-context',
421
+ content: decision.contexts.join('\n\n'),
422
+ host: ctx.host,
423
+ ...decision.evidence,
424
+ });
287
425
  }
288
- const HOOK_OPERATIONS = ['agent-stop', 'agent-after-edit', 'agent-after-read', 'agent-user-prompt', ...Object.keys(START_EVENTS)];
289
- const HOOK_USAGE = `sumi hook <${HOOK_OPERATIONS.join('|')}> <claude|codex|cursor>`;
290
- registerCommand('hook', `运行工具适配 hook:${HOOK_USAGE}`, async (args, io, root) => {
291
- const operation = args.positionals[0];
292
- if (!HOOK_OPERATIONS.includes(operation ?? '') || !['claude', 'codex', 'cursor'].includes(args.positionals[1] ?? '')) {
293
- io.err(`用法:${HOOK_USAGE}`);
294
- return 3;
426
+ async function compactContext(ctx) {
427
+ const { root, raw, host, normalized } = ctx;
428
+ if (host !== 'codex' || !normalized.session)
429
+ return null;
430
+ if (!takeCompaction(root, normalized.session, normalized.agentId))
431
+ return null;
432
+ const session = contextSession(raw);
433
+ if (session)
434
+ resetContextSession(root, session);
435
+ return runPromptChecks(root, normalized.pluginInput);
436
+ }
437
+ async function writeOutcome(ctx, output, pending) {
438
+ try {
439
+ await writeHookOutput(ctx.io, output);
295
440
  }
296
- const agent = args.positionals[1];
297
- const input = await readHookInput();
298
- const projectRoot = requireRoot(root);
299
- if (operation === 'agent-session-start' || operation === 'agent-subagent-start') {
300
- deliverStart(projectRoot, agent, operation, input, io.out);
441
+ catch (error) {
442
+ if (pending && ctx.normalized.session)
443
+ markCompaction(ctx.root, ctx.normalized.session, ctx.normalized.agentId);
444
+ throw error;
445
+ }
446
+ }
447
+ async function runBeforeTool(ctx) {
448
+ const decision = await runBeforeToolChecks(ctx.root, ctx.raw, ctx.host);
449
+ for (const diagnostic of decision.diagnostics)
450
+ ctx.io.err(diagnostic);
451
+ const routedChild = process.env[ROUTED_ENV] === '1';
452
+ if (decision.denied) {
453
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, { denied: decision.denied }));
454
+ ctx.io.err(decision.denied);
455
+ // 转交子进程靠退出码把拒绝交回发起方,由发起方按宿主回应
456
+ return routedChild ? 2 : ctx.adapter.denyExitCode;
457
+ }
458
+ const pending = ctx.host === 'cursor' || routedChild ? null : await compactContext(ctx);
459
+ const contexts = [...decision.contexts, ...(pending?.contexts ?? [])];
460
+ const output = ctx.adapter.formatOutput(ctx.event, { contexts });
461
+ // Cursor 的 preToolUse 仅拒绝时能给代理消息,上下文留给 postToolUse,这里不算送达。
462
+ const delivered = ctx.host !== 'cursor' && decision.ownContexts.length > 0;
463
+ if (routedChild) {
464
+ const receipt = { kind: 'before', channel: 'before-edit', contexts: decision.ownContexts, deliveries: decision.deliveries };
465
+ await writeHookOutput(ctx.io, delivered ? withReceipt(output, { ...receipt, evidence: decision.evidence }) : output);
301
466
  return 0;
302
467
  }
303
- if (operation === 'agent-after-read') {
304
- const read = agentReadOf(projectRoot, input);
305
- if (read)
306
- recordTrace(projectRoot, { kind: 'agent-read', source: read.path, channel: agent, content: read.content, ...traceFields(input) });
468
+ await writeOutcome(ctx, output, pending);
469
+ if (delivered) {
470
+ recordContexts(ctx, 'before-edit', { contexts: decision.ownContexts, evidence: decision.evidence });
471
+ acknowledgeBeforeTool(ctx.root, ctx.raw, decision);
472
+ }
473
+ if (pending?.contexts.length) {
474
+ recordContexts(ctx, 'compact', pending);
475
+ acknowledgePrompt(ctx.root, ctx.raw, pending);
476
+ }
477
+ acknowledgeRouted(decision.receipts);
478
+ return 0;
479
+ }
480
+ async function selectContext(ctx, names, registry) {
481
+ const choices = await Promise.all(names.map((name) => runHookCommand(ctx.root, ctx.normalized.pluginInput, name, registry, 10_000)));
482
+ const selected = choices.flatMap((child) => {
483
+ if (child.code !== 0)
484
+ return [];
485
+ try {
486
+ const value = JSON.parse(child.stdout);
487
+ if (value.contextScope !== undefined && !isContextScope(value.contextScope))
488
+ return [];
489
+ return value.exclusive === true && typeof value.additionalContext === 'string'
490
+ ? [{ context: value.additionalContext, scope: isContextScope(value.contextScope) ? value.contextScope : undefined }]
491
+ : [];
492
+ }
493
+ catch {
494
+ return [];
495
+ }
496
+ });
497
+ return selected.length === 1 ? selected[0] : undefined;
498
+ }
499
+ function acknowledgeSelectedContext(ctx, choice, channel, merge = false) {
500
+ const session = contextSession(ctx.raw);
501
+ if (session)
502
+ saveContextScope(ctx.root, session, choice.scope, { merge });
503
+ if (choice.context)
504
+ recordContexts(ctx, channel, { contexts: [choice.context] });
505
+ }
506
+ async function runStart(ctx, subagent) {
507
+ const { root, raw, host, normalized } = ctx;
508
+ if (host === 'cursor' && subagent)
307
509
  return 0;
510
+ if (subagent) {
511
+ const registry = loadRegistry(root, loadConfig(root));
512
+ const names = [...registry.plugins.values()].flatMap(({ decl }) => decl.hooks?.agent?.subagentContext ?? []);
513
+ const choice = await selectContext(ctx, names, registry);
514
+ if (choice) {
515
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, { contexts: choice.context ? [choice.context] : [] }));
516
+ acknowledgeSelectedContext(ctx, choice, 'subagent-start');
517
+ return 0;
518
+ }
519
+ }
520
+ const sessionScope = contextSession(raw);
521
+ if (sessionScope)
522
+ saveContextScope(root, sessionScope);
523
+ if (!subagent) {
524
+ const config = loadConfig(root);
525
+ const registry = loadRegistry(root, config);
526
+ const names = declaredHooks(registry, config).sessionStart;
527
+ await Promise.all(names.map((name) => runHookCommand(root, normalized.pluginInput, name, registry)));
308
528
  }
309
- if (operation === 'agent-user-prompt') {
310
- const prompt = promptOf(input);
311
- if (prompt)
312
- recordTrace(projectRoot, { kind: 'prompt', source: agent, content: prompt, ...traceFields(input), host: agent });
313
- const decision = runPromptChecks(projectRoot, input);
314
- if (decision.contexts.length && agent !== 'cursor') {
315
- const context = decision.contexts.join('\n\n');
316
- io.out(JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context } }));
317
- recordDelivery(projectRoot, input, {
318
- channel: 'prompt',
319
- method: 'additional-context',
320
- content: context,
321
- host: agent,
322
- ...decision.evidence,
323
- });
324
- acknowledgePrompt(projectRoot, input, decision);
529
+ if (host === 'codex' && !subagent && normalized.session)
530
+ clearCompaction(root, normalized.session, normalized.agentId);
531
+ if (normalized.source === 'resume')
532
+ return 0;
533
+ if (host === 'codex' && subagent && inheritedSubagentHistory(normalized.transcript))
534
+ return 0;
535
+ const session = contextSession(raw);
536
+ if (session && (normalized.source === 'compact' || normalized.source === 'clear'))
537
+ resetContextSession(root, session);
538
+ const decision = await runPromptChecks(root, normalized.pluginInput);
539
+ if (!decision.contexts.length)
540
+ return 0;
541
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, decision));
542
+ recordContexts(ctx, subagent ? 'subagent-start' : (normalized.source ?? 'session-start'), decision);
543
+ acknowledgePrompt(root, raw, decision);
544
+ return 0;
545
+ }
546
+ async function runAfterTool(ctx) {
547
+ const read = agentReadOf(ctx.root, ctx.normalized.pluginInput);
548
+ if (ctx.normalized.tool === 'Read') {
549
+ if (read)
550
+ recordTrace(ctx.root, { kind: 'agent-read', source: read.path, channel: ctx.host, content: read.content, ...traceFields(ctx.raw) });
551
+ const pending = ctx.host === 'cursor' ? null : await compactContext(ctx);
552
+ const registry = loadRegistry(ctx.root, loadConfig(ctx.root));
553
+ const agentType = JSON.parse(ctx.normalized.pluginInput).agent_type;
554
+ const names = declaredHooks(registry)
555
+ .afterRead.filter((hook) => hook.agentType === undefined || hook.agentType === agentType)
556
+ .map((hook) => hook.command);
557
+ const choice = await selectContext(ctx, names, registry);
558
+ const contexts = [...(pending?.contexts ?? []), ...(choice?.context ? [choice.context] : [])];
559
+ await writeOutcome(ctx, ctx.adapter.formatOutput(ctx.event, { contexts }), pending);
560
+ if (choice)
561
+ acknowledgeSelectedContext(ctx, choice, 'after-read', true);
562
+ if (pending?.contexts.length) {
563
+ recordContexts(ctx, 'compact', pending);
564
+ acknowledgePrompt(ctx.root, ctx.raw, pending);
325
565
  }
326
566
  return 0;
327
567
  }
328
- const afterEdit = operation === 'agent-after-edit' ? withRoutedAfterEdit(projectRoot, agent, input, runAfterEditChecks(projectRoot, input)) : null;
329
- const stop = afterEdit ? null : runAgentStop(projectRoot, agent, input);
330
- const response = afterEdit ? renderAfterEditResponse(agent, afterEdit) : renderStopResponse(agent, stop);
331
- if (response.stdout)
332
- io.out(response.stdout);
333
- if (response.stderr)
334
- io.err(response.stderr);
335
- for (const warning of stop?.warnings ?? [])
336
- io.err(`Sumi Stop 提醒:${warning}`);
337
- const emitted = response.code === 2 || (response.code === 0 && Boolean(response.stdout));
338
- const delivered = agent !== 'cursor' && afterEdit?.contexts.length && emitted;
339
- if (delivered && afterEdit)
340
- acknowledgeAfterEdit(projectRoot, input, afterEdit);
341
- if (delivered && afterEdit)
342
- recordDelivery(projectRoot, input, {
343
- channel: 'after-edit',
344
- method: response.code === 2 ? 'denial' : 'additional-context',
345
- content: afterEdit.contexts.join('\n\n'),
346
- ...afterEdit.evidence,
347
- });
348
- return response.code;
568
+ if (ctx.normalized.tool && ctx.normalized.tool !== 'Bash' && !editTool(ctx.normalized.tool)) {
569
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, {}));
570
+ return 0;
571
+ }
572
+ if (ctx.normalized.tool && editTool(ctx.normalized.tool))
573
+ recordTrace(ctx.root, { kind: 'agent-edit', ...traceFields(ctx.raw), host: ctx.host });
574
+ const local = await runAfterEditChecks(ctx.root, ctx.normalized.pluginInput);
575
+ const decision = withRoutedAfterEdit(ctx.root, ctx.host, ctx.normalized.pluginInput, local);
576
+ if (decision.code !== 0) {
577
+ const detail = renderAfterEditResponse(ctx.host, decision).stderr;
578
+ await writeHookOutput(ctx.io, ctx.adapter.formatOutput(ctx.event, { denied: decision.code === 2 ? detail : undefined }));
579
+ if (detail)
580
+ ctx.io.err(detail);
581
+ if (decision.code === 2 && detail)
582
+ recordDelivery(ctx.root, ctx.raw, { channel: 'after-edit', method: 'denial', content: detail, host: ctx.host });
583
+ // Cursor 只在退出 0 时读输出,非零退出会让上面写的上下文作废
584
+ return ctx.host === 'cursor' ? 0 : decision.code;
585
+ }
586
+ const routedChild = process.env[ROUTED_ENV] === '1';
587
+ const pending = ctx.host === 'cursor' || routedChild ? null : await compactContext(ctx);
588
+ const contexts = [...decision.contexts, ...(pending?.contexts ?? [])];
589
+ const output = ctx.adapter.formatOutput(ctx.event, { contexts });
590
+ if (routedChild) {
591
+ const receipt = { kind: 'after', channel: 'after-edit', contexts: local.contexts, deliveries: local.deliveries ?? [] };
592
+ await writeHookOutput(ctx.io, local.contexts.length ? withReceipt(output, { ...receipt, evidence: local.evidence }) : output);
593
+ return 0;
594
+ }
595
+ await writeOutcome(ctx, output, pending);
596
+ if (local.contexts.length) {
597
+ recordContexts(ctx, 'after-edit', local);
598
+ acknowledgeAfterEdit(ctx.root, ctx.raw, local);
599
+ }
600
+ if (pending?.contexts.length) {
601
+ recordContexts(ctx, 'compact', pending);
602
+ acknowledgePrompt(ctx.root, ctx.raw, pending);
603
+ }
604
+ acknowledgeRouted(decision.receipts ?? []);
605
+ return 0;
606
+ }
607
+ async function runUserPrompt(ctx) {
608
+ if (!ctx.normalized.valid)
609
+ return 0;
610
+ if (ctx.normalized.prompt)
611
+ recordTrace(ctx.root, { kind: 'prompt', source: ctx.host, content: ctx.normalized.prompt, ...traceFields(ctx.raw), host: ctx.host });
612
+ if (ctx.host === 'cursor')
613
+ return 0;
614
+ const pending = await compactContext(ctx);
615
+ const decision = pending ?? (await runPromptChecks(ctx.root, ctx.normalized.pluginInput));
616
+ if (!decision.contexts.length)
617
+ return 0;
618
+ await writeOutcome(ctx, ctx.adapter.formatOutput(ctx.event, decision), pending);
619
+ recordContexts(ctx, pending ? 'compact' : 'prompt', decision);
620
+ acknowledgePrompt(ctx.root, ctx.raw, decision);
621
+ return 0;
622
+ }
623
+ async function runStop(ctx) {
624
+ const stopState = stopPayload(ctx.raw);
625
+ const stopActive = stopState?.stop_hook_active === true || (typeof stopState?.loop_count === 'number' && stopState.loop_count > 0);
626
+ const checks = stopActive ? { blocked: false, reasons: [] } : await runStopChecks(ctx.root, ctx.normalized.pluginInput);
627
+ const decision = await runAgentStop(ctx.root, ctx.host, ctx.raw, checks);
628
+ const session = ctx.normalized.session;
629
+ const hints = stopHintMessages(ctx.root, session);
630
+ const response = renderStopResponse(ctx.host, { ...decision, warnings: [...hints, ...(decision.warnings ?? [])] });
631
+ await writeHookOutput(ctx.io, response.stdout);
632
+ for (const message of decision.warnings ?? [])
633
+ ctx.io.err(`Sumi Stop 提醒:${message}`);
634
+ if (ctx.host === 'cursor')
635
+ for (const message of hints)
636
+ ctx.io.err(`Sumi Stop 提醒:${message}`);
637
+ return 0;
638
+ }
639
+ async function runModelSwitch(ctx) {
640
+ const config = loadConfig(ctx.root);
641
+ const registry = loadRegistry(ctx.root, config);
642
+ const names = declaredHooks(registry, config).modelSwitch;
643
+ await Promise.all(names.map((name) => runHookCommand(ctx.root, ctx.normalized.pluginInput, name, registry)));
644
+ return 0;
645
+ }
646
+ async function runPostCompact(ctx) {
647
+ if (ctx.host === 'codex' && ctx.normalized.session)
648
+ markCompaction(ctx.root, ctx.normalized.session, ctx.normalized.agentId);
649
+ return 0;
650
+ }
651
+ const EVENT_HANDLERS = {
652
+ 'before-tool': runBeforeTool,
653
+ 'after-tool': runAfterTool,
654
+ 'session-start': (ctx) => runStart(ctx, false),
655
+ 'subagent-start': (ctx) => runStart(ctx, true),
656
+ 'post-compact': runPostCompact,
657
+ 'model-switch': runModelSwitch,
658
+ 'user-prompt': runUserPrompt,
659
+ stop: runStop,
660
+ };
661
+ async function runtimeHook(args, io, root) {
662
+ const operation = args.positionals[0];
663
+ const requestedHost = args.positionals[1];
664
+ if (!operation || !EVENT_HANDLERS[operation])
665
+ return 3;
666
+ const projectRoot = requireRoot(root);
667
+ // 身份错误必须在消费负载前交回 CLI,恢复处理才能读取同一次工具请求。
668
+ loadConfig(projectRoot);
669
+ const raw = await readHookInput();
670
+ const host = requestedHost === 'auto' ? (hostEvent(raw)?.host ?? 'claude') : requestedHost;
671
+ if (!HOST_ADAPTERS[host])
672
+ return 3;
673
+ const event = NEW_EVENTS[operation][host];
674
+ const adapter = HOST_ADAPTERS[host];
675
+ return EVENT_HANDLERS[operation]({ root: projectRoot, raw, host, event, adapter, io, normalized: adapter.normalizeInput(event, raw) });
676
+ }
677
+ /** 目标项目收到回执:父进程的输出已写出,这时才记账并标记已送达。回执里的命令必须是本项目注册的。 */
678
+ async function receiveRoutedReceipt(root) {
679
+ const { raw, receipt } = JSON.parse(await readHookInput());
680
+ const config = loadConfig(root);
681
+ const registered = [...loadRegistry(root, config).commands.values()].map((command) => JSON.stringify(resolveArgv(command.argv, command.dir)));
682
+ const deliveries = receipt.deliveries.filter((delivery) => registered.includes(JSON.stringify(delivery.argv)));
683
+ recordDelivery(root, raw, {
684
+ channel: receipt.channel,
685
+ method: 'additional-context',
686
+ content: receipt.contexts.join('\n\n'),
687
+ ...receipt.evidence,
688
+ });
689
+ if (receipt.kind === 'before')
690
+ acknowledgeBeforeTool(root, raw, { deliveries });
691
+ else
692
+ acknowledgeAfterEdit(root, raw, { deliveries });
693
+ return 0;
694
+ }
695
+ registerCommand('context-before-edit', '旧接线的前置 hook 别名', (_args, io, root) => runtimeHook({ positionals: ['before-tool', 'auto'] }, io, root));
696
+ registerCommand('hook', `运行工具适配 hook:${HOOK_USAGE}`, async (args, io, root) => {
697
+ const operation = args.positionals[0];
698
+ // 内部操作:父进程转交写入后回执给目标项目,不写进用法
699
+ if (operation === 'routed-receipt')
700
+ return receiveRoutedReceipt(requireRoot(root));
701
+ if (!HOOK_OPERATIONS.includes(operation ?? '') || !['claude', 'codex', 'cursor'].includes(args.positionals[1] ?? '')) {
702
+ io.err(`用法:${HOOK_USAGE}`);
703
+ return 3;
704
+ }
705
+ const agent = args.positionals[1];
706
+ if (NEW_EVENTS[operation])
707
+ return runtimeHook(args, io, root);
708
+ const alias = {
709
+ 'agent-stop': 'stop',
710
+ 'agent-after-edit': 'after-tool',
711
+ 'agent-after-read': 'after-tool',
712
+ 'agent-user-prompt': 'user-prompt',
713
+ 'agent-session-start': 'session-start',
714
+ 'agent-subagent-start': 'subagent-start',
715
+ 'context-before-edit': 'before-tool',
716
+ };
717
+ return runtimeHook({ positionals: [alias[operation], agent] }, io, root);
349
718
  });
350
- /** 写入目标属于其他已接入项目时,并入那些项目编辑后 hook 的补充上下文与阻断(它们各自记录送达)。 */
719
+ /** 写入目标属于其他已接入项目时,并入那些项目编辑后 hook 的补充上下文与阻断;它们的账本与回执在输出写出后再做。 */
351
720
  function withRoutedAfterEdit(root, agent, input, local) {
352
- const routed = routeToOwners(root, ['hook', 'agent-after-edit', agent], input);
721
+ const routed = routeToOwners(root, ['hook', 'after-tool', agent], input);
353
722
  const contexts = [...local.contexts];
354
723
  for (const out of routed.stdout) {
355
724
  try {
356
725
  const value = JSON.parse(out);
357
- if (typeof value.hookSpecificOutput?.additionalContext === 'string')
358
- contexts.push(value.hookSpecificOutput.additionalContext);
726
+ const context = firstHostString([value.hookSpecificOutput?.additionalContext, value.additional_context]);
727
+ if (context)
728
+ contexts.push(context);
359
729
  }
360
730
  catch {
361
731
  /* 没有补充上下文 */
362
732
  }
363
733
  }
364
734
  const stderr = [local.stderr, ...routed.stderr].filter(Boolean).join('\n');
365
- return { ...local, code: routed.denied ? 2 : local.code, contexts, stderr };
366
- }
367
- function toolName(input) {
368
- try {
369
- const value = JSON.parse(input);
370
- return typeof value.tool_name === 'string' ? value.tool_name : undefined;
371
- }
372
- catch {
373
- return undefined;
374
- }
375
- }
376
- function promptOf(input) {
377
- try {
378
- const value = JSON.parse(input);
379
- return typeof value.prompt === 'string' && value.prompt.length ? value.prompt : undefined;
380
- }
381
- catch {
382
- return undefined;
383
- }
735
+ return { ...local, code: routed.denied ? 2 : local.code, contexts, stderr, receipts: routed.receipts };
384
736
  }
385
737
  function agentReadOf(root, input) {
386
738
  try {
@@ -390,7 +742,7 @@ function agentReadOf(root, input) {
390
742
  const path = relative(root, resolve(value.tool_input.file_path));
391
743
  if (!path || path === '..' || path.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(path))
392
744
  return undefined;
393
- const response = value.tool_response;
745
+ const response = value.tool_response ?? value.tool_output;
394
746
  const content = typeof response === 'string'
395
747
  ? response
396
748
  : response && typeof response === 'object' && 'content' in response && typeof response.content === 'string'