@1agents/acp-service 0.9.0 → 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 (266) hide show
  1. package/README.md +19 -13
  2. package/dist/bin/a2a.js +6 -2
  3. package/dist/bin/acp-service.js +24 -0
  4. package/dist/bin/process.d.ts +4 -0
  5. package/dist/bin/process.js +57 -0
  6. package/dist/bin/rsi.d.ts +3 -0
  7. package/dist/bin/rsi.js +114 -0
  8. package/dist/bin/ticket.d.ts +13 -0
  9. package/dist/bin/ticket.js +97 -0
  10. package/dist/bin/trail.d.ts +4 -0
  11. package/dist/bin/trail.js +62 -0
  12. package/dist/src/a2a/artifact-content.d.ts +9 -0
  13. package/dist/src/a2a/artifact-content.js +45 -0
  14. package/dist/src/a2a/desktop-notify.d.ts +1 -0
  15. package/dist/src/a2a/desktop-notify.js +12 -0
  16. package/dist/src/a2a/execution-binding.d.ts +9 -0
  17. package/dist/src/a2a/execution-binding.js +19 -0
  18. package/dist/src/a2a/executor.d.ts +6 -0
  19. package/dist/src/a2a/executor.js +112 -12
  20. package/dist/src/a2a/gateway.d.ts +537 -2
  21. package/dist/src/a2a/gateway.js +1014 -87
  22. package/dist/src/a2a/index.d.ts +8 -1
  23. package/dist/src/a2a/index.js +4 -0
  24. package/dist/src/a2a/job-directory.d.ts +6 -0
  25. package/dist/src/a2a/job-directory.js +19 -0
  26. package/dist/src/a2a/preflight.js +16 -1
  27. package/dist/src/a2a/resubmit.d.ts +46 -0
  28. package/dist/src/a2a/resubmit.js +82 -0
  29. package/dist/src/a2a/result-metadata.d.ts +3 -0
  30. package/dist/src/a2a/result-metadata.js +23 -5
  31. package/dist/src/a2a/server.d.ts +10 -0
  32. package/dist/src/a2a/server.js +125 -1
  33. package/dist/src/a2a/session-lifecycle.d.ts +40 -0
  34. package/dist/src/a2a/session-lifecycle.js +54 -0
  35. package/dist/src/a2a/store.d.ts +4 -0
  36. package/dist/src/a2a/store.js +70 -1
  37. package/dist/src/a2a/types.d.ts +45 -0
  38. package/dist/src/a2a/workbench-ui.d.ts +28 -0
  39. package/dist/src/a2a/workbench-ui.js +182 -0
  40. package/dist/src/acp-connection.js +27 -3
  41. package/dist/src/bridge.d.ts +1 -0
  42. package/dist/src/bridge.js +191 -39
  43. package/dist/src/capacity-queue.d.ts +35 -0
  44. package/dist/src/capacity-queue.js +139 -2
  45. package/dist/src/capacity.d.ts +25 -0
  46. package/dist/src/capacity.js +48 -9
  47. package/dist/src/dsh.js +1 -1
  48. package/dist/src/execution/agent-files.d.ts +25 -0
  49. package/dist/src/execution/agent-files.js +90 -0
  50. package/dist/src/execution/agent-registry.d.ts +164 -0
  51. package/dist/src/execution/agent-registry.js +275 -0
  52. package/dist/src/execution/human-review.d.ts +2 -0
  53. package/dist/src/execution/human-review.js +3 -1
  54. package/dist/src/execution/ledger.d.ts +52 -0
  55. package/dist/src/execution/ledger.js +83 -5
  56. package/dist/src/execution/process-request.d.ts +151 -0
  57. package/dist/src/execution/process-request.js +177 -0
  58. package/dist/src/execution/targets.d.ts +15 -0
  59. package/dist/src/execution/targets.js +22 -3
  60. package/dist/src/execution/ticket-executor.d.ts +25 -0
  61. package/dist/src/execution/ticket-executor.js +27 -0
  62. package/dist/src/execution/ticket.d.ts +326 -0
  63. package/dist/src/execution/ticket.js +301 -0
  64. package/dist/src/execution/workbench-chat.d.ts +25 -0
  65. package/dist/src/execution/workbench-chat.js +54 -0
  66. package/dist/src/execution/workbench.d.ts +32 -1
  67. package/dist/src/execution/workbench.js +113 -22
  68. package/dist/src/rsi/gate.d.ts +25 -0
  69. package/dist/src/rsi/gate.js +59 -0
  70. package/dist/src/rsi/outline-run.d.ts +107 -0
  71. package/dist/src/rsi/outline-run.js +443 -0
  72. package/dist/workbench-ui/app.css +453 -0
  73. package/dist/workbench-ui/app.js +13 -0
  74. package/dist/workbench-ui/chunk-23JHGYT3.js +1 -0
  75. package/dist/workbench-ui/chunk-3H6STGPV.js +1 -0
  76. package/dist/workbench-ui/chunk-3SNBBMGH.js +1 -0
  77. package/dist/workbench-ui/chunk-3XJZ6DIE.js +1 -0
  78. package/dist/workbench-ui/chunk-44KDLLKJ.js +1 -0
  79. package/dist/workbench-ui/chunk-46H7FU5Y.js +7 -0
  80. package/dist/workbench-ui/chunk-4N44QPL7.js +1 -0
  81. package/dist/workbench-ui/chunk-4YN4BS7I.js +1 -0
  82. package/dist/workbench-ui/chunk-53EG4IVQ.js +96 -0
  83. package/dist/workbench-ui/chunk-5FIPUNR4.js +1 -0
  84. package/dist/workbench-ui/chunk-6DWWYA6G.js +2 -0
  85. package/dist/workbench-ui/chunk-6FU3T633.js +99 -0
  86. package/dist/workbench-ui/chunk-6XKIHRA4.js +1 -0
  87. package/dist/workbench-ui/chunk-7GIX43Y5.js +1 -0
  88. package/dist/workbench-ui/chunk-7Q4WBGX6.js +4 -0
  89. package/dist/workbench-ui/chunk-A3BQM7HR.js +1 -0
  90. package/dist/workbench-ui/chunk-AFCFDDOP.js +24 -0
  91. package/dist/workbench-ui/chunk-AG67EUYD.js +89 -0
  92. package/dist/workbench-ui/chunk-AGJHMMTN.js +1 -0
  93. package/dist/workbench-ui/chunk-AO6JUBV6.js +41 -0
  94. package/dist/workbench-ui/chunk-AUSLTP43.js +72 -0
  95. package/dist/workbench-ui/chunk-AVZL46TT.js +1 -0
  96. package/dist/workbench-ui/chunk-AZRIGIV2.js +168 -0
  97. package/dist/workbench-ui/chunk-B2LIVH37.js +1 -0
  98. package/dist/workbench-ui/chunk-B7YX5TR5.js +1 -0
  99. package/dist/workbench-ui/chunk-BCB4X4XX.js +1 -0
  100. package/dist/workbench-ui/chunk-BCRQUL2A.js +88 -0
  101. package/dist/workbench-ui/chunk-BI6UHHQP.js +1 -0
  102. package/dist/workbench-ui/chunk-BLSLQ4AQ.js +120 -0
  103. package/dist/workbench-ui/chunk-C3QSRS6E.js +1 -0
  104. package/dist/workbench-ui/chunk-CK7M2PJ3.js +62 -0
  105. package/dist/workbench-ui/chunk-CM6LZ7TU.js +1 -0
  106. package/dist/workbench-ui/chunk-CP63H27F.js +36 -0
  107. package/dist/workbench-ui/chunk-CPUMMIS2.js +70 -0
  108. package/dist/workbench-ui/chunk-CSEIBI5U.js +2 -0
  109. package/dist/workbench-ui/chunk-CUS65DKZ.js +161 -0
  110. package/dist/workbench-ui/chunk-CVQY7TNC.js +1 -0
  111. package/dist/workbench-ui/chunk-D6S3XBIX.js +106 -0
  112. package/dist/workbench-ui/chunk-E253Y562.js +1 -0
  113. package/dist/workbench-ui/chunk-EADDJUDC.js +1 -0
  114. package/dist/workbench-ui/chunk-EBGJ3YXG.js +206 -0
  115. package/dist/workbench-ui/chunk-EKPVZ3WY.js +8 -0
  116. package/dist/workbench-ui/chunk-EQDCEAFY.js +1 -0
  117. package/dist/workbench-ui/chunk-ES3SSDJY.js +40 -0
  118. package/dist/workbench-ui/chunk-ESFD2H7N.js +231 -0
  119. package/dist/workbench-ui/chunk-FVOHPMS6.js +1 -0
  120. package/dist/workbench-ui/chunk-FXMQAGVT.js +1 -0
  121. package/dist/workbench-ui/chunk-GGTADRXD.js +24 -0
  122. package/dist/workbench-ui/chunk-GHIVPGNQ.js +1 -0
  123. package/dist/workbench-ui/chunk-GLU2YQV2.js +1 -0
  124. package/dist/workbench-ui/chunk-GOCKBYSM.js +1 -0
  125. package/dist/workbench-ui/chunk-H2KMMTJB.js +1 -0
  126. package/dist/workbench-ui/chunk-HGVLDNPP.js +39 -0
  127. package/dist/workbench-ui/chunk-HSAVC5GY.js +1 -0
  128. package/dist/workbench-ui/chunk-HSEAD2JH.js +1 -0
  129. package/dist/workbench-ui/chunk-HSIHOBTY.js +1 -0
  130. package/dist/workbench-ui/chunk-IZXOKUGG.js +67 -0
  131. package/dist/workbench-ui/chunk-JFT2LC2T.js +1 -0
  132. package/dist/workbench-ui/chunk-JHL3ZDYK.js +3 -0
  133. package/dist/workbench-ui/chunk-JMORLCZG.js +257 -0
  134. package/dist/workbench-ui/chunk-JR4SIX7A.js +1 -0
  135. package/dist/workbench-ui/chunk-K23HAGEH.js +30 -0
  136. package/dist/workbench-ui/chunk-K43JDCBH.js +1 -0
  137. package/dist/workbench-ui/chunk-KINKFJY7.js +1 -0
  138. package/dist/workbench-ui/chunk-KKQSA4LI.js +2 -0
  139. package/dist/workbench-ui/chunk-KOUZX3UX.js +1 -0
  140. package/dist/workbench-ui/chunk-KR4DRHW2.js +78 -0
  141. package/dist/workbench-ui/chunk-KT4DJNOR.js +1 -0
  142. package/dist/workbench-ui/chunk-KTPNKRRZ.js +292 -0
  143. package/dist/workbench-ui/chunk-LFHIPGSU.js +7 -0
  144. package/dist/workbench-ui/chunk-LWDL4HZB.js +125 -0
  145. package/dist/workbench-ui/chunk-MVYC3CY4.js +1 -0
  146. package/dist/workbench-ui/chunk-NWUPALCY.js +129 -0
  147. package/dist/workbench-ui/chunk-NY7C662Z.js +1 -0
  148. package/dist/workbench-ui/chunk-O76WTHWP.js +1 -0
  149. package/dist/workbench-ui/chunk-OTF7YHRE.js +162 -0
  150. package/dist/workbench-ui/chunk-P6TKKRKP.js +1 -0
  151. package/dist/workbench-ui/chunk-PFHOOWV3.js +1 -0
  152. package/dist/workbench-ui/chunk-PUQLANIM.js +1 -0
  153. package/dist/workbench-ui/chunk-PZCGBYVO.js +1 -0
  154. package/dist/workbench-ui/chunk-QOHUZGP4.js +1 -0
  155. package/dist/workbench-ui/chunk-QSEG3OFF.js +1 -0
  156. package/dist/workbench-ui/chunk-QYPOXZIA.js +84 -0
  157. package/dist/workbench-ui/chunk-R6SOF3JC.js +1 -0
  158. package/dist/workbench-ui/chunk-RCLOYU5F.js +1 -0
  159. package/dist/workbench-ui/chunk-RSRUP64S.js +1 -0
  160. package/dist/workbench-ui/chunk-RVAIT6JW.js +1 -0
  161. package/dist/workbench-ui/chunk-S2CCN3II.js +1 -0
  162. package/dist/workbench-ui/chunk-S2Q52W46.js +1 -0
  163. package/dist/workbench-ui/chunk-S2W5THJ5.js +1 -0
  164. package/dist/workbench-ui/chunk-S6ZQZNOX.js +1 -0
  165. package/dist/workbench-ui/chunk-S74PLMMS.js +1 -0
  166. package/dist/workbench-ui/chunk-S7C4HKEY.js +1 -0
  167. package/dist/workbench-ui/chunk-SDTB3Q65.js +1 -0
  168. package/dist/workbench-ui/chunk-SLPRGYUV.js +32 -0
  169. package/dist/workbench-ui/chunk-SQE76S5B.js +1 -0
  170. package/dist/workbench-ui/chunk-SSDZPVPW.js +1 -0
  171. package/dist/workbench-ui/chunk-SVI7DGIE.js +1 -0
  172. package/dist/workbench-ui/chunk-T6QKLZ4H.js +62 -0
  173. package/dist/workbench-ui/chunk-TJNRPTFL.js +1 -0
  174. package/dist/workbench-ui/chunk-TP6U4EDH.js +2 -0
  175. package/dist/workbench-ui/chunk-TYAAT3GQ.js +1 -0
  176. package/dist/workbench-ui/chunk-U6OCY4ZH.js +1 -0
  177. package/dist/workbench-ui/chunk-UAN3NLRF.js +1 -0
  178. package/dist/workbench-ui/chunk-UMLU3FIX.js +1 -0
  179. package/dist/workbench-ui/chunk-URIY2OTM.js +1 -0
  180. package/dist/workbench-ui/chunk-V2NUKAA7.js +38 -0
  181. package/dist/workbench-ui/chunk-V4QLL4TE.js +139 -0
  182. package/dist/workbench-ui/chunk-VASHXUK4.js +2 -0
  183. package/dist/workbench-ui/chunk-VJLIWNIU.js +1 -0
  184. package/dist/workbench-ui/chunk-VQNQFBID.js +1 -0
  185. package/dist/workbench-ui/chunk-VSIWU7XA.js +3 -0
  186. package/dist/workbench-ui/chunk-VSJASPUZ.js +321 -0
  187. package/dist/workbench-ui/chunk-VXPNUNUX.js +3 -0
  188. package/dist/workbench-ui/chunk-WBKLDCV6.js +1 -0
  189. package/dist/workbench-ui/chunk-WOKJM3FY.js +1 -0
  190. package/dist/workbench-ui/chunk-X3U3NA3X.js +34 -0
  191. package/dist/workbench-ui/chunk-XBYU7M4J.js +1 -0
  192. package/dist/workbench-ui/chunk-XBZAO4ID.js +10 -0
  193. package/dist/workbench-ui/chunk-XLLPZ2WO.js +1 -0
  194. package/dist/workbench-ui/chunk-YFVL4NJL.js +1 -0
  195. package/dist/workbench-ui/chunk-YRFQENM4.js +1 -0
  196. package/dist/workbench-ui/chunk-YUADQVB2.js +1 -0
  197. package/dist/workbench-ui/chunk-Z3TCAKM5.js +1 -0
  198. package/dist/workbench-ui/chunk-Z6QR6FRE.js +10 -0
  199. package/dist/workbench-ui/chunk-ZJPSORPP.js +3 -0
  200. package/dist/workbench-ui/chunk-ZLGCSTR2.js +15 -0
  201. package/dist/workbench-ui/chunk-ZLR4SG5X.js +1 -0
  202. package/dist/workbench-ui/chunk-ZND3TTGF.js +1 -0
  203. package/dist/workbench-ui/chunk-ZOP3ZYH7.js +2 -0
  204. package/dist/workbench-ui/index.html +14 -0
  205. package/package.json +19 -8
  206. package/skills/acp-service/SKILL.md +3 -1
  207. package/skills/acp-service/references/a2a.md +17 -5
  208. package/skills/acp-service/references/dsh.md +2 -0
  209. package/skills/acp-service/references/roles-and-tasks.md +1 -1
  210. package/skills/rsi-coach/SKILL.md +134 -0
  211. package/vendor/dsh/README.md +10 -6
  212. package/vendor/dsh/a2a-executor.d.ts +56 -2
  213. package/vendor/dsh/a2a-executor.js +163 -17
  214. package/vendor/dsh/a2a.d.ts +12 -2
  215. package/vendor/dsh/a2a.js +9 -2
  216. package/vendor/dsh/adapter.d.ts +52 -3
  217. package/vendor/dsh/adapter.js +297 -30
  218. package/vendor/dsh/client.js +67 -11
  219. package/vendor/dsh/index.js +55 -3
  220. package/vendor/dsh/native-approvals.d.ts +4 -0
  221. package/vendor/dsh/native-approvals.js +44 -0
  222. package/vendor/dsh/preset-route.d.ts +49 -0
  223. package/vendor/dsh/preset-route.js +51 -0
  224. package/vendor/dsh/preset.js +10 -3
  225. package/vendor/dsh/process-admission.d.ts +25 -0
  226. package/vendor/dsh/process-admission.js +87 -0
  227. package/vendor/dsh/process-requests.d.ts +57 -0
  228. package/vendor/dsh/process-requests.js +49 -0
  229. package/vendor/dsh/review-mcp.d.ts +1 -0
  230. package/vendor/dsh/review-mcp.js +56 -0
  231. package/vendor/dsh/review.d.ts +30 -0
  232. package/vendor/dsh/review.js +149 -0
  233. package/vendor/dsh/session-settings.d.ts +34 -0
  234. package/vendor/dsh/session-settings.js +114 -0
  235. package/vendor/dsh/ticket-spec.d.ts +30 -0
  236. package/vendor/dsh/ticket-spec.js +10 -0
  237. package/vendor/dsh/ticket-tools.d.ts +21 -0
  238. package/vendor/dsh/ticket-tools.js +43 -0
  239. package/vendor/dsh/workbench.d.ts +18 -0
  240. package/vendor/dsh/workbench.js +91 -0
  241. package/vendor/runtime/README.md +6 -4
  242. package/vendor/runtime/dist/docs-site/CLI.html +2 -2
  243. package/vendor/runtime/dist/docs-site/VISION.html +2 -2
  244. package/vendor/runtime/dist/docs-site/agents.html +2 -2
  245. package/vendor/runtime/dist/docs-site/compare.html +2 -2
  246. package/vendor/runtime/dist/docs-site/config.html +2 -2
  247. package/vendor/runtime/dist/docs-site/custom-agents.html +2 -2
  248. package/vendor/runtime/dist/docs-site/exit-codes.html +2 -2
  249. package/vendor/runtime/dist/docs-site/flows.html +2 -2
  250. package/vendor/runtime/dist/docs-site/index.html +1 -1
  251. package/vendor/runtime/dist/docs-site/install.html +2 -2
  252. package/vendor/runtime/dist/docs-site/llms.txt +1 -1
  253. package/vendor/runtime/dist/docs-site/output-formats.html +2 -2
  254. package/vendor/runtime/dist/docs-site/permissions.html +2 -2
  255. package/vendor/runtime/dist/docs-site/prompting.html +2 -2
  256. package/vendor/runtime/dist/docs-site/quickstart.html +2 -2
  257. package/vendor/runtime/dist/docs-site/releasing.html +2 -2
  258. package/vendor/runtime/dist/docs-site/runtime-environment.html +2 -2
  259. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +2 -2
  260. package/vendor/runtime/dist/docs-site/safe-errors.html +2 -2
  261. package/vendor/runtime/dist/docs-site/session-control.html +2 -2
  262. package/vendor/runtime/dist/docs-site/session-watch.html +2 -2
  263. package/vendor/runtime/dist/docs-site/sessions.html +2 -2
  264. package/vendor/runtime/dist/docs-site/shared-sessions.html +2 -2
  265. package/vendor/runtime/package.json +6 -4
  266. package/vendor/runtime/skills/acpx/SKILL.md +2 -0
