@1agents/acp-service 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/README.md +25 -13
  2. package/dist/bin/a2a.js +16 -4
  3. package/dist/bin/acp-service.js +30 -0
  4. package/dist/bin/process.d.ts +4 -0
  5. package/dist/bin/process.js +57 -0
  6. package/dist/bin/roles.d.ts +1 -0
  7. package/dist/bin/roles.js +24 -0
  8. package/dist/bin/rsi.d.ts +3 -0
  9. package/dist/bin/rsi.js +114 -0
  10. package/dist/bin/ticket.d.ts +13 -0
  11. package/dist/bin/ticket.js +97 -0
  12. package/dist/bin/trail.d.ts +4 -0
  13. package/dist/bin/trail.js +62 -0
  14. package/dist/src/a2a/artifact-content.d.ts +9 -0
  15. package/dist/src/a2a/artifact-content.js +45 -0
  16. package/dist/src/a2a/desktop-notify.d.ts +1 -0
  17. package/dist/src/a2a/desktop-notify.js +12 -0
  18. package/dist/src/a2a/execution-binding.d.ts +9 -0
  19. package/dist/src/a2a/execution-binding.js +19 -0
  20. package/dist/src/a2a/executor.d.ts +22 -1
  21. package/dist/src/a2a/executor.js +308 -22
  22. package/dist/src/a2a/gateway.d.ts +613 -1
  23. package/dist/src/a2a/gateway.js +1337 -88
  24. package/dist/src/a2a/index.d.ts +14 -1
  25. package/dist/src/a2a/index.js +8 -0
  26. package/dist/src/a2a/job-directory.d.ts +6 -0
  27. package/dist/src/a2a/job-directory.js +19 -0
  28. package/dist/src/a2a/preflight.js +16 -1
  29. package/dist/src/a2a/resubmit.d.ts +46 -0
  30. package/dist/src/a2a/resubmit.js +82 -0
  31. package/dist/src/a2a/result-metadata.d.ts +6 -0
  32. package/dist/src/a2a/result-metadata.js +25 -6
  33. package/dist/src/a2a/server.d.ts +10 -0
  34. package/dist/src/a2a/server.js +127 -2
  35. package/dist/src/a2a/session-lifecycle.d.ts +40 -0
  36. package/dist/src/a2a/session-lifecycle.js +54 -0
  37. package/dist/src/a2a/store.d.ts +4 -0
  38. package/dist/src/a2a/store.js +76 -1
  39. package/dist/src/a2a/types.d.ts +77 -1
  40. package/dist/src/a2a/types.js +11 -1
  41. package/dist/src/a2a/workbench-ui.d.ts +28 -0
  42. package/dist/src/a2a/workbench-ui.js +182 -0
  43. package/dist/src/acp-connection.js +119 -14
  44. package/dist/src/bridge.d.ts +1 -0
  45. package/dist/src/bridge.js +312 -37
  46. package/dist/src/capacity-lifecycle.d.ts +5 -0
  47. package/dist/src/capacity-lifecycle.js +57 -0
  48. package/dist/src/capacity-queue.d.ts +58 -0
  49. package/dist/src/capacity-queue.js +388 -0
  50. package/dist/src/capacity.d.ts +101 -0
  51. package/dist/src/capacity.js +416 -0
  52. package/dist/src/dsh.js +1 -1
  53. package/dist/src/execution/agent-files.d.ts +25 -0
  54. package/dist/src/execution/agent-files.js +90 -0
  55. package/dist/src/execution/agent-registry.d.ts +164 -0
  56. package/dist/src/execution/agent-registry.js +275 -0
  57. package/dist/src/execution/human-review.d.ts +105 -0
  58. package/dist/src/execution/human-review.js +89 -0
  59. package/dist/src/execution/ledger.d.ts +57 -0
  60. package/dist/src/execution/ledger.js +122 -13
  61. package/dist/src/execution/ppt-delivery.d.ts +36 -3
  62. package/dist/src/execution/ppt-delivery.js +243 -53
  63. package/dist/src/execution/process-request.d.ts +151 -0
  64. package/dist/src/execution/process-request.js +177 -0
  65. package/dist/src/execution/project-discovery.d.ts +56 -0
  66. package/dist/src/execution/project-discovery.js +429 -0
  67. package/dist/src/execution/report-review.d.ts +60 -0
  68. package/dist/src/execution/report-review.js +173 -0
  69. package/dist/src/execution/targets.d.ts +20 -0
  70. package/dist/src/execution/targets.js +23 -3
  71. package/dist/src/execution/ticket-executor.d.ts +25 -0
  72. package/dist/src/execution/ticket-executor.js +27 -0
  73. package/dist/src/execution/ticket.d.ts +326 -0
  74. package/dist/src/execution/ticket.js +301 -0
  75. package/dist/src/execution/workbench-chat.d.ts +25 -0
  76. package/dist/src/execution/workbench-chat.js +54 -0
  77. package/dist/src/execution/workbench.d.ts +162 -0
  78. package/dist/src/execution/workbench.js +356 -0
  79. package/dist/src/index.d.ts +4 -0
  80. package/dist/src/index.js +3 -0
  81. package/dist/src/roles/index.d.ts +1 -0
  82. package/dist/src/roles/index.js +1 -0
  83. package/dist/src/roles/skills.d.ts +71 -0
  84. package/dist/src/roles/skills.js +427 -0
  85. package/dist/src/rsi/gate.d.ts +25 -0
  86. package/dist/src/rsi/gate.js +59 -0
  87. package/dist/src/rsi/outline-run.d.ts +107 -0
  88. package/dist/src/rsi/outline-run.js +443 -0
  89. package/dist/workbench-ui/app.css +453 -0
  90. package/dist/workbench-ui/app.js +13 -0
  91. package/dist/workbench-ui/chunk-23JHGYT3.js +1 -0
  92. package/dist/workbench-ui/chunk-3H6STGPV.js +1 -0
  93. package/dist/workbench-ui/chunk-3SNBBMGH.js +1 -0
  94. package/dist/workbench-ui/chunk-3XJZ6DIE.js +1 -0
  95. package/dist/workbench-ui/chunk-44KDLLKJ.js +1 -0
  96. package/dist/workbench-ui/chunk-46H7FU5Y.js +7 -0
  97. package/dist/workbench-ui/chunk-4N44QPL7.js +1 -0
  98. package/dist/workbench-ui/chunk-4YN4BS7I.js +1 -0
  99. package/dist/workbench-ui/chunk-53EG4IVQ.js +96 -0
  100. package/dist/workbench-ui/chunk-5FIPUNR4.js +1 -0
  101. package/dist/workbench-ui/chunk-6DWWYA6G.js +2 -0
  102. package/dist/workbench-ui/chunk-6FU3T633.js +99 -0
  103. package/dist/workbench-ui/chunk-6XKIHRA4.js +1 -0
  104. package/dist/workbench-ui/chunk-7GIX43Y5.js +1 -0
  105. package/dist/workbench-ui/chunk-7Q4WBGX6.js +4 -0
  106. package/dist/workbench-ui/chunk-A3BQM7HR.js +1 -0
  107. package/dist/workbench-ui/chunk-AFCFDDOP.js +24 -0
  108. package/dist/workbench-ui/chunk-AG67EUYD.js +89 -0
  109. package/dist/workbench-ui/chunk-AGJHMMTN.js +1 -0
  110. package/dist/workbench-ui/chunk-AO6JUBV6.js +41 -0
  111. package/dist/workbench-ui/chunk-AUSLTP43.js +72 -0
  112. package/dist/workbench-ui/chunk-AVZL46TT.js +1 -0
  113. package/dist/workbench-ui/chunk-AZRIGIV2.js +168 -0
  114. package/dist/workbench-ui/chunk-B2LIVH37.js +1 -0
  115. package/dist/workbench-ui/chunk-B7YX5TR5.js +1 -0
  116. package/dist/workbench-ui/chunk-BCB4X4XX.js +1 -0
  117. package/dist/workbench-ui/chunk-BCRQUL2A.js +88 -0
  118. package/dist/workbench-ui/chunk-BI6UHHQP.js +1 -0
  119. package/dist/workbench-ui/chunk-BLSLQ4AQ.js +120 -0
  120. package/dist/workbench-ui/chunk-C3QSRS6E.js +1 -0
  121. package/dist/workbench-ui/chunk-CK7M2PJ3.js +62 -0
  122. package/dist/workbench-ui/chunk-CM6LZ7TU.js +1 -0
  123. package/dist/workbench-ui/chunk-CP63H27F.js +36 -0
  124. package/dist/workbench-ui/chunk-CPUMMIS2.js +70 -0
  125. package/dist/workbench-ui/chunk-CSEIBI5U.js +2 -0
  126. package/dist/workbench-ui/chunk-CUS65DKZ.js +161 -0
  127. package/dist/workbench-ui/chunk-CVQY7TNC.js +1 -0
  128. package/dist/workbench-ui/chunk-D6S3XBIX.js +106 -0
  129. package/dist/workbench-ui/chunk-E253Y562.js +1 -0
  130. package/dist/workbench-ui/chunk-EADDJUDC.js +1 -0
  131. package/dist/workbench-ui/chunk-EBGJ3YXG.js +206 -0
  132. package/dist/workbench-ui/chunk-EKPVZ3WY.js +8 -0
  133. package/dist/workbench-ui/chunk-EQDCEAFY.js +1 -0
  134. package/dist/workbench-ui/chunk-ES3SSDJY.js +40 -0
  135. package/dist/workbench-ui/chunk-ESFD2H7N.js +231 -0
  136. package/dist/workbench-ui/chunk-FVOHPMS6.js +1 -0
  137. package/dist/workbench-ui/chunk-FXMQAGVT.js +1 -0
  138. package/dist/workbench-ui/chunk-GGTADRXD.js +24 -0
  139. package/dist/workbench-ui/chunk-GHIVPGNQ.js +1 -0
  140. package/dist/workbench-ui/chunk-GLU2YQV2.js +1 -0
  141. package/dist/workbench-ui/chunk-GOCKBYSM.js +1 -0
  142. package/dist/workbench-ui/chunk-H2KMMTJB.js +1 -0
  143. package/dist/workbench-ui/chunk-HGVLDNPP.js +39 -0
  144. package/dist/workbench-ui/chunk-HSAVC5GY.js +1 -0
  145. package/dist/workbench-ui/chunk-HSEAD2JH.js +1 -0
  146. package/dist/workbench-ui/chunk-HSIHOBTY.js +1 -0
  147. package/dist/workbench-ui/chunk-IZXOKUGG.js +67 -0
  148. package/dist/workbench-ui/chunk-JFT2LC2T.js +1 -0
  149. package/dist/workbench-ui/chunk-JHL3ZDYK.js +3 -0
  150. package/dist/workbench-ui/chunk-JMORLCZG.js +257 -0
  151. package/dist/workbench-ui/chunk-JR4SIX7A.js +1 -0
  152. package/dist/workbench-ui/chunk-K23HAGEH.js +30 -0
  153. package/dist/workbench-ui/chunk-K43JDCBH.js +1 -0
  154. package/dist/workbench-ui/chunk-KINKFJY7.js +1 -0
  155. package/dist/workbench-ui/chunk-KKQSA4LI.js +2 -0
  156. package/dist/workbench-ui/chunk-KOUZX3UX.js +1 -0
  157. package/dist/workbench-ui/chunk-KR4DRHW2.js +78 -0
  158. package/dist/workbench-ui/chunk-KT4DJNOR.js +1 -0
  159. package/dist/workbench-ui/chunk-KTPNKRRZ.js +292 -0
  160. package/dist/workbench-ui/chunk-LFHIPGSU.js +7 -0
  161. package/dist/workbench-ui/chunk-LWDL4HZB.js +125 -0
  162. package/dist/workbench-ui/chunk-MVYC3CY4.js +1 -0
  163. package/dist/workbench-ui/chunk-NWUPALCY.js +129 -0
  164. package/dist/workbench-ui/chunk-NY7C662Z.js +1 -0
  165. package/dist/workbench-ui/chunk-O76WTHWP.js +1 -0
  166. package/dist/workbench-ui/chunk-OTF7YHRE.js +162 -0
  167. package/dist/workbench-ui/chunk-P6TKKRKP.js +1 -0
  168. package/dist/workbench-ui/chunk-PFHOOWV3.js +1 -0
  169. package/dist/workbench-ui/chunk-PUQLANIM.js +1 -0
  170. package/dist/workbench-ui/chunk-PZCGBYVO.js +1 -0
  171. package/dist/workbench-ui/chunk-QOHUZGP4.js +1 -0
  172. package/dist/workbench-ui/chunk-QSEG3OFF.js +1 -0
  173. package/dist/workbench-ui/chunk-QYPOXZIA.js +84 -0
  174. package/dist/workbench-ui/chunk-R6SOF3JC.js +1 -0
  175. package/dist/workbench-ui/chunk-RCLOYU5F.js +1 -0
  176. package/dist/workbench-ui/chunk-RSRUP64S.js +1 -0
  177. package/dist/workbench-ui/chunk-RVAIT6JW.js +1 -0
  178. package/dist/workbench-ui/chunk-S2CCN3II.js +1 -0
  179. package/dist/workbench-ui/chunk-S2Q52W46.js +1 -0
  180. package/dist/workbench-ui/chunk-S2W5THJ5.js +1 -0
  181. package/dist/workbench-ui/chunk-S6ZQZNOX.js +1 -0
  182. package/dist/workbench-ui/chunk-S74PLMMS.js +1 -0
  183. package/dist/workbench-ui/chunk-S7C4HKEY.js +1 -0
  184. package/dist/workbench-ui/chunk-SDTB3Q65.js +1 -0
  185. package/dist/workbench-ui/chunk-SLPRGYUV.js +32 -0
  186. package/dist/workbench-ui/chunk-SQE76S5B.js +1 -0
  187. package/dist/workbench-ui/chunk-SSDZPVPW.js +1 -0
  188. package/dist/workbench-ui/chunk-SVI7DGIE.js +1 -0
  189. package/dist/workbench-ui/chunk-T6QKLZ4H.js +62 -0
  190. package/dist/workbench-ui/chunk-TJNRPTFL.js +1 -0
  191. package/dist/workbench-ui/chunk-TP6U4EDH.js +2 -0
  192. package/dist/workbench-ui/chunk-TYAAT3GQ.js +1 -0
  193. package/dist/workbench-ui/chunk-U6OCY4ZH.js +1 -0
  194. package/dist/workbench-ui/chunk-UAN3NLRF.js +1 -0
  195. package/dist/workbench-ui/chunk-UMLU3FIX.js +1 -0
  196. package/dist/workbench-ui/chunk-URIY2OTM.js +1 -0
  197. package/dist/workbench-ui/chunk-V2NUKAA7.js +38 -0
  198. package/dist/workbench-ui/chunk-V4QLL4TE.js +139 -0
  199. package/dist/workbench-ui/chunk-VASHXUK4.js +2 -0
  200. package/dist/workbench-ui/chunk-VJLIWNIU.js +1 -0
  201. package/dist/workbench-ui/chunk-VQNQFBID.js +1 -0
  202. package/dist/workbench-ui/chunk-VSIWU7XA.js +3 -0
  203. package/dist/workbench-ui/chunk-VSJASPUZ.js +321 -0
  204. package/dist/workbench-ui/chunk-VXPNUNUX.js +3 -0
  205. package/dist/workbench-ui/chunk-WBKLDCV6.js +1 -0
  206. package/dist/workbench-ui/chunk-WOKJM3FY.js +1 -0
  207. package/dist/workbench-ui/chunk-X3U3NA3X.js +34 -0
  208. package/dist/workbench-ui/chunk-XBYU7M4J.js +1 -0
  209. package/dist/workbench-ui/chunk-XBZAO4ID.js +10 -0
  210. package/dist/workbench-ui/chunk-XLLPZ2WO.js +1 -0
  211. package/dist/workbench-ui/chunk-YFVL4NJL.js +1 -0
  212. package/dist/workbench-ui/chunk-YRFQENM4.js +1 -0
  213. package/dist/workbench-ui/chunk-YUADQVB2.js +1 -0
  214. package/dist/workbench-ui/chunk-Z3TCAKM5.js +1 -0
  215. package/dist/workbench-ui/chunk-Z6QR6FRE.js +10 -0
  216. package/dist/workbench-ui/chunk-ZJPSORPP.js +3 -0
  217. package/dist/workbench-ui/chunk-ZLGCSTR2.js +15 -0
  218. package/dist/workbench-ui/chunk-ZLR4SG5X.js +1 -0
  219. package/dist/workbench-ui/chunk-ZND3TTGF.js +1 -0
  220. package/dist/workbench-ui/chunk-ZOP3ZYH7.js +2 -0
  221. package/dist/workbench-ui/index.html +14 -0
  222. package/package.json +23 -8
  223. package/skills/acp-service/SKILL.md +24 -8
  224. package/skills/acp-service/references/a2a.md +24 -8
  225. package/skills/acp-service/references/async-caller.md +48 -0
  226. package/skills/acp-service/references/dsh.md +2 -0
  227. package/skills/acp-service/references/roles-and-tasks.md +120 -0
  228. package/skills/acp-service/scripts/a2a-caller.py +242 -0
  229. package/skills/rsi-coach/SKILL.md +134 -0
  230. package/vendor/dsh/README.md +11 -5
  231. package/vendor/dsh/a2a-executor.d.ts +60 -3
  232. package/vendor/dsh/a2a-executor.js +208 -18
  233. package/vendor/dsh/a2a.d.ts +12 -2
  234. package/vendor/dsh/a2a.js +9 -2
  235. package/vendor/dsh/adapter.d.ts +61 -2
  236. package/vendor/dsh/adapter.js +354 -23
  237. package/vendor/dsh/client.js +67 -11
  238. package/vendor/dsh/index.js +57 -4
  239. package/vendor/dsh/native-approvals.d.ts +4 -0
  240. package/vendor/dsh/native-approvals.js +44 -0
  241. package/vendor/dsh/preset-route.d.ts +49 -0
  242. package/vendor/dsh/preset-route.js +51 -0
  243. package/vendor/dsh/preset.js +10 -3
  244. package/vendor/dsh/process-admission.d.ts +25 -0
  245. package/vendor/dsh/process-admission.js +87 -0
  246. package/vendor/dsh/process-requests.d.ts +57 -0
  247. package/vendor/dsh/process-requests.js +49 -0
  248. package/vendor/dsh/review-mcp.d.ts +1 -0
  249. package/vendor/dsh/review-mcp.js +56 -0
  250. package/vendor/dsh/review.d.ts +30 -0
  251. package/vendor/dsh/review.js +149 -0
  252. package/vendor/dsh/session-settings.d.ts +34 -0
  253. package/vendor/dsh/session-settings.js +114 -0
  254. package/vendor/dsh/ticket-spec.d.ts +30 -0
  255. package/vendor/dsh/ticket-spec.js +10 -0
  256. package/vendor/dsh/ticket-tools.d.ts +21 -0
  257. package/vendor/dsh/ticket-tools.js +43 -0
  258. package/vendor/dsh/workbench.d.ts +18 -0
  259. package/vendor/dsh/workbench.js +91 -0
  260. package/vendor/runtime/README.md +6 -4
  261. package/vendor/runtime/dist/{cli-DeOpE2Xz.js → cli-DXmYwv3U.js} +4 -4
  262. package/vendor/runtime/dist/{cli-DeOpE2Xz.js.map → cli-DXmYwv3U.js.map} +1 -1
  263. package/vendor/runtime/dist/cli.js +7 -7
  264. package/vendor/runtime/dist/client-VQsqcIOJ.d.ts.map +1 -1
  265. package/vendor/runtime/dist/docs-site/CLI.html +2 -2
  266. package/vendor/runtime/dist/docs-site/VISION.html +2 -2
  267. package/vendor/runtime/dist/docs-site/agents.html +2 -2
  268. package/vendor/runtime/dist/docs-site/compare.html +2 -2
  269. package/vendor/runtime/dist/docs-site/config.html +2 -2
  270. package/vendor/runtime/dist/docs-site/custom-agents.html +2 -2
  271. package/vendor/runtime/dist/docs-site/exit-codes.html +2 -2
  272. package/vendor/runtime/dist/docs-site/flows.html +2 -2
  273. package/vendor/runtime/dist/docs-site/index.html +1 -1
  274. package/vendor/runtime/dist/docs-site/install.html +2 -2
  275. package/vendor/runtime/dist/docs-site/llms.txt +1 -1
  276. package/vendor/runtime/dist/docs-site/output-formats.html +2 -2
  277. package/vendor/runtime/dist/docs-site/permissions.html +2 -2
  278. package/vendor/runtime/dist/docs-site/prompting.html +2 -2
  279. package/vendor/runtime/dist/docs-site/quickstart.html +2 -2
  280. package/vendor/runtime/dist/docs-site/releasing.html +2 -2
  281. package/vendor/runtime/dist/docs-site/runtime-environment.html +2 -2
  282. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +3 -2
  283. package/vendor/runtime/dist/docs-site/safe-errors.html +2 -2
  284. package/vendor/runtime/dist/docs-site/session-control.html +2 -2
  285. package/vendor/runtime/dist/docs-site/session-watch.html +2 -2
  286. package/vendor/runtime/dist/docs-site/sessions.html +2 -2
  287. package/vendor/runtime/dist/docs-site/shared-sessions.html +2 -2
  288. package/vendor/runtime/dist/{flows-oaBGn31w.js → flows-DJ17ajbw.js} +3 -3
  289. package/vendor/runtime/dist/{flows-oaBGn31w.js.map → flows-DJ17ajbw.js.map} +1 -1
  290. package/vendor/runtime/dist/flows.js +1 -1
  291. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js → invocation-options-PBfCgrdi.js} +3 -3
  292. package/vendor/runtime/dist/{invocation-options-CUDEE8vW.js.map → invocation-options-PBfCgrdi.js.map} +1 -1
  293. package/vendor/runtime/dist/{output-CFv3jcOQ.js → output-B3MDn7kv.js} +2 -2
  294. package/vendor/runtime/dist/{output-CFv3jcOQ.js.map → output-B3MDn7kv.js.map} +1 -1
  295. package/vendor/runtime/dist/{queue-owner-runtime-DvMJiGbP.js → queue-owner-runtime-DXCVngwU.js} +15 -8
  296. package/vendor/runtime/dist/queue-owner-runtime-DXCVngwU.js.map +1 -0
  297. package/vendor/runtime/dist/runtime.js +1 -1
  298. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js → session-watch-DURyCw31.js} +2 -2
  299. package/vendor/runtime/dist/{session-watch-Di-wIdCH.js.map → session-watch-DURyCw31.js.map} +1 -1
  300. package/vendor/runtime/package.json +6 -4
  301. package/vendor/runtime/skills/acpx/SKILL.md +2 -0
  302. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +0 -1
