@1agents/acp-service 0.8.3 → 0.9.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 (302) hide show
  1. package/README.md +25 -13
  2. package/dist/bin/a2a.js +16 -4
  3. package/dist/bin/acp-service.js +30 -0
  4. package/dist/bin/process.d.ts +4 -0
  5. package/dist/bin/process.js +57 -0
  6. package/dist/bin/roles.d.ts +1 -0
  7. package/dist/bin/roles.js +24 -0
  8. package/dist/bin/rsi.d.ts +3 -0
  9. package/dist/bin/rsi.js +114 -0
  10. package/dist/bin/ticket.d.ts +13 -0
  11. package/dist/bin/ticket.js +97 -0
  12. package/dist/bin/trail.d.ts +4 -0
  13. package/dist/bin/trail.js +62 -0
  14. package/dist/src/a2a/artifact-content.d.ts +9 -0
  15. package/dist/src/a2a/artifact-content.js +45 -0
  16. package/dist/src/a2a/desktop-notify.d.ts +1 -0
  17. package/dist/src/a2a/desktop-notify.js +12 -0
  18. package/dist/src/a2a/execution-binding.d.ts +9 -0
  19. package/dist/src/a2a/execution-binding.js +19 -0
  20. package/dist/src/a2a/executor.d.ts +22 -1
  21. package/dist/src/a2a/executor.js +308 -22
  22. package/dist/src/a2a/gateway.d.ts +613 -1
  23. package/dist/src/a2a/gateway.js +1337 -88
  24. package/dist/src/a2a/index.d.ts +14 -1
  25. package/dist/src/a2a/index.js +8 -0
  26. package/dist/src/a2a/job-directory.d.ts +6 -0
  27. package/dist/src/a2a/job-directory.js +19 -0
  28. package/dist/src/a2a/preflight.js +16 -1
  29. package/dist/src/a2a/resubmit.d.ts +46 -0
  30. package/dist/src/a2a/resubmit.js +82 -0
  31. package/dist/src/a2a/result-metadata.d.ts +6 -0
  32. package/dist/src/a2a/result-metadata.js +25 -6
  33. package/dist/src/a2a/server.d.ts +10 -0
  34. package/dist/src/a2a/server.js +127 -2
  35. package/dist/src/a2a/session-lifecycle.d.ts +40 -0
  36. package/dist/src/a2a/session-lifecycle.js +54 -0
  37. package/dist/src/a2a/store.d.ts +4 -0
  38. package/dist/src/a2a/store.js +76 -1
  39. package/dist/src/a2a/types.d.ts +77 -1
  40. package/dist/src/a2a/types.js +11 -1
  41. package/dist/src/a2a/workbench-ui.d.ts +28 -0
  42. package/dist/src/a2a/workbench-ui.js +182 -0
  43. package/dist/src/acp-connection.js +119 -14
  44. package/dist/src/bridge.d.ts +1 -0
  45. package/dist/src/bridge.js +312 -37
  46. package/dist/src/capacity-lifecycle.d.ts +5 -0
  47. package/dist/src/capacity-lifecycle.js +57 -0
  48. package/dist/src/capacity-queue.d.ts +58 -0
  49. package/dist/src/capacity-queue.js +388 -0
  50. package/dist/src/capacity.d.ts +101 -0
  51. package/dist/src/capacity.js +416 -0
  52. package/dist/src/dsh.js +1 -1
  53. package/dist/src/execution/agent-files.d.ts +25 -0
  54. package/dist/src/execution/agent-files.js +90 -0
  55. package/dist/src/execution/agent-registry.d.ts +164 -0
  56. package/dist/src/execution/agent-registry.js +275 -0
  57. package/dist/src/execution/human-review.d.ts +105 -0
  58. package/dist/src/execution/human-review.js +89 -0
  59. package/dist/src/execution/ledger.d.ts +57 -0
  60. package/dist/src/execution/ledger.js +122 -13
  61. package/dist/src/execution/ppt-delivery.d.ts +36 -3
  62. package/dist/src/execution/ppt-delivery.js +243 -53
  63. package/dist/src/execution/process-request.d.ts +151 -0
  64. package/dist/src/execution/process-request.js +177 -0
  65. package/dist/src/execution/project-discovery.d.ts +56 -0
  66. package/dist/src/execution/project-discovery.js +429 -0
  67. package/dist/src/execution/report-review.d.ts +60 -0
  68. package/dist/src/execution/report-review.js +173 -0
  69. package/dist/src/execution/targets.d.ts +20 -0
  70. package/dist/src/execution/targets.js +23 -3
  71. package/dist/src/execution/ticket-executor.d.ts +25 -0
  72. package/dist/src/execution/ticket-executor.js +27 -0
  73. package/dist/src/execution/ticket.d.ts +326 -0
  74. package/dist/src/execution/ticket.js +301 -0
  75. package/dist/src/execution/workbench-chat.d.ts +25 -0
  76. package/dist/src/execution/workbench-chat.js +54 -0
  77. package/dist/src/execution/workbench.d.ts +162 -0
  78. package/dist/src/execution/workbench.js +356 -0
  79. package/dist/src/index.d.ts +4 -0
  80. package/dist/src/index.js +3 -0
  81. package/dist/src/roles/index.d.ts +1 -0
  82. package/dist/src/roles/index.js +1 -0
  83. package/dist/src/roles/skills.d.ts +71 -0
  84. package/dist/src/roles/skills.js +427 -0
  85. package/dist/src/rsi/gate.d.ts +25 -0
  86. package/dist/src/rsi/gate.js +59 -0
  87. package/dist/src/rsi/outline-run.d.ts +107 -0
  88. package/dist/src/rsi/outline-run.js +443 -0
  89. package/dist/workbench-ui/app.css +453 -0
  90. package/dist/workbench-ui/app.js +13 -0
  91. package/dist/workbench-ui/chunk-23JHGYT3.js +1 -0
  92. package/dist/workbench-ui/chunk-3H6STGPV.js +1 -0
  93. package/dist/workbench-ui/chunk-3SNBBMGH.js +1 -0
  94. package/dist/workbench-ui/chunk-3XJZ6DIE.js +1 -0
  95. package/dist/workbench-ui/chunk-44KDLLKJ.js +1 -0
  96. package/dist/workbench-ui/chunk-46H7FU5Y.js +7 -0
  97. package/dist/workbench-ui/chunk-4N44QPL7.js +1 -0
  98. package/dist/workbench-ui/chunk-4YN4BS7I.js +1 -0
  99. package/dist/workbench-ui/chunk-53EG4IVQ.js +96 -0
  100. package/dist/workbench-ui/chunk-5FIPUNR4.js +1 -0
  101. package/dist/workbench-ui/chunk-6DWWYA6G.js +2 -0
  102. package/dist/workbench-ui/chunk-6FU3T633.js +99 -0
  103. package/dist/workbench-ui/chunk-6XKIHRA4.js +1 -0
  104. package/dist/workbench-ui/chunk-7GIX43Y5.js +1 -0
  105. package/dist/workbench-ui/chunk-7Q4WBGX6.js +4 -0
  106. package/dist/workbench-ui/chunk-A3BQM7HR.js +1 -0
  107. package/dist/workbench-ui/chunk-AFCFDDOP.js +24 -0
  108. package/dist/workbench-ui/chunk-AG67EUYD.js +89 -0
  109. package/dist/workbench-ui/chunk-AGJHMMTN.js +1 -0
  110. package/dist/workbench-ui/chunk-AO6JUBV6.js +41 -0
  111. package/dist/workbench-ui/chunk-AUSLTP43.js +72 -0
  112. package/dist/workbench-ui/chunk-AVZL46TT.js +1 -0
  113. package/dist/workbench-ui/chunk-AZRIGIV2.js +168 -0
  114. package/dist/workbench-ui/chunk-B2LIVH37.js +1 -0
  115. package/dist/workbench-ui/chunk-B7YX5TR5.js +1 -0
  116. package/dist/workbench-ui/chunk-BCB4X4XX.js +1 -0
  117. package/dist/workbench-ui/chunk-BCRQUL2A.js +88 -0
  118. package/dist/workbench-ui/chunk-BI6UHHQP.js +1 -0
  119. package/dist/workbench-ui/chunk-BLSLQ4AQ.js +120 -0
  120. package/dist/workbench-ui/chunk-C3QSRS6E.js +1 -0
  121. package/dist/workbench-ui/chunk-CK7M2PJ3.js +62 -0
  122. package/dist/workbench-ui/chunk-CM6LZ7TU.js +1 -0
  123. package/dist/workbench-ui/chunk-CP63H27F.js +36 -0
  124. package/dist/workbench-ui/chunk-CPUMMIS2.js +70 -0
  125. package/dist/workbench-ui/chunk-CSEIBI5U.js +2 -0
  126. package/dist/workbench-ui/chunk-CUS65DKZ.js +161 -0
  127. package/dist/workbench-ui/chunk-CVQY7TNC.js +1 -0
  128. package/dist/workbench-ui/chunk-D6S3XBIX.js +106 -0
  129. package/dist/workbench-ui/chunk-E253Y562.js +1 -0
  130. package/dist/workbench-ui/chunk-EADDJUDC.js +1 -0
  131. package/dist/workbench-ui/chunk-EBGJ3YXG.js +206 -0
  132. package/dist/workbench-ui/chunk-EKPVZ3WY.js +8 -0
  133. package/dist/workbench-ui/chunk-EQDCEAFY.js +1 -0
  134. package/dist/workbench-ui/chunk-ES3SSDJY.js +40 -0
  135. package/dist/workbench-ui/chunk-ESFD2H7N.js +231 -0
  136. package/dist/workbench-ui/chunk-FVOHPMS6.js +1 -0
  137. package/dist/workbench-ui/chunk-FXMQAGVT.js +1 -0
  138. package/dist/workbench-ui/chunk-GGTADRXD.js +24 -0
  139. package/dist/workbench-ui/chunk-GHIVPGNQ.js +1 -0
  140. package/dist/workbench-ui/chunk-GLU2YQV2.js +1 -0
  141. package/dist/workbench-ui/chunk-GOCKBYSM.js +1 -0
  142. package/dist/workbench-ui/chunk-H2KMMTJB.js +1 -0
  143. package/dist/workbench-ui/chunk-HGVLDNPP.js +39 -0
  144. package/dist/workbench-ui/chunk-HSAVC5GY.js +1 -0
  145. package/dist/workbench-ui/chunk-HSEAD2JH.js +1 -0
  146. package/dist/workbench-ui/chunk-HSIHOBTY.js +1 -0
  147. package/dist/workbench-ui/chunk-IZXOKUGG.js +67 -0
  148. package/dist/workbench-ui/chunk-JFT2LC2T.js +1 -0
  149. package/dist/workbench-ui/chunk-JHL3ZDYK.js +3 -0
  150. package/dist/workbench-ui/chunk-JMORLCZG.js +257 -0
  151. package/dist/workbench-ui/chunk-JR4SIX7A.js +1 -0
  152. package/dist/workbench-ui/chunk-K23HAGEH.js +30 -0
  153. package/dist/workbench-ui/chunk-K43JDCBH.js +1 -0
  154. package/dist/workbench-ui/chunk-KINKFJY7.js +1 -0
  155. package/dist/workbench-ui/chunk-KKQSA4LI.js +2 -0
  156. package/dist/workbench-ui/chunk-KOUZX3UX.js +1 -0
  157. package/dist/workbench-ui/chunk-KR4DRHW2.js +78 -0
  158. package/dist/workbench-ui/chunk-KT4DJNOR.js +1 -0
  159. package/dist/workbench-ui/chunk-KTPNKRRZ.js +292 -0
  160. package/dist/workbench-ui/chunk-LFHIPGSU.js +7 -0
  161. package/dist/workbench-ui/chunk-LWDL4HZB.js +125 -0
  162. package/dist/workbench-ui/chunk-MVYC3CY4.js +1 -0
  163. package/dist/workbench-ui/chunk-NWUPALCY.js +129 -0
  164. package/dist/workbench-ui/chunk-NY7C662Z.js +1 -0
  165. package/dist/workbench-ui/chunk-O76WTHWP.js +1 -0
  166. package/dist/workbench-ui/chunk-OTF7YHRE.js +162 -0
  167. package/dist/workbench-ui/chunk-P6TKKRKP.js +1 -0
  168. package/dist/workbench-ui/chunk-PFHOOWV3.js +1 -0
  169. package/dist/workbench-ui/chunk-PUQLANIM.js +1 -0
  170. package/dist/workbench-ui/chunk-PZCGBYVO.js +1 -0
  171. package/dist/workbench-ui/chunk-QOHUZGP4.js +1 -0
  172. package/dist/workbench-ui/chunk-QSEG3OFF.js +1 -0
  173. package/dist/workbench-ui/chunk-QYPOXZIA.js +84 -0
  174. package/dist/workbench-ui/chunk-R6SOF3JC.js +1 -0
  175. package/dist/workbench-ui/chunk-RCLOYU5F.js +1 -0
  176. package/dist/workbench-ui/chunk-RSRUP64S.js +1 -0
  177. package/dist/workbench-ui/chunk-RVAIT6JW.js +1 -0
  178. package/dist/workbench-ui/chunk-S2CCN3II.js +1 -0
  179. package/dist/workbench-ui/chunk-S2Q52W46.js +1 -0
  180. package/dist/workbench-ui/chunk-S2W5THJ5.js +1 -0
  181. package/dist/workbench-ui/chunk-S6ZQZNOX.js +1 -0
  182. package/dist/workbench-ui/chunk-S74PLMMS.js +1 -0
  183. package/dist/workbench-ui/chunk-S7C4HKEY.js +1 -0
  184. package/dist/workbench-ui/chunk-SDTB3Q65.js +1 -0
  185. package/dist/workbench-ui/chunk-SLPRGYUV.js +32 -0
  186. package/dist/workbench-ui/chunk-SQE76S5B.js +1 -0
  187. package/dist/workbench-ui/chunk-SSDZPVPW.js +1 -0
  188. package/dist/workbench-ui/chunk-SVI7DGIE.js +1 -0
  189. package/dist/workbench-ui/chunk-T6QKLZ4H.js +62 -0
  190. package/dist/workbench-ui/chunk-TJNRPTFL.js +1 -0
  191. package/dist/workbench-ui/chunk-TP6U4EDH.js +2 -0
  192. package/dist/workbench-ui/chunk-TYAAT3GQ.js +1 -0
  193. package/dist/workbench-ui/chunk-U6OCY4ZH.js +1 -0
  194. package/dist/workbench-ui/chunk-UAN3NLRF.js +1 -0
  195. package/dist/workbench-ui/chunk-UMLU3FIX.js +1 -0
  196. package/dist/workbench-ui/chunk-URIY2OTM.js +1 -0
  197. package/dist/workbench-ui/chunk-V2NUKAA7.js +38 -0
  198. package/dist/workbench-ui/chunk-V4QLL4TE.js +139 -0
  199. package/dist/workbench-ui/chunk-VASHXUK4.js +2 -0
  200. package/dist/workbench-ui/chunk-VJLIWNIU.js +1 -0
  201. package/dist/workbench-ui/chunk-VQNQFBID.js +1 -0
  202. package/dist/workbench-ui/chunk-VSIWU7XA.js +3 -0
  203. package/dist/workbench-ui/chunk-VSJASPUZ.js +321 -0
  204. package/dist/workbench-ui/chunk-VXPNUNUX.js +3 -0
  205. package/dist/workbench-ui/chunk-WBKLDCV6.js +1 -0
  206. package/dist/workbench-ui/chunk-WOKJM3FY.js +1 -0
  207. package/dist/workbench-ui/chunk-X3U3NA3X.js +34 -0
  208. package/dist/workbench-ui/chunk-XBYU7M4J.js +1 -0
  209. package/dist/workbench-ui/chunk-XBZAO4ID.js +10 -0
  210. package/dist/workbench-ui/chunk-XLLPZ2WO.js +1 -0
  211. package/dist/workbench-ui/chunk-YFVL4NJL.js +1 -0
  212. package/dist/workbench-ui/chunk-YRFQENM4.js +1 -0
  213. package/dist/workbench-ui/chunk-YUADQVB2.js +1 -0
  214. package/dist/workbench-ui/chunk-Z3TCAKM5.js +1 -0
  215. package/dist/workbench-ui/chunk-Z6QR6FRE.js +10 -0
  216. package/dist/workbench-ui/chunk-ZJPSORPP.js +3 -0
  217. package/dist/workbench-ui/chunk-ZLGCSTR2.js +15 -0
  218. package/dist/workbench-ui/chunk-ZLR4SG5X.js +1 -0
  219. package/dist/workbench-ui/chunk-ZND3TTGF.js +1 -0
  220. package/dist/workbench-ui/chunk-ZOP3ZYH7.js +2 -0
  221. package/dist/workbench-ui/index.html +14 -0
  222. package/package.json +23 -8
  223. package/skills/acp-service/SKILL.md +24 -8
  224. package/skills/acp-service/references/a2a.md +24 -8
  225. package/skills/acp-service/references/async-caller.md +48 -0
  226. package/skills/acp-service/references/dsh.md +2 -0
  227. package/skills/acp-service/references/roles-and-tasks.md +120 -0
  228. package/skills/acp-service/scripts/a2a-caller.py +242 -0
  229. package/skills/rsi-coach/SKILL.md +134 -0
  230. package/vendor/dsh/README.md +11 -5
  231. package/vendor/dsh/a2a-executor.d.ts +60 -3
  232. package/vendor/dsh/a2a-executor.js +208 -18
  233. package/vendor/dsh/a2a.d.ts +12 -2
  234. package/vendor/dsh/a2a.js +9 -2
  235. package/vendor/dsh/adapter.d.ts +61 -2
  236. package/vendor/dsh/adapter.js +354 -23
  237. package/vendor/dsh/client.js +67 -11
  238. package/vendor/dsh/index.js +57 -4
  239. package/vendor/dsh/native-approvals.d.ts +4 -0
  240. package/vendor/dsh/native-approvals.js +44 -0
  241. package/vendor/dsh/preset-route.d.ts +49 -0
  242. package/vendor/dsh/preset-route.js +51 -0
  243. package/vendor/dsh/preset.js +10 -3
  244. package/vendor/dsh/process-admission.d.ts +25 -0
  245. package/vendor/dsh/process-admission.js +87 -0
  246. package/vendor/dsh/process-requests.d.ts +57 -0
  247. package/vendor/dsh/process-requests.js +49 -0
  248. package/vendor/dsh/review-mcp.d.ts +1 -0
  249. package/vendor/dsh/review-mcp.js +56 -0
  250. package/vendor/dsh/review.d.ts +30 -0
  251. package/vendor/dsh/review.js +149 -0
  252. package/vendor/dsh/session-settings.d.ts +34 -0
  253. package/vendor/dsh/session-settings.js +114 -0
  254. package/vendor/dsh/ticket-spec.d.ts +30 -0
  255. package/vendor/dsh/ticket-spec.js +10 -0
  256. package/vendor/dsh/ticket-tools.d.ts +21 -0
  257. package/vendor/dsh/ticket-tools.js +43 -0
  258. package/vendor/dsh/workbench.d.ts +18 -0
  259. package/vendor/dsh/workbench.js +91 -0
  260. package/vendor/runtime/README.md +6 -4
  261. package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
  262. package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
  263. package/vendor/runtime/dist/cli.js +7 -7
  264. package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
  265. package/vendor/runtime/dist/docs-site/CLI.html +2 -2
  266. package/vendor/runtime/dist/docs-site/VISION.html +2 -2
  267. package/vendor/runtime/dist/docs-site/agents.html +2 -2
  268. package/vendor/runtime/dist/docs-site/compare.html +2 -2
  269. package/vendor/runtime/dist/docs-site/config.html +2 -2
  270. package/vendor/runtime/dist/docs-site/custom-agents.html +2 -2
  271. package/vendor/runtime/dist/docs-site/exit-codes.html +2 -2
  272. package/vendor/runtime/dist/docs-site/flows.html +2 -2
  273. package/vendor/runtime/dist/docs-site/index.html +1 -1
  274. package/vendor/runtime/dist/docs-site/install.html +2 -2
  275. package/vendor/runtime/dist/docs-site/llms.txt +1 -1
  276. package/vendor/runtime/dist/docs-site/output-formats.html +2 -2
  277. package/vendor/runtime/dist/docs-site/permissions.html +2 -2
  278. package/vendor/runtime/dist/docs-site/prompting.html +2 -2
  279. package/vendor/runtime/dist/docs-site/quickstart.html +2 -2
  280. package/vendor/runtime/dist/docs-site/releasing.html +2 -2
  281. package/vendor/runtime/dist/docs-site/runtime-environment.html +2 -2
  282. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +3 -2
  283. package/vendor/runtime/dist/docs-site/safe-errors.html +2 -2
  284. package/vendor/runtime/dist/docs-site/session-control.html +2 -2
  285. package/vendor/runtime/dist/docs-site/session-watch.html +2 -2
  286. package/vendor/runtime/dist/docs-site/sessions.html +2 -2
  287. package/vendor/runtime/dist/docs-site/shared-sessions.html +2 -2
  288. package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
  289. package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
  290. package/vendor/runtime/dist/flows.js +1 -1
  291. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
  292. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  293. package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
  294. package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
  295. package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
  296. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  297. package/vendor/runtime/dist/runtime.js +1 -1
  298. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
  299. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
  300. package/vendor/runtime/package.json +6 -4
  301. package/vendor/runtime/skills/acpx/SKILL.md +2 -0
  302. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