@@ -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,12 +15,24 @@ 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';
18
26
  import { ProjectRoleDiscovery, DISCOVERY_METHODS, projectDiscoveryConfigSchema } from '../execution/project-discovery.js';
19
27
  import { deliveryProgress, deliveryException } from '../execution/delivery-progress.js';
20
28
  import { JobLedger } from '../execution/ledger.js';
29
+ import { invokeTicket, reopenForContinue, TICKET_METHODS } from '../execution/ticket.js';
21
30
  import { decideHumanReview, HumanReviewError, humanReviewDecisionSchema } from '../execution/human-review.js';
22
- import { workbenchSnapshot, listWorkbenchTasks, getWorkbenchTask } from '../execution/workbench.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';
23
36
  import { createPptDeliveryRun, recoverPptDeliveryRun, assertPptDeliveryRecoverable, advancePptDelivery, pptDeliveryInputSchema, pptDeliveryPolicySchema, pptDeliveryRecoveryInputSchema, scriptDirectory, scriptRevisionName } from '../execution/ppt-delivery.js';
24
37
  import { advanceReportReview, createReportReviewRun, reportBindingDigest, reportRevision, reportReviewInputSchema, reportReviewPolicySchema } from '../execution/report-review.js';
25
38
  const string = z.string().trim().min(1).max(512);