@@ -18,6 +18,7 @@ export const runtime: import("@1agents/acp-service/runtime").AcpxRuntime;
18
18
  export const activeSessions: Map<any, any>;
19
19
  export const sessionBackgroundTasks: Map<any, any>;
20
20
  export function gracefulExit(source: any): Promise<void>;
21
+ export function prewarmGrokSession(targetCwd: any): Promise<void>;
21
22
  export const pendingPermissions: Map<any, any>;
22
23
  export const pendingAskUserQuestions: Map<any, any>;
23
24
  export const pendingExitPlanModes: Map<any, any>;
@@ -5,6 +5,8 @@ import * as path from "node:path";
5
5
  import { WebSocketServer } from "ws";
6
6
  import { attachAcpConnection } from "./acp-connection.js";
7
7
  import { createServiceAgentRegistry } from "./catalog.js";
8
+ import { CapacityQueue } from "./capacity-queue.js";
9
+ import { createCapacityLifecycle } from "./capacity-lifecycle.js";
8
10
  import { createAcpRuntime, createRuntimeStore, createTurnJournal, toSafeError, } from "@1agents/acp-service/runtime";
9
11
  import { historyToolInput, resolveRuntimeTurnId, stampHistoryTurnIds, } from "./history-turn-ids.js";
10
12
  // ----------------------------------------------------