@@ -0,0 +1,429 @@
1
+ /** Optional, metadata-only project role discovery. Never registers targets or starts agent work. */
2
+ import { execFile } from 'node:child_process';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { closeSync, constants, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
5
+ import { lstat, open, readdir, realpath } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { z } from 'zod';
8
+ import { roleSkillProfileSchema } from '../roles/skills.js';
9
+ const absolute = z.string().min(1).max(4096).refine(value => path.isAbsolute(value) && !value.includes('\0'), 'Expected an absolute local path');
10
+ export const projectDiscoveryConfigSchema = z.object({
11
+ readerExecutable: z.string().min(1).max(4096).refine(value => !value.includes('\0')).default('1session'),
12
+ allowedRoots: z.array(absolute).min(1).max(100), explicitRoots: z.array(absolute).max(1000).default([]),
13
+ timeoutMs: z.number().int().min(100).max(120_000).default(15_000),
14
+ maxProjects: z.number().int().min(1).max(1000).default(200),
15
+ }).strict();
16
+ const interval = z.number().int().min(60_000).max(86_400_000);
17
+ const settingsSchema = z.object({
18
+ mode: z.enum(['manual', 'interval']),
19
+ intervalMs: interval.optional(),
20
+ }).strict().superRefine((value, ctx) => {
21
+ if (value.mode === 'interval' && value.intervalMs === undefined) {
22
+ ctx.addIssue({ code: 'custom', message: 'intervalMs is required in interval mode', path: ['intervalMs'] });
23
+ }
24
+ });
25
+ const empty = z.object({}).strict();
26
+ export const DISCOVERY_METHODS = {
27
+ execution_project_scan: { description: '只读探查批准目录及可选 Session Reader 项目中的 .1agents 角色声明;不创建目标或任务。', parameters: z.toJSONSchema(empty) },
28
+ execution_project_list: { description: '读取项目角色候选缓存,不执行扫描或模型。', parameters: z.toJSONSchema(empty) },
29
+ execution_discovery_config_get: { description: '读取项目探查的手动/周期设置,不执行扫描。', parameters: z.toJSONSchema(empty) },
30
+ execution_discovery_config_update: { description: '更新手动/周期探查设置;周期模式需显式指定 intervalMs,不唤醒主会话。', parameters: z.toJSONSchema(settingsSchema) },
31
+ };
32
+ const candidateSchema = z.object({ key: z.string(), projectRoot: absolute, roleDirectory: absolute, profilePath: absolute,
33
+ roleId: z.string().optional(), roleVersion: z.string().optional(),
34
+ skillRefs: z.array(z.object({ key: z.string(), name: z.string() }).strict()).optional(),
35
+ status: z.enum(['candidate', 'invalid', 'missing', 'stale']), reasonCode: z.string().optional(), lastSeenAt: z.string().optional(),
36
+ }).strict();
37
+ const diagnosticSchema = z.object({ code: z.string(), path: z.string().optional() }).strict();
38
+ const snapshotSchema = z.object({ status: z.enum(['idle', 'complete', 'partial', 'error']), scannedAt: z.string().optional(),
39
+ candidates: z.array(candidateSchema).max(20_000), diagnostics: z.array(diagnosticSchema).max(2000),
40
+ }).strict();
41
+ const stateSchema = z.object({ version: z.literal(1), config: settingsSchema, snapshot: snapshotSchema }).strict();
42
+ const within = (root, value) => {
43
+ const relative = path.relative(root, value);
44
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
45
+ };
46
+ const candidateKey = (root, roleId) => createHash('sha256').update(JSON.stringify([root, roleId])).digest('hex');
47
+ const clone = (value) => structuredClone(value);
48
+ const readerPageSchema = z.object({ projects: z.array(z.object({ workspace: absolute,
49
+ workspaces: z.array(absolute).max(1000).optional(),
50
+ }).passthrough()).max(1000), hasMore: z.boolean(), nextPage: z.number().int().positive().optional() }).passthrough();
51
+ export class ProjectRoleDiscovery {
52
+ file;
53
+ config;
54
+ state;
55
+ started = false;
56
+ closed = false;
57
+ timer;
58
+ active;
59
+ controller;
60
+ constructor(options) {
61
+ if (!path.isAbsolute(options.stateDirectory))
62
+ throw new Error('Discovery stateDirectory must be absolute');
63
+ this.config = projectDiscoveryConfigSchema.parse(options.config);
64
+ mkdirSync(options.stateDirectory, { recursive: true, mode: 0o700 });
65
+ this.file = path.join(realpathSync(options.stateDirectory), 'discovery.json');
66
+ try {
67
+ const info = lstatSync(this.file);
68
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 16 * 1024 * 1024)
69
+ throw new Error('Invalid discovery state file');
70
+ this.state = stateSchema.parse(JSON.parse(readFileSync(this.file, 'utf8')));
71
+ }
72
+ catch (error) {
73
+ if (error.code !== 'ENOENT')
74
+ throw new Error('Cannot load discovery state');
75
+ this.state = { version: 1, config: { mode: 'manual' }, snapshot: { status: 'idle', candidates: [], diagnostics: [] } };
76
+ }
77
+ }
78
+ commit(next) {
79
+ stateSchema.parse(next);
80
+ const bytes = JSON.stringify(next);
81
+ if (Buffer.byteLength(bytes) > 16 * 1024 * 1024)
82
+ throw new Error('Discovery snapshot exceeds byte limit');
83
+ const temporary = `${this.file}.${randomUUID()}.tmp`, descriptor = openSync(temporary, 'wx', 0o600);
84
+ try {
85
+ try {
86
+ writeFileSync(descriptor, bytes);
87
+ fsyncSync(descriptor);
88
+ }
89
+ finally {
90
+ closeSync(descriptor);
91
+ }
92
+ renameSync(temporary, this.file);
93
+ const directory = openSync(path.dirname(this.file), 'r');
94
+ try {
95
+ fsyncSync(directory);
96
+ }
97
+ finally {
98
+ closeSync(directory);
99
+ }
100
+ this.state = next;
101
+ }
102
+ catch (error) {
103
+ try {
104
+ unlinkSync(temporary);
105
+ }
106
+ catch { }
107
+ throw error;
108
+ }
109
+ }
110
+ view() { return clone({ config: this.state.config, snapshot: this.state.snapshot }); }
111
+ start() { if (!this.closed) {
112
+ this.started = true;
113
+ this.schedule();
114
+ } }
115
+ schedule() {
116
+ if (this.timer)
117
+ clearTimeout(this.timer);
118
+ this.timer = undefined;
119
+ if (!this.started || this.closed || this.state.config.mode !== 'interval')
120
+ return;
121
+ this.timer = setTimeout(() => {
122
+ this.timer = undefined;
123
+ // Scans write their own diagnostic snapshot. Persistence failures must also stay contained.
124
+ void this.scan().catch(() => { }).finally(() => this.schedule());
125
+ }, this.state.config.intervalMs);
126
+ this.timer.unref();
127
+ }
128
+ async close() {
129
+ this.closed = true;
130
+ if (this.timer)
131
+ clearTimeout(this.timer);
132
+ this.timer = undefined;
133
+ this.controller?.abort();
134
+ await this.active?.catch(() => { });
135
+ }
136
+ async invoke(method, params) {
137
+ if (this.closed)
138
+ throw new Error('Project discovery is closed');
139
+ if (method === 'execution_discovery_config_update') {
140
+ const config = settingsSchema.parse(params);
141
+ this.commit({ ...this.state, config });
142
+ this.schedule();
143
+ return clone(config);
144
+ }
145
+ empty.parse(params);
146
+ if (method === 'execution_discovery_config_get')
147
+ return clone(this.state.config);
148
+ if (method === 'execution_project_list')
149
+ return this.view();
150
+ if (method === 'execution_project_scan')
151
+ return this.scan();
152
+ throw new Error('Unknown project discovery method');
153
+ }
154
+ scan() {
155
+ if (this.active)
156
+ return this.active;
157
+ if (this.closed)
158
+ return Promise.reject(new Error('Project discovery is closed'));
159
+ this.controller = new AbortController();
160
+ this.active = this.collect(this.controller.signal).finally(() => { this.active = undefined; this.controller = undefined; });
161
+ return this.active;
162
+ }
163
+ async reader(scope, page, limit, timeoutMs, signal) {
164
+ const stdout = await new Promise((resolve, reject) => {
165
+ // execFile forwards its timeout killSignal, but some Node versions use SIGTERM for AbortSignal.
166
+ // Explicitly kill the configured Reader on close, including Readers that ignore SIGTERM.
167
+ const abort = () => { child.kill('SIGKILL'); };
168
+ const child = execFile(this.config.readerExecutable, ['projects', '--scope', scope, '--page', String(page), '--limit', String(limit), '--json'], { encoding: 'utf8', timeout: timeoutMs, maxBuffer: 2 * 1024 * 1024, windowsHide: true, shell: false, killSignal: 'SIGKILL' }, (error, output) => {
169
+ signal.removeEventListener('abort', abort);
170
+ if (error)
171
+ reject(new Error(signal.aborted ? 'reader_cancelled' : 'reader_failed'));
172
+ else
173
+ resolve(output);
174
+ });
175
+ signal.addEventListener('abort', abort, { once: true });
176
+ if (signal.aborted)
177
+ abort();
178
+ });
179
+ try {
180
+ return readerPageSchema.parse(JSON.parse(stdout));
181
+ }
182
+ catch {
183
+ throw new Error('reader_invalid_output');
184
+ }
185
+ }
186
+ async collect(signal) {
187
+ const diagnostics = [], candidates = new Map(), now = new Date().toISOString();
188
+ let diagnosticBytes = 0;
189
+ const note = (code, value) => {
190
+ const item = { code, ...(value ? { path: value } : {}) }, bytes = Buffer.byteLength(JSON.stringify(item));
191
+ if (diagnostics.length < 2000 && diagnosticBytes + bytes < 64 * 1024) {
192
+ diagnostics.push(item);
193
+ diagnosticBytes += bytes;
194
+ }
195
+ };
196
+ const roots = [], paths = new Set();
197
+ let partial = false, readerSucceeded = false, projectCount = 0;
198
+ for (const configured of this.config.allowedRoots) {
199
+ try {
200
+ const root = await realpath(configured);
201
+ if (!(await lstat(root)).isDirectory())
202
+ throw new Error();
203
+ roots.push(root);
204
+ paths.add(root);
205
+ }
206
+ catch {
207
+ note('allowed_root_missing', configured);
208
+ partial = true;
209
+ }
210
+ }
211
+ const allowed = (value) => roots.some(root => within(root, value));
212
+ for (const explicit of this.config.explicitRoots)
213
+ paths.add(explicit);
214
+ const readerDeadline = Date.now() + this.config.timeoutMs;
215
+ const scopes = [...new Set(roots)];
216
+ for (const [scopeIndex, scope] of scopes.entries()) {
217
+ let page = 1;
218
+ while (!signal.aborted && projectCount < this.config.maxProjects) {
219
+ const remaining = readerDeadline - Date.now();
220
+ if (remaining <= 0) {
221
+ note('reader_timeout', scope);
222
+ partial = true;
223
+ break;
224
+ }
225
+ try {
226
+ const limit = Math.min(50, this.config.maxProjects - projectCount);
227
+ const result = await this.reader(scope, page, limit, remaining, signal);
228
+ if (result.projects.length > limit)
229
+ throw new Error('reader_invalid_output');
230
+ readerSucceeded = true;
231
+ projectCount += result.projects.length;
232
+ for (const project of result.projects)
233
+ for (const value of [project.workspace, ...project.workspaces ?? []]) {
234
+ if (paths.size < this.config.maxProjects * 10 + this.config.explicitRoots.length + roots.length)
235
+ paths.add(value);
236
+ else {
237
+ note('candidate_limit');
238
+ partial = true;
239
+ }
240
+ }
241
+ if (!result.hasMore)
242
+ break;
243
+ if (!result.projects.length || (result.nextPage !== undefined && result.nextPage !== page + 1))
244
+ throw new Error('reader_invalid_pagination');
245
+ if (projectCount >= this.config.maxProjects) {
246
+ note('project_limit');
247
+ partial = true;
248
+ break;
249
+ }
250
+ page++;
251
+ }
252
+ catch (error) {
253
+ note(error.message.startsWith('reader_') ? error.message : 'reader_failed', scope);
254
+ partial = true;
255
+ break;
256
+ }
257
+ }
258
+ if (projectCount >= this.config.maxProjects) {
259
+ if (scopeIndex < scopes.length - 1) {
260
+ note('project_limit');
261
+ partial = true;
262
+ }
263
+ break;
264
+ }
265
+ }
266
+ const visited = new Set(), roleBudget = { count: 0, bytes: 0, limited: false };
267
+ directories: for (const candidate of paths) {
268
+ if (signal.aborted)
269
+ break;
270
+ // Native sessions can start inside runtime jobs; never traverse role caches as projects.
271
+ const segments = path.resolve(candidate).split(path.sep), internal = segments.indexOf('.1agents');
272
+ const base = internal < 0 ? candidate : segments.slice(0, internal).join(path.sep) || path.sep;
273
+ let current;
274
+ try {
275
+ current = await realpath(base);
276
+ // A plain alias can resolve into a cache/job even when its lexical path has no .1agents.
277
+ const canonicalSegments = current.split(path.sep), canonicalInternal = canonicalSegments.indexOf('.1agents');
278
+ if (canonicalInternal >= 0)
279
+ current = canonicalSegments.slice(0, canonicalInternal).join(path.sep) || path.sep;
280
+ if (!(await lstat(current)).isDirectory())
281
+ throw new Error();
282
+ }
283
+ catch {
284
+ note('project_missing', base);
285
+ continue;
286
+ }
287
+ if (!allowed(current)) {
288
+ note('outside_allowed_roots', base);
289
+ continue;
290
+ }
291
+ for (let depth = 0; depth < 32 && allowed(current) && !signal.aborted; depth++) {
292
+ if (!visited.has(current)) {
293
+ if (visited.size >= 20_000) {
294
+ note('directory_limit');
295
+ partial = true;
296
+ break directories;
297
+ }
298
+ visited.add(current);
299
+ try {
300
+ await this.readRoles(current, candidates, now, signal, roleBudget);
301
+ }
302
+ catch (error) {
303
+ const code = error.message, exhausted = code === 'candidate_limit' || code === 'snapshot_limit';
304
+ note(exhausted ? code : 'role_directory_unreadable', current);
305
+ partial = true;
306
+ if (exhausted)
307
+ break directories;
308
+ }
309
+ }
310
+ const parent = path.dirname(current);
311
+ if (parent === current || !allowed(parent))
312
+ break;
313
+ if (depth === 31) {
314
+ note('ancestor_limit', current);
315
+ partial = true;
316
+ }
317
+ current = parent;
318
+ }
319
+ }
320
+ if (signal.aborted) {
321
+ note('scan_cancelled');
322
+ partial = true;
323
+ }
324
+ // Bound complete snapshots too: individually valid large profiles can exceed a safe cache size.
325
+ const retained = new Map();
326
+ const size = (candidate) => Buffer.byteLength(JSON.stringify(candidate)) + 1;
327
+ let candidateBytes = 0;
328
+ for (const old of this.state.snapshot.candidates) {
329
+ const value = { ...old, status: partial ? 'stale' : 'missing', reasonCode: partial ? 'scan_incomplete' : 'not_observed' };
330
+ retained.set(old.key, value);
331
+ candidateBytes += size(value);
332
+ }
333
+ let limited = roleBudget.limited || candidateBytes > 8 * 1024 * 1024;
334
+ for (const [key, value] of candidates) {
335
+ const old = retained.get(key), nextBytes = candidateBytes + size(value) - (old ? size(old) : 0);
336
+ if ((!old && retained.size >= 20_000) || nextBytes > 8 * 1024 * 1024) {
337
+ limited = true;
338
+ continue;
339
+ }
340
+ retained.set(key, value);
341
+ candidateBytes = nextBytes;
342
+ }
343
+ if (limited) {
344
+ note('snapshot_limit');
345
+ partial = true;
346
+ // On overflow keep the complete prior evidence, rather than evicting older candidates.
347
+ if (this.state.snapshot.candidates.length) {
348
+ retained.clear();
349
+ for (const old of this.state.snapshot.candidates)
350
+ retained.set(old.key, { ...old, status: 'stale' });
351
+ }
352
+ }
353
+ if (partial && !limited)
354
+ for (const [key, value] of retained)
355
+ if (!candidates.has(key))
356
+ retained.set(key, { ...value, status: 'stale', reasonCode: 'scan_incomplete' });
357
+ const snapshot = { scannedAt: now,
358
+ status: partial ? (readerSucceeded || retained.size || visited.size ? 'partial' : 'error') : 'complete',
359
+ candidates: [...retained.values()].sort((a, b) => a.projectRoot.localeCompare(b.projectRoot) || a.profilePath.localeCompare(b.profilePath)), diagnostics };
360
+ this.commit({ ...this.state, snapshot });
361
+ return this.view();
362
+ }
363
+ async readRoles(projectRoot, result, now, signal, budget) {
364
+ const agentDirectory = path.join(projectRoot, '.1agents'), roles = path.join(agentDirectory, 'roles');
365
+ for (const directory of [agentDirectory, roles]) {
366
+ let info;
367
+ try {
368
+ info = await lstat(directory);
369
+ }
370
+ catch (error) {
371
+ if (error.code === 'ENOENT')
372
+ return;
373
+ throw error;
374
+ }
375
+ if (info.isSymbolicLink() || !info.isDirectory() || !within(projectRoot, await realpath(directory)))
376
+ throw new Error('Unsafe role directory');
377
+ }
378
+ const entries = await readdir(roles, { withFileTypes: true });
379
+ if (entries.length > 1000) {
380
+ budget.limited = true;
381
+ throw new Error('candidate_limit');
382
+ }
383
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
384
+ if (signal.aborted)
385
+ return;
386
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
387
+ continue;
388
+ if (budget.count >= 10_000) {
389
+ budget.limited = true;
390
+ throw new Error('candidate_limit');
391
+ }
392
+ budget.count++;
393
+ const roleDirectory = path.join(roles, entry.name), profilePath = path.join(roleDirectory, 'profile.json');
394
+ const base = { key: candidateKey(projectRoot, entry.name), projectRoot, roleDirectory, profilePath, status: 'invalid', lastSeenAt: now };
395
+ let candidate = base;
396
+ try {
397
+ if (entry.isSymbolicLink() || !(await lstat(roleDirectory)).isDirectory() || !within(projectRoot, await realpath(roleDirectory)))
398
+ throw new Error('unsafe_role_path');
399
+ const handle = await open(profilePath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
400
+ let profile;
401
+ try {
402
+ const info = await handle.stat();
403
+ if (!info.isFile() || info.size > 256 * 1024 || !within(projectRoot, await realpath(profilePath)))
404
+ throw new Error('unsafe_profile');
405
+ profile = roleSkillProfileSchema.parse(JSON.parse(await handle.readFile('utf8')));
406
+ }
407
+ finally {
408
+ await handle.close();
409
+ }
410
+ candidate = { ...base, key: candidateKey(projectRoot, profile.id), roleId: profile.id, roleVersion: profile.version,
411
+ skillRefs: profile.skills.map(skill => ({ key: skill.key, name: skill.name })), status: 'candidate' };
412
+ }
413
+ catch (error) {
414
+ candidate = { ...base, status: error.code === 'ENOENT' ? 'missing' : 'invalid',
415
+ reasonCode: error.code === 'ENOENT' ? 'profile_missing' : 'profile_invalid_or_unsafe' };
416
+ }
417
+ const existing = result.get(candidate.key);
418
+ if (existing && existing.profilePath !== candidate.profilePath)
419
+ candidate = { ...existing, status: 'invalid', reasonCode: 'duplicate_role_id' };
420
+ const bytes = budget.bytes + Buffer.byteLength(JSON.stringify(candidate)) + 1 - (existing ? Buffer.byteLength(JSON.stringify(existing)) + 1 : 0);
421
+ if (bytes > 8 * 1024 * 1024) {
422
+ budget.limited = true;
423
+ throw new Error('snapshot_limit');
424
+ }
425
+ budget.bytes = bytes;
426
+ result.set(candidate.key, candidate);
427
+ }
428
+ }
429
+ }
@@ -0,0 +1,60 @@
1
+ import { z } from 'zod';
2
+ import { type HumanReviewRequest } from './human-review.js';
3
+ import type { LedgerAttempt } from './ledger.js';
4
+ export declare const reportReviewPolicySchema: z.ZodObject<{
5
+ workspaceRoot: z.ZodString;
6
+ allowedProjectRoots: z.ZodArray<z.ZodString>;
7
+ allowedRemotes: z.ZodArray<z.ZodString>;
8
+ }, z.core.$strict>;
9
+ export declare const reportReviewInputSchema: z.ZodObject<{
10
+ fileName: z.ZodDefault<z.ZodString>;
11
+ }, z.core.$strict>;
12
+ export type ReportReviewPolicy = z.infer<typeof reportReviewPolicySchema>;
13
+ export interface ReportReviewRun {
14
+ sourceId: string;
15
+ jobId: string;
16
+ attemptId: string;
17
+ originSessionId: string;
18
+ title: string;
19
+ targetId: string;
20
+ remote: string;
21
+ cwd: string;
22
+ authorInput: Record<string, unknown>;
23
+ directory: string;
24
+ reportPath: string;
25
+ revision: number;
26
+ reviewerId: string;
27
+ stage: 'research' | 'file_check' | 'human_review' | 'finished';
28
+ phase: string;
29
+ executionStatus: 'working' | 'input_required' | 'completed' | 'failed' | 'canceled';
30
+ child?: {
31
+ jobId: string;
32
+ attemptId: string;
33
+ };
34
+ humanReviews: HumanReviewRequest[];
35
+ digest?: string;
36
+ snapshotPath?: string;
37
+ fileCheck?: {
38
+ passed: boolean;
39
+ path: string;
40
+ checkedAt: string;
41
+ size?: number;
42
+ sha256?: string;
43
+ error?: string;
44
+ };
45
+ resultSummary?: string;
46
+ createdAt: string;
47
+ updatedAt: string;
48
+ }
49
+ export interface ReportReviewAdapter {
50
+ persist(run: ReportReviewRun): void;
51
+ submit(run: ReportReviewRun, prompt: string, previous?: ReportReviewRun['child']): Promise<ReportReviewRun['child']>;
52
+ child(attemptId: string): LedgerAttempt;
53
+ update(run: ReportReviewRun): void;
54
+ }
55
+ export declare const reportRevision: (run: ReportReviewRun) => string;
56
+ export declare function createReportReviewRun(input: Pick<ReportReviewRun, 'sourceId' | 'jobId' | 'attemptId' | 'originSessionId' | 'title' | 'targetId' | 'remote' | 'cwd' | 'authorInput' | 'reviewerId'>, policy: ReportReviewPolicy, report: z.input<typeof reportReviewInputSchema>): Promise<ReportReviewRun>;
57
+ /** Read bounded regular bytes without following symlinks or accepting linked aliases. */
58
+ export declare function readReportFile(file: string): Promise<Buffer>;
59
+ export declare function reportBindingDigest(run: ReportReviewRun): Promise<string>;
60
+ export declare function advanceReportReview(run: ReportReviewRun, adapter: ReportReviewAdapter): Promise<void>;
@@ -0,0 +1,173 @@
1
+ /** A temporary author, a deterministic file check, and a final human gate. No model reviewer. */
2
+ import { createHash } from 'node:crypto';
3
+ import { constants } from 'node:fs';
4
+ import { mkdir, open, realpath, writeFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { z } from 'zod';
7
+ import { createHumanReview, markHumanReviewApplied } from './human-review.js';
8
+ const absolute = z.string().min(1).refine(path.isAbsolute, 'Expected an absolute path');
9
+ export const reportReviewPolicySchema = z.object({
10
+ workspaceRoot: absolute, allowedProjectRoots: z.array(absolute).min(1),
11
+ allowedRemotes: z.array(z.string().min(1)).min(1),
12
+ }).strict();
13
+ export const reportReviewInputSchema = z.object({
14
+ fileName: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,120}\.md$/).default('architecture-report.md'),
15
+ }).strict();
16
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
17
+ const terminal = new Set(['completed', 'failed', 'canceled', 'rejected']);
18
+ export const reportRevision = (run) => `report-v${run.revision}`;
19
+ function within(root, file) {
20
+ const relative = path.relative(root, file);
21
+ return relative === '' || relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
22
+ }
23
+ export async function createReportReviewRun(input, policy, report) {
24
+ if (!policy.allowedRemotes.includes(input.remote))
25
+ throw new Error('Report checks require an explicitly configured shared-filesystem remote');
26
+ const cwd = await realpath(input.cwd), roots = await Promise.all(policy.allowedProjectRoots.map(root => realpath(root)));
27
+ if (!roots.some(root => within(root, cwd)))
28
+ throw new Error('Report project is outside allowedProjectRoots');
29
+ const { fileName } = reportReviewInputSchema.parse(report);
30
+ await mkdir(policy.workspaceRoot, { recursive: true });
31
+ const workspace = await realpath(policy.workspaceRoot);
32
+ const directory = path.join(workspace, input.jobId, input.attemptId);
33
+ await mkdir(directory, { recursive: true });
34
+ if (!within(workspace, await realpath(directory)))
35
+ throw new Error('Report output escaped its workspace');
36
+ const version = path.join(directory, 'report-v1');
37
+ await mkdir(version);
38
+ const at = new Date().toISOString();
39
+ return { ...input, cwd, directory, reportPath: path.join(version, fileName), revision: 1,
40
+ stage: 'research', phase: 'author_pending', executionStatus: 'working', humanReviews: [], createdAt: at, updatedAt: at };
41
+ }
42
+ /** Read bounded regular bytes without following symlinks or accepting linked aliases. */
43
+ export async function readReportFile(file) {
44
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
45
+ try {
46
+ const stat = await handle.stat();
47
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size === 0 || stat.size > 256 * 1024)
48
+ throw new Error('Expected a nonempty regular Markdown report of at most 256 KiB');
49
+ const bytes = Buffer.alloc(stat.size + 1);
50
+ const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
51
+ if (bytesRead !== stat.size)
52
+ throw new Error('Report changed during file check');
53
+ const result = bytes.subarray(0, bytesRead);
54
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(result);
55
+ if (!text.trim())
56
+ throw new Error('Report is empty');
57
+ return result;
58
+ }
59
+ finally {
60
+ await handle.close();
61
+ }
62
+ }
63
+ export async function reportBindingDigest(run) {
64
+ if (!run.snapshotPath)
65
+ throw new Error('Report snapshot is unavailable');
66
+ const bytes = await readReportFile(run.reportPath), snapshot = await readReportFile(run.snapshotPath);
67
+ if (hash(bytes) !== hash(snapshot))
68
+ throw new Error('Report bytes differ from the reviewed snapshot');
69
+ return hash(snapshot);
70
+ }
71
+ function authorPrompt(run, feedback) {
72
+ return `${String(run.authorInput.prompt)}\n\n任务源目录(只读):${run.cwd}。当前执行工作区为 ${run.directory},先记录真实 pwd。\n仅将任务要求的 Markdown 产物写入 ${run.reportPath}。语言与内容按任务说明执行。不得修改源目录、安装依赖、启动服务或创建其他任务。\n${feedback ? `这是同一任务的修订,保留旧版;用户意见:${feedback}\n` : ''}写入完成后立即结束。协调器检查文件,用户做最终确认。`;
73
+ }
74
+ export async function advanceReportReview(run, adapter) {
75
+ const save = () => { run.updatedAt = new Date().toISOString(); adapter.persist(run); adapter.update(run); };
76
+ if (terminal.has(run.executionStatus)) {
77
+ adapter.update(run);
78
+ return;
79
+ }
80
+ const review = run.humanReviews.at(-1), decision = review?.resume;
81
+ if (decision?.status === 'pending') {
82
+ if (decision.action === 'approve') {
83
+ if (await reportBindingDigest(run) !== review.digest)
84
+ throw new Error('Approved report version changed');
85
+ run.executionStatus = 'completed';
86
+ run.stage = 'finished';
87
+ run.phase = 'human_approved';
88
+ run.resultSummary = `人工已通过 ${reportRevision(run)}。报告:${run.reportPath}`;
89
+ }
90
+ else if (decision.action === 'cancel') {
91
+ run.executionStatus = 'canceled';
92
+ run.phase = 'human_canceled';
93
+ run.resultSummary = '用户已放弃报告任务,保留产物与审核历史。';
94
+ }
95
+ else {
96
+ run.revision++;
97
+ const version = path.join(run.directory, reportRevision(run));
98
+ await mkdir(version, { recursive: true });
99
+ run.reportPath = path.join(version, path.basename(run.reportPath));
100
+ delete run.digest;
101
+ delete run.snapshotPath;
102
+ delete run.fileCheck;
103
+ run.executionStatus = 'working';
104
+ run.stage = 'research';
105
+ run.phase = 'revision_pending';
106
+ }
107
+ run.humanReviews[run.humanReviews.length - 1] = markHumanReviewApplied(review, decision.decisionId);
108
+ save();
109
+ }
110
+ if (run.executionStatus !== 'working')
111
+ return;
112
+ if (run.phase === 'author_pending' || run.phase === 'revision_pending') {
113
+ const feedback = run.phase === 'revision_pending' ? review?.history.at(-1)?.note : undefined;
114
+ // The stable submission key allows recovery after an accepted-but-unrecorded child receipt.
115
+ run.child = await adapter.submit(run, authorPrompt(run, feedback), feedback ? run.child : undefined);
116
+ run.phase = 'author_running';
117
+ save();
118
+ }
119
+ if (!run.child)
120
+ throw new Error('Report child has no durable receipt');
121
+ const child = adapter.child(run.child.attemptId);
122
+ if (child.submissionStatus === 'submission_unknown' || child.submissionStatus === 'dispatching') {
123
+ run.executionStatus = 'input_required';
124
+ run.phase = 'child_admission_unknown';
125
+ run.resultSummary = '临时任务受理未知,停止重派,等待核对。';
126
+ save();
127
+ return;
128
+ }
129
+ if (!terminal.has(child.executionStatus))
130
+ return;
131
+ if (child.executionStatus !== 'completed') {
132
+ run.executionStatus = 'failed';
133
+ run.phase = 'author_failed';
134
+ run.resultSummary = '临时分析任务未完成,请查看子任务。';
135
+ save();
136
+ return;
137
+ }
138
+ run.stage = 'file_check';
139
+ run.phase = 'checking_report';
140
+ save();
141
+ try {
142
+ if (await realpath(path.dirname(run.reportPath)) !== path.dirname(run.reportPath))
143
+ throw new Error('Report directory is not the assigned directory');
144
+ const bytes = await readReportFile(run.reportPath), sha256 = hash(bytes);
145
+ const snapshotPath = path.join(run.directory, `${reportRevision(run)}.review-snapshot.md`);
146
+ try {
147
+ await writeFile(snapshotPath, bytes, { flag: 'wx', mode: 0o400 });
148
+ }
149
+ catch (error) {
150
+ if (error.code !== 'EEXIST' || hash(await readReportFile(snapshotPath)) !== sha256)
151
+ throw error;
152
+ }
153
+ run.fileCheck = { passed: true, path: run.reportPath, checkedAt: new Date().toISOString(), size: bytes.length, sha256 };
154
+ run.digest = sha256;
155
+ run.snapshotPath = snapshotPath;
156
+ run.humanReviews.push(createHumanReview({ jobId: run.jobId, attemptId: run.attemptId, stage: 'report',
157
+ authorJobId: run.child.jobId, authorAttemptId: run.child.attemptId,
158
+ authorSessionId: String(child.backendRunRef?.sessionId ?? run.child.attemptId), reviewerId: run.reviewerId,
159
+ revision: reportRevision(run), digest: sha256, title: run.title,
160
+ preview: { kind: 'markdown', title: run.title, markdown: bytes.toString('utf8'), reportPath: run.reportPath, slides: [] } }));
161
+ run.stage = 'human_review';
162
+ run.phase = 'awaiting_human';
163
+ run.executionStatus = 'input_required';
164
+ run.resultSummary = `报告文件检查通过,等待你确认 ${reportRevision(run)}。人工通过后任务才算完成。`;
165
+ }
166
+ catch (error) {
167
+ run.fileCheck = { passed: false, path: run.reportPath, checkedAt: new Date().toISOString(), error: error instanceof Error ? error.message : 'Report check failed' };
168
+ run.executionStatus = 'failed';
169
+ run.phase = 'file_check_failed';
170
+ run.resultSummary = '指定报告文件检查未通过,未进入人工审核。';
171
+ }
172
+ save();
173
+ }