@@ -39,12 +52,28 @@ const configSchema = z.object({
39
52
  pollIntervalMs: z.number().int().min(50).max(60_000).default(3000),
40
53
  pptDelivery: pptDeliveryPolicySchema.optional(),
41
54
  reportReview: reportReviewPolicySchema.optional(),
42
- workbench: z.object({ token: string, reviewerId: string.default('local-owner'), reviewerName: string.optional(), publicBaseUrl: endpoint.optional(),
43
- allowedOrigins: z.array(string).optional() }).strict().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 }),
44
73
  }).strict().superRefine((config, ctx) => {
45
74
  const machineTokens = [...Object.values(config.remotes).map(remote => remote.token), config.callback?.token,
46
75
  ...Object.values(config.notificationTargets).map(target => target.token), config.automation?.token];
47
- if (config.workbench && machineTokens.includes(config.workbench.token)) {
76
+ if (config.workbench?.token && machineTokens.includes(config.workbench.token)) {
48
77
  ctx.addIssue({ code: 'custom', path: ['workbench', 'token'], message: 'Workbench requires a separate credential from agent remotes' });
49
78
  }
50
79
  for (const [id, schedule] of Object.entries(config.automation?.schedules ?? {})) {
@@ -55,6 +84,8 @@ const configSchema = z.object({
55
84
  }
56
85
  });
57
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();
58
89
  const taskFields = { ...originFields, remote: string, taskId: string };
59
90
  const prompt = z.string().min(1).max(256 * 1024).refine(value => Boolean(value.trim()), 'Prompt must contain text');
60
91
  const spawnSchema = z.object({ ...originFields, remote: string, prompt,
@@ -62,26 +93,36 @@ const spawnSchema = z.object({ ...originFields, remote: string, prompt,
62
93
  agentPreset: string.optional(), notificationTarget: string.optional(), title: string.optional(),
63
94
  roleId: string.optional(), roleLockPath: string.refine(path.isAbsolute).optional(),
64
95
  preflight: a2aPreflightRequirementsSchema.optional(), resultContract: a2aResultContractSchema.optional(),
65
- clientRequestId: string.optional(),
96
+ clientRequestId: string.optional(), lifecycle: sessionLifecycleSchema.optional(),
97
+ provider: string.optional(), model: string.optional(), initiatedBy: actorSchema.optional(),
66
98
  }).strict();
67
99
  const preflightSchema = a2aPreflightInputSchema.extend({ ...originFields, remote: string }).strict();
68
100
  const taskSchema = z.object(taskFields).strict();
69
- const messageSchema = z.object({ ...taskFields, prompt, clientRequestId: string.optional(), roleId: string.optional(), roleLockPath: string.refine(path.isAbsolute).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();
70
104
  const inboxSchema = z.object(originFields).strict();
71
105
  const ackSchema = z.object({ ...originFields, noticeId: string }).strict();
72
106
  const executionSubmitSchema = z.object({ ...originFields, targetId: string, input: z.record(z.string(), z.unknown()),
73
107
  clientRequestId: string.optional(), title: string.optional(), parentJobRef: z.object({ sourceId: string, jobId: string }).strict().optional(),
74
108
  parentAttemptId: string.optional(), purpose: string.optional(), resultRevision: string.optional(),
75
- replacesJobRef: z.object({ sourceId: string, jobId: string }).strict().optional() }).strict();
109
+ replacesJobRef: z.object({ sourceId: string, jobId: string }).strict().optional(), initiatedBy: actorSchema.optional() }).strict();
76
110
  const executionJobSchema = z.object({ ...originFields, jobId: string }).strict();
77
111
  const executionCancelSchema = executionJobSchema.extend({ cascade: z.boolean().optional() }).strict();
78
112
  const executionListSchema = z.object({ ...originFields, targetId: string.optional(), executionStatus: string.optional(),
79
113
  limit: z.number().int().min(1).max(200).default(50), offset: z.number().int().min(0).default(0) }).strict();
80
- 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();
81
115
  const executionEventsSchema = z.object({ ...originFields, jobId: string.optional(), afterSequence: z.number().int().nonnegative().optional(),
82
116
  limit: z.number().int().min(1).max(500).default(100) }).strict();
83
117
  const executionReviewSchema = executionJobSchema.extend({ attemptId: string, resultRevision: string, resultDigest: string,
84
- 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();
85
126
  const EXECUTION_METHODS = {
86
127
  ...TARGET_METHODS,
87
128
  ...DISCOVERY_METHODS,
@@ -91,17 +132,24 @@ const EXECUTION_METHODS = {
91
132
  execution_get: { description: '读取任务、执行轮次、父子关系、交付阶段进度、已有产物及关闭回执;查询进度不唤醒主会话。在途/未决历史单列。', parameters: z.toJSONSchema(executionJobSchema) },
92
133
  execution_list: { description: '按来源范围、目标与状态分页列出统一任务。', parameters: z.toJSONSchema(executionListSchema) },
93
134
  execution_events: { description: '读取本来源范围内持久任务事件,不派单。', parameters: z.toJSONSchema(executionEventsSchema) },
94
- 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) },
95
140
  execution_inbox: { description: '读取领域交付任务的完成/需决策通知;旧A2A收件箱保持原合同。', parameters: z.toJSONSchema(inboxSchema) },
96
141
  execution_ack: { description: '确认已处理领域交付通知,不修改业务验收或执行状态。', parameters: z.toJSONSchema(ackSchema) },
142
+ ...TICKET_METHODS,
97
143
  };
98
144
  export const REMOTE_AGENT_METHODS = {
99
145
  ...EXECUTION_METHODS,
100
146
  remote_agent_preflight: { description: '在执行宿主检查真实 cwd、任务可写目录和指定运行时依赖,不创建会话、不调用模型。ok=false 时修复检查项后再派单;spawn 的 preflight 还会在受理前重检。', parameters: z.toJSONSchema(preflightSchema) },
101
- remote_agent_spawn: { description: '在配置的远端 DSH 工作目录中派发独立任务,立即返回 taskId。prompt 必须包含完整上下文。cwd 是远端绝对路径;每次 spawn 创建新会话。完成事件进入 originSessionId 的持久收件箱。', parameters: z.toJSONSchema(spawnSchema) },
102
- remote_agent_get: { description: '查询当前主会话派发的远端任务。离线时返回缓存与 stale 标记,离线不等于任务失败。', parameters: z.toJSONSchema(taskSchema) },
103
- remote_agent_cancel: { description: '取消指定远端任务,只取消这项任务自己的执行。', parameters: z.toJSONSchema(taskSchema) },
104
- 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) },
105
153
  remote_agent_list: { description: '列出当前主会话派发的远端任务。', parameters: z.toJSONSchema(inboxSchema) },
106
154
  remote_agent_inbox: { description: '读取当前主会话未确认的完成或需要输入通知。读取不删除;处理后调用 remote_agent_ack。', parameters: z.toJSONSchema(inboxSchema) },
107
155
  remote_agent_ack: { description: '确认主会话已处理指定通知。noticeId 稳定,重复确认安全。', parameters: z.toJSONSchema(ackSchema) },
@@ -110,6 +158,23 @@ export const REMOTE_AGENT_METHODS = {
110
158
  session_delivery_get: { description: '查询本主会话的消息投递状态。unknown 必须先核实宿主是否已接收,不能盲目重发。', parameters: z.toJSONSchema(sessionMessageSchema) },
111
159
  session_delivery_resolve: { description: '核实 unknown 或处理 rejected 投递并记录依据。accepted=true 表示已确认入队;false 仅用于已证实未入队且已处理阻碍后释放重试。note 必填,不等于任务业务处理确认。', parameters: z.toJSONSchema(sessionResolveSchema) },
112
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
+ }
113
178
  const terminal = new Set(['TASK_STATE_COMPLETED', 'TASK_STATE_FAILED', 'TASK_STATE_CANCELED', 'TASK_STATE_REJECTED']);
114
179
  const actionable = new Set([...terminal, 'TASK_STATE_INPUT_REQUIRED', 'TASK_STATE_AUTH_REQUIRED']);
115
180
  const wire = (task) => Task.toJSON(task);
@@ -141,6 +206,7 @@ export class RemoteAgentGateway {
141
206
  automation;
142
207
  sessions;
143
208
  targets;
209
+ agents;
144
210
  projectDiscovery;
145
211
  ledger;
146
212
  lease;
@@ -155,12 +221,20 @@ export class RemoteAgentGateway {
155
221
  operations = new Set();
156
222
  advancingDeliveries = new Map();
157
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;
158
231
  reconciling;
159
232
  workbenchQueue = Promise.resolve();
160
233
  timer;
161
234
  closed = false;
162
- constructor(input) {
235
+ constructor(input, options = {}) {
163
236
  this.config = configSchema.parse(input);
237
+ this.now = options.now ?? Date.now;
164
238
  if (!path.isAbsolute(this.config.stateDirectory))
165
239
  throw new Error('stateDirectory must be absolute');
166
240
  mkdirSync(this.config.stateDirectory, { recursive: true, mode: 0o700 });
@@ -191,6 +265,7 @@ export class RemoteAgentGateway {
191
265
  this.sessions = new SessionDelivery(this.config.stateDirectory, this.config.sessionHosts);
192
266
  this.targets = new TargetDirectory(this.config.stateDirectory, this.config.remotes);
193
267
  this.targets.ensureLegacyRemotes();
268
+ this.agents = new AgentRegistry(this.config.stateDirectory);
194
269
  this.ledger = new JobLedger(this.state.ledger, next => {
195
270
  atomicJson(this.stateFile, { ...this.state, version: 2, ledger: next });
196
271
  this.state.ledger = next;
@@ -221,6 +296,9 @@ export class RemoteAgentGateway {
221
296
  this.state.reportReviews ??= {};
222
297
  this.state.executionCancellations ??= {};
223
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 ?? []);
224
302
  for (const run of Object.values(this.state.pptDeliveries.runs)) {
225
303
  const attempt = this.ledger.getAttempt(run.attemptId);
226
304
  if (attempt.submissionStatus === 'prepared')
@@ -261,6 +339,14 @@ export class RemoteAgentGateway {
261
339
  return { targetId: `legacy:${job.remote}`, provider: 'a2a', remote: job.remote, cwd: job.cwd, agentPreset: job.agentPreset, historicalConfigUnknown: true };
262
340
  }
263
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
+ }
264
350
  targetSnapshot(resolved) {
265
351
  return { targetId: resolved.target.targetId, targetKind: resolved.target.kind, targetName: resolved.target.name,
266
352
  configVersion: resolved.configVersion, connectionId: resolved.connection.connectionId,
@@ -291,14 +377,15 @@ export class RemoteAgentGateway {
291
377
  this.assertDispatchOpen(input.originSessionId, options.jobId ?? input.parentJobRef?.jobId);
292
378
  const resolved = this.targets.resolve(input.targetId, input.input);
293
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)) {
294
- 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');
295
381
  }
296
382
  const reportRequest = input.input.reportReview;
297
383
  if (reportRequest !== undefined && (options.jobId || resolved.target.kind !== 'agent_host' || !this.config.reportReview || !this.config.workbench))
298
384
  throw new Error('Report review requires a new temporary agent_host task and configured report/workbench policy');
299
385
  if (reportRequest !== undefined)
300
386
  reportReviewInputSchema.parse(reportRequest);
301
- const prepared = this.ledger.prepare({ ...input, requestDigestInput: options.requestDigestInput, jobId: options.jobId, targetSnapshot: { ...this.targetSnapshot(resolved), ...(reportRequest !== undefined ? { provider: 'report_review', targetKind: 'workflow', driver: 'report_review' } : {}) },
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' } : {}) },
302
389
  operation: options.jobId ? 'continue' : 'submit' });
303
390
  if (prepared.idempotent)
304
391
  return this.ledgerView(input.originSessionId, prepared.job.jobId);
@@ -331,17 +418,43 @@ export class RemoteAgentGateway {
331
418
  return this.ledgerView(input.originSessionId, job.jobId);
332
419
  }
333
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');
334
428
  const preflight = fields.preflight === undefined ? undefined : a2aPreflightRequirementsSchema.parse(fields.preflight);
335
- const requirements = resolved.directoryPolicy ? { ...preflight, allowedDirectories: resolved.directoryPolicy.allowedDirectories } : preflight;
429
+ const declaredRequirements = resolved.directoryPolicy ? { ...preflight, allowedDirectories: resolved.directoryPolicy.allowedDirectories } : preflight;
336
430
  const declaredContract = fields.resultContract === undefined ? undefined : a2aResultContractSchema.parse(fields.resultContract);
337
- const resultContract = declaredContract && options.notificationOrigin ? { ...declaredContract, jobId: job.jobId } : declaredContract;
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 }));
338
439
  const networkRole = resolved.target.binding.skillPolicy === 'network_pinned' ? resolved.target.binding.roleId : undefined;
339
440
  if (resolved.target.binding.skillPolicy && !networkRole)
340
441
  throw new Error('Network skill policy requires a fixed roleId');
341
442
  const explicitRole = resolved.target.kind === 'agent_host' && fields.roleId !== undefined ? string.parse(fields.roleId) : undefined;
342
443
  const roleLockPath = fields.roleLockPath === undefined ? undefined
343
444
  : z.string().min(1).refine(path.isAbsolute, 'Expected an absolute role lock path').parse(fields.roleLockPath);
344
- await this.checkDispatch(resolved.remote, resolved.cwd, requirements, resolved.endpoint);
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
+ }
345
458
  const client = await this.client(resolved.remote, resolved.endpoint);
346
459
  // Target changes/disable during asynchronous preflight must win before sending.
347
460
  const fresh = this.targets.resolve(input.targetId, input.input);
@@ -350,11 +463,14 @@ export class RemoteAgentGateway {
350
463
  this.assertDispatchOpen(input.originSessionId, options.jobId ?? input.parentJobRef?.jobId);
351
464
  this.ledger.markDispatching(attempt.attemptId);
352
465
  sent = true;
466
+ const lifecycle = this.jobLifecycle(fields.lifecycle, options.previous?.lifecycle);
353
467
  const task = await client.sendMessage(SendMessageRequest.fromJSON({ message: { messageId: attempt.attemptId, role: 'ROLE_USER',
354
- ...(options.previous ? { contextId: options.previous.contextId } : {}), parts: [{ text: prompt.parse(fields.prompt) }] },
355
- metadata: { '1agents': { ...(!options.previous ? { cwd: resolved.cwd, ...(resolved.agentPreset ? { agentPreset: resolved.agentPreset } : {}) } : {}),
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 } : {}) } : {}),
356
471
  ...(explicitRole ? { roleId: explicitRole } : !options.previous && networkRole ? { roleId: networkRole } : {}), ...(roleLockPath ? { roleLockPath } : {}),
357
- ...(requirements ? { preflight: requirements } : {}), ...(resultContract ? { resultContract } : {}) } },
472
+ ...(requirements ? { preflight: requirements } : {}), ...(resultContract ? { resultContract } : {}), ...(provider ? { provider, model } : {}),
473
+ execution: { jobId: job.jobId, attemptId: attempt.attemptId } } },
358
474
  configuration: { returnImmediately: true, ...(this.config.callback ? { taskPushNotificationConfig: { url: this.config.callback.url,
359
475
  authentication: { scheme: 'Bearer', credentials: this.config.callback.token } } } : {}) } }), this.auth(resolved.remote));
360
476
  if (!('id' in task))
@@ -362,7 +478,7 @@ export class RemoteAgentGateway {
362
478
  this.accept(task, { remote: resolved.remote, remoteEndpoint: resolved.endpoint, originSessionId: options.notificationOrigin ?? input.originSessionId, cwd: resolved.cwd,
363
479
  agentPreset: resolved.agentPreset, title: input.title ?? (typeof fields.title === 'string' ? fields.title : undefined),
364
480
  notificationTarget: typeof fields.notificationTarget === 'string' ? fields.notificationTarget : undefined,
365
- ledgerJobId: job.jobId, attemptId: attempt.attemptId });
481
+ ledgerJobId: job.jobId, attemptId: attempt.attemptId, ...(lifecycle ? { lifecycle } : {}) });
366
482
  return this.ledgerView(input.originSessionId, job.jobId);
367
483
  }
368
484
  catch (error) {
@@ -455,7 +571,7 @@ export class RemoteAgentGateway {
455
571
  const reviewUrl = this.config.workbench?.publicBaseUrl ? new URL(this.config.workbench.publicBaseUrl) : undefined;
456
572
  if (reviewUrl && pendingReview)
457
573
  reviewUrl.hash = `acp/tasks/${encodeURIComponent(run.jobId)}?review=${encodeURIComponent(pendingReview.reviewId)}`;
458
- const reviewEntry = pendingReview ? `\n\n${reviewUrl ? `[打开文字稿审核](${reviewUrl.href})` : '请用户打开 1agents「任务工作台 → 待我确认」。'}\n审核版本:${pendingReview.revision};审核请求:${pendingReview.reviewId}。\n人工决定必须在审核页记录,execution_review 和通知已读均不能替代。` : '';
574
+ const reviewEntry = pendingReview ? `\n\n${reviewUrl ? `[打开文字稿审核](${reviewUrl.href})` : '请用户打开本机 A2A 网关的任务工作台页面(/workbench/ui/)→「待我确认」。'}\n审核版本:${pendingReview.revision};审核请求:${pendingReview.reviewId}。\n人工决定必须在审核页记录,execution_review 和通知已读均不能替代。` : '';
459
575
  const text = `[任务交付通知] ${pendingReview ? '文字稿待人工确认' : run.executionStatus === 'completed' ? '任务已完成' : run.executionStatus === 'canceled' ? '任务已取消' : '任务需要处理'}\n${run.input.projectName} PPT\n\n${resultSummary}\n\n` +
460
576
  artifactLinks.map(item => `[${item.mediaType?.includes('presentation') ? (run.executionStatus === 'completed' ? '最终 PPT' : '已有 PPT(未完成最终验收)') : '预览产物'}](${item.url})`).join('\n') +
461
577
  reviewEntry +
@@ -565,7 +681,7 @@ export class RemoteAgentGateway {
565
681
  jobId = job.parentJobRef?.jobId;
566
682
  }
567
683
  }
568
- async cancelExecution(origin, jobId, cascade) {
684
+ async cancelExecution(origin, jobId, cascade, reason) {
569
685
  const job = this.ledger.get(origin, jobId), run = this.state.pptDeliveries.runs[job.currentAttemptId];
570
686
  if (this.state.reportReviews?.[job.currentAttemptId] && cascade === false)
571
687
  throw new Error('Report cancellation must include its child task');
@@ -578,7 +694,7 @@ export class RemoteAgentGateway {
578
694
  }
579
695
  if (!record) {
580
696
  record = { jobId, attemptId: job.currentAttemptId, originSessionId: origin, cascade: cascade ?? Boolean(run || this.state.reportReviews?.[job.currentAttemptId]),
581
- requestedAt: new Date().toISOString(), status: 'pending', targets: [], diagnostics: [] };
697
+ requestedAt: new Date().toISOString(), status: 'pending', targets: [], diagnostics: [], ...(reason ? { reason } : {}) };
582
698
  this.state.executionCancellations[record.attemptId] = record;
583
699
  }
584
700
  // Close admission synchronously and durably, before waiting for an in-flight submit or contacting a backend.
@@ -788,16 +904,7 @@ export class RemoteAgentGateway {
788
904
  const config = configured ? { ...configured, url: pinnedEndpoint ?? configured.url } : undefined;
789
905
  if (!config)
790
906
  throw new Error(`Unknown remote: ${remote}`);
791
- const client = await this.client(remote, config.url), card = await client.getAgentCard(this.auth(remote));
792
- const endpoint = card.supportedInterfaces.find(value => value.protocolBinding === 'JSONRPC')?.url;
793
- if (!endpoint)
794
- throw new Error('Remote does not advertise a JSONRPC endpoint');
795
- const url = new URL(endpoint);
796
- if (url.origin !== new URL(config.url).origin || url.username || url.password)
797
- throw new Error('Preflight endpoint must use the configured remote origin');
798
- url.pathname = `${url.pathname.replace(/\/$/, '')}/preflight`;
799
- url.search = '';
800
- url.hash = '';
907
+ const url = await this.hostRoute(remote, config.url, '/preflight');
801
908
  const controller = new AbortController();
802
909
  this.controllers.add(controller);
803
910
  try {
@@ -814,6 +921,89 @@ export class RemoteAgentGateway {
814
921
  this.controllers.delete(controller);
815
922
  }
816
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
+ }
817
1007
  async checkDispatch(remote, cwd, requirements, pinnedEndpoint) {
818
1008
  if (!requirements)
819
1009
  return;
@@ -829,11 +1019,22 @@ export class RemoteAgentGateway {
829
1019
  }
830
1020
  view(job) {
831
1021
  const task = Task.fromJSON(job.task);
1022
+ const meta = task.metadata?.['1agents'];
832
1023
  const result = job.attemptId ? this.ledger.getAttempt(job.attemptId).result : undefined;
833
1024
  return { remote: job.remote, taskId: job.taskId, contextId: job.contextId, originSessionId: job.originSessionId,
834
1025
  ...(job.ledgerJobId ? { jobId: job.ledgerJobId, attemptId: job.attemptId, sourceId: this.ledger.sourceId } : {}),
835
- cwd: job.cwd, agentPreset: job.agentPreset, sessionId: task.metadata?.['1agents']?.sessionId,
836
- 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 } : {}),
837
1038
  resultRevision: result?.resultRevision, resultDigest: result?.resultDigest,
838
1039
  state: taskState(job), result: resultText(task), artifactLinks: artifactLinks(task), checkedAt: job.checkedAt, stale: Boolean(job.stale) };
839
1040
  }
@@ -862,14 +1063,18 @@ export class RemoteAgentGateway {
862
1063
  job.task = wire(task);
863
1064
  job.checkedAt = new Date().toISOString();
864
1065
  job.stale = false;
1066
+ const meta = task.metadata?.['1agents'];
1067
+ if (typeof meta?.sessionId === 'string' && meta.sessionId)
1068
+ job.sessionId = meta.sessionId;
865
1069
  const state = taskState(job);
866
1070
  if (actionable.has(state)) {
1071
+ const reason = state === 'TASK_STATE_CANCELED' && job.attemptId ? this.state.executionCancellations?.[job.attemptId]?.reason : undefined;
867
1072
  const noticeId = createHash('sha256').update(JSON.stringify([job.remote, job.taskId, state, task.status?.timestamp])).digest('hex');
868
1073
  if (!this.state.notices.some(value => value.notice.noticeId === noticeId))
869
1074
  this.state.notices.push({
870
1075
  ...(this.sessions.hasBinding(job.originSessionId) ? { sessionDeliveryId: `a2a-notice:${noticeId}` } : { target: job.notificationTarget }),
871
1076
  notice: { noticeId, originSessionId: job.originSessionId, remote: job.remote, taskId: job.taskId, contextId: job.contextId,
872
- 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),
873
1078
  ...(artifactLinks(task).length ? { artifactLinks: artifactLinks(task) } : {}), createdAt: new Date().toISOString() }
874
1079
  });
875
1080
  }
@@ -882,6 +1087,8 @@ export class RemoteAgentGateway {
882
1087
  }
883
1088
  else
884
1089
  this.save();
1090
+ if (oneShotShouldClose(job.lifecycle, state, this.taskAcknowledged(job, state)))
1091
+ this.releaseOneShot(job);
885
1092
  }
886
1093
  async refresh(job) {
887
1094
  const key = `${job.remote}:${job.taskId}`;
@@ -983,6 +1190,13 @@ export class RemoteAgentGateway {
983
1190
  await this.sessions.reconcile();
984
1191
  }
985
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();
986
1200
  await this.automation?.reconcileAcknowledgements();
987
1201
  })();
988
1202
  this.reconciling = pending;
@@ -1082,13 +1296,21 @@ export class RemoteAgentGateway {
1082
1296
  || current.target.binding.driver !== 'ppt_delivery')
1083
1297
  throw new Error('PPT checkpoint recovery cannot change its host or role');
1084
1298
  return this.submitExecution({ originSessionId: input.originSessionId, targetId: job.targetId, title: job.title,
1085
- input: attempt.input, clientRequestId: input.clientRequestId }, { jobId: job.jobId, deliveryRecovery: delivery, deliveryRecoveryInput: recoveryInput, requestDigestInput: input.input });
1299
+ input: attempt.input, clientRequestId: input.clientRequestId, initiatedBy: input.initiatedBy }, { jobId: job.jobId, deliveryRecovery: delivery, deliveryRecoveryInput: recoveryInput, requestDigestInput: input.input });
1086
1300
  }