@@ -80,10 +82,114 @@ function parseBackgroundTaskReminder(update) {
80
82
  // this session instead of letting later completions wipe earlier ones.
81
83
  const sessionBackgroundTasks = new Map();
82
84
  // Setup session runtime manager options
85
+ const processCapacity = new CapacityQueue();
86
+ let capacityLaunchAbort = new AbortController();
87
+ const sessionLaunchControllers = new Map();
88
+ const initializingSessionControllers = new Map();
89
+ const capacityLaunchSignals = new Map();
90
+ // A probed process lease is held before ensureSession. onBeforeSpawn must
91
+ // consume that lease instead of acquiring a second slot. launchId !== capacityId.
92
+ const preparedProcessLeases = new Map();
93
+ const preparedByLaunch = new Map();
94
+ const preparedLaunches = new Set();
95
+ const handshakeTimers = new Map();
96
+ function handshakeMs() {
97
+ const value = Number(process.env.ACP_HANDSHAKE_TIMEOUT_MS);
98
+ return Number.isFinite(value) && value > 0 ? value : 60_000;
99
+ }
100
+ // How long a permission, question or plan prompt waits for a person. The A2A
101
+ // workbench deadline (workbench.requestTimeoutMinutes) must not be longer.
102
+ function interactionTimeoutMs() {
103
+ const value = Number(process.env.ACP_INTERACTION_TIMEOUT_MS);
104
+ return Number.isFinite(value) && value > 0 ? value : 5 * 60 * 1000;
105
+ }
106
+ function interactionTimeoutText() {
107
+ return `${Math.round(interactionTimeoutMs() / 60_000)}min`;
108
+ }
109
+ function clearHandshake(launchId) {
110
+ const timer = handshakeTimers.get(launchId);
111
+ if (timer)
112
+ clearTimeout(timer);
113
+ handshakeTimers.delete(launchId);
114
+ preparedLaunches.delete(launchId);
115
+ preparedByLaunch.delete(launchId);
116
+ }
117
+ const launchOrigins = new Map();
118
+ const capacityLifecycle = createCapacityLifecycle({
119
+ acquire: request => {
120
+ const prepared = preparedByLaunch.get(request.id);
121
+ if (prepared)
122
+ return prepared;
123
+ const origin = launchOrigins.get(request.id);
124
+ return processCapacity.acquire(origin ? { ...request, origin } : request, {
125
+ signal: capacityLaunchSignals.get(request.id) || capacityLaunchAbort.signal,
126
+ });
127
+ },
128
+ });
129
+ /** Runtime session key -> the MCP servers its ensure_session asked for. */
130
+ const sessionMcpServers = new Map();
83
131
  const runtime = createAcpRuntime({
132
+ // Includes compatibility checks, probes and pre-warm launches. Native user
133
+ // processes outside this service are not admitted through this governor.
134
+ processLifecycle: {
135
+ async onBeforeSpawn(launch) {
136
+ const sessionKey = launch.scope.kind === "runtime-session" ? launch.scope.sessionKey : undefined;
137
+ const session = sessionKey ? sessionLaunchControllers.get(sessionKey) : undefined;
138
+ // Capture the generation before the lifecycle's deferred acquire runs.
139
+ const signal = AbortSignal.any([
140
+ capacityLaunchAbort.signal,
141
+ ...(session ? [session.controller.signal] : []),
142
+ ]);
143
+ capacityLaunchSignals.set(launch.launchId, signal);
144
+ signal.throwIfAborted();
145
+ if (sessionKey && preparedProcessLeases.has(sessionKey)) {
146
+ const lease = preparedProcessLeases.get(sessionKey);
147
+ preparedProcessLeases.delete(sessionKey);
148
+ preparedByLaunch.set(launch.launchId, Promise.resolve(lease));
149
+ preparedLaunches.add(launch.launchId);
150
+ }
151
+ const origin = typeof sessionKey === "string" && sessionKey.startsWith("prewarm_grok_")
152
+ ? "prewarm"
153
+ : typeof sessionKey === "string" && sessionKey ? "user-opened" : undefined;
154
+ if (origin)
155
+ launchOrigins.set(launch.launchId, origin);
156
+ await capacityLifecycle.onBeforeSpawn(launch);
157
+ signal.throwIfAborted();
158
+ // The 60s budget starts only after the process slot is held.
159
+ if (preparedLaunches.has(launch.launchId)) {
160
+ const timer = setTimeout(() => {
161
+ if (!preparedLaunches.has(launch.launchId))
162
+ return;
163
+ const current = sessionKey ? sessionLaunchControllers.get(sessionKey) : undefined;
164
+ current?.controller.abort(new Error("ACP handshake timed out"));
165
+ }, handshakeMs());
166
+ timer.unref?.();
167
+ handshakeTimers.set(launch.launchId, timer);
168
+ }
169
+ },
170
+ async onSpawned(started) {
171
+ clearHandshake(started.launchId);
172
+ await capacityLifecycle.onSpawned(started);
173
+ capacityLaunchSignals.delete(started.launchId);
174
+ launchOrigins.delete(started.launchId);
175
+ },
176
+ onSpawnFailed(failure) {
177
+ clearHandshake(failure.launchId);
178
+ capacityLaunchSignals.delete(failure.launchId);
179
+ launchOrigins.delete(failure.launchId);
180
+ return capacityLifecycle.onSpawnFailed(failure);
181
+ },
182
+ onExit(exit) {
183
+ clearHandshake(exit.launchId);
184
+ capacityLaunchSignals.delete(exit.launchId);
185
+ launchOrigins.delete(exit.launchId);
186
+ return capacityLifecycle.onExit(exit);
187
+ },
188
+ },
84
189
  cwd: process.cwd(),
85
190
  sessionStore: createRuntimeStore({ stateDir: DEFAULT_STATE_DIR }),
86
191
  agentRegistry: createServiceAgentRegistry(),
192
+ mcpServers: ({ sessionKey }) => sessionMcpServers.get(sessionKey) ?? [],
87
193
  permissionMode: "approve-reads", // default, will be overridden by session or client options
88
194
  onPermissionRequest: handlePermissionRequestCallback,
89
195
  onAskUserQuestion: handleAskUserQuestionCallback,
@@ -144,6 +250,8 @@ const turnJournal = createTurnJournal({ stateDir: DEFAULT_STATE_DIR });
144
250
  // sessionId -> { handle, activeTurn }
145
251
  const activeSessions = new Map();
146
252
  // Phase 2 Pre-warm pool for grok-build (scoped to the most recent CWD)
253
+ // Disabled: nothing schedules prewarmGrokSession. A spare starts without the
254
+ // session's env, so adopting one silently dropped settings such as GROK_HOME.
147
255
  let prewarmedGrokHandle = null;
148
256
  let prewarmedGrokCwd = null;
149
257
  let lastUsedCwd = process.cwd();
@@ -200,6 +308,40 @@ const HISTORY_PUSH_INTERVAL_MS = 300;
200
308
  const historyPushStates = new Map();
201
309
  // Map of currently initializing sessions: sessionId -> Promise<handle>
202
310
  const initializingSessions = new Map();
311
+ async function cancelInitializingSession(sessionId, expectedSignal) {
312
+ const initialization = initializingSessionControllers.get(sessionId);
313
+ if (!initialization)
314
+ return false;
315
+ if (expectedSignal && initialization.signal !== expectedSignal)
316
+ return false;
317
+ initialization.controller.abort(new DOMException("ACP session initialization canceled", "AbortError"));
318
+ // Wait for late handles and bridge state to be retired, not just ensureSession().
319
+ await initialization.done;
320
+ return true;
321
+ }
322
+ /**
323
+ * Close confirmation: the agent process recorded before close is gone and no process lease
324
+ * still names it. An unknown pid or a lease that outlives the wait stays unconfirmed.
325
+ */
326
+ async function confirmProcessReleased(pid, timeoutMs = 5_000) {
327
+ if (!Number.isInteger(pid) || pid <= 0)
328
+ return false;
329
+ const deadline = Date.now() + timeoutMs;
330
+ for (;;) {
331
+ let alive = true;
332
+ try {
333
+ process.kill(pid, 0);
334
+ }
335
+ catch (err) {
336
+ alive = err?.code === "EPERM";
337
+ }
338
+ if (!alive && !(await processCapacity.holdsChild(pid)))
339
+ return true;
340
+ if (Date.now() >= deadline)
341
+ return false;
342
+ await new Promise(resolve => setTimeout(resolve, 100));
343
+ }
344
+ }
203
345
  // Map of Agent UUID -> Client Session ID (for permission callbacks)
204
346
  const agentSessionToClientSession = new Map();
205
347
  function registerAgentSessionMapping(sessionId, handle) {
@@ -1111,6 +1253,11 @@ export async function dispatchCommand(ws, payload) {
1111
1253
  try {
1112
1254
  switch (action) {
1113
1255
  case "ensure_session": {
1256
+ // This object is supplied only by the process-local ACP adapter. JSON
1257
+ // extension metadata cannot manufacture an AbortSignal instance.
1258
+ const initializationSignal = payload.initializationSignal instanceof AbortSignal
1259
+ ? payload.initializationSignal : undefined;
1260
+ initializationSignal?.throwIfAborted();
1114
1261
  const { workspacePath, agentType, systemContext, mcpServers, resumeSessionId, acpSessionId, permissionMode, responsePolicy, env, launch, } = payload;
1115
1262
  const normalizedResponsePolicy = responsePolicy === "summary" ? "summary" : "stream";
1116
1263
  console.time(`ensure_session_${sessionId}`);
@@ -1135,12 +1282,7 @@ export async function dispatchCommand(ws, payload) {
1135
1282
  // client supplying extra context wants.
1136
1283
  sessionOptions.systemPrompt = { append: systemContext };
1137
1284
  }
1138
- // Per-session MCP servers (e.g. the AI Project Manager's
1139
- // project-locked task tools). Merged with runtime-level servers in
1140
- // the engine; only applies when this session's client is created.
1141
- if (Array.isArray(mcpServers) && mcpServers.length > 0) {
1142
- sessionOptions.mcpServers = mcpServers;
1143
- }
1285
+ const hasMcpServers = Array.isArray(mcpServers) && mcpServers.length > 0;
1144
1286
  if (env && typeof env === "object" && !Array.isArray(env)) {
1145
1287
  const safeEnv = Object.fromEntries(Object.entries(env).filter(([key, value]) => typeof key === "string" && typeof value === "string"));
1146
1288
  if (Object.keys(safeEnv).length > 0) {
@@ -1204,6 +1346,13 @@ export async function dispatchCommand(ws, payload) {
1204
1346
  const runtimeSessionKey = profileId
1205
1347
  ? `${sessionId}@${profileId}-r${profileRevision}`
1206
1348
  : (payload.runtimeSessionKey || sessionId);
1349
+ // Per-session MCP servers (e.g. the DSH hand-back and ticket tools). The engine ignores
1350
+ // sessionOptions.mcpServers and reads only the runtime-level option, which looks them up
1351
+ // here by session key whenever it creates this session's client.
1352
+ if (hasMcpServers)
1353
+ sessionMcpServers.set(runtimeSessionKey, mcpServers);
1354
+ else
1355
+ sessionMcpServers.delete(runtimeSessionKey);
1207
1356
  // Prefer the explicit resumeSessionId (the agent-side UUID
1208
1357
  // recorded in the 1agents index); fall back to acpSessionId
1209
1358
  // for older clients. Empty string means "start a fresh session".
@@ -1237,7 +1386,10 @@ export async function dispatchCommand(ws, payload) {
1237
1386
  }
1238
1387
  if (existingSession) {
1239
1388
  console.log(`[acpx-server] Reconnecting to existing session: ${sessionId}`);
1240
- notifySessionTakenOver(existingSession.ws, ws, sessionId);
1389
+ // ACP attachment commits after its status read. A canceled attach
1390
+ // must not invalidate the original user's live request first.
1391
+ if (!initializationSignal)
1392
+ notifySessionTakenOver(existingSession.ws, ws, sessionId);
1241
1393
  existingSession.ws = ws;
1242
1394
  if (launchArgv.length > 0) {
1243
1395
  await runtime.ensureSession({
@@ -1302,11 +1454,14 @@ export async function dispatchCommand(ws, payload) {
1302
1454
  }
1303
1455
  if (initializingSessions.has(sessionId)) {
1304
1456
  console.log(`[acpx-server] Session ${sessionId} is currently initializing, awaiting...`);
1457
+ const initialization = initializingSessionControllers.get(sessionId);
1305
1458
  try {
1306
1459
  const handle = await initializingSessions.get(sessionId);
1460
+ initialization?.controller.signal.throwIfAborted();
1307
1461
  const sess = activeSessions.get(sessionId);
1308
1462
  if (sess) {
1309
- notifySessionTakenOver(sess.ws, ws, sessionId);
1463
+ if (!initializationSignal)
1464
+ notifySessionTakenOver(sess.ws, ws, sessionId);
1310
1465
  sess.ws = ws;
1311
1466
  sess.agentType = agentType;
1312
1467
  sess.sessionMode = await resolveGrokPermissionMode(handle, agentType);
@@ -1314,8 +1469,10 @@ export async function dispatchCommand(ws, payload) {
1314
1469
  sess.permissionMode = seededMode;
1315
1470
  }
1316
1471
  }
1472
+ initialization?.controller.signal.throwIfAborted();
1317
1473
  registerAgentSessionMapping(sessionId, handle);
1318
1474
  await sendAuthoritativeTurnSync(ws, sessionId, sess || { handle, agentType });
1475
+ initialization?.controller.signal.throwIfAborted();
1319
1476
  ws.send(JSON.stringify({
1320
1477
  event: "session_ready",
1321
1478
  sessionId,
@@ -1334,19 +1491,25 @@ export async function dispatchCommand(ws, payload) {
1334
1491
  lastUsedCwd = normalizedPath;
1335
1492
  }
1336
1493
  // Phase 2: Instant pre-warm hit for fresh grok-build sessions if CWD matches!
1337
- if (agentType === "grok-build" && launchArgv.length === 0 && !resumeId && prewarmedGrokHandle) {
1494
+ // The spare was created without this session's MCP servers, so such a session starts its own process.
1495
+ if (agentType === "grok-build" && launchArgv.length === 0 && !resumeId && !hasMcpServers && prewarmedGrokHandle) {
1338
1496
  if (prewarmedGrokCwd === normalizedPath) {
1339
1497
  console.time(`ensure_session_${sessionId}`);
1340
1498
  console.log(`[PRE-WARM] 🚀 Instant hit! Reusing pre-warmed grok-build handle for CWD=${normalizedPath}, session=${sessionId}`);
1499
+ // Take the spare before awaiting: concurrent ensure_session calls would otherwise adopt the same process.
1500
+ const spare = prewarmedGrokHandle;
1501
+ prewarmedGrokHandle = null;
1502
+ prewarmedGrokCwd = null;
1341
1503
  const handle = await runtime.adoptSession({
1342
- handle: prewarmedGrokHandle,
1504
+ handle: spare,
1343
1505
  sessionKey: sessionId,
1344
1506
  });
1345
- prewarmedGrokHandle = null;
1346
- prewarmedGrokCwd = null;
1347
1507
  console.timeEnd(`ensure_session_${sessionId}`);
1348
- // Asynchronously trigger background pre-warm for the next session using the same CWD
1349
- setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1508
+ // An earlier CAPACITY_PENDING attempt left this capacityId queued. The adopted process
1509
+ // already holds its own lease, so the entry would sit at the FIFO head and block every later launch.
1510
+ if (typeof payload.capacityId === "string" && payload.capacityId.trim()) {
1511
+ await processCapacity.cancel({ id: payload.capacityId.trim(), kind: "process" });
1512
+ }
1350
1513
  activeSessions.set(sessionId, {
1351
1514
  handle,
1352
1515
  activeTurn: null,
@@ -1384,6 +1547,28 @@ export async function dispatchCommand(ws, payload) {
1384
1547
  prewarmedGrokCwd = null;
1385
1548
  }
1386
1549
  }
1550
+ if (typeof payload.capacityId === "string" && payload.capacityId.trim()) {
1551
+ const capacityId = payload.capacityId.trim();
1552
+ if (capacityId.length > 4096) {
1553
+ sendError(ws, sessionId, "INVALID_PARAMS", "capacityId is invalid");
1554
+ console.timeEnd(`ensure_session_${sessionId}`);
1555
+ break;
1556
+ }
1557
+ const admission = await processCapacity.tryAdmit({ kind: "process", source: "automatic", id: capacityId, origin: capacityId.startsWith("a2a-") ? "job" : "user-opened" }, { signal: initializationSignal });
1558
+ if (admission?.pending === true) {
1559
+ sendCapacityPending(ws, sessionId, admission);
1560
+ console.timeEnd(`ensure_session_${sessionId}`);
1561
+ break;
1562
+ }
1563
+ const previousLease = preparedProcessLeases.get(runtimeSessionKey);
1564
+ if (previousLease && previousLease !== admission) {
1565
+ try {
1566
+ await previousLease.release();
1567
+ }
1568
+ catch { /* A later exit observation retries release. */ }
1569
+ }
1570
+ preparedProcessLeases.set(runtimeSessionKey, admission);
1571
+ }
1387
1572
  console.log(`[acpx-server] Initializing session. Agent: ${agentType}, Cwd: ${normalizedPath}, ResumeSessionId: ${resumeId || "<none>"}`);
1388
1573
  console.time(`ensure_session_${sessionId}`);
1389
1574
  let profileResumeFallback = profileChanged && !resumeId;
@@ -1397,11 +1582,25 @@ export async function dispatchCommand(ws, payload) {
1397
1582
  agentArgv: launchArgv.length > 0 ? launchArgv : undefined,
1398
1583
  authCredentials: transientCredentials,
1399
1584
  };
1585
+ let finishInitialization;
1586
+ const initialization = {
1587
+ controller: new AbortController(),
1588
+ signal: initializationSignal,
1589
+ done: new Promise(resolve => { finishInitialization = resolve; }),
1590
+ };
1591
+ const forwardCancellation = () => initialization.controller.abort(initializationSignal.reason);
1592
+ initializationSignal?.addEventListener("abort", forwardCancellation, { once: true });
1593
+ if (initializationSignal?.aborted)
1594
+ forwardCancellation();
1595
+ initializingSessionControllers.set(sessionId, initialization);
1596
+ sessionLaunchControllers.set(runtimeSessionKey, initialization);
1400
1597
  const sessionPromise = (async () => {
1401
1598
  try {
1599
+ initialization.controller.signal.throwIfAborted();
1402
1600
  return await runtime.ensureSession(ensureInput);
1403
1601
  }
1404
1602
  catch (err) {
1603
+ initialization.controller.signal.throwIfAborted();
1405
1604
  if (!profileChanged || !resumeId) {
1406
1605
  throw err;
1407
1606
  }
@@ -1410,21 +1609,22 @@ export async function dispatchCommand(ws, payload) {
1410
1609
  }
1411
1610
  })();
1412
1611
  initializingSessions.set(sessionId, sessionPromise);
1612
+ let initializedHandle;
1413
1613
  try {
1414
1614
  const handle = await sessionPromise;
1615
+ initializedHandle = handle;
1616
+ initialization.controller.signal.throwIfAborted();
1617
+ const sessionMode = await resolveGrokPermissionMode(handle, agentType);
1618
+ initialization.controller.signal.throwIfAborted();
1415
1619
  console.timeEnd(`ensure_session_${sessionId}`);
1416
1620
  console.log(`[DEBUG] ensure_session finished for session=${sessionId}`);
1417
- // Asynchronously trigger background pre-warm after a cold spawn using the new CWD
1418
- if (agentType === "grok-build" && launchArgv.length === 0) {
1419
- setTimeout(() => prewarmGrokSession(normalizedPath), 500);
1420
- }
1421
1621
  activeSessions.set(sessionId, {
1422
1622
  handle,
1423
1623
  activeTurn: null,
1424
1624
  promptQueue: [],
1425
1625
  ws,
1426
1626
  agentType,
1427
- sessionMode: await resolveGrokPermissionMode(handle, agentType),
1627
+ sessionMode,
1428
1628
  // permissionMode is per-session and overrides the runtime
1429
1629
  // default in handlePermissionRequestCallback. The Composer's
1430
1630
  // mode toggle later updates this via set_permission_mode.
@@ -1441,6 +1641,7 @@ export async function dispatchCommand(ws, payload) {
1441
1641
  if (normalizedResponsePolicy !== "summary") {
1442
1642
  await sendAuthoritativeTurnSync(ws, sessionId, activeSessions.get(sessionId), true);
1443
1643
  }
1644
+ initialization.controller.signal.throwIfAborted();
1444
1645
  ws.send(JSON.stringify({
1445
1646
  event: "session_ready",
1446
1647
  sessionId,
@@ -1459,8 +1660,35 @@ export async function dispatchCommand(ws, payload) {
1459
1660
  }));
1460
1661
  }
1461
1662
  }
1663
+ catch (error) {
1664
+ const leftover = preparedProcessLeases.get(runtimeSessionKey);
1665
+ if (leftover) {
1666
+ preparedProcessLeases.delete(runtimeSessionKey);
1667
+ try {
1668
+ await leftover.release();
1669
+ }
1670
+ catch { /* A later exit observation retries release. */ }
1671
+ }
1672
+ if (initialization.controller.signal.aborted && initializedHandle) {
1673
+ const current = activeSessions.get(sessionId);
1674
+ if (current?.handle === initializedHandle) {
1675
+ activeSessions.delete(sessionId);
1676
+ sessionBackgroundTasks.delete(sessionId);
1677
+ }
1678
+ unregisterAgentSessionMapping(initializedHandle);
1679
+ await runtime.close({ handle: initializedHandle, reason: "Session initialization canceled" });
1680
+ }
1681
+ throw error;
1682
+ }
1462
1683
  finally {
1463
- initializingSessions.delete(sessionId);
1684
+ initializationSignal?.removeEventListener("abort", forwardCancellation);
1685
+ if (initializingSessions.get(sessionId) === sessionPromise)
1686
+ initializingSessions.delete(sessionId);
1687
+ if (initializingSessionControllers.get(sessionId) === initialization)
1688
+ initializingSessionControllers.delete(sessionId);
1689
+ if (sessionLaunchControllers.get(runtimeSessionKey) === initialization)
1690
+ sessionLaunchControllers.delete(runtimeSessionKey);
1691
+ finishInitialization();
1464
1692
  }
1465
1693
  break;
1466
1694
  }
@@ -1848,6 +2076,10 @@ export async function dispatchCommand(ws, payload) {
1848
2076
  }
1849
2077
  const session = activeSessions.get(sessionId);
1850
2078
  if (!session) {
2079
+ if (await cancelInitializingSession(sessionId)) {
2080
+ clearSessionHistoryPush(sessionId);
2081
+ break;
2082
+ }
1851
2083
  sendError(ws, sessionId, "SESSION_NOT_FOUND", "Session not initialized");
1852
2084
  return;
1853
2085
  }
@@ -1901,16 +2133,24 @@ export async function dispatchCommand(ws, payload) {
1901
2133
  sendError(ws, sessionId, "INVALID_PARAMS", "sessionId is required");
1902
2134
  return;
1903
2135
  }
2136
+ const expectedSignal = payload.initializationSignal instanceof AbortSignal ? payload.initializationSignal : undefined;
2137
+ if (expectedSignal && activeSessions.get(sessionId)?.ws && activeSessions.get(sessionId).ws !== ws)
2138
+ break;
2139
+ await cancelInitializingSession(sessionId, expectedSignal);
1904
2140
  const session = activeSessions.get(sessionId);
2141
+ if (expectedSignal && session && session.ws !== ws)
2142
+ break;
1905
2143
  if (session) {
1906
2144
  console.log(`[acpx-server] Closing session: ${sessionId}`);
1907
2145
  unregisterAgentSessionMapping(session.handle);
2146
+ const pid = (await loadActiveSessionRecord(runtime, session.handle))?.pid;
1908
2147
  try {
1909
2148
  if (session.activeTurn) {
1910
2149
  await session.activeTurn.cancel({ reason: "Session closed" });
1911
2150
  }
1912
2151
  await cancelSessionQueue(session, sessionId);
1913
2152
  await runtime.close({ handle: session.handle, reason: "Session closed by request" });
2153
+ sessionMcpServers.delete(session.handle.sessionKey);
1914
2154
  }
1915
2155
  catch (err) {
1916
2156
  console.error(`[acpx-server] Error closing runtime handle:`, err);
@@ -1918,6 +2158,7 @@ export async function dispatchCommand(ws, payload) {
1918
2158
  }
1919
2159
  activeSessions.delete(sessionId);
1920
2160
  sessionBackgroundTasks.delete(sessionId);
2161
+ ws.send(JSON.stringify({ event: "session_released", sessionId, processReleased: await confirmProcessReleased(pid) }));
1921
2162
  }
1922
2163
  clearSessionHistoryPush(sessionId);
1923
2164
  break;
@@ -2157,6 +2398,15 @@ export async function dispatchCommand(ws, payload) {
2157
2398
  ws.send(JSON.stringify({ event: "all_sessions_closed" }));
2158
2399
  break;
2159
2400
  }
2401
+ case "capacity_cancel": {
2402
+ const capacityId = typeof payload.capacityId === "string" ? payload.capacityId.trim() : "";
2403
+ if (!capacityId || capacityId.length > 4096) {
2404
+ sendError(ws, sessionId, "INVALID_PARAMS", "capacityId is required");
2405
+ return;
2406
+ }
2407
+ await processCapacity.cancel({ id: capacityId, kind: "process" });
2408
+ break;
2409
+ }
2160
2410
  default:
2161
2411
  sendError(ws, sessionId, "UNKNOWN_ACTION", `Action ${action} is not supported`);
2162
2412
  }
@@ -2299,6 +2549,17 @@ function notifySessionTakenOver(previousWs, nextWs, sessionId) {
2299
2549
  console.warn(`[acpx-server] Failed to notify taken-over ws for ${sessionId}:`, err.message);
2300
2550
  }
2301
2551
  }
2552
+ function sendCapacityPending(ws, sessionId, pending) {
2553
+ ws.send(JSON.stringify({
2554
+ event: "error",
2555
+ sessionId,
2556
+ code: "CAPACITY_PENDING",
2557
+ message: "CAPACITY_PENDING",
2558
+ scope: "control",
2559
+ terminal: false,
2560
+ data: { position: pending.position, waitedMs: pending.waitedMs },
2561
+ }));
2562
+ }
2302
2563
  // Helper for sending error events
2303
2564
  function sendError(ws, sessionId, errorCode, message) {
2304
2565
  ws.send(JSON.stringify({
@@ -2817,13 +3078,13 @@ async function handleExitPlanModeCallback(req, ctx) {
2817
3078
  event: "exit_plan_mode_timeout",
2818
3079
  requestId,
2819
3080
  toolCallId,
2820
- message: "exit_plan_mode auto-abandoned after 5min timeout.",
3081
+ message: `exit_plan_mode auto-abandoned after ${interactionTimeoutText()} timeout.`,
2821
3082
  });
2822
3083
  }
2823
3084
  catch {
2824
3085
  // socket may already be closed
2825
3086
  }
2826
- }, 5 * 60 * 1000);
3087
+ }, interactionTimeoutMs());
2827
3088
  const payload = {
2828
3089
  event: "exit_plan_mode",
2829
3090
  sessionId: clientSessionId,
@@ -2886,13 +3147,13 @@ async function handleAskUserQuestionCallback(req, ctx) {
2886
3147
  event: "ask_user_question_timeout",
2887
3148
  requestId,
2888
3149
  toolCallId,
2889
- message: "ask_user_question auto-cancelled after 5min timeout.",
3150
+ message: `ask_user_question auto-cancelled after ${interactionTimeoutText()} timeout.`,
2890
3151
  });
2891
3152
  }
2892
3153
  catch {
2893
3154
  // socket may already be closed
2894
3155
  }
2895
- }, 5 * 60 * 1000);
3156
+ }, interactionTimeoutMs());
2896
3157
  const payload = {
2897
3158
  event: "ask_user_question",
2898
3159
  sessionId: clientSessionId,
@@ -2972,19 +3233,25 @@ async function handlePermissionRequestCallback(req, ctx) {
2972
3233
  (req.inferredKind === "edit" || req.inferredKind === "move" || req.inferredKind === "delete")) {
2973
3234
  return { outcome: "allow_once" };
2974
3235
  }
2975
- // Per-session mode shortcut — gates the prompt without round-tripping
2976
- // through the UI. approve-reads falls through to the normal flow
2977
- // (1acp internally auto-allows read/search; everything else prompts).
2978
- // approve-all and deny-all are blanket decisions for the entire
2979
- // session until the user toggles the mode again.
3236
+ // Bridge permissionMode (approve-reads / approve-all / deny-all) is not
3237
+ // applied. Tool posture follows ACP settings the user can select or import:
3238
+ // native mode (session/set_mode; Grok handled above) and config options such
3239
+ // as reasoning effort (session/set_config_option). Other agents fall through
3240
+ // to project allow-rules and a prompt.
3241
+ /*
2980
3242
  if (!grokMode && session.permissionMode === "approve-all") {
2981
- console.log(`[acpx-server] permission mode=approve-all → auto allow_once for ${req.raw.toolCall.title}`);
2982
- return { outcome: "allow_once" };
3243
+ console.log(
3244
+ `[acpx-server] permission mode=approve-all → auto allow_once for ${req.raw.toolCall.title}`,
3245
+ );
3246
+ return { outcome: "allow_once" };
2983
3247
  }
2984
3248
  if (!grokMode && session.permissionMode === "deny-all") {
2985
- console.log(`[acpx-server] permission mode=deny-all → auto reject_once for ${req.raw.toolCall.title}`);
2986
- return { outcome: "reject_once" };
3249
+ console.log(
3250
+ `[acpx-server] permission mode=deny-all → auto reject_once for ${req.raw.toolCall.title}`,
3251
+ );
3252
+ return { outcome: "reject_once" };
2987
3253
  }
3254
+ */
2988
3255
  // Project-level "总是允许" allowlist: a prior allow_always for this
2989
3256
  // tool+prefix auto-approves without prompting again. Read fresh from the
2990
3257
  // project file so it survives reap/resume/restart and is shared across
@@ -2998,7 +3265,7 @@ async function handlePermissionRequestCallback(req, ctx) {
2998
3265
  const requestId = `perm_${nextRequestId++}`;
2999
3266
  console.log(`[acpx-server] Intercepted permission request: ${req.raw.toolCall.title}. RequestId: ${requestId} for client session: ${clientSessionId}`);
3000
3267
  return new Promise((resolve, reject) => {
3001
- // Timeout handler: 5 minutes auto-deny
3268
+ // Timeout handler: auto-deny after the interaction timeout
3002
3269
  const timer = setTimeout(() => {
3003
3270
  console.warn(`[acpx-server] Permission request ${requestId} timed out. Auto-denying.`);
3004
3271
  pendingPermissions.delete(requestId);
@@ -3007,9 +3274,9 @@ async function handlePermissionRequestCallback(req, ctx) {
3007
3274
  sendRuntimeTurnEvent(session.ws, clientSessionId, session.activeTurn, {
3008
3275
  event: "permission_timeout",
3009
3276
  requestId,
3010
- message: `Permission request for "${req.raw.toolCall.title}" auto-denied after 5min timeout.`,
3277
+ message: `Permission request for "${req.raw.toolCall.title}" auto-denied after ${interactionTimeoutText()} timeout.`,
3011
3278
  });
3012
- }, 5 * 60 * 1000);
3279
+ }, interactionTimeoutMs());
3013
3280
  // Save pending info — include session and full payload so the reconnect
3014
3281
  // path can re-deliver the event to a new WebSocket without re-running
3015
3282
  // the permission logic.
@@ -3073,7 +3340,15 @@ async function handlePermissionRequestCallback(req, ctx) {
3073
3340
  // ----------------------------------------------------
3074
3341
  async function killAllManagedAgents() {
3075
3342
  console.log("[acpx-server] Cleaning up all active sessions and child processes...");
3343
+ const pendingLaunches = capacityLaunchAbort;
3344
+ capacityLaunchAbort = new AbortController();
3345
+ pendingLaunches.abort(new Error("ACP service is closing pending launches"));
3346
+ const pendingInitializations = [...initializingSessionControllers.values()];
3347
+ for (const initialization of pendingInitializations) {
3348
+ initialization.controller.abort(new Error("ACP service is closing pending launches"));
3349
+ }
3076
3350
  const promises = [];
3351
+ promises.push(...pendingInitializations.map(initialization => initialization.done));
3077
3352
  for (const [sessionId, session] of activeSessions.entries()) {
3078
3353
  try {
3079
3354
  unregisterAgentSessionMapping(session.handle);
@@ -3128,6 +3403,6 @@ export function attachProcessSignalHandlers() {
3128
3403
  void gracefulExit("SIGTERM");
3129
3404
  });
3130
3405
  }
3131
- export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, };
3406
+ export { runtime, activeSessions, sessionBackgroundTasks, killAllManagedAgents, gracefulExit, prewarmGrokSession, };
3132
3407
  export { pendingPermissions, pendingAskUserQuestions, pendingExitPlanModes, loadSessionHistory };
3133
3408
  export async function readRuntimeRecord(id) { return runtime.options.sessionStore.load(id); }
@@ -0,0 +1,5 @@
1
+ /** Bind runtime launch admission to durable device capacity reservations. */
2
+ import type { AcpProcessLifecycle } from '@1agents/acp-service/runtime';
3
+ import type { CapacityGovernor, CapacitySource } from './capacity.js';
4
+ /** The runtime owns child termination; capacity remains reserved until its exit is observed. */
5
+ export declare function createCapacityLifecycle(governor: Pick<CapacityGovernor, 'acquire'>, source?: CapacitySource): AcpProcessLifecycle;