@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
@@ -1,8 +1,9 @@
1
1
  /** Main-agent tools backed by standard A2A, with a durable completion inbox. */
2
2
  import { createHash, randomUUID, timingSafeEqual } from 'node:crypto';
3
- import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
4
4
  import http from 'node:http';
5
5
  import path from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
6
7
  import { CancelTaskRequest, GetTaskRequest, SendMessageRequest, Task } from '@a2a-js/sdk';
7
8
  import { ClientFactory, DefaultAgentCardResolver, JsonRpcTransportFactory } from '@a2a-js/sdk/client';
8
9
  import { reportAndHoldRegistration, reportToAgent } from '@1agents/dreammate-node/client';
@@ -14,10 +15,26 @@ import { SessionDelivery, sessionBindSchema, sessionSendSchema, sessionMessageSc
14
15
  import { artifactLinks, formatNotice } from './notices.js';
15
16
  import { a2aPreflightInputSchema, a2aPreflightRequirementsSchema, a2aPreflightReportSchema } from './preflight.js';
16
17
  import { a2aResultContractSchema } from './result-metadata.js';
18
+ import { ARTIFACT_CONTENT_LIMIT } from './artifact-content.js';
19
+ import { artifactInstructions, defaultJobDirectory, defaultManifestPath } from './job-directory.js';
20
+ import { WORKBENCH_UI_PATH, WorkbenchUi } from './workbench-ui.js';
21
+ import { notifyDesktop } from './desktop-notify.js';
22
+ import { isAcpAgentPreset, legacyLifecycle, normalizeLifecycle, oneShotShouldClose, sessionLifecycleSchema } from './session-lifecycle.js';
23
+ import { CapacityGovernor } from '../capacity.js';
24
+ import { CapacityQueue } from '../capacity-queue.js';
17
25
  import { TargetDirectory, TARGET_METHODS } from '../execution/targets.js';
26
+ import { ProjectRoleDiscovery, DISCOVERY_METHODS, projectDiscoveryConfigSchema } from '../execution/project-discovery.js';
18
27
  import { deliveryProgress, deliveryException } from '../execution/delivery-progress.js';
19
28
  import { JobLedger } from '../execution/ledger.js';
20
- import { createPptDeliveryRun, recoverPptDeliveryRun, assertPptDeliveryRecoverable, advancePptDelivery, pptDeliveryInputSchema, pptDeliveryPolicySchema } from '../execution/ppt-delivery.js';
29
+ import { invokeTicket, reopenForContinue, TICKET_METHODS } from '../execution/ticket.js';
30
+ import { decideHumanReview, HumanReviewError, humanReviewDecisionSchema } from '../execution/human-review.js';
31
+ import { answerProcessRequest, createProcessRequest, expireProcessRequest, processRequestAnswerSchema, processRequestCreateSchema, processRequestSchema, ProcessRequestError, projectProcessRequest, sameProcessRequest } from '../execution/process-request.js';
32
+ import { chatItems, pageChat } from '../execution/workbench-chat.js';
33
+ import { workbenchSnapshot, listWorkbenchTasks, listWorkbenchAgents, getWorkbenchTask } from '../execution/workbench.js';
34
+ import { AgentRegistry, AgentRegistryError, readDevelopment } from '../execution/agent-registry.js';
35
+ import { agentNamePattern, listAgentFiles } from '../execution/agent-files.js';
36
+ import { createPptDeliveryRun, recoverPptDeliveryRun, assertPptDeliveryRecoverable, advancePptDelivery, pptDeliveryInputSchema, pptDeliveryPolicySchema, pptDeliveryRecoveryInputSchema, scriptDirectory, scriptRevisionName } from '../execution/ppt-delivery.js';
37
+ import { advanceReportReview, createReportReviewRun, reportBindingDigest, reportRevision, reportReviewInputSchema, reportReviewPolicySchema } from '../execution/report-review.js';
21
38
  const string = z.string().trim().min(1).max(512);
22
39
  const endpoint = z.string().url().refine(value => {
23
40
  const url = new URL(value);
@@ -31,9 +48,34 @@ const configSchema = z.object({
31
48
  notificationTargets: z.record(string, z.object({ url: endpoint, token: string }).strict()).default({}),
32
49
  sessionHosts: z.record(string, sessionHostSchema).default({}),
33
50
  automation: automationConfigSchema.optional(),
51
+ projectDiscovery: projectDiscoveryConfigSchema.optional(),
34
52
  pollIntervalMs: z.number().int().min(50).max(60_000).default(3000),
35
53
  pptDelivery: pptDeliveryPolicySchema.optional(),
54
+ reportReview: reportReviewPolicySchema.optional(),
55
+ workbench: z.object({ /** Omit on a trusted network: the page opens without login and the API needs no bearer. */ token: string.optional(), reviewerId: string.default('local-owner'), reviewerName: string.optional(), publicBaseUrl: endpoint.optional(),
56
+ /** Shared with a host that serves this page itself (DSH). Over the bearer API, only its relayed page requests may publish or decide reviews. */
57
+ pageRelaySecret: z.string().min(32).optional(),
58
+ allowedOrigins: z.array(string).optional(),
59
+ /** How long a question, plan or tool approval waits for a person. The ACP bridge's ACP_INTERACTION_TIMEOUT_MS must be at least as long. */
60
+ requestTimeoutMinutes: z.number().int().min(1).max(24 * 60).default(5),
61
+ /** Show a macOS notification when a request starts waiting. */
62
+ desktopNotifications: z.boolean().default(false) }).strict().optional(),
63
+ /** Same-machine ACP ledger. Omitted callers do not read the default home directory. */
64
+ capacityDirectory: z.string().min(1).optional(),
65
+ /** P3 idle close for persistent ACP sessions. idleTtlSeconds on a job overrides persistentIdleTtlSeconds. */
66
+ sessionLifecycle: z.object({
67
+ persistentIdleTtlSeconds: z.number().int().min(0).max(30 * 24 * 60 * 60).default(600),
68
+ idleScanIntervalMs: z.number().int().min(50).max(10 * 60_000).default(60_000),
69
+ inputRequiredAlertSeconds: z.number().int().min(1).max(30 * 24 * 60 * 60).default(2 * 60 * 60),
70
+ /** remote_agent_close mode "delete" is refused unless this is set. Delete cannot be undone. */
71
+ allowDelete: z.boolean().default(false),
72
+ }).strict().default({ persistentIdleTtlSeconds: 600, idleScanIntervalMs: 60_000, inputRequiredAlertSeconds: 2 * 60 * 60, allowDelete: false }),
36
73
  }).strict().superRefine((config, ctx) => {
74
+ const machineTokens = [...Object.values(config.remotes).map(remote => remote.token), config.callback?.token,
75
+ ...Object.values(config.notificationTargets).map(target => target.token), config.automation?.token];
76
+ if (config.workbench?.token && machineTokens.includes(config.workbench.token)) {
77
+ ctx.addIssue({ code: 'custom', path: ['workbench', 'token'], message: 'Workbench requires a separate credential from agent remotes' });
78
+ }
37
79
  for (const [id, schedule] of Object.entries(config.automation?.schedules ?? {})) {
38
80
  if (!Object.hasOwn(config.remotes, schedule.remote))
39
81
  ctx.addIssue({ code: 'custom', path: ['automation', 'schedules', id, 'remote'], message: 'Unknown automation remote' });
@@ -42,51 +84,72 @@ const configSchema = z.object({
42
84
  }
43
85
  });
44
86
  const originFields = { originSessionId: string };
87
+ /** Who acted: a person, or a coach agent naming its session. */
88
+ const actorSchema = z.object({ kind: z.enum(['person', 'coach']), agent: string.optional(), sessionId: string.optional() }).strict();
45
89
  const taskFields = { ...originFields, remote: string, taskId: string };
46
90
  const prompt = z.string().min(1).max(256 * 1024).refine(value => Boolean(value.trim()), 'Prompt must contain text');
47
91
  const spawnSchema = z.object({ ...originFields, remote: string, prompt,
48
92
  cwd: string.refine(value => path.posix.isAbsolute(value), 'cwd must be an absolute remote path'),
49
93
  agentPreset: string.optional(), notificationTarget: string.optional(), title: string.optional(),
94
+ roleId: string.optional(), roleLockPath: string.refine(path.isAbsolute).optional(),
50
95
  preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional(),
51
- clientRequestId: string.optional(),
96
+ clientRequestId: string.optional(), lifecycle: sessionLifecycleSchema.optional(),
97
+ provider: string.optional(), model: string.optional(), initiatedBy: actorSchema.optional(),
52
98
  }).strict();
53
99
  const preflightSchema = a2aPreflightInputSchema.extend({ ...originFields, remote: string }).strict();
54
100
  const taskSchema = z.object(taskFields).strict();
55
- const messageSchema = z.object({ ...taskFields, prompt, clientRequestId: string.optional(), preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional() }).strict();
101
+ const messageSchema = z.object({ ...taskFields, prompt, initiatedBy: actorSchema.optional(), clientRequestId: string.optional(), roleId: string.optional(), roleLockPath: string.refine(path.isAbsolute).optional(), preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional(), lifecycle: sessionLifecycleSchema.optional(), autoResume: z.boolean().optional(), provider: string.optional(), model: string.optional() }).strict();
102
+ const closeSchema = z.object({ ...originFields, remote: string, taskId: string.optional(), contextId: string.optional(), sessionId: string.optional(), mode: z.enum(['close', 'delete']).optional(), force: z.boolean().optional(), clientRequestId: string.optional() }).strict();
103
+ const sessionsSchema = z.object({}).strict();
56
104
  const inboxSchema = z.object(originFields).strict();
57
105
  const ackSchema = z.object({ ...originFields, noticeId: string }).strict();
58
106
  const executionSubmitSchema = z.object({ ...originFields, targetId: string, input: z.record(z.string(), z.unknown()),
59
107
  clientRequestId: string.optional(), title: string.optional(), parentJobRef: z.object({ sourceId: string, jobId: string }).strict().optional(),
60
108
  parentAttemptId: string.optional(), purpose: string.optional(), resultRevision: string.optional(),
61
- replacesJobRef: z.object({ sourceId: string, jobId: string }).strict().optional() }).strict();
109
+ replacesJobRef: z.object({ sourceId: string, jobId: string }).strict().optional(), initiatedBy: actorSchema.optional() }).strict();
62
110
  const executionJobSchema = z.object({ ...originFields, jobId: string }).strict();
63
111
  const executionCancelSchema = executionJobSchema.extend({ cascade: z.boolean().optional() }).strict();
64
112
  const executionListSchema = z.object({ ...originFields, targetId: string.optional(), executionStatus: string.optional(),
65
113
  limit: z.number().int().min(1).max(200).default(50), offset: z.number().int().min(0).default(0) }).strict();
66
- const executionContinueSchema = executionJobSchema.extend({ input: z.record(z.string(), z.unknown()), clientRequestId: string.optional() }).strict();
114
+ const executionContinueSchema = executionJobSchema.extend({ input: z.record(z.string(), z.unknown()), clientRequestId: string.optional(), initiatedBy: actorSchema.optional() }).strict();
67
115
  const executionEventsSchema = z.object({ ...originFields, jobId: string.optional(), afterSequence: z.number().int().nonnegative().optional(),
68
116
  limit: z.number().int().min(1).max(500).default(100) }).strict();
69
117
  const executionReviewSchema = executionJobSchema.extend({ attemptId: string, resultRevision: string, resultDigest: string,
70
- reviewStatus: z.enum(['pending', 'accepted', 'changes_requested']), note: string.optional() }).strict();
118
+ reviewStatus: z.enum(['pending', 'accepted', 'changes_requested']), note: string.optional(), decidedBy: actorSchema }).strict();
119
+ const workbenchContinueSchema = z.object({ prompt: string }).strict();
120
+ const workbenchAcceptSchema = z.object({ note: string.optional() }).strict();
121
+ const executionUnwatchSchema = executionJobSchema.extend({ reason: string }).strict();
122
+ /** The coach answers an executor's process request: the same answer as the workbench page, naming who decided and why. */
123
+ const processAnswerSchema = executionJobSchema.extend({ requestId: string, clientRequestId: string,
124
+ outcome: z.enum(['accepted', 'cancelled', 'approved', 'rejected', 'abandoned']), note: string.optional(), stopTask: z.literal(true).optional(),
125
+ decidedBy: actorSchema.optional() }).strict();
71
126
  const EXECUTION_METHODS = {
72
127
  ...TARGET_METHODS,
73
- execution_submit: { description: '向已登记目标提交任务;派发前持久保存jobId/attemptId和幂等请求。固定角色不接受cwd/preset覆盖。', parameters: z.toJSONSchema(executionSubmitSchema) },
74
- execution_continue: { description: '同任务显式继续或返工,新建执行轮次;旧终态不重新打开,受理未知时禁止新派发。', parameters: z.toJSONSchema(executionContinueSchema) },
128
+ ...DISCOVERY_METHODS,
129
+ execution_submit: { description: '向已登记目标提交任务;派发前持久保存jobId/attemptId和幂等请求。固定角色不接受cwd/preset覆盖。临时报告可用input.reportReview:{fileName},机器文件检查与人工最终通过后父任务才完成。', parameters: z.toJSONSchema(executionSubmitSchema) },
130
+ execution_continue: { description: '同任务显式继续或返工,新建执行轮次;旧终态不重新打开,受理未知/关闭时禁止新派发。PPT仅重试验收用input:{recoveryMode:"review_only",reviewTargetId,sourceSnapshotDirectory?},复用冻结成稿,不派制作。', parameters: z.toJSONSchema(executionContinueSchema) },
75
131
  execution_cancel: { description: '持久关闭任务并取消执行;PPT交付默认级联全部子任务,通用任务可显式cascade=true。未知受理或失联保留未决状态,确认全部停止后才完成关闭。', parameters: z.toJSONSchema(executionCancelSchema) },
76
132
  execution_get: { description: '读取任务、执行轮次、父子关系、交付阶段进度、已有产物及关闭回执;查询进度不唤醒主会话。在途/未决历史单列。', parameters: z.toJSONSchema(executionJobSchema) },
77
133
  execution_list: { description: '按来源范围、目标与状态分页列出统一任务。', parameters: z.toJSONSchema(executionListSchema) },
78
134
  execution_events: { description: '读取本来源范围内持久任务事件,不派单。', parameters: z.toJSONSchema(executionEventsSchema) },
79
- execution_review: { description: '保存绑定当前执行轮次、结果版本和hash的业务接受/退回;不等于通知ack。', parameters: z.toJSONSchema(executionReviewSchema) },
135
+ execution_review: { description: '保存绑定当前执行轮次、结果版本和hash的业务接受/退回;decidedBy 必填,写明是人还是教练;不等于通知ack。', parameters: z.toJSONSchema(executionReviewSchema) },
136
+ execution_rewatch: { description: '发起方重新等待任务当前这一轮,撤销 execution_unwatch 的记录。', parameters: z.toJSONSchema(executionJobSchema) },
137
+ execution_unwatch: { description: '发起方不再等待任务当前这一轮(等待超时,或自己出错),reason 写原因。执行轮次本身不变;工作台把它列为异常,可以之后重新查询执行宿主。', parameters: z.toJSONSchema(executionUnwatchSchema) },
138
+ execution_process_requests: { description: '读取任务上的过程请求(执行者的工具审批、提问、计划),含已回答的和谁回答的。', parameters: z.toJSONSchema(executionJobSchema) },
139
+ execution_process_answer: { description: '回答任务上的一条过程请求,和工作台页面同一记录;decidedBy 写明是人还是教练(教练写明所在的智能体会话),note 写理由。', parameters: z.toJSONSchema(processAnswerSchema) },
80
140
  execution_inbox: { description: '读取领域交付任务的完成/需决策通知;旧A2A收件箱保持原合同。', parameters: z.toJSONSchema(inboxSchema) },
81
141
  execution_ack: { description: '确认已处理领域交付通知,不修改业务验收或执行状态。', parameters: z.toJSONSchema(ackSchema) },
142
+ ...TICKET_METHODS,
82
143
  };
83
144
  export const REMOTE_AGENT_METHODS = {
84
145
  ...EXECUTION_METHODS,
85
146
  remote_agent_preflight: { description: '在执行宿主检查真实 cwd、任务可写目录和指定运行时依赖,不创建会话、不调用模型。ok=false 时修复检查项后再派单;spawn 的 preflight 还会在受理前重检。', parameters: z.toJSONSchema(preflightSchema) },
86
- remote_agent_spawn: { description: '在配置的远端 DSH 工作目录中派发独立任务,立即返回 taskId。prompt 必须包含完整上下文。cwd 是远端绝对路径;每次 spawn 创建新会话。完成事件进入 originSessionId 的持久收件箱。', parameters: z.toJSONSchema(spawnSchema) },
87
- remote_agent_get: { description: '查询当前主会话派发的远端任务。离线时返回缓存与 stale 标记,离线不等于任务失败。', parameters: z.toJSONSchema(taskSchema) },
88
- remote_agent_cancel: { description: '取消指定远端任务,只取消这项任务自己的执行。', parameters: z.toJSONSchema(taskSchema) },
89
- remote_agent_message: { description: '向同一个远端 DSH 会话发送后续指令,返回新 taskId,复用 contextId 与 cwd。', parameters: z.toJSONSchema(messageSchema) },
147
+ remote_agent_spawn: { description: '在配置的远端 DSH 工作目录中派发独立任务,立即返回 taskId。prompt 必须包含完整上下文。cwd 是远端绝对路径;每次 spawn 创建新会话。完成事件进入 originSessionId 的持久收件箱。可选 lifecycle 省略时为 one-shot:完成、失败或取消后普通关闭进程,之后 message 用 session/load 接回;runtime 仍是 persistent。需要进程常驻等追问时显式传 mode persistent。provider 与 model 只用于 standard 等非 oneagents-acp-* 预设,须一起传;宿主模型目录里没有时任务失败,不退回默认模型;省略时用 DSH 当时的默认模型。', parameters: z.toJSONSchema(spawnSchema) },
148
+ remote_agent_get: { description: '查询当前主会话派发的远端任务。离线时返回缓存与 stale 标记,离线不等于任务失败。进程名额排队时 state 仍是 submitted,并带 capacity 的队列位置和已等时长,以及 taskSlot 与 processSlot。', parameters: z.toJSONSchema(taskSchema) },
149
+ remote_agent_cancel: { description: '取消指定远端任务,只取消这项任务自己的执行。不能释放已经完成的会话进程;释放进程用 remote_agent_close。', parameters: z.toJSONSchema(taskSchema) },
150
+ remote_agent_message: { description: '向同一个远端 DSH 会话发送后续指令,返回新 taskId,复用 contextId 与 cwd。未传 lifecycle 时沿用原会话策略。已关闭会话默认接回,任务上返回 resumed: true;historyReplayed 只说明宿主是否把历史重新推给了它的客户端,不影响接回本身。autoResume 为 false 时不向远端发送,返回 SESSION_CLOSED。未传 provider 与 model 时沿用该会话已选模型;传了就在本轮前切换,规则同 spawn。', parameters: z.toJSONSchema(messageSchema) },
151
+ remote_agent_close: { description: '关闭该主会话派出的远端 ACP 进程并保留会话记录与绑定。taskId、contextId、sessionId 三选一。进行中返回 SESSION_BUSY;force 为 true 时先取消再关闭。宿主未实现时返回 UNSUPPORTED,且不把任务记成已关闭。standard 不发送 session/close。mode 为 delete 时还删除 ACP 会话记录,之后不能接回;仅在网关配置 sessionLifecycle.allowDelete 时接受,否则返回 DELETE_DISABLED,不删除 DSH 会话历史。', parameters: z.toJSONSchema(closeSchema) },
152
+ remote_agent_sessions: { description: '按 prewarm、job、user-opened 和未标注列出本机进程租约,并给出 taskSlot 与 processSlot。只读,不关闭、不补标已经在跑的进程。', parameters: z.toJSONSchema(sessionsSchema) },
90
153
  remote_agent_list: { description: '列出当前主会话派发的远端任务。', parameters: z.toJSONSchema(inboxSchema) },
91
154
  remote_agent_inbox: { description: '读取当前主会话未确认的完成或需要输入通知。读取不删除;处理后调用 remote_agent_ack。', parameters: z.toJSONSchema(inboxSchema) },
92
155
  remote_agent_ack: { description: '确认主会话已处理指定通知。noticeId 稳定,重复确认安全。', parameters: z.toJSONSchema(ackSchema) },
@@ -95,6 +158,23 @@ export const REMOTE_AGENT_METHODS = {
95
158
  session_delivery_get: { description: '查询本主会话的消息投递状态。unknown 必须先核实宿主是否已接收,不能盲目重发。', parameters: z.toJSONSchema(sessionMessageSchema) },
96
159
  session_delivery_resolve: { description: '核实 unknown 或处理 rejected 投递并记录依据。accepted=true 表示已确认入队;false 仅用于已证实未入队且已处理阻碍后释放重试。note 必填,不等于任务业务处理确认。', parameters: z.toJSONSchema(sessionResolveSchema) },
97
160
  };
161
+ export class WorkbenchArtifactError extends Error {
162
+ status;
163
+ code;
164
+ constructor(status, code) {
165
+ super(code);
166
+ this.status = status;
167
+ this.code = code;
168
+ }
169
+ }
170
+ export class RemoteAgentError extends Error {
171
+ code;
172
+ constructor(code, message) {
173
+ super(message);
174
+ this.code = code;
175
+ this.name = 'RemoteAgentError';
176
+ }
177
+ }
98
178
  const terminal = new Set(['TASK_STATE_COMPLETED', 'TASK_STATE_FAILED', 'TASK_STATE_CANCELED', 'TASK_STATE_REJECTED']);
99
179
  const actionable = new Set([...terminal, 'TASK_STATE_INPUT_REQUIRED', 'TASK_STATE_AUTH_REQUIRED']);
100
180
  const wire = (task) => Task.toJSON(task);
@@ -126,6 +206,8 @@ export class RemoteAgentGateway {
126
206
  automation;
127
207
  sessions;
128
208
  targets;
209
+ agents;
210
+ projectDiscovery;
129
211
  ledger;
130
212
  lease;
131
213
  stateFile;
@@ -139,11 +221,20 @@ export class RemoteAgentGateway {
139
221
  operations = new Set();
140
222
  advancingDeliveries = new Map();
141
223
  canceling = new Map();
224
+ closingSessions = new Map();
225
+ automaticCloseStopped = new Set();
226
+ now;
227
+ idleScannedAt = Number.NEGATIVE_INFINITY;
228
+ /** taskId and status timestamp of INPUT_REQUIRED turns already warned about. */
229
+ inputRequiredAlerts = new Map();
230
+ closeFailures = 0;
142
231
  reconciling;
232
+ workbenchQueue = Promise.resolve();
143
233
  timer;
144
234
  closed = false;
145
- constructor(input) {
235
+ constructor(input, options = {}) {
146
236
  this.config = configSchema.parse(input);
237
+ this.now = options.now ?? Date.now;
147
238
  if (!path.isAbsolute(this.config.stateDirectory))
148
239
  throw new Error('stateDirectory must be absolute');
149
240
  mkdirSync(this.config.stateDirectory, { recursive: true, mode: 0o700 });
@@ -174,6 +265,7 @@ export class RemoteAgentGateway {
174
265
  this.sessions = new SessionDelivery(this.config.stateDirectory, this.config.sessionHosts);
175
266
  this.targets = new TargetDirectory(this.config.stateDirectory, this.config.remotes);
176
267
  this.targets.ensureLegacyRemotes();
268
+ this.agents = new AgentRegistry(this.config.stateDirectory);
177
269
  this.ledger = new JobLedger(this.state.ledger, next => {
178
270
  atomicJson(this.stateFile, { ...this.state, version: 2, ledger: next });
179
271
  this.state.ledger = next;
@@ -191,12 +283,22 @@ export class RemoteAgentGateway {
191
283
  job.ledgerJobId = migrated.job.jobId;
192
284
  job.attemptId = migrated.attempt.attemptId;
193
285
  }
286
+ // Upgrade cached completed results without contacting the host, dispatching work or creating notices.
287
+ if (job.attemptId && taskState(job) === 'TASK_STATE_COMPLETED') {
288
+ const attempt = this.ledger.getAttempt(job.attemptId);
289
+ if (!attempt.result?.resultRevision || !attempt.result.resultDigest)
290
+ this.ledger.observe(job.attemptId, { ...this.resultObservation(Task.fromJSON(job.task)), checkedAt: job.checkedAt, stale: job.stale ?? false });
291
+ }
194
292
  }
195
293
  this.state.ledger = this.ledger.snapshot();
196
294
  this.state.version = 2;
197
295
  this.state.executionNotices ??= [];
296
+ this.state.reportReviews ??= {};
198
297
  this.state.executionCancellations ??= {};
199
298
  this.state.pptDeliveries ??= { version: 1, runs: {} };
299
+ if (this.state.processRequests !== undefined && !Array.isArray(this.state.processRequests))
300
+ throw new Error('Invalid gateway state');
301
+ this.state.processRequests = z.array(processRequestSchema).parse(this.state.processRequests ?? []);
200
302
  for (const run of Object.values(this.state.pptDeliveries.runs)) {
201
303
  const attempt = this.ledger.getAttempt(run.attemptId);
202
304
  if (attempt.submissionStatus === 'prepared')
@@ -209,8 +311,13 @@ export class RemoteAgentGateway {
209
311
  this.save();
210
312
  if (this.config.automation)
211
313
  this.automation = new A2AAutomation(this, this.config.automation);
314
+ if (this.config.projectDiscovery) {
315
+ this.projectDiscovery = new ProjectRoleDiscovery({ stateDirectory: path.join(this.config.stateDirectory, 'project-discovery'), config: this.config.projectDiscovery });
316
+ this.projectDiscovery.start();
317
+ }
212
318
  }
213
319
  catch (error) {
320
+ void this.projectDiscovery?.close().catch(() => { });
214
321
  this.lease.close();
215
322
  throw error;
216
323
  }
@@ -232,8 +339,17 @@ export class RemoteAgentGateway {
232
339
  return { targetId: `legacy:${job.remote}`, provider: 'a2a', remote: job.remote, cwd: job.cwd, agentPreset: job.agentPreset, historicalConfigUnknown: true };
233
340
  }
234
341
  }
342
+ /** A continuation keeps the channel frozen on its current attempt. A new task is admitted from the registry. */
343
+ developmentFor(target, jobId) {
344
+ if (!jobId)
345
+ return this.agents.admit(target);
346
+ const job = this.ledger.snapshot().jobs[jobId];
347
+ const attempt = job ? this.ledger.snapshot().attempts[job.currentAttemptId] : undefined;
348
+ return readDevelopment(attempt?.targetSnapshot?.development);
349
+ }
235
350
  targetSnapshot(resolved) {
236
- return { targetId: resolved.target.targetId, configVersion: resolved.configVersion, connectionId: resolved.connection.connectionId,
351
+ return { targetId: resolved.target.targetId, targetKind: resolved.target.kind, targetName: resolved.target.name,
352
+ configVersion: resolved.configVersion, connectionId: resolved.connection.connectionId,
237
353
  connectionVersion: resolved.connectionVersion, provider: resolved.target.binding.driver === 'ppt_delivery' ? 'resident_role' : 'a2a',
238
354
  roleId: resolved.target.binding.roleId, binding: resolved.target.binding, remote: resolved.remote, endpoint: resolved.endpoint, cwd: resolved.cwd,
239
355
  agentPreset: resolved.agentPreset, capabilities: resolved.target.capabilities };
@@ -243,7 +359,9 @@ export class RemoteAgentGateway {
243
359
  const attempt = view.attempts.find(item => item.attemptId === view.currentAttemptId);
244
360
  const raw = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
245
361
  const delivery = this.state.pptDeliveries?.runs[attempt.attemptId];
362
+ const report = this.state.reportReviews?.[attempt.attemptId];
246
363
  return { ...view, ...(delivery ? { deliveryProgress: deliveryProgress(delivery) } : {}),
364
+ ...(report ? { reportProgress: { stage: report.stage, phase: report.phase, reportPath: report.reportPath, fileCheck: report.fileCheck, humanReview: report.humanReviews.at(-1) } } : {}),
247
365
  ...(this.state.executionCancellations?.[attempt.attemptId] ? { cancellation: structuredClone(this.state.executionCancellations[attempt.attemptId]) } : {}), attemptId: attempt.attemptId, submissionStatus: attempt.submissionStatus,
248
366
  backendRunRef: attempt.backendRunRef, phase: attempt.phase, stale: attempt.stale,
249
367
  resultSummary: view.result?.resultSummary, artifactLinks: view.result?.artifactLinks ?? [],
@@ -259,35 +377,84 @@ export class RemoteAgentGateway {
259
377
  this.assertDispatchOpen(input.originSessionId, options.jobId ?? input.parentJobRef?.jobId);
260
378
  const resolved = this.targets.resolve(input.targetId, input.input);
261
379
  if (options.previous && (options.previous.remote !== resolved.remote || (options.previous.remoteEndpoint && options.previous.remoteEndpoint !== resolved.endpoint) || options.previous.cwd !== resolved.cwd || options.previous.agentPreset !== resolved.agentPreset)) {
262
- throw new Error('Continue must preserve the original remote, cwd and preset');
380
+ throw new RemoteAgentError('SESSION_CONFLICT', 'Continue must preserve the original remote, cwd and preset');
263
381
  }
264
- const prepared = this.ledger.prepare({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, targetSnapshot: this.targetSnapshot(resolved),
382
+ const reportRequest = input.input.reportReview;
383
+ if (reportRequest !== undefined && (options.jobId || resolved.target.kind !== 'agent_host' || !this.config.reportReview || !this.config.workbench))
384
+ throw new Error('Report review requires a new temporary agent_host task and configured report/workbench policy');
385
+ if (reportRequest !== undefined)
386
+ reportReviewInputSchema.parse(reportRequest);
387
+ const development = this.developmentFor(resolved.target, options.jobId);
388
+ const prepared = this.ledger.prepare({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, targetSnapshot: { ...this.targetSnapshot(resolved), ...(development ? { development } : {}), ...(reportRequest !== undefined ? { provider: 'report_review', targetKind: 'workflow', driver: 'report_review' } : {}) },
265
389
  operation: options.jobId ? 'continue' : 'submit' });
266
390
  if (prepared.idempotent)
267
391
  return this.ledgerView(input.originSessionId, prepared.job.jobId);
268
392
  const { job, attempt } = prepared;
269
393
  let sent = false;
270
394
  try {
395
+ if (reportRequest !== undefined) {
396
+ const { reportReview: _review, ...authorInput } = resolved.input;
397
+ const run = await createReportReviewRun({ sourceId: this.ledger.sourceId, jobId: job.jobId, attemptId: attempt.attemptId,
398
+ originSessionId: input.originSessionId, title: input.title ?? '项目架构分析报告', targetId: input.targetId, remote: resolved.remote,
399
+ cwd: resolved.cwd, authorInput, reviewerId: this.config.workbench.reviewerId }, this.config.reportReview, reportReviewInputSchema.parse(reportRequest));
400
+ this.state.reportReviews[attempt.attemptId] = run;
401
+ this.ledger.markDispatching(attempt.attemptId);
402
+ this.ledger.accept(attempt.attemptId, { provider: 'report_review', runId: attempt.attemptId }, { executionStatus: 'working', phase: run.phase });
403
+ return this.ledgerView(input.originSessionId, job.jobId);
404
+ }
271
405
  if (resolved.target.binding.driver === 'ppt_delivery') {
272
406
  if (options.jobId && !options.deliveryRecovery)
273
- throw new Error('PPT continuation requires an independently passed recovery checkpoint');
407
+ throw new Error('PPT continuation requires a verified recovery checkpoint');
274
408
  const roleInput = pptDeliveryInputSchema.parse(input.input);
275
409
  if (!this.config.pptDelivery)
276
410
  throw new Error('PPT delivery role policy is not configured');
277
- const run = options.deliveryRecovery ? await recoverPptDeliveryRun(options.deliveryRecovery, attempt.attemptId)
411
+ const run = options.deliveryRecovery ? await recoverPptDeliveryRun(options.deliveryRecovery, attempt.attemptId, options.deliveryRecoveryInput)
278
412
  : await createPptDeliveryRun({ sourceId: this.ledger.sourceId, jobId: job.jobId, attemptId: attempt.attemptId,
279
- originSessionId: input.originSessionId, input: roleInput, policy: this.config.pptDelivery });
413
+ originSessionId: input.originSessionId, input: roleInput, policy: { ...this.config.pptDelivery,
414
+ ...(this.config.workbench ? { humanReviewerId: this.config.workbench.reviewerId } : {}) } });
280
415
  this.state.pptDeliveries.runs[attempt.attemptId] = run;
281
416
  this.ledger.markDispatching(attempt.attemptId);
282
417
  this.ledger.accept(attempt.attemptId, { provider: 'resident_role', runId: attempt.attemptId }, { executionStatus: 'working', phase: 'preparing' });
283
418
  return this.ledgerView(input.originSessionId, job.jobId);
284
419
  }
285
420
  const fields = resolved.input;
421
+ const fixed = resolved.target.binding;
422
+ const provider = fields.provider === undefined ? fixed.provider : string.parse(fields.provider);
423
+ const model = fields.model === undefined ? fixed.model : string.parse(fields.model);
424
+ if ((provider === undefined) !== (model === undefined))
425
+ throw new Error('provider and model must be passed together');
426
+ if (provider && isAcpAgentPreset(resolved.agentPreset))
427
+ throw new Error('provider and model apply only to standard presets; oneagents-acp-* presets switch models through session/set_config_option');
286
428
  const preflight = fields.preflight === undefined ? undefined : a2aPreflightRequirementsSchema.parse(fields.preflight);
287
- const requirements = resolved.directoryPolicy ? { ...preflight, allowedDirectories: resolved.directoryPolicy.allowedDirectories } : preflight;
429
+ const declaredRequirements = resolved.directoryPolicy ? { ...preflight, allowedDirectories: resolved.directoryPolicy.allowedDirectories } : preflight;
288
430
  const declaredContract = fields.resultContract === undefined ? undefined : a2aResultContractSchema.parse(fields.resultContract);
289
- const resultContract = declaredContract && options.notificationOrigin ? { ...declaredContract, jobId: job.jobId } : declaredContract;
290
- await this.checkDispatch(resolved.remote, resolved.cwd, requirements, resolved.endpoint);
431
+ const declaredResult = declaredContract && options.notificationOrigin ? { ...declaredContract, jobId: job.jobId } : declaredContract;
432
+ // Unless the caller declared its own artifact location, every task gets <cwd>/.1agents/jobs/<jobId>/ and a
433
+ // per-attempt manifest, announced to the agent in the prompt. The host creates the directory during preflight.
434
+ let artifacts = !declaredResult?.artifactManifestPath && !declaredRequirements?.jobDirectory && resolved.cwd
435
+ ? { directory: defaultJobDirectory(resolved.cwd, job.jobId), manifest: defaultManifestPath(resolved.cwd, job.jobId, attempt.attemptId) } : undefined;
436
+ const withArtifacts = (declared, add) => artifacts ? add(artifacts) : declared;
437
+ let requirements = withArtifacts(declaredRequirements, found => ({ ...declaredRequirements, jobDirectory: found.directory }));
438
+ let resultContract = withArtifacts(declaredResult, found => ({ ...(declaredResult ?? { jobId: job.jobId }), artifactManifestPath: found.manifest }));
439
+ const networkRole = resolved.target.binding.skillPolicy === 'network_pinned' ? resolved.target.binding.roleId : undefined;
440
+ if (resolved.target.binding.skillPolicy && !networkRole)
441
+ throw new Error('Network skill policy requires a fixed roleId');
442
+ const explicitRole = resolved.target.kind === 'agent_host' && fields.roleId !== undefined ? string.parse(fields.roleId) : undefined;
443
+ const roleLockPath = fields.roleLockPath === undefined ? undefined
444
+ : z.string().min(1).refine(path.isAbsolute, 'Expected an absolute role lock path').parse(fields.roleLockPath);
445
+ try {
446
+ await this.checkDispatch(resolved.remote, resolved.cwd, requirements, resolved.endpoint);
447
+ }
448
+ catch (error) {
449
+ // The default directory is best effort: a host that predates it (or lacks preflight) must still run the task,
450
+ // just without artifacts. Whatever the caller declared is checked again below and still fails dispatch.
451
+ if (!artifacts)
452
+ throw error;
453
+ artifacts = undefined;
454
+ requirements = declaredRequirements;
455
+ resultContract = declaredResult;
456
+ await this.checkDispatch(resolved.remote, resolved.cwd, requirements, resolved.endpoint);
457
+ }
291
458
  const client = await this.client(resolved.remote, resolved.endpoint);
292
459
  // Target changes/disable during asynchronous preflight must win before sending.
293
460
  const fresh = this.targets.resolve(input.targetId, input.input);
@@ -296,10 +463,14 @@ export class RemoteAgentGateway {
296
463
  this.assertDispatchOpen(input.originSessionId, options.jobId ?? input.parentJobRef?.jobId);
297
464
  this.ledger.markDispatching(attempt.attemptId);
298
465
  sent = true;
466
+ const lifecycle = this.jobLifecycle(fields.lifecycle, options.previous?.lifecycle);
299
467
  const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: attempt.attemptId, role: 'ROLE_USER',
300
- ...(options.previous ? { contextId: options.previous.contextId } : {}), parts: [{ text: prompt.parse(fields.prompt) }] },
301
- metadata: { '1agents': { ...(!options.previous ? { cwd: resolved.cwd, ...(resolved.agentPreset ? { agentPreset: resolved.agentPreset } : {}) } : {}),
302
- ...(requirements ? { preflight: requirements } : {}), ...(resultContract ? { resultContract } : {}) } },
468
+ ...(options.previous ? { contextId: options.previous.contextId } : {}), parts: [{ text: prompt.parse(fields.prompt) + (artifacts ? artifactInstructions(artifacts.directory, artifacts.manifest) : '') }] },
469
+ metadata: { '1agents': { ...(!options.previous ? { cwd: resolved.cwd, ...(resolved.agentPreset ? { agentPreset: resolved.agentPreset } : {}),
470
+ ...(resolved.target.binding.agentFile ? { agentFile: resolved.target.binding.agentFile } : {}) } : {}),
471
+ ...(explicitRole ? { roleId: explicitRole } : !options.previous && networkRole ? { roleId: networkRole } : {}), ...(roleLockPath ? { roleLockPath } : {}),
472
+ ...(requirements ? { preflight: requirements } : {}), ...(resultContract ? { resultContract } : {}), ...(provider ? { provider, model } : {}),
473
+ execution: { jobId: job.jobId, attemptId: attempt.attemptId } } },
303
474
  configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
304
475
  authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(resolved.remote));
305
476
  if (!('id' in task))
@@ -307,7 +478,7 @@ export class RemoteAgentGateway {
307
478
  this.accept(task, { remote: resolved.remote, remoteEndpoint: resolved.endpoint, originSessionId: options.notificationOrigin ?? input.originSessionId, cwd: resolved.cwd,
308
479
  agentPreset: resolved.agentPreset, title: input.title ?? (typeof fields.title === 'string' ? fields.title : undefined),
309
480
  notificationTarget: typeof fields.notificationTarget === 'string' ? fields.notificationTarget : undefined,
310
- ledgerJobId: job.jobId, attemptId: attempt.attemptId });
481
+ ledgerJobId: job.jobId, attemptId: attempt.attemptId, ...(lifecycle ? { lifecycle } : {}) });
311
482
  return this.ledgerView(input.originSessionId, job.jobId);
312
483
  }
313
484
  catch (error) {
@@ -383,7 +554,10 @@ export class RemoteAgentGateway {
383
554
  });
384
555
  }
385
556
  executionNotice(run, resultSummary, links) {
386
- const noticeId = createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, run.revision, run.executionStatus])).digest('hex');
557
+ const pendingReview = run.executionStatus === 'input_required' && run.phase === 'awaiting_human' && !run.cancellationRequestedAt
558
+ ? run.humanReviews?.find(review => review.status === 'pending' && review.attemptId === run.attemptId && review.revision === scriptRevisionName(run)) : undefined;
559
+ const noticeId = createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, run.revision, run.executionStatus,
560
+ ...(pendingReview ? [pendingReview.reviewId] : [])])).digest('hex');
387
561
  if (this.state.executionNotices.some(item => item.noticeId === noticeId))
388
562
  return;
389
563
  if (run.executionStatus !== 'completed') {
@@ -394,13 +568,92 @@ export class RemoteAgentGateway {
394
568
  links = partial.artifacts;
395
569
  }
396
570
  const artifactLinks = links.map(item => ({ url: item.url, mediaType: item.mediaType, sha256: item.sha256, size: item.size }));
397
- const text = `[任务交付通知] ${run.executionStatus === 'completed' ? '任务已完成' : run.executionStatus === 'canceled' ? '任务已取消' : '任务需要处理'}\n${run.input.projectName} PPT\n\n${resultSummary}\n\n` +
571
+ const reviewUrl = this.config.workbench?.publicBaseUrl ? new URL(this.config.workbench.publicBaseUrl) : undefined;
572
+ if (reviewUrl && pendingReview)
573
+ reviewUrl.hash = `acp/tasks/${encodeURIComponent(run.jobId)}?review=${encodeURIComponent(pendingReview.reviewId)}`;
574
+ const reviewEntry = pendingReview ? `\n\n${reviewUrl ? `[打开文字稿审核](${reviewUrl.href})` : '请用户打开本机 A2A 网关的任务工作台页面(/workbench/ui/)→「待我确认」。'}\n审核版本:${pendingReview.revision};审核请求:${pendingReview.reviewId}。\n人工决定必须在审核页记录,execution_review 和通知已读均不能替代。` : '';
575
+ const text = `[任务交付通知] ${pendingReview ? '文字稿待人工确认' : run.executionStatus === 'completed' ? '任务已完成' : run.executionStatus === 'canceled' ? '任务已取消' : '任务需要处理'}\n${run.input.projectName} PPT\n\n${resultSummary}\n\n` +
398
576
  artifactLinks.map(item => `[${item.mediaType?.includes('presentation') ? (run.executionStatus === 'completed' ? '最终 PPT' : '已有 PPT(未完成最终验收)') : '预览产物'}](${item.url})`).join('\n') +
577
+ reviewEntry +
399
578
  `\n\n请通过 a2a-gateway 的 execution_get 或 execution_inbox 读取交付回执;业务接受调用 execution_review,通知处理调用 execution_ack,两者分别记录。\n---\n任务定位信息:\n${JSON.stringify({ noticeId, sourceId: run.sourceId, jobId: run.jobId, attemptId: run.attemptId, originSessionId: run.originSessionId })}`;
400
579
  this.state.executionNotices.push({ noticeId, messageId: `execution-notice:${noticeId}`, originSessionId: run.originSessionId,
401
580
  jobId: run.jobId, attemptId: run.attemptId, executionStatus: run.executionStatus, resultSummary, artifactLinks, createdAt: new Date().toISOString(), text });
402
581
  this.save();
403
582
  }
583
+ async advanceReport(run) {
584
+ const existing = this.advancingDeliveries.get(run.attemptId);
585
+ if (existing)
586
+ return existing;
587
+ const operation = advanceReportReview(run, {
588
+ persist: value => { this.state.reportReviews[value.attemptId] = value; this.save(); },
589
+ child: attemptId => this.ledger.getAttempt(attemptId),
590
+ submit: async (value, prompt, previous) => {
591
+ this.assertDispatchOpen(value.originSessionId, value.jobId);
592
+ const prior = previous ? this.state.jobs.find(job => job.attemptId === previous.attemptId) : undefined;
593
+ if (previous && !prior)
594
+ throw new Error('Original report author session is unavailable');
595
+ const result = await this.submitExecution({ originSessionId: value.originSessionId, targetId: value.targetId,
596
+ title: `${value.title}:临时执行`, input: { ...value.authorInput, cwd: value.directory, prompt },
597
+ clientRequestId: `${value.jobId}:${reportRevision(value)}:author`,
598
+ parentJobRef: { sourceId: value.sourceId, jobId: value.jobId }, parentAttemptId: value.attemptId, purpose: 'architecture_report' }, { ...(prior ? { jobId: previous.jobId, previous: prior } : {}), notificationOrigin: `report-review:${value.jobId}` });
599
+ return { jobId: result.jobId, attemptId: result.attemptId };
600
+ },
601
+ update: value => this.updateReport(value),
602
+ });
603
+ this.advancingDeliveries.set(run.attemptId, operation);
604
+ try {
605
+ await operation;
606
+ }
607
+ finally {
608
+ this.advancingDeliveries.delete(run.attemptId);
609
+ }
610
+ }
611
+ updateReport(run) {
612
+ this.ledger.observe(run.attemptId, { executionStatus: run.executionStatus, phase: run.phase, resultSummary: run.resultSummary,
613
+ ...(run.digest ? { resultDigest: run.digest, resultRevision: reportRevision(run), structuredResultRef: {
614
+ reportPath: run.reportPath, snapshotPath: run.snapshotPath, fileCheck: run.fileCheck,
615
+ humanReview: run.humanReviews.at(-1),
616
+ } } : {}) });
617
+ // Only final task outcomes reach the delegator; child completion and human waiting stay in the workbench.
618
+ if (!['completed', 'failed', 'canceled'].includes(run.executionStatus))
619
+ return;
620
+ const noticeId = createHash('sha256').update(JSON.stringify([run.sourceId, run.jobId, run.attemptId, reportRevision(run), run.executionStatus])).digest('hex');
621
+ if (this.state.executionNotices.some(notice => notice.noticeId === noticeId))
622
+ return;
623
+ const text = `[报告任务通知] ${run.executionStatus === 'completed' ? '人工已确认,任务完成' : '任务未完成'}\n${run.title}\n${run.resultSummary ?? ''}\n报告:${run.reportPath}\n请单次读取 execution_get 回执,记录结论后 execution_ack。\n---\n${JSON.stringify({ noticeId, sourceId: run.sourceId, jobId: run.jobId, attemptId: run.attemptId, originSessionId: run.originSessionId })}`;
624
+ this.state.executionNotices.push({ noticeId, messageId: `execution-notice:${noticeId}`, originSessionId: run.originSessionId,
625
+ jobId: run.jobId, attemptId: run.attemptId, executionStatus: run.executionStatus, resultSummary: run.resultSummary ?? '', artifactLinks: [], createdAt: new Date().toISOString(), text });
626
+ this.save();
627
+ }
628
+ async decideReportReview(run, reviewId, input) {
629
+ const review = run.humanReviews.find(item => item.reviewId === reviewId);
630
+ if (!review)
631
+ throw new Error('Review not found in authorized task');
632
+ const decision = humanReviewDecisionSchema.parse(input), replay = review.history.some(item => item.clientRequestId === decision.clientRequestId);
633
+ if (!replay && (this.state.executionCancellations?.[run.attemptId] || ['completed', 'failed', 'canceled'].includes(run.executionStatus)))
634
+ throw new HumanReviewError('already_decided', 'Report task is no longer awaiting a decision');
635
+ let digest = run.digest ?? '';
636
+ if (!replay && decision.action === 'approve') {
637
+ try {
638
+ digest = await reportBindingDigest(run);
639
+ }
640
+ catch {
641
+ throw new HumanReviewError('version_conflict', 'Report bytes changed or are unavailable; this version cannot be approved');
642
+ }
643
+ }
644
+ const config = this.config.workbench;
645
+ const result = decideHumanReview(review, decision, { id: config.reviewerId, displayName: config.reviewerName, source: '1agents-web' }, { attemptId: run.attemptId, revision: reportRevision(run), digest });
646
+ if (!result.idempotent) {
647
+ const next = { ...run, humanReviews: run.humanReviews.map(item => item.reviewId === reviewId ? result.review : item) };
648
+ const reportReviews = { ...this.state.reportReviews, [run.attemptId]: next };
649
+ atomicJson(this.stateFile, { ...this.state, reportReviews });
650
+ this.state.reportReviews = reportReviews;
651
+ }
652
+ const current = this.state.reportReviews[run.attemptId];
653
+ if (current.humanReviews.some(item => item.resume?.status === 'pending'))
654
+ void this.advanceReport(current).catch(() => { });
655
+ return this.workbenchTask(run.jobId);
656
+ }
404
657
  cancellationJobs(origin, jobId, cascade) {
405
658
  const found = new Set();
406
659
  const visit = (id) => {
@@ -421,11 +674,17 @@ export class RemoteAgentGateway {
421
674
  seen.add(jobId);
422
675
  if (Object.values(this.state.executionCancellations ?? {}).some(item => item.jobId === jobId))
423
676
  throw new Error('Job is closing or closed; no further dispatch is allowed');
424
- jobId = this.ledger.get(origin, jobId).parentJobRef?.jobId;
677
+ const job = this.ledger.get(origin, jobId), run = this.state.pptDeliveries?.runs[job.currentAttemptId];
678
+ if (job.executionStatus === 'canceled' || run?.cancellationRequestedAt || run?.executionStatus === 'canceled'
679
+ || run?.humanReviews?.some(review => review.status === 'canceled'))
680
+ throw new Error('Job is closing or closed; no further dispatch is allowed');
681
+ jobId = job.parentJobRef?.jobId;
425
682
  }
426
683
  }
427
- async cancelExecution(origin, jobId, cascade) {
684
+ async cancelExecution(origin, jobId, cascade, reason) {
428
685
  const job = this.ledger.get(origin, jobId), run = this.state.pptDeliveries.runs[job.currentAttemptId];
686
+ if (this.state.reportReviews?.[job.currentAttemptId] && cascade === false)
687
+ throw new Error('Report cancellation must include its child task');
429
688
  if (run && cascade === false)
430
689
  throw new Error('PPT delivery cancellation must include its child tasks');
431
690
  let record = this.state.executionCancellations[job.currentAttemptId];
@@ -434,8 +693,8 @@ export class RemoteAgentGateway {
434
693
  record.status = 'pending';
435
694
  }
436
695
  if (!record) {
437
- record = { jobId, attemptId: job.currentAttemptId, originSessionId: origin, cascade: cascade ?? Boolean(run),
438
- requestedAt: new Date().toISOString(), status: 'pending', targets: [], diagnostics: [] };
696
+ record = { jobId, attemptId: job.currentAttemptId, originSessionId: origin, cascade: cascade ?? Boolean(run || this.state.reportReviews?.[job.currentAttemptId]),
697
+ requestedAt: new Date().toISOString(), status: 'pending', targets: [], diagnostics: [], ...(reason ? { reason } : {}) };
439
698
  this.state.executionCancellations[record.attemptId] = record;
440
699
  }
441
700
  // Close admission synchronously and durably, before waiting for an in-flight submit or contacting a backend.
@@ -445,8 +704,14 @@ export class RemoteAgentGateway {
445
704
  const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
446
705
  if (delivery && !['completed', 'failed', 'canceled'].includes(delivery.executionStatus)) {
447
706
  delivery.cancellationRequestedAt ??= record.requestedAt;
707
+ if (delivery.humanWaitStartedAt) {
708
+ delivery.humanWaitingMs = (delivery.humanWaitingMs ?? 0) + Math.max(0, Date.parse(record.requestedAt) - Date.parse(delivery.humanWaitStartedAt));
709
+ delete delivery.humanWaitStartedAt;
710
+ }
448
711
  delivery.phase = 'canceling_children';
449
712
  delivery.updatedAt = new Date().toISOString();
713
+ delivery.humanReviews = delivery.humanReviews?.map(review => review.status === 'pending'
714
+ ? { ...review, status: 'canceled', updatedAt: delivery.updatedAt } : review);
450
715
  }
451
716
  }
452
717
  }
@@ -478,11 +743,16 @@ export class RemoteAgentGateway {
478
743
  for (const attempt of this.ledger.get(origin, id).attempts)
479
744
  await this.advancingDeliveries.get(attempt.attemptId);
480
745
  }
481
- const ids = this.cancellationJobs(origin, record.jobId, record.cascade), localRuns = [];
746
+ const ids = this.cancellationJobs(origin, record.jobId, record.cascade), localRuns = [], localReports = [];
482
747
  for (const id of ids) {
483
748
  for (const attempt of this.ledger.get(origin, id).attempts) {
484
749
  if (['completed', 'failed', 'canceled', 'rejected'].includes(attempt.executionStatus))
485
750
  continue;
751
+ const report = this.state.reportReviews?.[attempt.attemptId];
752
+ if (report) {
753
+ localReports.push(report);
754
+ continue;
755
+ }
486
756
  const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
487
757
  if (delivery) {
488
758
  if (['completed', 'failed', 'canceled'].includes(delivery.executionStatus)) {
@@ -511,7 +781,7 @@ export class RemoteAgentGateway {
511
781
  }
512
782
  }
513
783
  }
514
- const localIds = new Set(localRuns.map(run => run.attemptId));
784
+ const localIds = new Set([...localRuns, ...localReports].map(run => run.attemptId));
515
785
  const targets = ids.flatMap(id => this.ledger.get(origin, id).attempts).map(attempt => ({ jobId: attempt.jobId, attemptId: attempt.attemptId,
516
786
  executionStatus: attempt.executionStatus, submissionStatus: attempt.submissionStatus }));
517
787
  const unresolved = targets.filter(item => !localIds.has(item.attemptId)
@@ -536,6 +806,15 @@ export class RemoteAgentGateway {
536
806
  this.ledger.observe(run.attemptId, { executionStatus: 'canceled', phase: run.phase, resultSummary: partial.summary, artifactLinks: partial.artifacts });
537
807
  this.executionNotice(run, partial.summary, partial.artifacts);
538
808
  }
809
+ if (!unresolved.length)
810
+ for (const run of localReports) {
811
+ run.executionStatus = 'canceled';
812
+ run.phase = 'user_canceled';
813
+ run.updatedAt = new Date().toISOString();
814
+ run.humanReviews = run.humanReviews.map(review => review.status === 'pending' ? { ...review, status: 'canceled', updatedAt: run.updatedAt } : review);
815
+ this.save();
816
+ this.updateReport(run);
817
+ }
539
818
  record.status = unresolved.length ? 'blocked' : 'completed';
540
819
  record.targets = ids.flatMap(id => this.ledger.get(origin, id).attempts).map(attempt => ({ jobId: attempt.jobId, attemptId: attempt.attemptId,
541
820
  executionStatus: attempt.executionStatus, submissionStatus: attempt.submissionStatus }));
@@ -625,16 +904,7 @@ export class RemoteAgentGateway {
625
904
  const config = configured ? { ...configured, url: pinnedEndpoint ?? configured.url } : undefined;
626
905
  if (!config)
627
906
  throw new Error(`Unknown remote: ${remote}`);
628
- const client = await this.client(remote, config.url), card = await client.getAgentCard(this.auth(remote));
629
- const endpoint = card.supportedInterfaces.find(value => value.protocolBinding === 'JSONRPC')?.url;
630
- if (!endpoint)
631
- throw new Error('Remote does not advertise a JSONRPC endpoint');
632
- const url = new URL(endpoint);
633
- if (url.origin !== new URL(config.url).origin || url.username || url.password)
634
- throw new Error('Preflight endpoint must use the configured remote origin');
635
- url.pathname = `${url.pathname.replace(/\/$/, '')}/preflight`;
636
- url.search = '';
637
- url.hash = '';
907
+ const url = await this.hostRoute(remote, config.url, '/preflight');
638
908
  const controller = new AbortController();
639
909
  this.controllers.add(controller);
640
910
  try {
@@ -651,6 +921,89 @@ export class RemoteAgentGateway {
651
921
  this.controllers.delete(controller);
652
922
  }
653
923
  }
924
+ /** Host extensions sit beside the JSONRPC endpoint the remote advertises, and only on its configured origin. */
925
+ async hostRoute(remote, base, suffix) {
926
+ const client = await this.client(remote, base), card = await client.getAgentCard(this.auth(remote));
927
+ const endpoint = card.supportedInterfaces.find(value => value.protocolBinding === 'JSONRPC')?.url;
928
+ if (!endpoint)
929
+ throw new Error('Remote does not advertise a JSONRPC endpoint');
930
+ const url = new URL(endpoint);
931
+ if (url.origin !== new URL(base).origin || url.username || url.password)
932
+ throw new Error('Host endpoint must use the configured remote origin');
933
+ url.pathname = `${url.pathname.replace(/\/$/, '')}${suffix}`;
934
+ url.search = '';
935
+ url.hash = '';
936
+ return url;
937
+ }
938
+ /** One verified artifact, read from the host that produced it and checked against the recorded receipt again here. */
939
+ /** The execution host replaced a finished task's result (manual takeover): read it now rather than wait for a webhook. */
940
+ async refreshWorkbenchTask(jobId) {
941
+ this.workbenchTask(jobId);
942
+ await Promise.allSettled(this.state.jobs.filter(raw => raw.ledgerJobId === jobId).map(raw => this.refresh(raw)));
943
+ return this.workbenchTask(jobId);
944
+ }
945
+ /** A person sends a failed task another round in its own session. */
946
+ async continueWorkbenchTask(jobId, prompt) {
947
+ const task = this.workbenchTask(jobId);
948
+ if (!task.canContinue)
949
+ throw new Error('只有执行失败的任务可以在这里继续。');
950
+ await this.invoke('execution_continue', { originSessionId: task.originSessionId, jobId, input: { prompt }, initiatedBy: { kind: 'person' } });
951
+ return this.workbenchTask(jobId);
952
+ }
953
+ /** A person marks the task's current result as read (已阅). */
954
+ acceptWorkbenchTask(jobId, note) {
955
+ const task = this.workbenchTask(jobId);
956
+ if (!task.canAccept)
957
+ throw new Error('只有已完成、还没有结论的任务可以标记已阅。');
958
+ const result = this.ledger.getAttempt(task.currentAttemptId).result;
959
+ this.ledger.acceptance(task.originSessionId, jobId, { attemptId: task.currentAttemptId, resultRevision: result.resultRevision, resultDigest: result.resultDigest,
960
+ reviewStatus: 'accepted', ...(note ? { note } : {}), decidedBy: { kind: 'person' } });
961
+ return this.workbenchTask(jobId);
962
+ }
963
+ async workbenchArtifact(jobId, sha256) {
964
+ this.workbenchTask(jobId);
965
+ for (const raw of this.state.jobs) {
966
+ if (raw.ledgerJobId !== jobId)
967
+ continue;
968
+ const result = Task.fromJSON(raw.task).metadata?.['1agents']?.result;
969
+ const artifact = result?.artifacts?.find(item => item.sha256 === sha256);
970
+ if (!artifact)
971
+ continue;
972
+ const config = this.config.remotes[raw.remote];
973
+ if (!config)
974
+ throw new WorkbenchArtifactError(404, 'artifact-host-not-configured');
975
+ if (artifact.size > ARTIFACT_CONTENT_LIMIT)
976
+ throw new WorkbenchArtifactError(413, 'artifact-too-large');
977
+ const controller = new AbortController();
978
+ this.controllers.add(controller);
979
+ try {
980
+ const url = await this.hostRoute(raw.remote, config.url, '/artifacts/content');
981
+ const response = await fetch(url, { method: 'POST', redirect: 'error',
982
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.token}` },
983
+ body: JSON.stringify({ taskId: raw.taskId, path: artifact.path, sha256 }),
984
+ signal: AbortSignal.any([controller.signal, AbortSignal.timeout(30_000)]) });
985
+ if (!response.ok) {
986
+ await response.body?.cancel();
987
+ // An older host has no such route; everything else keeps the host's own verdict.
988
+ throw new WorkbenchArtifactError(response.status === 409 || response.status === 413 ? response.status : 404, response.status === 404 || response.status === 409 || response.status === 413 ? 'artifact-unavailable-on-host' : 'artifact-host-unsupported');
989
+ }
990
+ const content = Buffer.from(await response.arrayBuffer());
991
+ if (content.length !== artifact.size || createHash('sha256').update(content).digest('hex') !== sha256) {
992
+ throw new WorkbenchArtifactError(409, 'artifact-digest-mismatch');
993
+ }
994
+ return { content, name: path.basename(artifact.path), ...(artifact.mediaType ? { mediaType: artifact.mediaType } : {}) };
995
+ }
996
+ catch (error) {
997
+ if (error instanceof WorkbenchArtifactError)
998
+ throw error;
999
+ throw new WorkbenchArtifactError(502, 'artifact-host-unreachable');
1000
+ }
1001
+ finally {
1002
+ this.controllers.delete(controller);
1003
+ }
1004
+ }
1005
+ throw new WorkbenchArtifactError(404, 'artifact-not-found');
1006
+ }
654
1007
  async checkDispatch(remote, cwd, requirements, pinnedEndpoint) {
655
1008
  if (!requirements)
656
1009
  return;
@@ -666,12 +1019,31 @@ export class RemoteAgentGateway {
666
1019
  }
667
1020
  view(job) {
668
1021
  const task = Task.fromJSON(job.task);
1022
+ const meta = task.metadata?.['1agents'];
1023
+ const result = job.attemptId ? this.ledger.getAttempt(job.attemptId).result : undefined;
669
1024
  return { remote: job.remote, taskId: job.taskId, contextId: job.contextId, originSessionId: job.originSessionId,
670
1025
  ...(job.ledgerJobId ? { jobId: job.ledgerJobId, attemptId: job.attemptId, sourceId: this.ledger.sourceId } : {}),
671
- cwd: job.cwd, agentPreset: job.agentPreset, sessionId: task.metadata?.['1agents']?.sessionId,
672
- preflight: task.metadata?.['1agents']?.preflight, resultMetadata: task.metadata?.['1agents']?.result,
1026
+ cwd: job.cwd, agentPreset: job.agentPreset, sessionId: meta?.sessionId ?? job.sessionId,
1027
+ preflight: meta?.preflight, resultMetadata: meta?.result,
1028
+ ...(meta?.capacity ? { capacity: meta.capacity } : {}),
1029
+ ...(meta?.taskSlot ? { taskSlot: meta.taskSlot } : {}),
1030
+ ...(meta?.processSlot ? { processSlot: meta.processSlot } : {}),
1031
+ ...(meta?.resumed === true ? { resumed: true } : {}),
1032
+ // Load and resume are one reattach; they differ only in whether the host replayed the transcript to its client.
1033
+ ...(meta?.resumed === true && (meta.restoreMethod === 'session/load' || meta.restoreMethod === 'session/resume') ? { historyReplayed: meta.restoreMethod === 'session/load' } : {}),
1034
+ ...(typeof meta?.provider === 'string' && typeof meta.model === 'string' ? { provider: meta.provider, model: meta.model } : {}),
1035
+ ...(job.lifecycle ? { lifecycle: job.lifecycle } : {}),
1036
+ ...(job.sessionState ? { sessionState: job.sessionState } : {}),
1037
+ ...(job.processReleased !== undefined ? { processReleased: job.processReleased } : {}),
1038
+ resultRevision: result?.resultRevision, resultDigest: result?.resultDigest,
673
1039
  state: taskState(job), result: resultText(task), artifactLinks: artifactLinks(task), checkedAt: job.checkedAt, stale: Boolean(job.stale) };
674
1040
  }
1041
+ resultObservation(task) {
1042
+ const metadata = task.metadata?.['1agents']?.result;
1043
+ return { executionStatus: this.standardState(wire(task).status?.state), providerState: wire(task).status?.state,
1044
+ resultSummary: resultText(task), artifactLinks: artifactLinks(task),
1045
+ resultArtifacts: metadata?.artifacts ?? [], ...(metadata?.recordPath ? { structuredResultRef: metadata.recordPath } : {}) };
1046
+ }
675
1047
  accept(task, fields) {
676
1048
  const target = task.metadata?.['1agents'];
677
1049
  const job = { ...fields, taskId: task.id, contextId: task.contextId, task: wire(task), checkedAt: new Date().toISOString(),
@@ -691,22 +1063,23 @@ export class RemoteAgentGateway {
691
1063
  job.task = wire(task);
692
1064
  job.checkedAt = new Date().toISOString();
693
1065
  job.stale = false;
1066
+ const meta = task.metadata?.['1agents'];
1067
+ if (typeof meta?.sessionId === 'string' && meta.sessionId)
1068
+ job.sessionId = meta.sessionId;
694
1069
  const state = taskState(job);
695
1070
  if (actionable.has(state)) {
1071
+ const reason = state === 'TASK_STATE_CANCELED' && job.attemptId ? this.state.executionCancellations?.[job.attemptId]?.reason : undefined;
696
1072
  const noticeId = createHash('sha256').update(JSON.stringify([job.remote, job.taskId, state, task.status?.timestamp])).digest('hex');
697
1073
  if (!this.state.notices.some(value => value.notice.noticeId === noticeId))
698
1074
  this.state.notices.push({
699
1075
  ...(this.sessions.hasBinding(job.originSessionId) ? { sessionDeliveryId: `a2a-notice:${noticeId}` } : { target: job.notificationTarget }),
700
1076
  notice: { noticeId, originSessionId: job.originSessionId, remote: job.remote, taskId: job.taskId, contextId: job.contextId,
701
- cwd: job.cwd, agentPreset: job.agentPreset, title: job.title, state, result: resultText(task),
1077
+ cwd: job.cwd, agentPreset: job.agentPreset, title: job.title, state, result: reason ? `${reason}\n\n${resultText(task)}`.trim() : resultText(task),
702
1078
  ...(artifactLinks(task).length ? { artifactLinks: artifactLinks(task) } : {}), createdAt: new Date().toISOString() }
703
1079
  });
704
1080
  }
705
1081
  if (job.attemptId) {
706
- const metadata = task.metadata?.['1agents']?.result;
707
- const observed = { executionStatus: this.standardState(state), providerState: state, stale: false,
708
- resultSummary: resultText(task), artifactLinks: artifactLinks(task),
709
- ...(metadata ? { structuredResultRef: metadata.recordPath } : {}) };
1082
+ const observed = { ...this.resultObservation(task), stale: false };
710
1083
  if (this.ledger.getAttempt(job.attemptId).submissionStatus !== 'accepted')
711
1084
  this.ledger.accept(job.attemptId, { provider: 'a2a', remote: job.remote, endpoint: job.remoteEndpoint, taskId: task.id, contextId: task.contextId, sessionId: task.metadata?.['1agents']?.sessionId }, observed);
712
1085
  else
@@ -714,6 +1087,8 @@ export class RemoteAgentGateway {
714
1087
  }
715
1088
  else
716
1089
  this.save();
1090
+ if (oneShotShouldClose(job.lifecycle, state, this.taskAcknowledged(job, state)))
1091
+ this.releaseOneShot(job);
717
1092
  }
718
1093
  async refresh(job) {
719
1094
  const key = `${job.remote}:${job.taskId}`;
@@ -761,7 +1136,7 @@ export class RemoteAgentGateway {
761
1136
  break;
762
1137
  if (run.cancellationRequestedAt && run.executionStatus !== 'canceled')
763
1138
  continue;
764
- if (run.executionStatus === 'working' || run.parentUpdatePending) {
1139
+ if (run.executionStatus === 'working' || run.parentUpdatePending || run.humanReviews?.some(review => review.resume?.status === 'pending')) {
765
1140
  try {
766
1141
  await this.advanceDelivery(run);
767
1142
  }
@@ -773,6 +1148,21 @@ export class RemoteAgentGateway {
773
1148
  if (run.executionStatus !== 'working' && !run.parentUpdatePending)
774
1149
  this.executionNotice(run, run.resultSummary ?? this.ledgerView(run.originSessionId, run.jobId).resultSummary ?? run.diagnostics.at(-1) ?? 'PPT delivery requires attention', run.validation?.artifacts ?? []);
775
1150
  }
1151
+ for (const run of Object.values(this.state.reportReviews ?? {})) {
1152
+ if (this.closed)
1153
+ break;
1154
+ if (this.state.executionCancellations?.[run.attemptId])
1155
+ continue;
1156
+ if (run.executionStatus === 'working' || run.humanReviews.some(review => review.resume?.status === 'pending') || ['completed', 'failed', 'canceled'].includes(run.executionStatus)) {
1157
+ try {
1158
+ await this.advanceReport(run);
1159
+ }
1160
+ catch (error) {
1161
+ run.resultSummary = `报告协调器等待处理:${error instanceof Error ? error.message : 'unknown error'}`;
1162
+ this.save();
1163
+ }
1164
+ }
1165
+ }
776
1166
  // The persisted notice owns its route. Later bindings must not double-deliver old webhooks.
777
1167
  if (this.sessions.healthy)
778
1168
  for (const record of this.state.notices) {
@@ -800,6 +1190,13 @@ export class RemoteAgentGateway {
800
1190
  await this.sessions.reconcile();
801
1191
  }
802
1192
  await Promise.allSettled(this.state.notices.filter(record => record.target && !record.delivered && !record.acknowledged).map(record => this.deliver(record)));
1193
+ for (const job of this.state.jobs) {
1194
+ if (this.closed)
1195
+ break;
1196
+ if (oneShotShouldClose(job.lifecycle, taskState(job), this.taskAcknowledged(job, taskState(job))))
1197
+ this.releaseOneShot(job);
1198
+ }
1199
+ await this.reconcileIdleSessions();
803
1200
  await this.automation?.reconcileAcknowledgements();
804
1201
  })();
805
1202
  this.reconciling = pending;
@@ -846,6 +1243,11 @@ export class RemoteAgentGateway {
846
1243
  }
847
1244
  }
848
1245
  async invokeMethod(method, params) {
1246
+ if (Object.hasOwn(DISCOVERY_METHODS, method)) {
1247
+ if (!this.projectDiscovery)
1248
+ throw new Error('Project discovery is disabled; configure projectDiscovery in the trusted gateway configuration');
1249
+ return this.projectDiscovery.invoke(method, params);
1250
+ }
849
1251
  if (Object.hasOwn(TARGET_METHODS, method)) {
850
1252
  if (method === 'execution_target_probe')
851
1253
  return this.probeTarget(z.object({ targetId: string }).strict().parse(params).targetId);
@@ -863,13 +1265,28 @@ export class RemoteAgentGateway {
863
1265
  const attempt = job.attempts.find(item => item.attemptId === job.currentAttemptId);
864
1266
  if (job.unresolvedAttemptIds.length)
865
1267
  throw new Error('Job has submission_unknown or unresolved attempts; reconcile before continuing');
1268
+ if (this.state.reportReviews?.[attempt.attemptId])
1269
+ throw new Error('Report workflow continues only through its version-bound human review');
866
1270
  const delivery = this.state.pptDeliveries.runs[attempt.attemptId];
867
1271
  if (delivery) {
868
- if (Object.keys(input.input).length)
869
- throw new Error('PPT checkpoint recovery preserves the frozen input; use an empty input object');
1272
+ this.assertDispatchOpen(input.originSessionId, job.jobId);
1273
+ const recovery = Object.keys(input.input).length ? pptDeliveryRecoveryInputSchema.safeParse(input.input) : undefined;
1274
+ if (recovery && !recovery.success)
1275
+ throw new Error('PPT recovery preserves the frozen input; use {} or {recoveryMode:"review_only",reviewTargetId,sourceSnapshotDirectory?}');
1276
+ const recoveryInput = recovery?.data;
870
1277
  if (job.inFlightAttemptIds.length)
871
1278
  throw new Error('PPT parent still has in-flight execution rounds');
872
- assertPptDeliveryRecoverable(delivery);
1279
+ assertPptDeliveryRecoverable(delivery, recoveryInput);
1280
+ if (recoveryInput) {
1281
+ for (const childId of this.cancellationJobs(input.originSessionId, job.jobId, true)) {
1282
+ const child = this.ledger.get(input.originSessionId, childId);
1283
+ if (child.inFlightAttemptIds.length || child.unresolvedAttemptIds.length)
1284
+ throw new Error('PPT recovery has unresolved or running descendants');
1285
+ }
1286
+ const reviewer = this.targets.resolve(recoveryInput.reviewTargetId, { prompt: 'Independent review recovery preflight' });
1287
+ if (reviewer.target.binding.driver === 'ppt_delivery')
1288
+ throw new Error('Independent reviewer must be an A2A execution target');
1289
+ }
873
1290
  const current = this.targets.resolve(job.targetId, attempt.input);
874
1291
  if (!current.target.capabilities?.continue)
875
1292
  throw new Error('PPT target does not enable checkpoint continuation');
@@ -879,13 +1296,21 @@ export class RemoteAgentGateway {
879
1296
  || current.target.binding.driver !== 'ppt_delivery')
880
1297
  throw new Error('PPT checkpoint recovery cannot change its host or role');
881
1298
  return this.submitExecution({ originSessionId: input.originSessionId, targetId: job.targetId, title: job.title,
882
- input: attempt.input, clientRequestId: input.clientRequestId }, { jobId: job.jobId, deliveryRecovery: delivery, requestDigestInput: input.input });
1299
+ input: attempt.input, clientRequestId: input.clientRequestId, initiatedBy: input.initiatedBy }, { jobId: job.jobId, deliveryRecovery: delivery, deliveryRecoveryInput: recoveryInput, requestDigestInput: input.input });
883
1300
  }
884
1301
  const previous = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
885
1302
  if (!previous)
886
1303
  throw new Error('Continue is unsupported for this provider');
887
- return this.submitExecution({ originSessionId: input.originSessionId, targetId: job.targetId, title: job.title,
888
- input: { ...attempt.input, ...input.input }, clientRequestId: input.clientRequestId }, { jobId: job.jobId, previous, requestDigestInput: input.input });
1304
+ // A round queued behind a running one could not surface the running round's approvals, and the two would wait on each other.
1305
+ if (job.inFlightAttemptIds.length)
1306
+ await this.refresh(previous);
1307
+ const current = this.ledger.get(input.originSessionId, job.jobId);
1308
+ if (current.attempts.some(item => current.inFlightAttemptIds.includes(item.attemptId) && item.executionStatus !== 'input_required'))
1309
+ throw new Error('Job still has a running round; wait for it to end or cancel it before continuing');
1310
+ const submitted = await this.submitExecution({ originSessionId: input.originSessionId, targetId: job.targetId, title: job.title,
1311
+ input: { ...attempt.input, ...input.input }, clientRequestId: input.clientRequestId, initiatedBy: input.initiatedBy }, { jobId: job.jobId, previous, requestDigestInput: input.input });
1312
+ reopenForContinue(this.ledger, input.originSessionId, job.jobId);
1313
+ return submitted;
889
1314
  }
890
1315
  if (method === 'execution_get') {
891
1316
  const input = executionJobSchema.parse(params), job = this.ledger.get(input.originSessionId, input.jobId);
@@ -912,6 +1337,28 @@ export class RemoteAgentGateway {
912
1337
  const { originSessionId, jobId, ...review } = executionReviewSchema.parse(params);
913
1338
  return this.ledger.acceptance(originSessionId, jobId, review);
914
1339
  }
1340
+ if (Object.hasOwn(TICKET_METHODS, method))
1341
+ return invokeTicket(this.ledger, method, params);
1342
+ if (method === 'execution_unwatch') {
1343
+ const input = executionUnwatchSchema.parse(params);
1344
+ this.ledger.unwatch(input.originSessionId, input.jobId, input.reason);
1345
+ return this.ledgerView(input.originSessionId, input.jobId);
1346
+ }
1347
+ if (method === 'execution_rewatch') {
1348
+ const input = executionJobSchema.parse(params);
1349
+ this.ledger.rewatch(input.originSessionId, input.jobId);
1350
+ return this.ledgerView(input.originSessionId, input.jobId);
1351
+ }
1352
+ if (method === 'execution_process_requests') {
1353
+ const input = executionJobSchema.parse(params);
1354
+ this.ledger.get(input.originSessionId, input.jobId);
1355
+ return { requests: this.workbenchTask(input.jobId).processRequests };
1356
+ }
1357
+ if (method === 'execution_process_answer') {
1358
+ const { originSessionId, jobId, requestId, ...answer } = processAnswerSchema.parse(params);
1359
+ this.ledger.get(originSessionId, jobId);
1360
+ return (await this.answerProcessRequest(jobId, requestId, answer)).processRequests.find(request => request.requestId === requestId);
1361
+ }
915
1362
  if (method === 'execution_inbox') {
916
1363
  const { originSessionId } = inboxSchema.parse(params);
917
1364
  return { notices: this.state.executionNotices.filter(item => item.originSessionId === originSessionId && !item.processedAt)
@@ -951,8 +1398,8 @@ export class RemoteAgentGateway {
951
1398
  const input = spawnSchema.parse(params);
952
1399
  if (input.notificationTarget && !this.config.notificationTargets[input.notificationTarget])
953
1400
  throw new Error('Unknown notificationTarget');
954
- const { originSessionId, remote, clientRequestId, title, ...fields } = input;
955
- const submitted = await this.submitExecution({ originSessionId, targetId: `legacy:${remote}`, input: fields, clientRequestId, title });
1401
+ const { originSessionId, remote, clientRequestId, title, initiatedBy, ...fields } = input;
1402
+ const submitted = await this.submitExecution({ originSessionId, targetId: `legacy:${remote}`, input: fields, clientRequestId, title, initiatedBy });
956
1403
  if ('error' in submitted)
957
1404
  throw new Error(`${submitted.error}; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
958
1405
  const raw = this.state.jobs.find(item => item.attemptId === submitted.attemptId);
@@ -974,14 +1421,22 @@ export class RemoteAgentGateway {
974
1421
  }
975
1422
  if (method === 'remote_agent_message') {
976
1423
  const input = messageSchema.parse(params), previous = this.job(input);
1424
+ if (previous.sessionState === 'deleted')
1425
+ throw new RemoteAgentError('SESSION_DELETED', 'Session was deleted');
1426
+ if (input.autoResume === false && (previous.sessionState === 'closed' || previous.sessionState === 'closing')) {
1427
+ throw new RemoteAgentError('SESSION_CLOSED', 'Session is closed');
1428
+ }
977
1429
  if (!previous.ledgerJobId)
978
1430
  throw new Error('Task has no unified job association');
979
1431
  const record = this.ledger.get(input.originSessionId, previous.ledgerJobId);
980
1432
  const target = this.targets.getTarget(record.targetId);
981
1433
  const submitted = await this.submitExecution({ originSessionId: input.originSessionId, targetId: record.targetId,
982
- clientRequestId: input.clientRequestId, title: previous.title,
1434
+ clientRequestId: input.clientRequestId, title: previous.title, initiatedBy: input.initiatedBy,
983
1435
  input: { ...(target.kind === 'agent_host' ? { cwd: previous.cwd, ...(previous.agentPreset ? { agentPreset: previous.agentPreset } : {}) } : {}), prompt: input.prompt,
984
1436
  ...(input.preflight ? { preflight: input.preflight } : {}), ...(input.resultContract ? { resultContract: input.resultContract } : {}),
1437
+ ...(input.roleId ? { roleId: input.roleId } : {}), ...(input.roleLockPath ? { roleLockPath: input.roleLockPath } : {}),
1438
+ ...(input.lifecycle ? { lifecycle: input.lifecycle } : previous.lifecycle ? { lifecycle: previous.lifecycle } : {}),
1439
+ ...(input.provider !== undefined ? { provider: input.provider } : {}), ...(input.model !== undefined ? { model: input.model } : {}),
985
1440
  ...(previous.notificationTarget ? { notificationTarget: previous.notificationTarget } : {}) } }, { jobId: previous.ledgerJobId, previous });
986
1441
  if ('error' in submitted)
987
1442
  throw new Error(`${submitted.error}; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
@@ -1003,8 +1458,24 @@ export class RemoteAgentGateway {
1003
1458
  notice.acknowledged = true;
1004
1459
  this.save();
1005
1460
  this.sessions.acknowledgeNotice(input.originSessionId, input.noticeId);
1461
+ const acked = this.state.jobs.find(item => item.originSessionId === input.originSessionId && item.taskId === notice.notice.taskId);
1462
+ if (acked && oneShotShouldClose(acked.lifecycle, notice.notice.state, true))
1463
+ this.releaseOneShot(acked);
1006
1464
  return { acknowledged: true, noticeId: input.noticeId };
1007
1465
  }
1466
+ if (method === 'remote_agent_close') {
1467
+ const input = closeSchema.parse(params);
1468
+ const present = [input.taskId, input.contextId, input.sessionId].filter(value => value !== undefined);
1469
+ if (present.length !== 1)
1470
+ throw new RemoteAgentError('SESSION_CONFLICT', 'Provide exactly one of taskId, contextId, or sessionId');
1471
+ if (input.mode === 'delete' && !this.config.sessionLifecycle.allowDelete)
1472
+ throw new RemoteAgentError('DELETE_DISABLED', 'Session delete is disabled on this gateway');
1473
+ return this.performClose(input, 'explicit');
1474
+ }
1475
+ if (method === 'remote_agent_sessions') {
1476
+ sessionsSchema.parse(params ?? {});
1477
+ return this.capacityReport(true);
1478
+ }
1008
1479
  throw new Error(`Unknown method: ${method}`);
1009
1480
  }
1010
1481
  /** Push events are hints. GetTask remains authoritative, including after missed callbacks. */
@@ -1016,6 +1487,494 @@ export class RemoteAgentGateway {
1016
1487
  throw new Error('Missing A2A event task ID');
1017
1488
  await Promise.allSettled(this.state.jobs.filter(job => job.taskId === taskId).map(job => this.refresh(job)));
1018
1489
  }
1490
+ workbenchProjection() {
1491
+ const config = this.config.workbench;
1492
+ if (!config)
1493
+ throw new Error('Workbench is not configured');
1494
+ const runs = Object.values(this.state.pptDeliveries.runs);
1495
+ const reportRuns = Object.values(this.state.reportReviews ?? {});
1496
+ return workbenchSnapshot({ ledger: this.ledger.snapshot(), runs, reportRuns, reviews: [...runs.flatMap(run => run.humanReviews ?? []), ...reportRuns.flatMap(run => run.humanReviews)],
1497
+ processRequests: this.state.processRequests ?? [], actorId: config.reviewerId, ...(config.allowedOrigins ? { allowedOrigins: config.allowedOrigins } : {}) });
1498
+ }
1499
+ workbench(operation) {
1500
+ const run = this.workbenchQueue.then(operation);
1501
+ this.workbenchQueue = run.then(() => { }, () => { });
1502
+ return run;
1503
+ }
1504
+ writeProcessRequest(request) {
1505
+ const items = this.state.processRequests ?? [];
1506
+ const index = items.findIndex(item => item.requestId === request.requestId);
1507
+ const next = items.slice();
1508
+ if (index < 0)
1509
+ next.push(request);
1510
+ else
1511
+ next[index] = request;
1512
+ this.state.processRequests = next;
1513
+ const { requestId, kind, toolTitle, status, answer } = request;
1514
+ this.ledger.processEvent(request.jobId, request.attemptId, index < 0 ? 'process.opened' : status === 'expired' ? 'process.expired' : 'process.answered', {
1515
+ requestId, kind, ...(toolTitle ? { toolTitle } : {}), status,
1516
+ ...(answer ? { outcome: answer.outcome, ...(answer.note ? { note: answer.note } : {}), ...(answer.stopTask ? { stopTask: true } : {}), ...(answer.decidedBy ? { decidedBy: answer.decidedBy } : {}) } : {})
1517
+ });
1518
+ this.save();
1519
+ }
1520
+ workbenchList(query = {}) { return listWorkbenchTasks(this.workbenchProjection(), query); }
1521
+ workbenchAgents() {
1522
+ const residents = this.targets.listTargets().filter(target => target.kind === 'resident_agent').map(target => ({
1523
+ targetId: target.targetId, name: target.name, ...(target.binding.roleId ? { roleId: target.binding.roleId } : {}),
1524
+ ...(target.binding.agentPreset ? { agentPreset: target.binding.agentPreset } : {})
1525
+ }));
1526
+ const connections = this.targets.listConnections().filter(connection => connection.enabled && connection.provider === 'a2a')
1527
+ .map(connection => ({ connectionId: connection.connectionId, remote: connection.remote }));
1528
+ return { ...listWorkbenchAgents(this.workbenchProjection(), this.agents.snapshot(), residents), connections };
1529
+ }
1530
+ /**
1531
+ * Register every agents/*.md under a directory as a developing draft with its own path-agent target: cwd and preset
1532
+ * fixed to that directory and runtime, the file as the role. Each runtime (an ACP agent or a DSH-native preset) gets
1533
+ * its own draft `<name>@<runtime>` and target, so one directory can run on several. Registering the same runtime again
1534
+ * refreshes its drafts and targets.
1535
+ * The file is read here for its name and again by the execution host at dispatch, so both must see the same path.
1536
+ */
1537
+ registerWorkbenchAgentPath(input) {
1538
+ return this.workbench(async () => {
1539
+ // Either an ACP agent (preset oneagents-acp-<agent>) or a DSH-native preset such as standard, optionally with a fixed model.
1540
+ const parsed = z.object({ path: z.string().min(1).max(4096).refine(value => path.isAbsolute(value) && !value.includes('\0'), 'Expected an absolute local path'),
1541
+ acpAgent: z.string().trim().min(1).max(64).regex(agentNamePattern).optional(),
1542
+ agentPreset: z.string().trim().min(1).max(256).regex(/^[A-Za-z0-9][A-Za-z0-9.:_-]*$/).refine(value => !isAcpAgentPreset(value), 'Use acpAgent for ACP presets').optional(),
1543
+ provider: string.optional(), model: string.optional(), connectionId: string }).strict()
1544
+ .refine(value => (value.acpAgent === undefined) !== (value.agentPreset === undefined), 'Pass acpAgent or agentPreset')
1545
+ .refine(value => (value.provider === undefined) === (value.model === undefined) && !(value.acpAgent && value.provider), 'provider and model go together and only with agentPreset')
1546
+ .safeParse(input);
1547
+ if (!parsed.success)
1548
+ throw new AgentRegistryError(parsed.error.issues[0]?.message ?? 'Invalid path registration', 'invalid');
1549
+ let agents;
1550
+ try {
1551
+ agents = await listAgentFiles(parsed.data.path);
1552
+ }
1553
+ catch (error) {
1554
+ throw new AgentRegistryError(error instanceof Error ? error.message : String(error), 'invalid');
1555
+ }
1556
+ if (!agents.length)
1557
+ throw new AgentRegistryError('No agent files under agents/', 'invalid');
1558
+ const connection = this.targets.listConnections().find(item => item.connectionId === parsed.data.connectionId);
1559
+ if (!connection?.enabled || connection.provider !== 'a2a')
1560
+ throw new AgentRegistryError('Unknown or disabled A2A connection', 'invalid');
1561
+ const cwd = realpathSync(parsed.data.path), scope = createHash('sha256').update(cwd).digest('hex').slice(0, 8);
1562
+ const { acpAgent, provider, model } = parsed.data, agentPreset = acpAgent ? `oneagents-acp-${acpAgent}` : parsed.data.agentPreset;
1563
+ const runtime = acpAgent ? { acpAgent } : { agentPreset, ...(provider ? { provider, model: model } : {}) }, runtimeKey = acpAgent ?? agentPreset, registered = [];
1564
+ for (const agent of agents) {
1565
+ // An existing draft keeps its target, including one registered before targets carried the runtime.
1566
+ const targetId = this.agents.pathDraft(agent.file, runtimeKey)?.targetId ?? `path:${scope}:${runtimeKey}:${agent.name}`, binding = { cwd, agentPreset, agentFile: agent.file, ...(provider ? { provider, model } : {}) };
1567
+ const fields = { kind: 'agent_host', name: `${path.basename(cwd)}/${agent.name}@${runtimeKey}`, connectionId: connection.connectionId,
1568
+ ...(agent.description ? { description: agent.description } : {}), binding };
1569
+ const existing = this.targets.listTargets().find(item => item.targetId === targetId);
1570
+ try {
1571
+ if (existing)
1572
+ this.targets.invoke('execution_target_update', { targetId, patch: { ...fields, ...(existing.description && !agent.description ? { description: existing.description } : {}) } });
1573
+ else
1574
+ this.targets.invoke('execution_target_create', { targetId, ...fields });
1575
+ }
1576
+ catch (error) {
1577
+ throw new AgentRegistryError(error instanceof Error ? error.message : String(error), 'invalid');
1578
+ }
1579
+ const draft = this.agents.registerPathDraft({ name: `${agent.name}@${runtimeKey}`, ...runtime, targetId,
1580
+ source: { path: cwd, file: agent.file }, ...(agent.description ? { description: agent.description } : {}) });
1581
+ registered.push({ agentId: draft.agentId, name: draft.name, targetId, file: agent.file });
1582
+ }
1583
+ return { registered, ...this.workbenchAgents() };
1584
+ });
1585
+ }
1586
+ createWorkbenchAgent(input) { return this.workbench(async () => ({ draft: this.agents.create(input), ...this.workbenchAgents() })); }
1587
+ updateWorkbenchAgent(agentId, input) { return this.workbench(async () => ({ draft: this.agents.update(agentId, input), ...this.workbenchAgents() })); }
1588
+ publishWorkbenchAgent(agentId, input) { return this.workbench(async () => ({ release: this.agents.publish(agentId, input), ...this.workbenchAgents() })); }
1589
+ workbenchTask(jobId) { return getWorkbenchTask(this.workbenchProjection(), jobId); }
1590
+ /** Read-only transcript from the stored A2A history of the job's attempts; the same scope check as the task detail. */
1591
+ workbenchChat(jobId, query = {}) {
1592
+ this.workbenchTask(jobId);
1593
+ return pageChat(chatItems(this.state.jobs.filter(job => job.ledgerJobId === jobId)), query);
1594
+ }
1595
+ /** Only the dedicated HTTP workbench calls this; it is deliberately absent from the agent tool catalogue. */
1596
+ async decideWorkbenchReview(jobId, reviewId, input) {
1597
+ return this.workbench(async () => {
1598
+ if (this.closed)
1599
+ throw new Error('Gateway is closed');
1600
+ const scope = this.workbenchTask(jobId), config = this.config.workbench;
1601
+ await this.advancingDeliveries.get(scope.currentAttemptId);
1602
+ const report = this.state.reportReviews?.[scope.currentAttemptId];
1603
+ if (report)
1604
+ return this.decideReportReview(report, reviewId, input);
1605
+ const run = this.state.pptDeliveries.runs[scope.currentAttemptId];
1606
+ const review = run?.humanReviews?.find(item => item.reviewId === reviewId && item.jobId === jobId);
1607
+ if (!run || !review)
1608
+ throw new Error('Review not found in authorized task');
1609
+ const decision = humanReviewDecisionSchema.parse(input);
1610
+ const replay = review.history.some(item => item.clientRequestId === decision.clientRequestId);
1611
+ if (!replay && (run.cancellationRequestedAt || ['completed', 'failed', 'canceled'].includes(run.executionStatus))) {
1612
+ throw new HumanReviewError('already_decided', 'Task is no longer awaiting a human decision');
1613
+ }
1614
+ let currentDigest = run.scriptDigest ?? '';
1615
+ if (!replay && review.revision === scriptRevisionName(run)) {
1616
+ try {
1617
+ currentDigest = createHash('sha256').update(readFileSync(path.join(scriptDirectory(run), 'slide-script.json'))).digest('hex');
1618
+ }
1619
+ catch {
1620
+ throw new HumanReviewError('version_conflict', 'The reviewed content snapshot is unavailable');
1621
+ }
1622
+ }
1623
+ const result = decideHumanReview(review, decision, { id: config.reviewerId,
1624
+ ...(config.reviewerName ? { displayName: config.reviewerName } : {}), source: '1agents-web' }, { attemptId: scope.currentAttemptId, revision: scriptRevisionName(run), digest: currentDigest });
1625
+ if (!result.idempotent) {
1626
+ const nextRun = { ...run, humanReviews: run.humanReviews.map(item => item.reviewId === reviewId ? result.review : item) };
1627
+ const nextDeliveries = { ...this.state.pptDeliveries, runs: { ...this.state.pptDeliveries.runs, [run.attemptId]: nextRun } };
1628
+ atomicJson(this.stateFile, { ...this.state, pptDeliveries: nextDeliveries });
1629
+ this.state.pptDeliveries = nextDeliveries;
1630
+ }
1631
+ const current = this.state.pptDeliveries.runs[run.attemptId];
1632
+ if (current.humanReviews?.some(item => item.resume?.status === 'pending'))
1633
+ void this.advanceDelivery(current).catch(() => { });
1634
+ return this.workbenchTask(jobId);
1635
+ });
1636
+ }
1637
+ /** Records a question or plan approval against the running attempt. The workbench token never travels in A2A metadata. */
1638
+ async openProcessRequest(jobId, input) {
1639
+ return this.workbench(async () => {
1640
+ if (this.closed)
1641
+ throw new Error('Gateway is closed');
1642
+ const scope = this.workbenchTask(jobId);
1643
+ const parsed = processRequestCreateSchema.parse(input);
1644
+ if (parsed.jobId !== jobId)
1645
+ throw new ProcessRequestError('invalid', 'Process request job does not match the task');
1646
+ let attempt;
1647
+ try {
1648
+ attempt = this.ledger.getAttempt(parsed.attemptId);
1649
+ }
1650
+ catch {
1651
+ throw new ProcessRequestError('invalid', 'Process request attempt was not found');
1652
+ }
1653
+ if (attempt.jobId !== jobId || attempt.attemptId !== scope.currentAttemptId)
1654
+ throw new ProcessRequestError('invalid', 'Process request attempt is not current');
1655
+ if (['completed', 'failed', 'canceled', 'rejected'].includes(scope.executionStatus))
1656
+ throw new ProcessRequestError('already_decided', 'Task is no longer running');
1657
+ if (parsed.requestId) {
1658
+ const existing = this.state.processRequests?.find(item => item.requestId === parsed.requestId);
1659
+ if (existing) {
1660
+ if (!sameProcessRequest(existing, parsed))
1661
+ throw new ProcessRequestError('idempotency_conflict', 'requestId conflicts with a recorded process request');
1662
+ return projectProcessRequest(existing);
1663
+ }
1664
+ }
1665
+ const config = this.config.workbench;
1666
+ const created = createProcessRequest(parsed, undefined, config ? config.requestTimeoutMinutes * 60_000 : undefined);
1667
+ this.writeProcessRequest(created);
1668
+ if (config?.desktopNotifications) {
1669
+ const what = created.kind === 'permission' ? `工具「${created.toolTitle}」等待批准` : created.kind === 'plan' ? '计划等待批准' : '问题等待回答';
1670
+ notifyDesktop(`任务工作台 · ${scope.title}`.slice(0, 120), `${what},${config.requestTimeoutMinutes} 分钟内处理`.slice(0, 240), config.publicBaseUrl);
1671
+ }
1672
+ return created;
1673
+ });
1674
+ }
1675
+ processRequest(jobId, requestId) {
1676
+ const request = this.workbenchTask(jobId).processRequests.find(item => item.requestId === requestId);
1677
+ if (!request)
1678
+ throw new ProcessRequestError('not_found', 'Process request not found in authorized task');
1679
+ return request;
1680
+ }
1681
+ /** Completes the stored request. The caller must still finish the original userQuestions wait; this does not send another prompt. */
1682
+ async answerProcessRequest(jobId, requestId, input) {
1683
+ let stop;
1684
+ const task = await this.workbench(async () => {
1685
+ if (this.closed)
1686
+ throw new Error('Gateway is closed');
1687
+ this.workbenchTask(jobId);
1688
+ const stored = this.state.processRequests?.find(item => item.requestId === requestId && item.jobId === jobId);
1689
+ if (!stored)
1690
+ throw new ProcessRequestError('not_found', 'Process request not found in authorized task');
1691
+ const parsed = processRequestAnswerSchema.parse(input);
1692
+ if (stored.status === 'pending' && Date.parse(stored.deadlineAt) <= Date.now() && stored.answer?.clientRequestId !== parsed.clientRequestId) {
1693
+ this.writeProcessRequest(expireProcessRequest(stored));
1694
+ throw new ProcessRequestError('expired', 'This process request has expired');
1695
+ }
1696
+ let result;
1697
+ try {
1698
+ result = answerProcessRequest(stored, parsed);
1699
+ }
1700
+ catch (error) {
1701
+ if (error instanceof ProcessRequestError && error.code === 'expired' && stored.status === 'pending')
1702
+ this.writeProcessRequest(expireProcessRequest(stored));
1703
+ throw error;
1704
+ }
1705
+ if (!result.idempotent)
1706
+ this.writeProcessRequest(result.request);
1707
+ const view = this.workbenchTask(jobId);
1708
+ if (parsed.stopTask && !result.idempotent)
1709
+ stop = { origin: view.originSessionId,
1710
+ reason: `人工拒绝工具调用并停止任务${stored.toolTitle ? `(${stored.toolTitle.slice(0, 200)})` : ''}${parsed.note ? `:${parsed.note}` : ''}` };
1711
+ return view;
1712
+ });
1713
+ // Recorded first, so the waiting agent sees the rejection before the cancel lands.
1714
+ if (!stop)
1715
+ return task;
1716
+ await this.cancelExecution(stop.origin, jobId, undefined, stop.reason);
1717
+ return this.workbenchTask(jobId);
1718
+ }
1719
+ /** A follow-up keeps its session's policy. A new task without one is one-shot. */
1720
+ jobLifecycle(value, previous) {
1721
+ if (value === undefined && previous)
1722
+ return previous;
1723
+ return normalizeLifecycle(value, this.config.sessionLifecycle.persistentIdleTtlSeconds);
1724
+ }
1725
+ /**
1726
+ * P3. A persistent ACP session closes once the host confirms it is attached and idle and its
1727
+ * last turn ended more than idleTtlSeconds ago. Busy, INPUT_REQUIRED and unknown status stay open.
1728
+ */
1729
+ async reconcileIdleSessions() {
1730
+ const policy = this.config.sessionLifecycle;
1731
+ const now = this.now();
1732
+ if (now - this.idleScannedAt < policy.idleScanIntervalMs)
1733
+ return;
1734
+ this.idleScannedAt = now;
1735
+ const contexts = new Map();
1736
+ for (const job of this.state.jobs) {
1737
+ const key = `${job.originSessionId}\0${job.remote}\0${job.contextId}`;
1738
+ contexts.set(key, [...(contexts.get(key) ?? []), job]);
1739
+ }
1740
+ for (const jobs of contexts.values()) {
1741
+ if (this.closed)
1742
+ return;
1743
+ for (const job of jobs)
1744
+ if (taskState(job) === 'TASK_STATE_INPUT_REQUIRED')
1745
+ this.alertInputRequired(job, now);
1746
+ if (jobs.some(job => !terminal.has(taskState(job))))
1747
+ continue;
1748
+ const job = jobs.at(-1);
1749
+ if (!isAcpAgentPreset(job.agentPreset) || !job.sessionId || job.sessionState === 'closed' || job.sessionState === 'closing' || job.sessionState === 'deleted')
1750
+ continue;
1751
+ const lifecycle = job.lifecycle ?? legacyLifecycle(policy.persistentIdleTtlSeconds);
1752
+ if (lifecycle.mode !== 'persistent' || lifecycle.idleTtlSeconds === 0)
1753
+ continue;
1754
+ const ttlMs = lifecycle.idleTtlSeconds * 1000;
1755
+ const endedAt = Date.parse(Task.fromJSON(job.task).status?.timestamp ?? '');
1756
+ if (!Number.isFinite(endedAt) || now - endedAt < ttlMs)
1757
+ continue;
1758
+ let status;
1759
+ try {
1760
+ status = await this.postSession(job.remote, 'status', { sessionId: job.sessionId, contextId: job.contextId }, job.remoteEndpoint);
1761
+ }
1762
+ catch {
1763
+ continue;
1764
+ }
1765
+ if (status.attached !== true || status.activeTurn !== false)
1766
+ continue;
1767
+ const lastUsedAt = typeof status.lastUsedAt === 'string' ? Date.parse(status.lastUsedAt) : Number.NaN;
1768
+ if (Number.isFinite(lastUsedAt) && now - lastUsedAt < ttlMs)
1769
+ continue;
1770
+ try {
1771
+ await this.performClose({ originSessionId: job.originSessionId, remote: job.remote, contextId: job.contextId }, 'idle-ttl');
1772
+ }
1773
+ catch (error) {
1774
+ if (error instanceof RemoteAgentError && error.code === 'SESSION_BUSY')
1775
+ continue;
1776
+ this.closeFailures += 1;
1777
+ console.warn(`A2A idle close failed session=${job.sessionId} context=${job.contextId} code=${error instanceof RemoteAgentError ? error.code : 'REMOTE_UNAVAILABLE'}`);
1778
+ }
1779
+ }
1780
+ }
1781
+ /** Warns once per INPUT_REQUIRED turn after the alert window. The process is never closed for this. */
1782
+ alertInputRequired(job, now) {
1783
+ const since = Task.fromJSON(job.task).status?.timestamp ?? '';
1784
+ const sinceMs = Date.parse(since);
1785
+ if (!Number.isFinite(sinceMs) || now - sinceMs < this.config.sessionLifecycle.inputRequiredAlertSeconds * 1000)
1786
+ return;
1787
+ const key = `${job.taskId}\0${since}`;
1788
+ if (this.inputRequiredAlerts.has(key))
1789
+ return;
1790
+ this.inputRequiredAlerts.set(key, { ...(job.sessionId ? { sessionId: job.sessionId } : {}), contextId: job.contextId, since });
1791
+ console.warn(`A2A input required for too long session=${job.sessionId ?? ''} context=${job.contextId} task=${job.taskId} since=${since}`);
1792
+ }
1793
+ /** Read-only lifecycle counts for /health. Close reasons and resumes are counted per context from saved jobs. */
1794
+ lifecycleReport() {
1795
+ const contexts = new Map();
1796
+ for (const job of this.state.jobs) {
1797
+ const key = `${job.originSessionId}\0${job.remote}\0${job.contextId}`;
1798
+ contexts.set(key, [...(contexts.get(key) ?? []), job]);
1799
+ }
1800
+ const closeReasons = { explicit: 0, 'one-shot': 0, 'idle-ttl': 0 };
1801
+ let resumes = 0;
1802
+ let busy = 0, processReleasePending = 0;
1803
+ for (const jobs of contexts.values()) {
1804
+ if (jobs.some(job => !terminal.has(taskState(job))))
1805
+ busy += 1;
1806
+ const last = jobs.at(-1);
1807
+ if (last.closeReason)
1808
+ closeReasons[last.closeReason] += 1;
1809
+ if (last.processReleased === 'pending')
1810
+ processReleasePending += 1;
1811
+ for (const job of jobs)
1812
+ if (Task.fromJSON(job.task).metadata?.['1agents']?.resumed === true)
1813
+ resumes += 1;
1814
+ }
1815
+ const current = [...this.inputRequiredAlerts.entries()].filter(([key]) => {
1816
+ const job = this.state.jobs.find(item => item.taskId === key.split('\0')[0]);
1817
+ return job !== undefined && taskState(job) === 'TASK_STATE_INPUT_REQUIRED' && Task.fromJSON(job.task).status?.timestamp === key.split('\0')[1];
1818
+ }).map(([, alert]) => alert);
1819
+ return { busy, inputRequiredAlerts: current, closeReasons, resumes, closeFailures: this.closeFailures, processReleasePending };
1820
+ }
1821
+ taskAcknowledged(job, state) {
1822
+ return this.state.notices.some(record => record.acknowledged === true && record.notice.taskId === job.taskId
1823
+ && record.notice.originSessionId === job.originSessionId && record.notice.state === state);
1824
+ }
1825
+ releaseOneShot(job) {
1826
+ if (this.automaticCloseStopped.has(job.remote))
1827
+ return;
1828
+ if (job.closeReason || job.sessionState === 'closed' || job.sessionState === 'closing' || job.sessionState === 'deleted')
1829
+ return;
1830
+ const key = `${job.remote}\0${job.contextId}\0one-shot`;
1831
+ if (this.closingSessions.has(key))
1832
+ return;
1833
+ const operation = this.finishClose(job).finally(() => {
1834
+ if (this.closingSessions.get(key) === operation)
1835
+ this.closingSessions.delete(key);
1836
+ });
1837
+ this.closingSessions.set(key, operation);
1838
+ }
1839
+ async finishClose(job) {
1840
+ try {
1841
+ await this.performClose({ originSessionId: job.originSessionId, remote: job.remote, contextId: job.contextId }, 'one-shot');
1842
+ }
1843
+ catch (error) {
1844
+ if (error instanceof RemoteAgentError && error.code === 'UNSUPPORTED')
1845
+ this.automaticCloseStopped.add(job.remote);
1846
+ else
1847
+ this.closeFailures += 1;
1848
+ // The host has no such session, so there is nothing left to close. Record it once; retrying every reconcile never succeeds.
1849
+ if (error instanceof RemoteAgentError && error.code === 'SESSION_NOT_FOUND') {
1850
+ this.markClosed(this.jobsForClose({ originSessionId: job.originSessionId, remote: job.remote, contextId: job.contextId }), 'one-shot', 'pending');
1851
+ }
1852
+ console.warn(`A2A session close failed session=${job.sessionId ?? ''} context=${job.contextId} task=${job.taskId} code=${error instanceof RemoteAgentError ? error.code : 'REMOTE_UNAVAILABLE'}`);
1853
+ }
1854
+ }
1855
+ jobsForClose(input) {
1856
+ const owned = this.state.jobs.filter(job => job.originSessionId === input.originSessionId && job.remote === input.remote);
1857
+ const sessionOf = (job) => job.sessionId ?? Task.fromJSON(job.task).metadata?.['1agents']?.sessionId;
1858
+ if (input.taskId) {
1859
+ const job = owned.find(item => item.taskId === input.taskId);
1860
+ return job ? owned.filter(item => item.contextId === job.contextId) : [];
1861
+ }
1862
+ if (input.contextId)
1863
+ return owned.filter(item => item.contextId === input.contextId);
1864
+ return owned.filter(item => sessionOf(item) === input.sessionId);
1865
+ }
1866
+ markClosed(jobs, reason, processReleased, deleted = false) {
1867
+ const closedAt = new Date().toISOString();
1868
+ const sessionState = deleted ? 'deleted' : processReleased === true ? 'closed' : 'closing';
1869
+ for (const job of jobs) {
1870
+ job.sessionState = sessionState;
1871
+ job.closedAt = closedAt;
1872
+ job.closeReason = reason;
1873
+ job.processReleased = processReleased;
1874
+ }
1875
+ this.save();
1876
+ }
1877
+ async performClose(input, reason) {
1878
+ const deleting = input.mode === 'delete';
1879
+ const jobs = this.jobsForClose(input);
1880
+ if (!jobs.length)
1881
+ throw new RemoteAgentError('SESSION_NOT_FOUND', 'Session not found for this origin session');
1882
+ const contexts = new Set(jobs.map(job => job.contextId));
1883
+ if (contexts.size !== 1)
1884
+ throw new RemoteAgentError('SESSION_CONFLICT', 'Session identifier matches more than one context');
1885
+ const contextId = jobs[0].contextId;
1886
+ if (jobs.every(job => job.sessionState === 'deleted' || (!deleting && (job.sessionState === 'closed' || job.sessionState === 'closing')))) {
1887
+ const sample = jobs[0];
1888
+ return { remote: input.remote, contextId, sessionId: sample.sessionId, state: sample.sessionState === 'deleted' ? 'deleted' : 'closed', alreadyClosed: true,
1889
+ processReleased: sample.processReleased ?? 'pending', canceledTaskIds: [], ...(sample.agentPreset?.startsWith('oneagents-acp-') ? { acp: true } : sample.agentPreset ? { acp: false } : {}) };
1890
+ }
1891
+ const busy = jobs.filter(job => !terminal.has(taskState(job)));
1892
+ const canceledTaskIds = [];
1893
+ if (busy.length && !input.force)
1894
+ throw new RemoteAgentError('SESSION_BUSY', 'Session is busy');
1895
+ if (busy.length && input.force) {
1896
+ for (const job of busy) {
1897
+ if (job.attemptId)
1898
+ this.ledger.requestCancellation(job.attemptId);
1899
+ try {
1900
+ const client = await this.client(job.remote, job.remoteEndpoint);
1901
+ this.update(job, await client.cancelTask(CancelTaskRequest.fromJSON({ id: job.taskId }), this.auth(job.remote)));
1902
+ canceledTaskIds.push(job.taskId);
1903
+ }
1904
+ catch (error) {
1905
+ if (error instanceof RemoteAgentError)
1906
+ throw error;
1907
+ if (!terminal.has(taskState(job)))
1908
+ throw new RemoteAgentError('SESSION_BUSY', 'Session is busy');
1909
+ }
1910
+ }
1911
+ }
1912
+ const sessionId = jobs.map(job => job.sessionId).find((value) => typeof value === 'string' && value.length > 0);
1913
+ const state = deleting ? 'deleted' : 'closed';
1914
+ if (!sessionId) {
1915
+ this.markClosed(jobs, reason, true, deleting);
1916
+ return { remote: input.remote, contextId, state, alreadyClosed: false, processReleased: true, canceledTaskIds, acp: false };
1917
+ }
1918
+ const result = await this.postSession(input.remote, deleting ? 'delete' : 'close', { sessionId, contextId }, jobs[0].remoteEndpoint);
1919
+ const processReleased = result.processReleased === true ? true : 'pending';
1920
+ this.markClosed(jobs, reason, processReleased, deleting);
1921
+ return { remote: input.remote, contextId, sessionId, state, alreadyClosed: result.alreadyClosed === true,
1922
+ processReleased, canceledTaskIds, ...(typeof result.acp === 'boolean' ? { acp: result.acp } : {}) };
1923
+ }
1924
+ async postSession(remote, action, body, pinnedEndpoint) {
1925
+ const configured = this.config.remotes[remote];
1926
+ const config = configured ? { ...configured, url: pinnedEndpoint ?? configured.url } : undefined;
1927
+ if (!config)
1928
+ throw new RemoteAgentError('REMOTE_UNAVAILABLE', 'Unknown remote');
1929
+ const client = await this.client(remote, config.url), card = await client.getAgentCard(this.auth(remote));
1930
+ const endpoint = card.supportedInterfaces.find(value => value.protocolBinding === 'JSONRPC')?.url;
1931
+ if (!endpoint)
1932
+ throw new RemoteAgentError('REMOTE_UNAVAILABLE', 'Remote does not advertise a JSONRPC endpoint');
1933
+ const url = new URL(endpoint);
1934
+ if (url.origin !== new URL(config.url).origin || url.username || url.password)
1935
+ throw new RemoteAgentError('REMOTE_UNAVAILABLE', 'Session endpoint must use the configured remote origin');
1936
+ url.pathname = `${url.pathname.replace(/\/$/, '')}/sessions/${action}`;
1937
+ url.search = '';
1938
+ url.hash = '';
1939
+ const controller = new AbortController();
1940
+ this.controllers.add(controller);
1941
+ try {
1942
+ const response = await fetch(url, { method: 'POST', redirect: 'error',
1943
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${config.token}` },
1944
+ body: JSON.stringify(body), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(20_000)]) });
1945
+ const payload = await response.json().catch(() => ({}));
1946
+ if (response.status === 501 || payload.error === 'UNSUPPORTED')
1947
+ throw new RemoteAgentError('UNSUPPORTED', `Remote host does not support session ${action}`);
1948
+ if (!response.ok) {
1949
+ const code = payload.error === 'SESSION_NOT_FOUND' || payload.error === 'SESSION_BUSY' || payload.error === 'SESSION_CONFLICT' || payload.error === 'REMOTE_UNAVAILABLE'
1950
+ ? payload.error : 'REMOTE_UNAVAILABLE';
1951
+ throw new RemoteAgentError(code, code === 'SESSION_NOT_FOUND' ? 'Session not found for this origin session' : 'Remote session close failed');
1952
+ }
1953
+ return payload;
1954
+ }
1955
+ finally {
1956
+ this.controllers.delete(controller);
1957
+ }
1958
+ }
1959
+ /** Read-only ledger view. strict requests fail when the directory is unset or the ledger cannot be read. */
1960
+ async capacityReport(strict = false) {
1961
+ if (!this.config.capacityDirectory) {
1962
+ if (strict)
1963
+ throw new Error('ACP capacity directory is not configured');
1964
+ return;
1965
+ }
1966
+ try {
1967
+ const governor = new CapacityGovernor({ directory: this.config.capacityDirectory });
1968
+ const queue = new CapacityQueue({ directory: this.config.capacityDirectory });
1969
+ const report = await governor.inspect();
1970
+ return { ...report, processSlot: { ...report.processSlot, headWaitMs: await queue.headWaitMs('process') } };
1971
+ }
1972
+ catch (error) {
1973
+ if (!strict)
1974
+ return;
1975
+ throw new Error(error instanceof Error && error.message.startsWith('ACP capacity') ? error.message : 'ACP capacity state is unavailable');
1976
+ }
1977
+ }
1019
1978
  async close() {
1020
1979
  if (this.closed)
1021
1980
  return;
@@ -1023,8 +1982,10 @@ export class RemoteAgentGateway {
1023
1982
  clearInterval(this.timer);
1024
1983
  for (const controller of this.controllers)
1025
1984
  controller.abort();
1985
+ await this.projectDiscovery?.close();
1986
+ await this.workbenchQueue;
1026
1987
  await this.sessions.close();
1027
- await Promise.allSettled([...this.refreshing.values(), ...this.operations, ...(this.reconciling ? [this.reconciling] : [])]);
1988
+ await Promise.allSettled([...this.refreshing.values(), ...this.operations, ...this.advancingDeliveries.values(), ...(this.reconciling ? [this.reconciling] : [])]);
1028
1989
  // Delivery promises release their controllers after abort; HTTP requests
1029
1990
  // may have already succeeded, so any retry keeps the stable notice ID.
1030
1991
  this.lease.close();
@@ -1045,25 +2006,257 @@ function json(res, status, data) {
1045
2006
  res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
1046
2007
  res.end(JSON.stringify(data));
1047
2008
  }
2009
+ const ARTIFACT_TYPES = { md: 'text/markdown', txt: 'text/plain', csv: 'text/csv', json: 'application/json', html: 'text/html',
2010
+ pdf: 'application/pdf', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml',
2011
+ mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', wav: 'audio/wav' };
2012
+ /** The manifest's media type when well formed, else one from the extension; text is always served as UTF-8. */
2013
+ function artifactContentType(name, declared) {
2014
+ const type = declared && /^[a-z0-9][\w.+-]*\/[\w.+-]+$/i.test(declared) ? declared.toLowerCase()
2015
+ : ARTIFACT_TYPES[path.extname(name).slice(1).toLowerCase()] ?? 'application/octet-stream';
2016
+ return type.startsWith('text/') ? `${type}; charset=utf-8` : type;
2017
+ }
1048
2018
  function authenticated(req, token) {
1049
2019
  const expected = Buffer.from(`Bearer ${token}`), supplied = Buffer.from(req.headers.authorization ?? '');
1050
2020
  return supplied.length === expected.length && timingSafeEqual(supplied, expected);
1051
2021
  }
2022
+ /** Publishing and review decisions are a person's acts, made on the workbench page. */
2023
+ const PAGE_ONLY_ROUTES = [/^\/workbench\/agents\/[^/]+\/publish$/, /^\/workbench\/tasks\/[^/]+\/reviews\/[^/]+\/decisions$/, /^\/workbench\/tasks\/[^/]+\/continue$/, /^\/workbench\/tasks\/[^/]+\/acceptance$/];
2024
+ function relayedFromPage(req, secret) {
2025
+ if (!secret)
2026
+ return false;
2027
+ const expected = Buffer.from(secret), supplied = Buffer.from(String(req.headers['x-workbench-page-relay'] ?? ''));
2028
+ return supplied.length === expected.length && timingSafeEqual(supplied, expected);
2029
+ }
1052
2030
  async function listen(server, port, host) {
1053
2031
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
1054
2032
  return server.address().port;
1055
2033
  }
2034
+ /** Only a missing bind address is retried. A busy port or a permission error is a bad configuration. */
2035
+ export function isRetryableCallbackBindError(error) {
2036
+ return error.code === 'EADDRNOTAVAIL';
2037
+ }
2038
+ /** Keeps trying `bind` after EADDRNOTAVAIL. Any other error rejects without another sleep. */
2039
+ export async function retryCallbackBind(options) {
2040
+ const sleep = options.sleep ?? ((ms, signal) => delay(ms, undefined, { signal }));
2041
+ let waitMs = options.initialDelayMs ?? 1000;
2042
+ const maxDelayMs = options.maxDelayMs ?? 30_000;
2043
+ for (;;) {
2044
+ options.signal.throwIfAborted();
2045
+ try {
2046
+ await options.bind();
2047
+ return;
2048
+ }
2049
+ catch (error) {
2050
+ if (!isRetryableCallbackBindError(error))
2051
+ throw error;
2052
+ options.onPending(error, new Date().toISOString());
2053
+ await sleep(waitMs, options.signal);
2054
+ waitMs = Math.min(waitMs * 2, maxDelayMs);
2055
+ }
2056
+ }
2057
+ }
1056
2058
  async function stop(server) {
1057
2059
  server.closeIdleConnections();
1058
2060
  await new Promise(resolve => server.close(() => resolve()));
1059
2061
  }
2062
+ // The node rejects the whole registration when a method descriptor breaks its
2063
+ // contract, and its HTTP reason hides the offending method. Mirror the rule
2064
+ // here so the operator learns which method to fix.
2065
+ function methodContractViolations(methods) {
2066
+ return Object.entries(methods).flatMap(([name, method]) => {
2067
+ const description = typeof method?.description === 'string' ? method.description.trim() : '';
2068
+ const parameters = method?.parameters;
2069
+ if (!description)
2070
+ return [`method "${name}" requires a non-empty description`];
2071
+ if (!parameters || typeof parameters !== 'object' || parameters.type !== 'object') {
2072
+ return [`method "${name}" parameters must be an object schema with type: "object"`];
2073
+ }
2074
+ return [];
2075
+ });
2076
+ }
1060
2077
  export async function serveA2AGateway(input, options = {}) {
1061
2078
  const gateway = new RemoteAgentGateway(input);
2079
+ const workbenchUi = gateway.config.workbench ? new WorkbenchUi(gateway.config.workbench.token) : undefined;
2080
+ const callbackHealth = {};
1062
2081
  const server = http.createServer((req, res) => {
1063
2082
  void (async () => {
1064
2083
  try {
1065
- if (req.method === 'GET' && req.url === '/health')
1066
- return json(res, gateway.sessions.healthy ? 200 : 503, { status: gateway.sessions.healthy ? 'ok' : 'degraded', service: 'a2a-gateway', remotes: Object.keys(gateway.config.remotes), sessionDelivery: gateway.sessions.healthy ? 'ok' : 'storage-unavailable' });
2084
+ if (req.method === 'GET' && req.url === '/health') {
2085
+ const slots = await gateway.capacityReport();
2086
+ return json(res, gateway.sessions.healthy ? 200 : 503, {
2087
+ status: gateway.sessions.healthy ? 'ok' : 'degraded', service: 'a2a-gateway', remotes: Object.keys(gateway.config.remotes),
2088
+ sessionDelivery: gateway.sessions.healthy ? 'ok' : 'storage-unavailable',
2089
+ ...(slots ? { taskSlot: slots.taskSlot, processSlot: slots.processSlot } : {}),
2090
+ sessions: gateway.lifecycleReport(),
2091
+ ...(callbackHealth.state === 'pending' ? { callback: 'pending' } : {})
2092
+ });
2093
+ }
2094
+ const url = new URL(req.url ?? '/', 'http://localhost');
2095
+ const page = url.pathname === WORKBENCH_UI_PATH || url.pathname.startsWith(`${WORKBENCH_UI_PATH}/`);
2096
+ if (page || url.pathname.startsWith('/workbench/')) {
2097
+ if (!gateway.config.workbench || !workbenchUi)
2098
+ return json(res, 503, { error: 'Workbench is not configured' });
2099
+ // The page reaches the same routes as the bearer API once its own login and origin checks pass.
2100
+ let pathname = url.pathname;
2101
+ if (page) {
2102
+ const routed = await workbenchUi.handle(req, res, url);
2103
+ if (!routed)
2104
+ return;
2105
+ pathname = routed.route;
2106
+ }
2107
+ else {
2108
+ if (gateway.config.workbench.token && !authenticated(req, gateway.config.workbench.token))
2109
+ return json(res, 401, { error: 'Unauthorized' });
2110
+ if (req.headers.origin)
2111
+ return json(res, 403, { error: 'Use the authenticated workbench page' });
2112
+ if (req.method === 'POST' && PAGE_ONLY_ROUTES.some(route => route.test(pathname)) && !relayedFromPage(req, gateway.config.workbench.pageRelaySecret)) {
2113
+ return json(res, 403, { error: 'page_action_required', message: '发布、验收决定和继续任务只能由人在工作台页面发起。' });
2114
+ }
2115
+ }
2116
+ if (req.method === 'GET' && pathname === '/workbench/tasks') {
2117
+ const query = z.object({ filter: z.enum(['all', 'pending', 'working', 'failed']).optional(),
2118
+ limit: z.coerce.number().int().min(1).max(200).optional(), offset: z.coerce.number().int().min(0).optional() }).strict().parse(Object.fromEntries(url.searchParams));
2119
+ return json(res, 200, gateway.workbenchList(query));
2120
+ }
2121
+ if (pathname === '/workbench/agents/register-path') {
2122
+ if (req.method !== 'POST')
2123
+ return json(res, 405, { error: 'Method not allowed' });
2124
+ if (url.search)
2125
+ return json(res, 400, { error: 'Invalid workbench parameters' });
2126
+ try {
2127
+ return json(res, 200, await gateway.registerWorkbenchAgentPath(await body(req)));
2128
+ }
2129
+ catch (error) {
2130
+ if (error instanceof AgentRegistryError)
2131
+ return json(res, error.code === 'conflict' ? 409 : 400, { error: error.code, message: error.message });
2132
+ throw error;
2133
+ }
2134
+ }
2135
+ const agentCreate = req.method === 'POST' && pathname === '/workbench/agents';
2136
+ const agentChange = /^\/workbench\/agents\/([^/]+)\/(settings|publish)$/.exec(pathname);
2137
+ if (pathname === '/workbench/agents' || agentChange) {
2138
+ if (url.search)
2139
+ return json(res, 400, { error: 'Invalid workbench parameters' });
2140
+ }
2141
+ if (req.method === 'GET' && pathname === '/workbench/agents')
2142
+ return json(res, 200, gateway.workbenchAgents());
2143
+ if (agentCreate || agentChange) {
2144
+ if (req.method !== 'POST')
2145
+ return json(res, 405, { error: 'Method not allowed' });
2146
+ try {
2147
+ const payload = await body(req);
2148
+ if (agentCreate)
2149
+ return json(res, 200, await gateway.createWorkbenchAgent(payload));
2150
+ const agentId = decodeURIComponent(agentChange[1]), action = agentChange[2];
2151
+ return json(res, 200, await (action === 'publish' ? gateway.publishWorkbenchAgent(agentId, payload) : gateway.updateWorkbenchAgent(agentId, payload)));
2152
+ }
2153
+ catch (error) {
2154
+ if (error instanceof AgentRegistryError) {
2155
+ const status = error.code === 'not_found' ? 404 : error.code === 'conflict' ? 409 : 400;
2156
+ return json(res, status, { error: error.code, message: error.message });
2157
+ }
2158
+ if (error instanceof z.ZodError)
2159
+ return json(res, 400, { error: 'Invalid workbench parameters' });
2160
+ throw error;
2161
+ }
2162
+ }
2163
+ const chat = /^\/workbench\/tasks\/([^/]+)\/chat$/.exec(pathname);
2164
+ if (chat) {
2165
+ if (req.method !== 'GET')
2166
+ return json(res, 405, { error: 'Method not allowed' });
2167
+ const query = z.object({ limit: z.coerce.number().int().min(1).max(200).optional(), before: z.coerce.number().int().min(0).optional() }).strict().parse(Object.fromEntries(url.searchParams));
2168
+ try {
2169
+ return json(res, 200, gateway.workbenchChat(decodeURIComponent(chat[1]), query));
2170
+ }
2171
+ catch (error) {
2172
+ return json(res, 404, { error: error instanceof Error ? error.message : 'Task not found' });
2173
+ }
2174
+ }
2175
+ const artifact = /^\/workbench\/tasks\/([^/]+)\/artifacts\/([a-f0-9]{64})$/.exec(pathname);
2176
+ if (artifact) {
2177
+ if (req.method !== 'GET')
2178
+ return json(res, 405, { error: 'Method not allowed' });
2179
+ if (url.search)
2180
+ return json(res, 404, { error: 'No workbench route' });
2181
+ try {
2182
+ const file = await gateway.workbenchArtifact(decodeURIComponent(artifact[1]), artifact[2]);
2183
+ // Agent-written bytes: never sniffed, and a sandboxed document with no script or network even when opened directly.
2184
+ res.writeHead(200, { 'Content-Type': artifactContentType(file.name, file.mediaType), 'Content-Length': file.content.length,
2185
+ 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, max-age=3600',
2186
+ 'Content-Disposition': `inline; filename*=UTF-8''${encodeURIComponent(file.name)}`,
2187
+ 'Content-Security-Policy': "sandbox; default-src 'none'; img-src 'self' data:; media-src 'self'; style-src 'unsafe-inline'; frame-ancestors 'self'" });
2188
+ return void res.end(file.content);
2189
+ }
2190
+ catch (error) {
2191
+ if (error instanceof WorkbenchArtifactError)
2192
+ return json(res, error.status, { error: error.code });
2193
+ return json(res, 404, { error: error instanceof Error ? error.message : 'Task not found' });
2194
+ }
2195
+ }
2196
+ if (url.search)
2197
+ return json(res, 404, { error: 'No workbench route' });
2198
+ const route = /^\/workbench\/tasks\/([^/]+)(.*)$/.exec(pathname);
2199
+ if (!route)
2200
+ return json(res, 404, { error: 'No workbench route' });
2201
+ const jobId = decodeURIComponent(route[1]), rest = route[2] ?? '';
2202
+ // Only the DSH host opens process requests; the page can read and answer them.
2203
+ if (page && rest === '/process-requests')
2204
+ return json(res, 403, { error: 'browser_action_required', message: 'Process requests are opened by the execution host.' });
2205
+ const review = /^\/reviews\/([^/]+)\/decisions$/.exec(rest);
2206
+ const answer = /^\/process-requests\/([^/]+)\/answers$/.exec(rest);
2207
+ const one = /^\/process-requests\/([^/]+)$/.exec(rest);
2208
+ try {
2209
+ if (rest === '' && req.method === 'GET')
2210
+ return json(res, 200, gateway.workbenchTask(jobId));
2211
+ if (rest === '/refresh' && req.method === 'POST')
2212
+ return json(res, 200, await gateway.refreshWorkbenchTask(jobId));
2213
+ if (rest === '/continue' && req.method === 'POST') {
2214
+ const { prompt } = workbenchContinueSchema.parse(await body(req));
2215
+ gateway.workbenchTask(jobId);
2216
+ try {
2217
+ return json(res, 200, await gateway.continueWorkbenchTask(jobId, prompt));
2218
+ }
2219
+ catch (error) {
2220
+ return json(res, 409, { error: 'continue_refused', message: error instanceof Error ? error.message : String(error) });
2221
+ }
2222
+ }
2223
+ if (rest === '/acceptance' && req.method === 'POST') {
2224
+ const { note } = workbenchAcceptSchema.parse(await body(req));
2225
+ gateway.workbenchTask(jobId);
2226
+ try {
2227
+ return json(res, 200, gateway.acceptWorkbenchTask(jobId, note));
2228
+ }
2229
+ catch (error) {
2230
+ return json(res, 409, { error: 'accept_refused', message: error instanceof Error ? error.message : String(error) });
2231
+ }
2232
+ }
2233
+ if (review && req.method === 'POST')
2234
+ return json(res, 200, await gateway.decideWorkbenchReview(jobId, decodeURIComponent(review[1]), await body(req)));
2235
+ if (rest === '/process-requests' && req.method === 'POST')
2236
+ return json(res, 200, await gateway.openProcessRequest(jobId, await body(req)));
2237
+ // The page, here or relayed by its host, always answers as a person; only the gateway's own callers name a coach.
2238
+ if (answer && req.method === 'POST') {
2239
+ const input = await body(req), asPerson = page || relayedFromPage(req, gateway.config.workbench.pageRelaySecret);
2240
+ return json(res, 200, await gateway.answerProcessRequest(jobId, decodeURIComponent(answer[1]), asPerson ? { ...input, decidedBy: { kind: 'person' } } : input));
2241
+ }
2242
+ if (one && req.method === 'GET')
2243
+ return json(res, 200, gateway.processRequest(jobId, decodeURIComponent(one[1])));
2244
+ if (rest === '' || rest === '/refresh' || rest === '/continue' || rest === '/acceptance' || review || answer || one || rest === '/process-requests')
2245
+ return json(res, 405, { error: 'Method not allowed' });
2246
+ return json(res, 404, { error: 'No workbench route' });
2247
+ }
2248
+ catch (error) {
2249
+ if (error instanceof HumanReviewError)
2250
+ return json(res, error.code === 'forbidden' ? 403 : 409, { error: error.code, message: error.message });
2251
+ if (error instanceof ProcessRequestError) {
2252
+ const status = error.code === 'forbidden' ? 403 : error.code === 'not_found' ? 404 : error.code === 'invalid' ? 400 : 409;
2253
+ return json(res, status, { error: error.code, message: error.message });
2254
+ }
2255
+ if (error instanceof z.ZodError)
2256
+ return json(res, 400, { error: 'Invalid workbench parameters' });
2257
+ return json(res, 404, { error: error instanceof Error ? error.message : 'Task not found' });
2258
+ }
2259
+ }
1067
2260
  if (req.method !== 'POST' || req.url !== '/invoke')
1068
2261
  return json(res, 404, { error: 'No route' });
1069
2262
  // Local tools are trusted. The separate tailnet receiver below never exposes /invoke.
@@ -1077,31 +2270,71 @@ export async function serveA2AGateway(input, options = {}) {
1077
2270
  }
1078
2271
  })();
1079
2272
  });
1080
- let receiver;
2273
+ const callbackServers = new Set();
2274
+ const callbackAbort = new AbortController();
1081
2275
  let callbackPort;
1082
2276
  let automationServer;
1083
2277
  let automationPort;
2278
+ const callbackHandler = gateway.config.callback ? (req, res) => {
2279
+ void (async () => {
2280
+ const callback = gateway.config.callback;
2281
+ if (!authenticated(req, callback.token))
2282
+ return json(res, 401, { error: 'Unauthorized' });
2283
+ if (req.method !== 'POST' || req.url !== new URL(callback.url).pathname)
2284
+ return json(res, 404, { error: 'No route' });
2285
+ try {
2286
+ const event = await body(req);
2287
+ json(res, 202, { accepted: true });
2288
+ void gateway.receivePush(event).catch(() => { });
2289
+ }
2290
+ catch {
2291
+ json(res, 400, { error: 'Invalid A2A event' });
2292
+ }
2293
+ })();
2294
+ } : undefined;
2295
+ const bindCallback = async () => {
2296
+ if (!gateway.config.callback || !callbackHandler)
2297
+ return;
2298
+ if (callbackAbort.signal.aborted)
2299
+ throw callbackAbort.signal.reason ?? new Error('callback stopped');
2300
+ const receiver = http.createServer(callbackHandler);
2301
+ callbackServers.add(receiver);
2302
+ try {
2303
+ callbackPort = await listen(receiver, gateway.config.callback.port, gateway.config.callback.host);
2304
+ if (callbackAbort.signal.aborted) {
2305
+ await stop(receiver);
2306
+ throw callbackAbort.signal.reason ?? new Error('callback stopped');
2307
+ }
2308
+ callbackHealth.state = 'listening';
2309
+ }
2310
+ catch (error) {
2311
+ callbackServers.delete(receiver);
2312
+ receiver.close(() => { });
2313
+ throw error;
2314
+ }
2315
+ };
1084
2316
  try {
1085
2317
  const port = await listen(server, gateway.config.port, '127.0.0.1');
1086
2318
  if (gateway.config.callback) {
1087
2319
  const callback = gateway.config.callback;
1088
- receiver = http.createServer((req, res) => {
1089
- void (async () => {
1090
- if (!authenticated(req, callback.token))
1091
- return json(res, 401, { error: 'Unauthorized' });
1092
- if (req.method !== 'POST' || req.url !== new URL(callback.url).pathname)
1093
- return json(res, 404, { error: 'No route' });
1094
- try {
1095
- const event = await body(req);
1096
- json(res, 202, { accepted: true });
1097
- void gateway.receivePush(event).catch(() => { });
1098
- }
1099
- catch {
1100
- json(res, 400, { error: 'Invalid A2A event' });
1101
- }
1102
- })();
1103
- });
1104
- callbackPort = await listen(receiver, callback.port, callback.host);
2320
+ try {
2321
+ await bindCallback();
2322
+ }
2323
+ catch (error) {
2324
+ if (!isRetryableCallbackBindError(error))
2325
+ throw error;
2326
+ callbackHealth.state = 'pending';
2327
+ console.error(`[a2a-gateway] ${new Date().toISOString()} callback listen pending: ${callback.host}:${callback.port} ${error instanceof Error ? error.message : String(error)}`);
2328
+ void retryCallbackBind({
2329
+ bind: bindCallback,
2330
+ signal: callbackAbort.signal,
2331
+ onPending: (cause, at) => console.error(`[a2a-gateway] ${at} callback listen pending: ${callback.host}:${callback.port} ${cause instanceof Error ? cause.message : String(cause)}`),
2332
+ }).catch(cause => {
2333
+ if (callbackAbort.signal.aborted)
2334
+ return;
2335
+ console.error(`[a2a-gateway] ${new Date().toISOString()} callback listen failed: ${cause instanceof Error ? cause.message : String(cause)}`);
2336
+ });
2337
+ }
1105
2338
  }
1106
2339
  if (gateway.config.automation && gateway.automation) {
1107
2340
  automationServer = createAutomationServer(gateway.automation);
@@ -1109,27 +2342,43 @@ export async function serveA2AGateway(input, options = {}) {
1109
2342
  }
1110
2343
  const entry = { id: 'a2a-gateway', name: 'DSH 远端智能体', kind: 'agent_runtime',
1111
2344
  capabilities: Object.keys(REMOTE_AGENT_METHODS), execution: 'http', port, reachability: 'localhost', health: '/health', methods: REMOTE_AGENT_METHODS,
1112
- metadata: { local_only_methods: Object.keys(TARGET_METHODS) } };
2345
+ metadata: { local_only_methods: [...Object.keys(TARGET_METHODS), ...Object.keys(DISCOVERY_METHODS)] } };
2346
+ const contractViolations = methodContractViolations(REMOTE_AGENT_METHODS);
2347
+ if (contractViolations.length)
2348
+ console.error(`[a2a-gateway] DreamMate registration contract violated: ${contractViolations.join('; ')}`);
1113
2349
  const registration = options.report === false ? undefined : await reportAndHoldRegistration(entry);
2350
+ if (registration && !registration.ok)
2351
+ console.error(`[a2a-gateway] DreamMate registration failed: ${registration.reason ?? 'unknown reason'}`);
1114
2352
  // Node's directory is ephemeral. Re-report after a Node restart; this never registers new execution targets.
1115
- const reporting = options.report === false ? undefined : setInterval(() => { void reportToAgent(entry).catch(() => { }); }, 15_000);
2353
+ const reporting = options.report === false ? undefined : setInterval(() => {
2354
+ void reportToAgent(entry).then(result => {
2355
+ if (!result.ok)
2356
+ console.error(`[a2a-gateway] DreamMate re-registration failed: ${result.reason ?? 'unknown reason'}`);
2357
+ }).catch(error => {
2358
+ console.error(`[a2a-gateway] DreamMate re-registration error: ${error instanceof Error ? error.message : String(error)}`);
2359
+ });
2360
+ }, 15_000);
1116
2361
  reporting?.unref();
1117
2362
  let closing;
1118
2363
  return { gateway, port, callbackPort, automationPort, registration, close: async () => {
1119
2364
  closing ??= (async () => {
1120
2365
  if (reporting)
1121
2366
  clearInterval(reporting);
2367
+ callbackAbort.abort();
2368
+ // Stop the Reader before draining HTTP requests that may be awaiting a scan.
2369
+ await gateway.projectDiscovery?.close();
1122
2370
  // Stop accepting requests and drain their ledger writes while this instance
1123
2371
  // still owns the storage lease. Automation continuations and its admission
1124
2372
  // queue can outlive the gateway operation they awaited.
1125
- await Promise.all([stop(server), ...(receiver ? [stop(receiver)] : []), ...(automationServer ? [stop(automationServer)] : [])]);
2373
+ await Promise.all([stop(server), ...[...callbackServers].map(item => stop(item)), ...(automationServer ? [stop(automationServer)] : [])]);
1126
2374
  await gateway.close();
1127
2375
  })();
1128
2376
  await closing;
1129
2377
  } };
1130
2378
  }
1131
2379
  catch (error) {
1132
- await Promise.all([stop(server), ...(receiver ? [stop(receiver)] : []), ...(automationServer ? [stop(automationServer)] : [])]);
2380
+ callbackAbort.abort();
2381
+ await Promise.all([stop(server), ...[...callbackServers].map(item => stop(item)), ...(automationServer ? [stop(automationServer)] : [])]);
1133
2382
  await gateway.close();
1134
2383
  throw error;
1135
2384
  }