1087
1301
  const previous = this.state.jobs.find(item => item.attemptId === attempt.attemptId);
1088
1302
  if (!previous)
1089
1303
  throw new Error('Continue is unsupported for this provider');
1090
- return this.submitExecution({ originSessionId: input.originSessionId, targetId: job.targetId, title: job.title,
1091
- 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;
1092
1314
  }
1093
1315
  if (method === 'execution_get') {
1094
1316
  const input = executionJobSchema.parse(params), job = this.ledger.get(input.originSessionId, input.jobId);
@@ -1115,6 +1337,28 @@ export class RemoteAgentGateway {
1115
1337
  const { originSessionId, jobId, ...review } = executionReviewSchema.parse(params);
1116
1338
  return this.ledger.acceptance(originSessionId, jobId, review);
1117
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
+ }
1118
1362
  if (method === 'execution_inbox') {
1119
1363
  const { originSessionId } = inboxSchema.parse(params);
1120
1364
  return { notices: this.state.executionNotices.filter(item => item.originSessionId === originSessionId && !item.processedAt)
@@ -1154,8 +1398,8 @@ export class RemoteAgentGateway {
1154
1398
  const input = spawnSchema.parse(params);
1155
1399
  if (input.notificationTarget && !this.config.notificationTargets[input.notificationTarget])
1156
1400
  throw new Error('Unknown notificationTarget');
1157
- const { originSessionId, remote, clientRequestId, title, ...fields } = input;
1158
- 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 });
1159
1403
  if ('error' in submitted)
1160
1404
  throw new Error(`${submitted.error}; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
1161
1405
  const raw = this.state.jobs.find(item => item.attemptId === submitted.attemptId);
@@ -1177,15 +1421,22 @@ export class RemoteAgentGateway {
1177
1421
  }
1178
1422
  if (method === 'remote_agent_message') {
1179
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
+ }
1180
1429
  if (!previous.ledgerJobId)
1181
1430
  throw new Error('Task has no unified job association');
1182
1431
  const record = this.ledger.get(input.originSessionId, previous.ledgerJobId);
1183
1432
  const target = this.targets.getTarget(record.targetId);
1184
1433
  const submitted = await this.submitExecution({ originSessionId: input.originSessionId, targetId: record.targetId,
1185
- clientRequestId: input.clientRequestId, title: previous.title,
1434
+ clientRequestId: input.clientRequestId, title: previous.title, initiatedBy: input.initiatedBy,
1186
1435
  input: { ...(target.kind === 'agent_host' ? { cwd: previous.cwd, ...(previous.agentPreset ? { agentPreset: previous.agentPreset } : {}) } : {}), prompt: input.prompt,
1187
1436
  ...(input.preflight ? { preflight: input.preflight } : {}), ...(input.resultContract ? { resultContract: input.resultContract } : {}),
1188
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 } : {}),
1189
1440
  ...(previous.notificationTarget ? { notificationTarget: previous.notificationTarget } : {}) } }, { jobId: previous.ledgerJobId, previous });
1190
1441
  if ('error' in submitted)
1191
1442
  throw new Error(`${submitted.error}; jobId=${submitted.jobId}; attemptId=${submitted.attemptId}`);
@@ -1207,8 +1458,24 @@ export class RemoteAgentGateway {
1207
1458
  notice.acknowledged = true;
1208
1459
  this.save();
1209
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);
1210
1464
  return { acknowledged: true, noticeId: input.noticeId };
1211
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
+ }
1212
1479
  throw new Error(`Unknown method: ${method}`);
1213
1480
  }
1214
1481
  /** Push events are hints. GetTask remains authoritative, including after missed callbacks. */
@@ -1227,13 +1494,107 @@ export class RemoteAgentGateway {
1227
1494
  const runs = Object.values(this.state.pptDeliveries.runs);
1228
1495
  const reportRuns = Object.values(this.state.reportReviews ?? {});
1229
1496
  return workbenchSnapshot({ ledger: this.ledger.snapshot(), runs, reportRuns, reviews: [...runs.flatMap(run => run.humanReviews ?? []), ...reportRuns.flatMap(run => run.humanReviews)],
1230
- actorId: config.reviewerId, ...(config.allowedOrigins ? { allowedOrigins: config.allowedOrigins } : {}) });
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();
1231
1519
  }
1232
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() })); }
1233
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
+ }
1234
1595
  /** Only the dedicated HTTP workbench calls this; it is deliberately absent from the agent tool catalogue. */
1235
1596
  async decideWorkbenchReview(jobId, reviewId, input) {
1236
- const operation = this.workbenchQueue.then(async () => {
1597
+ return this.workbench(async () => {
1237
1598
  if (this.closed)
1238
1599
  throw new Error('Gateway is closed');
1239
1600
  const scope = this.workbenchTask(jobId), config = this.config.workbench;
@@ -1272,8 +1633,347 @@ export class RemoteAgentGateway {
1272
1633
  void this.advanceDelivery(current).catch(() => { });
1273
1634
  return this.workbenchTask(jobId);
1274
1635
  });
1275
- this.workbenchQueue = operation.then(() => { }, () => { });
1276
- return operation;
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
+ }
1277
1977
  }
1278
1978
  async close() {
1279
1979
  if (this.closed)
@@ -1306,14 +2006,55 @@ function json(res, status, data) {
1306
2006
  res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
1307
2007
  res.end(JSON.stringify(data));
1308
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
+ }
1309
2018
  function authenticated(req, token) {
1310
2019
  const expected = Buffer.from(`Bearer ${token}`), supplied = Buffer.from(req.headers.authorization ?? '');
1311
2020
  return supplied.length === expected.length && timingSafeEqual(supplied, expected);
1312
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
+ }
1313
2030
  async function listen(server, port, host) {
1314
2031
  await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
1315
2032
  return server.address().port;
1316
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
+ }
1317
2058
  async function stop(server) {
1318
2059
  server.closeIdleConnections();
1319
2060
  await new Promise(resolve => server.close(() => resolve()));
@@ -1335,38 +2076,182 @@ function methodContractViolations(methods) {
1335
2076
  }
1336
2077
  export async function serveA2AGateway(input, options = {}) {
1337
2078
  const gateway = new RemoteAgentGateway(input);
2079
+ const workbenchUi = gateway.config.workbench ? new WorkbenchUi(gateway.config.workbench.token) : undefined;
2080
+ const callbackHealth = {};
1338
2081
  const server = http.createServer((req, res) => {
1339
2082
  void (async () => {
1340
2083
  try {
1341
- if (req.method === 'GET' && req.url === '/health')
1342
- 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
+ }
1343
2094
  const url = new URL(req.url ?? '/', 'http://localhost');
1344
- if (url.pathname.startsWith('/workbench/')) {
1345
- if (!gateway.config.workbench)
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)
1346
2098
  return json(res, 503, { error: 'Workbench is not configured' });
1347
- if (!authenticated(req, gateway.config.workbench.token))
1348
- return json(res, 401, { error: 'Unauthorized' });
1349
- if (req.headers.origin)
1350
- return json(res, 403, { error: 'Use the authenticated application workbench' });
1351
- if (req.method === 'GET' && url.pathname === '/workbench/tasks') {
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') {
1352
2117
  const query = z.object({ filter: z.enum(['all', 'pending', 'working', 'failed']).optional(),
1353
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));
1354
2119
  return json(res, 200, gateway.workbenchList(query));
1355
2120
  }
1356
- const route = /^\/workbench\/tasks\/([^/]+)(?:\/reviews\/([^/]+)\/decisions)?$/.exec(url.pathname);
1357
- if (!route || url.search)
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)
1358
2200
  return json(res, 404, { error: 'No workbench route' });
1359
- const jobId = decodeURIComponent(route[1]);
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);
1360
2208
  try {
1361
- if (req.method === 'GET' && !route[2])
2209
+ if (rest === '' && req.method === 'GET')
1362
2210
  return json(res, 200, gateway.workbenchTask(jobId));
1363
- if (req.method === 'POST' && route[2])
1364
- return json(res, 200, await gateway.decideWorkbenchReview(jobId, decodeURIComponent(route[2]), await body(req)));
1365
- return json(res, 405, { error: 'Method not allowed' });
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' });
1366
2247
  }
1367
2248
  catch (error) {
1368
2249
  if (error instanceof HumanReviewError)
1369
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
+ }
1370
2255
  if (error instanceof z.ZodError)
1371
2256
  return json(res, 400, { error: 'Invalid workbench parameters' });
1372
2257
  return json(res, 404, { error: error instanceof Error ? error.message : 'Task not found' });
@@ -1385,31 +2270,71 @@ export async function serveA2AGateway(input, options = {}) {
1385
2270
  }
1386
2271
  })();
1387
2272
  });
1388
- let receiver;
2273
+ const callbackServers = new Set();
2274
+ const callbackAbort = new AbortController();
1389
2275
  let callbackPort;
1390
2276
  let automationServer;
1391
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
+ };
1392
2316
  try {
1393
2317
  const port = await listen(server, gateway.config.port, '127.0.0.1');
1394
2318
  if (gateway.config.callback) {
1395
2319
  const callback = gateway.config.callback;
1396
- receiver = http.createServer((req, res) => {
1397
- void (async () => {
1398
- if (!authenticated(req, callback.token))
1399
- return json(res, 401, { error: 'Unauthorized' });
1400
- if (req.method !== 'POST' || req.url !== new URL(callback.url).pathname)
1401
- return json(res, 404, { error: 'No route' });
1402
- try {
1403
- const event = await body(req);
1404
- json(res, 202, { accepted: true });
1405
- void gateway.receivePush(event).catch(() => { });
1406
- }
1407
- catch {
1408
- json(res, 400, { error: 'Invalid A2A event' });
1409
- }
1410
- })();
1411
- });
1412
- 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
+ }
1413
2338
  }
1414
2339
  if (gateway.config.automation && gateway.automation) {
1415
2340
  automationServer = createAutomationServer(gateway.automation);
@@ -1439,19 +2364,21 @@ export async function serveA2AGateway(input, options = {}) {
1439
2364
  closing ??= (async () => {
1440
2365
  if (reporting)
1441
2366
  clearInterval(reporting);
2367
+ callbackAbort.abort();
1442
2368
  // Stop the Reader before draining HTTP requests that may be awaiting a scan.
1443
2369
  await gateway.projectDiscovery?.close();
1444
2370
  // Stop accepting requests and drain their ledger writes while this instance
1445
2371
  // still owns the storage lease. Automation continuations and its admission
1446
2372
  // queue can outlive the gateway operation they awaited.
1447
- 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)] : [])]);
1448
2374
  await gateway.close();
1449
2375
  })();
1450
2376
  await closing;
1451
2377
  } };
1452
2378
  }
1453
2379
  catch (error) {
1454
- 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)] : [])]);
1455
2382
  await gateway.close();
1456
2383
  throw error;
1457
2384
  }