@madarco/agentbox 0.31.4 → 0.32.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 (722) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/_cloud-attach-UXH3VKTM.js +31 -0
  3. package/dist/{chunk-VQONUZE4.js → chunk-2W3W3KNR.js} +4 -4
  4. package/dist/{chunk-RUKTOHK7.js → chunk-3AYSA62C.js} +2 -2
  5. package/dist/{chunk-EXF4PLBN.js → chunk-3ISG5THX.js} +3 -3
  6. package/dist/{chunk-BYZPRB7U.js → chunk-5D46PE5V.js} +5 -5
  7. package/dist/{chunk-IF4VXKJK.js → chunk-5F5NBZG7.js} +3 -3
  8. package/dist/{chunk-ZUTC2JZM.js → chunk-65G5R2HW.js} +27 -5
  9. package/dist/chunk-65G5R2HW.js.map +1 -0
  10. package/dist/{chunk-KCDLAP5Q.js → chunk-66GAYIJZ.js} +3252 -936
  11. package/dist/chunk-66GAYIJZ.js.map +1 -0
  12. package/dist/{chunk-IQMDGAMB.js → chunk-6N7OSMEA.js} +4 -4
  13. package/dist/{chunk-CUIJ2PIN.js → chunk-7PTM6JEX.js} +26 -22
  14. package/dist/{chunk-CUIJ2PIN.js.map → chunk-7PTM6JEX.js.map} +1 -1
  15. package/dist/{chunk-EP4IFSV5.js → chunk-B3C6NQB7.js} +75 -26
  16. package/dist/chunk-B3C6NQB7.js.map +1 -0
  17. package/dist/{chunk-L567TKOK.js → chunk-BJLUG6TE.js} +5 -5
  18. package/dist/{chunk-AYREFYEF.js → chunk-BV2UZ4SG.js} +4 -4
  19. package/dist/{chunk-MBZ4UOWF.js → chunk-EAT5IEWA.js} +3 -3
  20. package/dist/{chunk-ENFWBFBI.js → chunk-GBEV7ETR.js} +4 -4
  21. package/dist/{chunk-4NO5MO2P.js → chunk-GLIWCNFE.js} +6 -6
  22. package/dist/chunk-GVNKIACA.js +223 -0
  23. package/dist/chunk-GVNKIACA.js.map +1 -0
  24. package/dist/{chunk-VWJBQGXD.js → chunk-HCKRUAHW.js} +6 -6
  25. package/dist/{chunk-IFPTD73K.js → chunk-HUVSTEJR.js} +2 -2
  26. package/dist/{chunk-NKHRFR5G.js → chunk-IL7R2X6B.js} +16 -16
  27. package/dist/{chunk-5UX2HAF4.js → chunk-IQ4WLVXE.js} +43 -43
  28. package/dist/{chunk-AAMPHDB2.js → chunk-JL4EJ4EH.js} +5 -5
  29. package/dist/{chunk-OXBWZG2N.js → chunk-KTB7JGPA.js} +4 -4
  30. package/dist/{chunk-YL3VEQTS.js → chunk-LFBCFWG6.js} +5 -5
  31. package/dist/{chunk-MJZPECVQ.js → chunk-M2DWTQRF.js} +2 -2
  32. package/dist/{chunk-PXH3DERD.js → chunk-MB2K74BI.js} +164 -2
  33. package/dist/chunk-MB2K74BI.js.map +1 -0
  34. package/dist/{chunk-2MBELUE6.js → chunk-NGCG3IBH.js} +9 -9
  35. package/dist/{chunk-QT4MOS6R.js → chunk-NX27A3F2.js} +23 -23
  36. package/dist/{chunk-4Y365UYP.js → chunk-OUHDSEVQ.js} +2 -2
  37. package/dist/{chunk-M6VAID7T.js → chunk-QBVRWGXD.js} +2 -2
  38. package/dist/{chunk-VOVRWIBC.js → chunk-QLZPJIWF.js} +13 -13
  39. package/dist/{chunk-GCS5XAPC.js → chunk-R3XDO4SN.js} +3 -3
  40. package/dist/{chunk-IQ6BQ2LX.js → chunk-RF7Q7SHU.js} +3 -3
  41. package/dist/{chunk-YSC4VY43.js → chunk-SAEZJZ5Z.js} +3 -3
  42. package/dist/{chunk-QDVIMN57.js → chunk-TDPHZWJI.js} +4 -4
  43. package/dist/{chunk-QWWDG5B7.js → chunk-U5MUWZOS.js} +6 -6
  44. package/dist/{chunk-LR5RNEVO.js → chunk-ULQPPQ23.js} +3 -3
  45. package/dist/{chunk-75JF44DH.js → chunk-VWSERFTW.js} +2 -2
  46. package/dist/{chunk-4LSLXBFN.js → chunk-XFMCRD2J.js} +6 -6
  47. package/dist/{chunk-X6SZPGL5.js → chunk-YNAJUTYC.js} +6 -6
  48. package/dist/{chunk-C67DVYWA.js → chunk-ZKOLV4ZN.js} +37 -2
  49. package/dist/chunk-ZKOLV4ZN.js.map +1 -0
  50. package/dist/{cli-XRF7WFE5.js → cli-HFZMZWRM.js} +8 -8
  51. package/dist/{cli-KT5X4J74.js → cli-HPYDF5AP.js} +8 -8
  52. package/dist/{cli-HFLU5QTD.js → cli-PWK63DQI.js} +7 -7
  53. package/dist/{cli-7JW54ZTA.js → cli-RC5F6DYP.js} +8 -8
  54. package/dist/{cli-7Z7BD23R.js → cli-S7RGCNHG.js} +7 -7
  55. package/dist/cloud-backends.js +4 -4
  56. package/dist/{control-plane-DGLF4MBB.js → control-plane-HRJRAYKV.js} +19 -19
  57. package/dist/{cp-hub-upload-7YESYCVS.js → cp-hub-upload-N4PPUZHE.js} +6 -6
  58. package/dist/{custody-client-P7SCEDU2.js → custody-client-KYEZET6C.js} +4 -4
  59. package/dist/{deploy-hetzner-FOCNRRB2.js → deploy-hetzner-A42GILM3.js} +8 -8
  60. package/dist/{dist-63YBVZW4.js → dist-5OXP2N6H.js} +8 -8
  61. package/dist/{dist-36WLI6E2.js → dist-64QL2Q5L.js} +6 -6
  62. package/dist/{dist-MITAKWKQ.js → dist-D4LLY6JV.js} +7 -7
  63. package/dist/{dist-TJJ6KBNZ.js → dist-ETGTZQUT.js} +255 -5
  64. package/dist/{dist-54VRDCUU.js → dist-GS36Y2CW.js} +7 -7
  65. package/dist/{dist-CBPQZPQN.js → dist-HGUSK4LL.js} +7 -7
  66. package/dist/{dist-E4VLIH3H.js → dist-JU5COR7Y.js} +7 -7
  67. package/dist/{dist-2CAWJQT5.js → dist-NJ2U42MZ.js} +9 -5
  68. package/dist/{dist-FHPNYDCF.js → dist-URWWHI3X.js} +8 -2
  69. package/dist/{dist-XSAPZOEG.js → dist-Z4S5EKUS.js} +7 -7
  70. package/dist/{host-reach-drainer-XFLSMTSX.js → host-reach-drainer-WIKLZSLZ.js} +2 -2
  71. package/dist/host-session-YP5RKV6T.js +29 -0
  72. package/dist/hub-A6U3YB5D.js +39 -0
  73. package/dist/{hub-adopt-IYZ3WXYN.js → hub-adopt-O4LQLW6N.js} +6 -6
  74. package/dist/{hub-api-client-WOZ2BQ6H.js → hub-api-client-BI3E37CF.js} +3 -3
  75. package/dist/{hub-docker-target-IQHX6OYX.js → hub-docker-target-D67UXZSU.js} +13 -13
  76. package/dist/index.js +1223 -229
  77. package/dist/index.js.map +1 -1
  78. package/dist/{plugin-update-2ACFHFUI.js → plugin-update-LI3QDA4K.js} +4 -4
  79. package/dist/prepare-5Y7DWMZ7.js +45 -0
  80. package/dist/prepared-custody-L6PXXLD3.js +39 -0
  81. package/dist/{prepared-state-FO74QUCP-PZLOM6HD.js → prepared-state-FO74QUCP-M4Q2X3KN.js} +3 -3
  82. package/dist/{publish-credentials-TO5IIW2T.js → publish-credentials-WJ4KLIMW.js} +8 -8
  83. package/dist/{registry-X33JZU6B.js → registry-6VF5VPGD.js} +4 -4
  84. package/dist/relay-732OVYXR.js +22 -0
  85. package/dist/{remote-docker-share-YADHIHXV.js → remote-docker-share-WY5U5USV.js} +10 -10
  86. package/dist/remote-docker-share-WY5U5USV.js.map +1 -0
  87. package/dist/{tool-grant-push-7G2QAN3J.js → tool-grant-push-YQYYNMRQ.js} +3 -3
  88. package/package.json +1 -1
  89. package/runtime/_shared/ctl.cjs +1026 -309
  90. package/runtime/digitalocean/ctl.cjs +1026 -309
  91. package/runtime/docker/packages/ctl/dist/bin.cjs +1026 -309
  92. package/runtime/e2b/ctl.cjs +1026 -309
  93. package/runtime/hetzner/ctl.cjs +1026 -309
  94. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  95. package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +24 -0
  96. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  97. package/runtime/hub/apps/hub/.next/routes-manifest.json +188 -0
  98. package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page_client-reference-manifest.js +1 -1
  99. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
  100. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
  101. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
  102. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +4 -4
  103. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
  104. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/agent/route.js.nft.json +1 -1
  105. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/backup/route.js +2 -2
  106. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/backup/route.js.nft.json +1 -1
  107. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
  108. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js +2 -2
  109. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js.nft.json +1 -1
  110. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/clone/route.js +2 -2
  111. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/clone/route.js.nft.json +1 -1
  112. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +4 -4
  113. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
  114. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
  115. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/logs/route.js.nft.json +1 -1
  116. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
  117. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
  118. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
  119. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
  120. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
  121. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
  122. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
  123. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
  124. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/upload/route.js +2 -2
  125. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/upload/route.js.nft.json +1 -1
  126. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js.nft.json +1 -1
  127. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/web/route.js.nft.json +1 -1
  128. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +4 -4
  129. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
  130. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/checkpoints/route.js.nft.json +1 -1
  131. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/[...path]/route.js +3 -3
  132. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
  133. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
  134. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
  135. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
  136. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
  137. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
  138. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
  139. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
  140. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/route.js.nft.json +1 -1
  141. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/app-paths-manifest.json +3 -0
  142. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/build-manifest.json +9 -0
  143. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/server-reference-manifest.json +4 -0
  144. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js +9 -0
  145. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js.map +5 -0
  146. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js.nft.json +1 -0
  147. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route_client-reference-manifest.js +3 -0
  148. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/app-paths-manifest.json +3 -0
  149. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/build-manifest.json +9 -0
  150. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/server-reference-manifest.json +4 -0
  151. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js +10 -0
  152. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js.map +5 -0
  153. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js.nft.json +1 -0
  154. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route_client-reference-manifest.js +3 -0
  155. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/app-paths-manifest.json +3 -0
  156. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/build-manifest.json +9 -0
  157. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/server-reference-manifest.json +4 -0
  158. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js +10 -0
  159. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js.map +5 -0
  160. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js.nft.json +1 -0
  161. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route_client-reference-manifest.js +3 -0
  162. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/app-paths-manifest.json +3 -0
  163. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/build-manifest.json +9 -0
  164. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/server-reference-manifest.json +4 -0
  165. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js +9 -0
  166. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js.map +5 -0
  167. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js.nft.json +1 -0
  168. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route_client-reference-manifest.js +3 -0
  169. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/app-paths-manifest.json +3 -0
  170. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/build-manifest.json +9 -0
  171. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/server-reference-manifest.json +4 -0
  172. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js +10 -0
  173. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js.map +5 -0
  174. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js.nft.json +1 -0
  175. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route_client-reference-manifest.js +3 -0
  176. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/app-paths-manifest.json +3 -0
  177. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/build-manifest.json +9 -0
  178. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/server-reference-manifest.json +4 -0
  179. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js +9 -0
  180. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js.map +5 -0
  181. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js.nft.json +1 -0
  182. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route_client-reference-manifest.js +3 -0
  183. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/app-paths-manifest.json +3 -0
  184. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/build-manifest.json +9 -0
  185. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/server-reference-manifest.json +4 -0
  186. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js +10 -0
  187. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js.map +5 -0
  188. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js.nft.json +1 -0
  189. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route_client-reference-manifest.js +3 -0
  190. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/app-paths-manifest.json +3 -0
  191. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/build-manifest.json +9 -0
  192. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/server-reference-manifest.json +4 -0
  193. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js +10 -0
  194. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js.map +5 -0
  195. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js.nft.json +1 -0
  196. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route_client-reference-manifest.js +3 -0
  197. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
  198. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/bots/route.js.nft.json +1 -1
  199. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
  200. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/create-preflight/route.js +2 -2
  201. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/create-preflight/route.js.nft.json +1 -1
  202. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/restore/route.js +2 -2
  203. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/restore/route.js.nft.json +1 -1
  204. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
  205. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/seed/route.js.nft.json +1 -1
  206. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
  207. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
  208. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
  209. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
  210. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
  211. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
  212. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/size-check/route.js +2 -2
  213. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/size-check/route.js.nft.json +1 -1
  214. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
  215. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js +2 -2
  216. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js.nft.json +1 -1
  217. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/system/route.js.nft.json +1 -1
  218. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/app-paths-manifest.json +3 -0
  219. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/build-manifest.json +9 -0
  220. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/server-reference-manifest.json +4 -0
  221. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js +10 -0
  222. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js.map +5 -0
  223. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js.nft.json +1 -0
  224. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route_client-reference-manifest.js +3 -0
  225. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/app-paths-manifest.json +3 -0
  226. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/build-manifest.json +9 -0
  227. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/server-reference-manifest.json +4 -0
  228. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js +9 -0
  229. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js.map +5 -0
  230. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js.nft.json +1 -0
  231. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route_client-reference-manifest.js +3 -0
  232. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/app-paths-manifest.json +3 -0
  233. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/build-manifest.json +9 -0
  234. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/server-reference-manifest.json +4 -0
  235. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js +9 -0
  236. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js.map +5 -0
  237. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js.nft.json +1 -0
  238. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route_client-reference-manifest.js +3 -0
  239. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/app-paths-manifest.json +3 -0
  240. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/build-manifest.json +9 -0
  241. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/server-reference-manifest.json +4 -0
  242. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js +10 -0
  243. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js.map +5 -0
  244. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js.nft.json +1 -0
  245. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route_client-reference-manifest.js +3 -0
  246. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/app-paths-manifest.json +3 -0
  247. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/build-manifest.json +9 -0
  248. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/server-reference-manifest.json +4 -0
  249. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js +10 -0
  250. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js.map +5 -0
  251. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js.nft.json +1 -0
  252. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route_client-reference-manifest.js +3 -0
  253. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/app-paths-manifest.json +3 -0
  254. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/build-manifest.json +9 -0
  255. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/server-reference-manifest.json +4 -0
  256. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js +9 -0
  257. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js.map +5 -0
  258. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js.nft.json +1 -0
  259. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route_client-reference-manifest.js +3 -0
  260. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/app-paths-manifest.json +3 -0
  261. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/build-manifest.json +9 -0
  262. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/server-reference-manifest.json +4 -0
  263. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js +10 -0
  264. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js.map +5 -0
  265. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js.nft.json +1 -0
  266. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route_client-reference-manifest.js +3 -0
  267. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/app-paths-manifest.json +3 -0
  268. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/build-manifest.json +9 -0
  269. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/server-reference-manifest.json +4 -0
  270. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js +10 -0
  271. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js.map +5 -0
  272. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js.nft.json +1 -0
  273. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route_client-reference-manifest.js +3 -0
  274. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/app-paths-manifest.json +3 -0
  275. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/build-manifest.json +9 -0
  276. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/server-reference-manifest.json +4 -0
  277. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js +9 -0
  278. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js.map +5 -0
  279. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js.nft.json +1 -0
  280. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route_client-reference-manifest.js +3 -0
  281. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/app-paths-manifest.json +3 -0
  282. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/build-manifest.json +9 -0
  283. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/server-reference-manifest.json +4 -0
  284. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js +10 -0
  285. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js.map +5 -0
  286. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js.nft.json +1 -0
  287. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route_client-reference-manifest.js +3 -0
  288. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/app-paths-manifest.json +3 -0
  289. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/build-manifest.json +9 -0
  290. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/server-reference-manifest.json +4 -0
  291. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js +9 -0
  292. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js.map +5 -0
  293. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js.nft.json +1 -0
  294. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route_client-reference-manifest.js +3 -0
  295. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/app-paths-manifest.json +3 -0
  296. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/build-manifest.json +9 -0
  297. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/server-reference-manifest.json +4 -0
  298. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js +10 -0
  299. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js.map +5 -0
  300. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js.nft.json +1 -0
  301. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route_client-reference-manifest.js +3 -0
  302. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/app-paths-manifest.json +3 -0
  303. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/build-manifest.json +9 -0
  304. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/server-reference-manifest.json +4 -0
  305. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js +10 -0
  306. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js.map +5 -0
  307. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js.nft.json +1 -0
  308. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route_client-reference-manifest.js +3 -0
  309. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/app-paths-manifest.json +3 -0
  310. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/build-manifest.json +9 -0
  311. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/server-reference-manifest.json +4 -0
  312. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js +10 -0
  313. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js.map +5 -0
  314. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js.nft.json +1 -0
  315. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route_client-reference-manifest.js +3 -0
  316. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/app-paths-manifest.json +3 -0
  317. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/build-manifest.json +9 -0
  318. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/server-reference-manifest.json +4 -0
  319. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js +10 -0
  320. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js.map +5 -0
  321. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js.nft.json +1 -0
  322. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route_client-reference-manifest.js +3 -0
  323. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/app-paths-manifest.json +3 -0
  324. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/build-manifest.json +9 -0
  325. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/server-reference-manifest.json +4 -0
  326. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js +10 -0
  327. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js.map +5 -0
  328. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js.nft.json +1 -0
  329. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route_client-reference-manifest.js +3 -0
  330. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  331. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
  332. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
  333. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
  334. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js.nft.json +1 -1
  335. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/web/route.js.nft.json +1 -1
  336. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page.js.nft.json +1 -1
  337. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page_client-reference-manifest.js +1 -1
  338. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  339. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  340. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
  341. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
  342. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  343. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  344. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page.js.nft.json +1 -1
  345. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page_client-reference-manifest.js +1 -1
  346. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +1 -1
  347. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
  348. package/runtime/hub/apps/hub/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  349. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  350. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  351. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  352. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  353. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  354. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  355. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  356. package/runtime/hub/apps/hub/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  357. package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +24 -0
  358. package/runtime/hub/apps/hub/.next/server/chunks/00je_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_assign_route_actions_1sufsej.js +3 -0
  359. package/runtime/hub/apps/hub/.next/server/chunks/00je_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_done_route_actions_216dixx.js +3 -0
  360. package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_managers_route_actions_1_vtgih.js +3 -0
  361. package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_tasks_route_actions_1h8tg_m.js +3 -0
  362. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_managers_sessions_route_actions_16dksub.js +3 -0
  363. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_managers_start_route_actions_1g-vmis.js +3 -0
  364. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_route_actions_03oih6y.js +3 -0
  365. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_assign_route_actions_196zwo9.js +3 -0
  366. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_reorder_route_actions_1zkcfk-.js +3 -0
  367. package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_workspaces_route_actions_12a7_y8.js +3 -0
  368. package/runtime/hub/apps/hub/.next/server/chunks/0web_next-internal_server_app_(dashboard)_api_v1_managers_[id]_route_actions_07cpyb_.js +3 -0
  369. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_attach_route_actions_0o-khw8.js +3 -0
  370. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_message_route_actions_0rjcqe5.js +3 -0
  371. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_notes_route_actions_1-mf4r_.js +3 -0
  372. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_resume_route_actions_0-cm1mu.js +3 -0
  373. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_stop_route_actions_16nrl1r.js +3 -0
  374. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_detect_route_actions_1sdbs-_.js +3 -0
  375. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_managers_route_actions_1sxymv0.js +3 -0
  376. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_rename_route_actions_0df5zi2.js +3 -0
  377. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_rescan_route_actions_1yra_w8.js +3 -0
  378. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_route_actions_1f56n_0.js +3 -0
  379. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_tasks_route_actions_1t-6quw.js +3 -0
  380. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_timeline_route_actions_0pbxblt.js +3 -0
  381. package/runtime/hub/apps/hub/.next/server/chunks/1viy_api_v1_workspaces_[id]_tasks_[taskId]_unassign_route_actions_18a1p_r.js +3 -0
  382. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-c97gb._.js +1 -1
  383. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0spnud2._.js → [root-of-the-server]__0-kl55b._.js} +1 -1
  384. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__028ifqb._.js → [root-of-the-server]__0-xlf9z._.js} +2 -2
  385. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__074mxl5._.js → [root-of-the-server]__0004tsz._.js} +2 -2
  386. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00bupbc._.js +1 -1
  387. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1cpr4qy._.js → [root-of-the-server]__0126167._.js} +1 -1
  388. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01fy5q0._.js +1 -1
  389. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02c077x._.js +3 -0
  390. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1ta1gr1._.js → [root-of-the-server]__02sueng._.js} +1 -1
  391. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0nndlre._.js → [root-of-the-server]__04-gm8c._.js} +2 -2
  392. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05uinnp._.js +1 -1
  393. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__06wy8zz._.js +3 -0
  394. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__071c-t4._.js +3 -0
  395. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__08jg8w8._.js +1 -1
  396. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09059m-._.js +1 -1
  397. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__092y7_z._.js +1 -1
  398. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09ti2-t._.js +3 -0
  399. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09y4pdw._.js +3 -0
  400. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_mog_h._.js +1 -1
  401. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a689u5._.js +3 -0
  402. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a8ere2._.js +3 -0
  403. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0bzqrje._.js +3 -0
  404. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c_r3oe._.js +3 -0
  405. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cdoz9i._.js +1 -1
  406. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cmu4sk._.js +1 -1
  407. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cxjxz0._.js +1 -1
  408. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d27tlu._.js +3 -0
  409. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d3fx1z._.js +3 -0
  410. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dm5oqm._.js +1 -1
  411. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dy5g2k._.js +1 -1
  412. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0e1uaxg._.js +1 -1
  413. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0e6_t-d._.js +3 -0
  414. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ets4cd._.js +1 -1
  415. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f2u0ul._.js +1 -1
  416. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f9p_4f._.js +1 -1
  417. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f_jmq2._.js +1 -1
  418. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0fksz_r._.js +1 -1
  419. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0fpygqn._.js +3 -0
  420. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0gym-rp._.js +1 -1
  421. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0hhlb2_._.js +1 -1
  422. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0i9phow._.js +1 -1
  423. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ikyoac._.js +1 -1
  424. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0j72bti._.js +1 -1
  425. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jb371p._.js +1 -1
  426. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jq6cdw._.js +3 -0
  427. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jt1d2s._.js +3 -0
  428. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0kcw8t0._.js +1 -1
  429. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0kdt9-i._.js +1 -1
  430. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0l27vs0._.js +1 -1
  431. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lc-j_n._.js +3 -0
  432. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lna-vq._.js +3 -0
  433. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0m5woxc._.js +1 -1
  434. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0mi9xib._.js +3 -0
  435. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0muy7eg._.js +3 -0
  436. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nn0_b5._.js +3 -0
  437. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0no30or._.js +3 -0
  438. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0o3sjtx._.js +1 -1
  439. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0onk5r0._.js +1 -1
  440. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0pik2ie._.js +3 -0
  441. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qde3vr._.js +1 -1
  442. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qt_r6a._.js +3 -0
  443. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ry8baf._.js +1 -1
  444. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0sg4y_2._.js +3 -0
  445. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0sgjn2j._.js +1 -1
  446. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0st6oln._.js +1 -1
  447. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t0p64l._.js +1 -1
  448. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0tbl11-._.js +3 -0
  449. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ve_tqz._.js +1 -1
  450. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w4smfx._.js +3 -0
  451. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0wo4sqj._.js +1 -1
  452. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0wujjkl._.js +3 -0
  453. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xbu3yj._.js +3 -0
  454. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xl1-w6._.js +1 -1
  455. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yct1tu._.js +1 -1
  456. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yg67t0._.js +1 -1
  457. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ykw5oe._.js +3 -0
  458. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1c1rcl-._.js → [root-of-the-server]__0zznyx2._.js} +2 -2
  459. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1--u2xl._.js +3 -0
  460. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-8sj4i._.js +1 -1
  461. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10kmcrt._.js +3 -0
  462. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10l_-cd._.js +3 -0
  463. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10yfcvu._.js +1 -1
  464. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__112hqrh._.js +3 -0
  465. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11c-21i._.js +3 -0
  466. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11qbpq8._.js +3 -0
  467. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11s1mrd._.js +1 -1
  468. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__128w1nz._.js +3 -0
  469. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__12b2kuv._.js +1 -1
  470. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__12gbq5m._.js +1 -1
  471. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13nfpq5._.js +3 -0
  472. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13vl4-h._.js +1 -1
  473. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__153b7kv._.js +1 -1
  474. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__157kmse._.js +1 -1
  475. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16695dw._.js +1 -1
  476. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__166_uek._.js +3 -0
  477. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16o0ij7._.js +1 -1
  478. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__175lucf._.js +1 -1
  479. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17p53e3._.js +3 -0
  480. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17y9pmx._.js +3 -0
  481. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__18ec5_t._.js +3 -0
  482. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__18xpvkc._.js +1 -1
  483. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1925hyw._.js +3 -0
  484. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19ew1r2._.js +3 -0
  485. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19grunx._.js +1 -1
  486. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_4v0mh._.js +3 -0
  487. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_cbcl1._.js +1 -1
  488. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_wb2uh._.js +3 -0
  489. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_xgm2e._.js +3 -0
  490. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1an6-yb._.js +3 -0
  491. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c0ex8m._.js +1 -1
  492. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c1e08-._.js +3 -0
  493. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c9f4uu._.js +1 -1
  494. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ci8hc2._.js +1 -1
  495. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1cs6d52._.js +3 -0
  496. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d60scp._.js +3 -0
  497. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dicjoc._.js +3 -0
  498. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1diipl4._.js +3 -0
  499. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dp2exz._.js +1 -1
  500. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1epnstn._.js +1 -1
  501. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1fjnz2l._.js +3 -0
  502. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1g5wnt2._.js +1 -1
  503. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1g9v7bq._.js +1 -1
  504. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1gon0_4._.js +3 -0
  505. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h_59cs._.js +1 -1
  506. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h_q3sn._.js +3 -0
  507. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hlugb4._.js +1 -1
  508. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hux-70._.js +1 -1
  509. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i-7bnu._.js +3 -0
  510. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i_el2y._.js +3 -0
  511. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1j6clag._.js +1 -1
  512. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1k6q17t._.js +3 -0
  513. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1khvg39._.js +1 -1
  514. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1lx9lyn._.js +3 -0
  515. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1m36v6k._.js +1 -1
  516. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mgu19x._.js +3 -0
  517. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mhyrr5._.js +3 -0
  518. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mk_lpu._.js +3 -0
  519. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mt32fu._.js +1 -1
  520. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1n1_2tw._.js +1 -1
  521. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1na4sdw._.js +3 -0
  522. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ntihlm._.js +3 -0
  523. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1odu62n._.js +3 -0
  524. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q6xrlt._.js +2 -2
  525. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1r4x1-y._.js +3 -0
  526. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rjs_x0._.js +1 -1
  527. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rxud0j._.js +1 -1
  528. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1s5app0._.js +1 -1
  529. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1sjz59l._.js +3 -0
  530. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1slo4q_._.js +1 -1
  531. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1thrazp._.js +3 -0
  532. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1twtnwr._.js +1 -1
  533. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1txvsbk._.js +3 -0
  534. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1uch-60._.js +1 -1
  535. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1um2jum._.js +3 -0
  536. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1vnnuo1._.js +1 -1
  537. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wegvep._.js +3 -0
  538. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wi5roz._.js +1 -1
  539. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xa9oiv._.js +3 -0
  540. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ypmy86._.js +3 -0
  541. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1zml9me._.js +1 -1
  542. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1zrf_a6._.js +1 -1
  543. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__2019yzl._.js +3 -0
  544. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20jyxyo._.js +2 -2
  545. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20ybhif._.js +1 -1
  546. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20zl5fr._.js +1 -1
  547. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__212dyoi._.js +1 -1
  548. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__218oup-._.js +1 -1
  549. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__21abvx9._.js +3 -0
  550. package/runtime/hub/apps/hub/.next/server/chunks/_0907rw0._.js +2 -1
  551. package/runtime/hub/apps/hub/.next/server/chunks/_0mcxq5g._.js +1 -1
  552. package/runtime/hub/apps/hub/.next/server/chunks/_0vg6gvw._.js +41 -41
  553. package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_openapi_ts_1yokmzt._.js +1 -1
  554. package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_validate_ts_16dhbzz._.js +1 -1
  555. package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +6 -6
  556. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__03-x9xy._.js +1 -1
  557. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1jqga8h._.js +1 -1
  558. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0r2xlss._.js +2 -1
  559. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_14-qzbg._.js +26 -26
  560. package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +1 -1
  561. package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +24 -0
  562. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  563. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  564. package/runtime/hub/apps/hub/.next/static/chunks/{31e1wjin30i__.css → 03_fxfc3849ms.css} +1 -1
  565. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/[action]/route.ts +4 -2
  566. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.ts +6 -4
  567. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/route.ts +2 -1
  568. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/actor.ts +48 -0
  569. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/envelope.ts +5 -2
  570. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/openapi.ts +1687 -52
  571. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/validate.ts +527 -1
  572. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/attach/route.ts +26 -0
  573. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/message/route.ts +34 -0
  574. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/notes/route.ts +26 -0
  575. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/resume/route.ts +26 -0
  576. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/route.ts +34 -0
  577. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/stop/route.ts +23 -0
  578. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/detect/route.ts +33 -0
  579. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/route.ts +27 -0
  580. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/tasks/route.ts +30 -0
  581. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/route.ts +19 -0
  582. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.ts +22 -0
  583. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.ts +61 -0
  584. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/rename/route.ts +25 -0
  585. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.ts +20 -0
  586. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/route.ts +34 -0
  587. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.ts +33 -0
  588. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.ts +23 -0
  589. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.ts +54 -0
  590. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.ts +25 -0
  591. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.ts +34 -0
  592. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.ts +33 -0
  593. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.ts +59 -0
  594. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.ts +25 -0
  595. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/route.ts +31 -0
  596. package/runtime/hub/apps/hub/{chunk-SM2XYDPL.js → chunk-FBNAIUXZ.js} +36 -1
  597. package/runtime/hub/apps/hub/{chunk-F6GOERHP.js → chunk-GGHXBTGL.js} +3 -3
  598. package/runtime/hub/apps/hub/{chunk-7IIG6MIB.js → chunk-LEELYQVR.js} +9 -9
  599. package/runtime/hub/apps/hub/{chunk-AAF4CYVH.js → chunk-MD2UNTZR.js} +5 -5
  600. package/runtime/hub/apps/hub/{chunk-7JBH42LK.js → chunk-MQ7AJUJJ.js} +2 -2
  601. package/runtime/hub/apps/hub/{chunk-AIFVVQPX.js → chunk-OFJRKISZ.js} +3317 -1031
  602. package/runtime/hub/apps/hub/{dist-DS5LGBGK.js → dist-3LDUYWPK.js} +7 -1
  603. package/runtime/hub/apps/hub/{dist-YOTRYCRK.js → dist-DENRW6O5.js} +7 -3
  604. package/runtime/hub/apps/hub/{dist-BKCL4HAA.js → dist-NQYEPZJY.js} +4 -4
  605. package/runtime/hub/apps/hub/{dist-H7NIUVBD.js → dist-RIXE6NHS.js} +5 -5
  606. package/runtime/hub/apps/hub/{dist-YG4RVC24.js → dist-RK6SSH23.js} +5 -5
  607. package/runtime/hub/apps/hub/{dist-MQADLEEQ.js → dist-U5SDGYOA.js} +4 -4
  608. package/runtime/hub/apps/hub/{dist-LV6CHJVA.js → dist-U6XVHUNU.js} +4 -4
  609. package/runtime/hub/apps/hub/{dist-RJBPZWSZ.js → dist-W4YRUL6E.js} +4 -4
  610. package/runtime/hub/apps/hub/{dist-VENYRIRW.js → dist-Y3Q5YEOC.js} +4 -4
  611. package/runtime/hub/apps/hub/{hub-worker-DLFLGKCV.js → hub-worker-DVATYYST.js} +6 -6
  612. package/runtime/hub/apps/hub/lib/backend/background.ts +19 -0
  613. package/runtime/hub/apps/hub/lib/backend/box-facts.ts +97 -0
  614. package/runtime/hub/apps/hub/lib/backend/box-prs.ts +213 -0
  615. package/runtime/hub/apps/hub/lib/backend/deps.ts +99 -0
  616. package/runtime/hub/apps/hub/lib/backend/errors.ts +7 -0
  617. package/runtime/hub/apps/hub/lib/backend/github-prs.ts +302 -0
  618. package/runtime/hub/apps/hub/lib/backend/managers.ts +748 -0
  619. package/runtime/hub/apps/hub/lib/backend/timeline-lanes.ts +150 -0
  620. package/runtime/hub/apps/hub/lib/backend/timeline.ts +611 -0
  621. package/runtime/hub/apps/hub/lib/backend/workspaces.ts +439 -0
  622. package/runtime/hub/apps/hub/lib/boxes/backend-types.ts +355 -10
  623. package/runtime/hub/apps/hub/lib/boxes/postgres-source.ts +3 -0
  624. package/runtime/hub/apps/hub/lib/boxes/source.ts +18 -1
  625. package/runtime/hub/apps/hub/lib/boxes/types.ts +66 -0
  626. package/runtime/hub/apps/hub/lib/hub-backend.ts +114 -7
  627. package/runtime/hub/apps/hub/{prepared-state-FO74QUCP-FZ6PT4LA.js → prepared-state-FO74QUCP-75UBPW5I.js} +2 -2
  628. package/runtime/hub/apps/hub/server.js +2032 -163
  629. package/runtime/hub/apps/hub/test/backend-managers-background.test.ts +336 -0
  630. package/runtime/hub/apps/hub/test/backend-managers.test.ts +493 -0
  631. package/runtime/hub/apps/hub/test/backend-workspaces.test.ts +208 -0
  632. package/runtime/hub/apps/hub/test/box-prs.test.ts +198 -0
  633. package/runtime/hub/apps/hub/test/timeline-lanes.test.ts +261 -0
  634. package/runtime/hub/apps/hub/test/timeline.test.ts +1185 -0
  635. package/runtime/hub/apps/hub/test/validate.test.ts +252 -0
  636. package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
  637. package/runtime/relay/bin.cjs +1399 -616
  638. package/runtime/vercel/ctl.cjs +1026 -309
  639. package/share/host-skills/agentbox-info/SKILL.md +25 -4
  640. package/dist/_cloud-attach-B3BCOZ7U.js +0 -31
  641. package/dist/chunk-C67DVYWA.js.map +0 -1
  642. package/dist/chunk-EP4IFSV5.js.map +0 -1
  643. package/dist/chunk-KCDLAP5Q.js.map +0 -1
  644. package/dist/chunk-PXH3DERD.js.map +0 -1
  645. package/dist/chunk-ZUTC2JZM.js.map +0 -1
  646. package/dist/hub-OMGLWQEV.js +0 -39
  647. package/dist/prepare-OOZF37J6.js +0 -45
  648. package/dist/prepared-custody-E7CSZJ6V.js +0 -39
  649. package/dist/relay-7D5NOFKS.js +0 -22
  650. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00o_3sf._.js +0 -3
  651. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__08xwxyo._.js +0 -3
  652. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-mtsr6._.js +0 -3
  653. /package/dist/{_cloud-attach-B3BCOZ7U.js.map → _cloud-attach-UXH3VKTM.js.map} +0 -0
  654. /package/dist/{chunk-VQONUZE4.js.map → chunk-2W3W3KNR.js.map} +0 -0
  655. /package/dist/{chunk-RUKTOHK7.js.map → chunk-3AYSA62C.js.map} +0 -0
  656. /package/dist/{chunk-EXF4PLBN.js.map → chunk-3ISG5THX.js.map} +0 -0
  657. /package/dist/{chunk-BYZPRB7U.js.map → chunk-5D46PE5V.js.map} +0 -0
  658. /package/dist/{chunk-IF4VXKJK.js.map → chunk-5F5NBZG7.js.map} +0 -0
  659. /package/dist/{chunk-IQMDGAMB.js.map → chunk-6N7OSMEA.js.map} +0 -0
  660. /package/dist/{chunk-L567TKOK.js.map → chunk-BJLUG6TE.js.map} +0 -0
  661. /package/dist/{chunk-AYREFYEF.js.map → chunk-BV2UZ4SG.js.map} +0 -0
  662. /package/dist/{chunk-MBZ4UOWF.js.map → chunk-EAT5IEWA.js.map} +0 -0
  663. /package/dist/{chunk-ENFWBFBI.js.map → chunk-GBEV7ETR.js.map} +0 -0
  664. /package/dist/{chunk-4NO5MO2P.js.map → chunk-GLIWCNFE.js.map} +0 -0
  665. /package/dist/{chunk-VWJBQGXD.js.map → chunk-HCKRUAHW.js.map} +0 -0
  666. /package/dist/{chunk-IFPTD73K.js.map → chunk-HUVSTEJR.js.map} +0 -0
  667. /package/dist/{chunk-NKHRFR5G.js.map → chunk-IL7R2X6B.js.map} +0 -0
  668. /package/dist/{chunk-5UX2HAF4.js.map → chunk-IQ4WLVXE.js.map} +0 -0
  669. /package/dist/{chunk-AAMPHDB2.js.map → chunk-JL4EJ4EH.js.map} +0 -0
  670. /package/dist/{chunk-OXBWZG2N.js.map → chunk-KTB7JGPA.js.map} +0 -0
  671. /package/dist/{chunk-YL3VEQTS.js.map → chunk-LFBCFWG6.js.map} +0 -0
  672. /package/dist/{chunk-MJZPECVQ.js.map → chunk-M2DWTQRF.js.map} +0 -0
  673. /package/dist/{chunk-2MBELUE6.js.map → chunk-NGCG3IBH.js.map} +0 -0
  674. /package/dist/{chunk-QT4MOS6R.js.map → chunk-NX27A3F2.js.map} +0 -0
  675. /package/dist/{chunk-4Y365UYP.js.map → chunk-OUHDSEVQ.js.map} +0 -0
  676. /package/dist/{chunk-M6VAID7T.js.map → chunk-QBVRWGXD.js.map} +0 -0
  677. /package/dist/{chunk-VOVRWIBC.js.map → chunk-QLZPJIWF.js.map} +0 -0
  678. /package/dist/{chunk-GCS5XAPC.js.map → chunk-R3XDO4SN.js.map} +0 -0
  679. /package/dist/{chunk-IQ6BQ2LX.js.map → chunk-RF7Q7SHU.js.map} +0 -0
  680. /package/dist/{chunk-YSC4VY43.js.map → chunk-SAEZJZ5Z.js.map} +0 -0
  681. /package/dist/{chunk-QDVIMN57.js.map → chunk-TDPHZWJI.js.map} +0 -0
  682. /package/dist/{chunk-QWWDG5B7.js.map → chunk-U5MUWZOS.js.map} +0 -0
  683. /package/dist/{chunk-LR5RNEVO.js.map → chunk-ULQPPQ23.js.map} +0 -0
  684. /package/dist/{chunk-75JF44DH.js.map → chunk-VWSERFTW.js.map} +0 -0
  685. /package/dist/{chunk-4LSLXBFN.js.map → chunk-XFMCRD2J.js.map} +0 -0
  686. /package/dist/{chunk-X6SZPGL5.js.map → chunk-YNAJUTYC.js.map} +0 -0
  687. /package/dist/{cli-7JW54ZTA.js.map → cli-HFZMZWRM.js.map} +0 -0
  688. /package/dist/{cli-7Z7BD23R.js.map → cli-HPYDF5AP.js.map} +0 -0
  689. /package/dist/{cli-HFLU5QTD.js.map → cli-PWK63DQI.js.map} +0 -0
  690. /package/dist/{cli-KT5X4J74.js.map → cli-RC5F6DYP.js.map} +0 -0
  691. /package/dist/{cli-XRF7WFE5.js.map → cli-S7RGCNHG.js.map} +0 -0
  692. /package/dist/{control-plane-DGLF4MBB.js.map → control-plane-HRJRAYKV.js.map} +0 -0
  693. /package/dist/{cp-hub-upload-7YESYCVS.js.map → cp-hub-upload-N4PPUZHE.js.map} +0 -0
  694. /package/dist/{custody-client-P7SCEDU2.js.map → custody-client-KYEZET6C.js.map} +0 -0
  695. /package/dist/{deploy-hetzner-FOCNRRB2.js.map → deploy-hetzner-A42GILM3.js.map} +0 -0
  696. /package/dist/{dist-2CAWJQT5.js.map → dist-5OXP2N6H.js.map} +0 -0
  697. /package/dist/{dist-36WLI6E2.js.map → dist-64QL2Q5L.js.map} +0 -0
  698. /package/dist/{dist-63YBVZW4.js.map → dist-D4LLY6JV.js.map} +0 -0
  699. /package/dist/{dist-CBPQZPQN.js.map → dist-ETGTZQUT.js.map} +0 -0
  700. /package/dist/{dist-54VRDCUU.js.map → dist-GS36Y2CW.js.map} +0 -0
  701. /package/dist/{dist-FHPNYDCF.js.map → dist-HGUSK4LL.js.map} +0 -0
  702. /package/dist/{dist-E4VLIH3H.js.map → dist-JU5COR7Y.js.map} +0 -0
  703. /package/dist/{dist-MITAKWKQ.js.map → dist-NJ2U42MZ.js.map} +0 -0
  704. /package/dist/{dist-TJJ6KBNZ.js.map → dist-URWWHI3X.js.map} +0 -0
  705. /package/dist/{dist-XSAPZOEG.js.map → dist-Z4S5EKUS.js.map} +0 -0
  706. /package/dist/{host-reach-drainer-XFLSMTSX.js.map → host-reach-drainer-WIKLZSLZ.js.map} +0 -0
  707. /package/dist/{hub-OMGLWQEV.js.map → host-session-YP5RKV6T.js.map} +0 -0
  708. /package/dist/{hub-adopt-IYZ3WXYN.js.map → hub-A6U3YB5D.js.map} +0 -0
  709. /package/dist/{hub-api-client-WOZ2BQ6H.js.map → hub-adopt-O4LQLW6N.js.map} +0 -0
  710. /package/dist/{prepare-OOZF37J6.js.map → hub-api-client-BI3E37CF.js.map} +0 -0
  711. /package/dist/{hub-docker-target-IQHX6OYX.js.map → hub-docker-target-D67UXZSU.js.map} +0 -0
  712. /package/dist/{plugin-update-2ACFHFUI.js.map → plugin-update-LI3QDA4K.js.map} +0 -0
  713. /package/dist/{prepared-custody-E7CSZJ6V.js.map → prepare-5Y7DWMZ7.js.map} +0 -0
  714. /package/dist/{prepared-state-FO74QUCP-PZLOM6HD.js.map → prepared-custody-L6PXXLD3.js.map} +0 -0
  715. /package/dist/{registry-X33JZU6B.js.map → prepared-state-FO74QUCP-M4Q2X3KN.js.map} +0 -0
  716. /package/dist/{publish-credentials-TO5IIW2T.js.map → publish-credentials-WJ4KLIMW.js.map} +0 -0
  717. /package/dist/{relay-7D5NOFKS.js.map → registry-6VF5VPGD.js.map} +0 -0
  718. /package/dist/{remote-docker-share-YADHIHXV.js.map → relay-732OVYXR.js.map} +0 -0
  719. /package/dist/{tool-grant-push-7G2QAN3J.js.map → tool-grant-push-YQYYNMRQ.js.map} +0 -0
  720. /package/runtime/hub/apps/hub/.next/static/{o9_g9S5JH-r8bfNfmPa5H → psd9s1F7NglKqhj4_onRN}/_buildManifest.js +0 -0
  721. /package/runtime/hub/apps/hub/.next/static/{o9_g9S5JH-r8bfNfmPa5H → psd9s1F7NglKqhj4_onRN}/_clientMiddlewareManifest.js +0 -0
  722. /package/runtime/hub/apps/hub/.next/static/{o9_g9S5JH-r8bfNfmPa5H → psd9s1F7NglKqhj4_onRN}/_ssgManifest.js +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../packages/relay/src/types.ts","../../../packages/relay/src/registry.ts","../../../packages/relay/src/status-store.ts","../../../packages/relay/src/store/memory-store.ts","../../../packages/relay/src/prompts.ts","../../../packages/relay/src/permission.ts","../../../packages/relay/src/worktree.ts","../../../packages/relay/src/git-pat.ts","../../../packages/relay/src/lease.ts","../../../packages/relay/src/store/store-rpc.ts","../../../packages/relay/src/store/store-rpc-routes.ts","../../../packages/relay/src/custody/store.ts","../../../packages/relay/src/custody/routes.ts","../../../packages/relay/src/remote-boxes.ts","../../../packages/relay/src/store/write-through-store.ts","../../../packages/relay/src/github-app.ts","../../../packages/relay/src/queue.ts","../../../packages/relay/src/create-worker.ts","../../../packages/relay/src/core/handler.ts","../../../packages/relay/src/store/schema.ts","../../../packages/relay/src/store/postgres-store.ts","../../../packages/relay/src/store/sqlite-store.ts","../../../packages/relay/src/store/index.ts","../../../packages/relay/src/custody/fs-store.ts","../../../packages/relay/src/server.ts","../../../packages/relay/src/host-actions.ts","../../../packages/relay/src/gh.ts","../../../packages/relay/src/host-initiated.ts","../../../packages/relay/src/cp-rpc.ts","../../../packages/relay/src/cp-cache-capture.ts","../../../packages/relay/src/cp-cache.ts","../../../packages/relay/src/host-tools.ts","../../../packages/relay/src/host-exec.ts","../../../packages/relay/src/safe-transfer.ts","../../../packages/relay/src/registration-to-record.ts","../../../packages/relay/src/open-link.ts","../../../packages/relay/src/browser-open-budget.ts","../../../packages/relay/src/host-action-queue.ts","../../../packages/relay/src/host-reach.ts","../../../packages/relay/src/cp-cache-serve.ts","../../../packages/relay/src/cp-outbox.ts","../../../packages/relay/src/hub-notifier.ts","../../../packages/relay/src/notices.ts","../../../packages/relay/src/admin-gate.ts","../../../packages/relay/src/job-log-tail.ts","../../../packages/relay/src/credentials-fanout.ts","../../../packages/relay/src/autopause.ts","../../../packages/relay/src/cloud-keepalive.ts","../../../packages/relay/src/persistent-boxes.ts","../../../packages/relay/src/retention.ts","../../../packages/relay/src/host-reach-poller.ts","../../../packages/relay/src/sse-read.ts","../../../packages/relay/src/cp-outbox-drain.ts","../../../packages/relay/src/daemon.ts","../../../packages/relay/src/store/remote-store.ts"],"sourcesContent":["// DownloadKind's canonical decision home is `@agentbox/core`'s sync/files.ts;\n// imported here so DownloadRpcParams below can reference it, re-exported below\n// so existing `./types.js` importers stay unchanged.\nimport type { DownloadKind, PromptDetail, PromptKind as CorePromptKind } from '@agentbox/core';\n\nexport const DEFAULT_RELAY_PORT = 8787;\n/**\n * In-box relay port — distinct from {@link DEFAULT_RELAY_PORT} so a nested\n * agentbox run (developing agentbox inside a box) can bind its own host\n * relay on 8787 inside the outer box without colliding with the in-box\n * supervisor's relay. ctl always binds this port — as a real `mode: 'box'`\n * relay in cloud sandboxes, or a transparent forwarder to the host relay in\n * docker boxes. Override with `AGENTBOX_BOX_RELAY_PORT`.\n */\nexport const DEFAULT_BOX_RELAY_PORT = 8788;\nexport const RELAY_CONTAINER_NAME = 'agentbox-relay';\nexport const RELAY_NETWORK_NAME = 'agentbox-net';\nexport const RELAY_IMAGE_REF = 'agentbox/relay:dev';\nexport const RELAY_EVENT_RING_SIZE = 1000;\n\nexport type BoxKind = 'docker' | 'cloud';\n\nexport interface BoxRegistration {\n boxId: string;\n token: string;\n name: string;\n /** ISO-8601 time the relay received this registration. */\n registeredAt: string;\n /**\n * Which sandbox backend the box runs on. Drives whether the host relay\n * spawns a `CloudBoxPoller` for it. Absent on legacy registrations →\n * treated as 'docker'.\n */\n kind?: BoxKind;\n /**\n * For `kind === 'cloud'`: which cloud backend the executor must resolve\n * (e.g. 'daytona'). The host action executor lazy-imports\n * `@agentbox/sandbox-{backend}` to drive the in-sandbox channel.\n */\n backend?: string;\n /**\n * For `kind === 'cloud'`: the provider-native sandbox id (e.g. the Hetzner\n * server id). The per-box SSH key material lives on disk keyed by this id\n * (`~/.agentbox/boxes/<sandboxId>/ssh/`), so a PC that adopts a hub-created\n * box (`agentbox hub pull`) writes the downloaded keys under the same id, and\n * a reap can locate the box's custody `boxes/<sandboxId>/` subtree. Absent for\n * providers that mint no keypair (e2b/vercel) and legacy registrations.\n */\n sandboxId?: string;\n /** Docker container name; the relay needs it to `docker pause` an idle box. */\n containerName?: string;\n /** ISO-8601 box-creation time (BoxRecord.createdAt); used as a tie-break in auto-pause ordering. */\n createdAt?: string;\n /**\n * 1-based per-project box index (`agentbox list`'s `N` column). When set,\n * the relay writes status.json under `~/.agentbox/boxes/<id>-<n>-<mnemonic>/`\n * to match the host's `boxDirSegment` helper. Absent for legacy\n * (pre-feature) boxes; absent registrations fall back to `<id>-<mnemonic>`.\n */\n projectIndex?: number;\n /**\n * Container-path → host-worktree-dir mapping the host uses to resolve\n * git.pull/git.push RPCs. Empty when the box has no git repos.\n */\n worktrees?: BoxWorktree[];\n /**\n * Preview URL of the in-sandbox relay's `/bridge/*` surface. Set by cloud\n * registrations; the host's `CloudBoxPoller` long-polls it for status +\n * queued host-only RPCs.\n */\n previewUrl?: string;\n /**\n * Provider-proxy token for `previewUrl` (e.g. Daytona's\n * `x-daytona-preview-token`). The host poller attaches it as a header so\n * Daytona's preview proxy lets the request reach the in-sandbox relay.\n */\n previewToken?: string;\n /**\n * Bearer secret authenticating the host poller to `/bridge/*` on the\n * in-sandbox relay. Distinct from `token` (which the in-box agent sees)\n * so a compromised agent can't impersonate the host.\n */\n bridgeToken?: string;\n /**\n * When true, host-action confirm prompts for this box (git push, cp,\n * gh writes, checkpoint, browser.open) resolve to `y` without a human/orchestrator\n * answering. Set at registration from `box.autoApproveHostActions`. Off by\n * default; every auto-approval still emits a `host-action-auto-approved`\n * relay event so the bypass is auditable.\n */\n autoApproveHostActions?: boolean;\n /**\n * Mirrors `box.autoApproveSafeHostActions` (default true). When not `false`,\n * the SAFE subset of host actions (open PR, PR/review comments,\n * sanctioned-branch push, contained non-secret file copy/download, CI rerun,\n * checkpoint, granted host-tool calls, opening a link on the host browser)\n * auto-resolves without a prompt — each still emits a\n * `host-action-auto-approved` event. Absent → enabled.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * The box repo's origin remote URL (any git URL shape). The hosted control\n * plane resolves owner/repo from THIS registered value when leasing a\n * GitHub-App token (never from box-supplied RPC params). Absent for boxes\n * without a git origin.\n */\n originUrl?: string;\n /**\n * Public IP/host of the box's VM for direct-SSH providers (hetzner,\n * digitalocean). Lets a PC adopting this box (`agentbox hub adopt`)\n * reconstruct the `BoxRecord.ssh` target without asking the provider API.\n * Absent for SDK-reached providers (e2b/vercel/daytona) and legacy rows.\n */\n publicHost?: string;\n /** Resolved image/snapshot ref the box booted from (mirrors `CloudBoxFields.image`). */\n image?: string;\n /** In-box WebProxy port (mirrors `CloudBoxFields.webPort`), for `url` reconstruction. */\n webPort?: number;\n /** Agent the box was created for — an `AgentId` → `BoxRecord.lastAgent`. */\n agent?: string;\n /**\n * Custody `projects/<slug>` key of the box's project (owner__repo). Links a\n * registration to its seed material and secrets without re-deriving the slug\n * from `originUrl` on every consumer.\n */\n projectSlug?: string;\n}\n\nexport interface BoxWorktree {\n /** Path inside the container (e.g. /workspace, /workspace/app). */\n containerPath: string;\n /**\n * Absolute host path of the main repo whose `.git/` is shared with the\n * container. `git push/fetch` RPCs run with `git -C <hostMainRepo>` — the\n * worktree's working tree lives inside the container's writable layer, but\n * refs/objects are in this shared `.git/`, so push from the main repo dir\n * sees the in-container commits.\n */\n hostMainRepo: string;\n /** Branch the in-container worktree was created on (`agentbox/<box-name>`). */\n branch: string;\n /**\n * Last branch the HOST sanctioned for this box (create-time `branch`, updated\n * by host `agentbox git checkout`/`branch`/`pull <branch>`). The push gate\n * auto-approves only a scratch branch or this value; absent → treated as\n * `branch`.\n */\n sanctionedBranch?: string;\n}\n\nexport interface RelayEvent {\n /** Monotonic per-relay-process id, useful for `since=` polling. */\n id: number;\n /** Box id that posted the event. */\n boxId: string;\n /** Free-form event type, e.g. 'service-state', 'task-state', 'notify'. */\n type: string;\n /** ISO-8601 timestamp the relay assigned on receipt. */\n receivedAt: string;\n /** ISO-8601 client-supplied timestamp, if any. */\n ts?: string;\n /** Arbitrary JSON payload. */\n payload?: unknown;\n}\n\nexport interface PostEventBody {\n type: string;\n ts?: string;\n payload?: unknown;\n}\n\nexport interface PostRpcBody {\n method: string;\n params?: unknown;\n}\n\nexport interface RegisterBoxBody {\n boxId: string;\n token: string;\n name: string;\n /** Sandbox backend kind. Defaults to 'docker' when absent (legacy). */\n kind?: BoxKind;\n /** For cloud boxes: which backend (e.g. 'daytona'). Drives executor lazy-import. */\n backend?: string;\n /** For cloud boxes: provider-native sandbox id (SSH-key + custody dir key). */\n sandboxId?: string;\n containerName?: string;\n createdAt?: string;\n /**\n * 1-based per-project box index. Optional — additive; older boxes and\n * legacy (pre-feature) records register without it and the status path\n * falls back to `<id>-<mnemonic>`.\n */\n projectIndex?: number;\n worktrees?: BoxWorktree[];\n /** Required when `kind === 'cloud'`: in-sandbox relay's /bridge URL. */\n previewUrl?: string;\n /** When the cloud provider's proxy needs a token (Daytona) — attached as a header. */\n previewToken?: string;\n /** Required when `kind === 'cloud'`: bearer for /bridge/* auth. */\n bridgeToken?: string;\n /**\n * Mirrors `box.autoApproveHostActions`: when true, host-action confirm\n * prompts auto-resolve to `y` (audited via a relay event).\n */\n autoApproveHostActions?: boolean;\n /** Mirrors `box.autoApproveSafeHostActions` (default true; absent → enabled). */\n autoApproveSafeHostActions?: boolean;\n /** The box repo's origin remote URL (for GitHub-App lease repo resolution). */\n originUrl?: string;\n /** Public VM IP/host for direct-SSH providers (PC adoption). */\n publicHost?: string;\n /** Resolved image/snapshot ref the box booted from. */\n image?: string;\n /** In-box WebProxy port. */\n webPort?: number;\n /** Agent the box was created for. */\n agent?: string;\n /** Custody `projects/<slug>` key of the box's project. */\n projectSlug?: string;\n}\n\n/**\n * A host-only RPC the in-sandbox relay (box mode) parked while waiting for\n * the host poller to drain, execute on the host, and post back a result.\n * Equivalent of an in-flight `/rpc` call queued through the bridge.\n */\nexport interface HostAction {\n /** Server-generated uuid; the host poller echoes it back in the result. */\n id: string;\n /** Box that initiated the in-sandbox `/rpc`. */\n boxId: string;\n /** Original `/rpc` method (e.g. 'git.push', 'cp.toHost'). */\n method: string;\n /** Original `/rpc` params payload, opaque to the queue. */\n params: unknown;\n /** ISO-8601 enqueue time. */\n createdAt: string;\n /**\n * Host-reach only: custody prefix under which the executing machine should\n * cache what it copies out, so the same request still answers when that\n * machine is offline. Carried beside `params` rather than inside it — the\n * executor hands `params` to the normal RPC path untouched, and the box must\n * never be able to name a custody location.\n */\n cachePrefix?: string;\n}\n\nexport interface HostActionResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Response shape for `GET /bridge/poll`. */\nexport interface BridgePollResponse {\n /** Newly-queued host actions the poller hasn't drained yet. */\n actions: HostAction[];\n /** Events appended since `?since=<id>`. */\n events: RelayEvent[];\n /** Latest box-status snapshot, when one has been pushed. */\n status: unknown | null;\n /** Highest event id seen — the poller's next `?since=`. */\n cursor: number;\n}\n\n/** Body of `POST /bridge/action-result`. */\nexport interface BridgeActionResultBody {\n id: string;\n exitCode: number;\n stdout: string;\n stderr: string;\n /**\n * Host-reach only: which polling process is answering. The control box drops a\n * result from a machine that no longer owns the action, so a previous owner\n * still finishing after a re-offer cannot settle the box's request.\n */\n poller?: string;\n}\n\n// GitRpcParams's canonical wire-type home is `@agentbox/core`'s sync/git-refs.ts\n// (shared with the in-box ctl); re-exported here so `./types.js` importers stay unchanged.\nexport type { GitRpcParams } from '@agentbox/core';\n\nexport interface GitRpcResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface CheckpointRpcParams {\n /** Checkpoint name; defaults host-side to `<box-name>-<next>`. */\n name?: string;\n /** Flatten lower+upper into one tree instead of a layered delta. */\n merged?: boolean;\n /** Mark the new checkpoint as the project default. */\n setDefault?: boolean;\n /**\n * If a checkpoint with the same name exists, rm it (manifest + image)\n * before capturing. Makes the call safe to retry — useful when the\n * agent's harness lost the previous invocation's stdout and can't tell\n * whether it succeeded.\n */\n replace?: boolean;\n}\n\n/**\n * Host-action prompt UX is a y/N confirmation in the host wrapper's footer.\n * `select` / `text` exist because {@link PromptRequest} — the create-time\n * prompt schema every front-end renders — shares this union; no host-action\n * gate emits them today. A wrapper that meets a kind it cannot render falls\n * back to the confirm shape, so an older box against a newer relay degrades\n * rather than breaks (and vice-versa).\n */\nexport type PromptKind = CorePromptKind;\n\nexport interface PromptContext {\n /** Short label, e.g. \"git push\" or \"cp toHost: /workspace/x -> ~/dl/x\". */\n command?: string;\n /** Container path of the calling cwd, when known. */\n cwd?: string;\n /** Full argv; wrapper truncates for the footer. */\n argv?: string[];\n}\n\n/**\n * The shape pushed over SSE on `event: prompt-ask`. Also the shape the\n * relay-internal `askPrompt()` helper produces. Not a /rpc method — the\n * relay generates these itself when it is about to take a host-side\n * action; the in-box ctl never asks for prompts directly.\n */\nexport interface PromptAskEvent {\n /** Relay-generated UUIDv4 (the wrapper echoes it back in the answer). */\n id: string;\n kind: PromptKind;\n /** Primary question; wrapper truncates to footer width. */\n message: string;\n /** Optional second-line context; wrapper may show or skip. */\n detail?: string;\n /** Default when the user just hits Enter; default 'n' so y/N is the safe shape. */\n defaultAnswer?: 'y' | 'n';\n context?: PromptContext;\n /**\n * `kind: 'open-link'` only: the http(s) URL to open. The client that claims\n * the prompt opens THIS on its own machine and answers with\n * `openedByClient: true`; the relay opens it host-side only for a plain `y`\n * (an older client that rendered a confirm).\n */\n url?: string;\n /**\n * `kind: 'open-link'` only: no human needed — the host already decided this\n * link may open (safe subset + rate budget), so a client that can open a URL\n * should claim it and open it straight away instead of showing a card. Absent\n * means a human has to act (over budget, or strict mode).\n */\n autoOpen?: boolean;\n /**\n * Structured content a client MAY render richly (a file table, a credential\n * card) instead of the flat `detail` line. Shared with the create-time prompt\n * schema so the hub web and the tray need ONE renderer for both surfaces. No\n * host-action gate sets it yet; a client that meets an unknown variant renders\n * its `summary`.\n */\n richDetail?: PromptDetail;\n}\n\n/** Body of `POST /admin/prompts/answer`. */\nexport interface PromptAnswerBody {\n id: string;\n answer: 'y' | 'n';\n /** Set when the user dismissed the prompt (Esc / Ctrl-c); treated as 'n'. */\n cancelled?: boolean;\n /**\n * `kind: 'open-link'` only: \"I already opened this URL on my own machine.\"\n * Suppresses the relay's host-side fallback opener — without it a `y` opens\n * the link on whatever machine the relay runs on, which is the control box\n * rather than the human's laptop on a remote hub.\n */\n openedByClient?: boolean;\n}\n\n/**\n * Notice kinds. `checkpoint` is the first — a box is transiently frozen\n * while a checkpoint is captured (`docker commit` pauses the container).\n * Kept open-ended like {@link PromptKind} so an older wrapper degrades\n * gracefully (renders the message) when a newer relay sends a new kind.\n */\nexport type NoticeKind = 'checkpoint';\n\n/**\n * The shape pushed over SSE on `event: notice-set`. Unlike a prompt, a\n * notice is purely informational — there is no answer and the box's RPC\n * is not blocked on it. The host wrapper renders it as an animated footer\n * line so the user knows the box is busy, not stuck. Cleared by a\n * `notice-clear` event carrying `{ id }`.\n */\nexport interface BoxNoticeEvent {\n /** Relay-generated UUIDv4. */\n id: string;\n kind: NoticeKind;\n /** Warning text; the wrapper truncates to footer width. */\n message: string;\n}\n\n/** Body of `POST /admin/notices/set`; the response is `{ id }`. */\nexport interface SetNoticeBody {\n boxId: string;\n kind: NoticeKind;\n message: string;\n /** Auto-expiry backstop in ms; defaults relay-side. */\n ttlMs?: number;\n}\n\n/** Body of `POST /admin/notices/clear`. */\nexport interface ClearNoticeBody {\n boxId: string;\n id: string;\n}\n\nexport interface CpRpcParams {\n /**\n * Source path(s): box paths for `cp.toHost`, host paths for `cp.fromHost`.\n * The host CLI side is what carries the `<box>:` prefix when re-shelled.\n */\n sources?: string[];\n /** Destination path: host path for `cp.toHost`, box path for `cp.fromHost`. */\n dest?: string;\n /**\n * Legacy single-source wire shape (older in-box `agentbox-ctl` baked into a\n * box image before multi-source support). The relay normalizes these into\n * `sources`/`dest`. `boxPath` is the container path; `hostPath` the host path\n * (dst for toHost, src for fromHost).\n */\n boxPath?: string;\n hostPath?: string;\n /** Defaults true; relay always uses `docker exec tar` (recursive). */\n recursive?: boolean;\n /** tar glob patterns / bare dir names to exclude, forwarded to `agentbox cp --exclude`. */\n exclude?: string[];\n /** false → forward `--no-default-excludes` (keep heavy dirs the host CLI drops). */\n defaultExcludes?: boolean;\n /** true → forward `--yes` (copy past the host's size limit). */\n yes?: boolean;\n}\n\nexport interface BrowserOpenRpcParams {\n /** Absolute http(s) URL to open in the host's default browser. */\n url: string;\n}\n\nexport type { DownloadKind };\n\nexport interface DownloadRpcParams {\n kind: DownloadKind;\n /**\n * Host destination override. Reserved — the v1 relay ignores it and uses\n * the host CLI's defaults (`box.workspacePath`, or `~/.claude`). Kept in\n * the wire so a later upgrade can land without bumping the type.\n */\n hostPath?: string;\n /** Reserved for per-kind flags (e.g. workspace: includeNodeModules). */\n options?: Record<string, unknown>;\n}\n","import type { BoxRegistration, RelayEvent } from './types.js';\nimport { RELAY_EVENT_RING_SIZE } from './types.js';\n\nexport class BoxRegistry {\n private readonly map = new Map<string, BoxRegistration>();\n\n register(reg: BoxRegistration): void {\n this.map.set(reg.boxId, reg);\n }\n\n forget(boxId: string): boolean {\n return this.map.delete(boxId);\n }\n\n /** Returns the registration whose token matches, or null. */\n authenticate(token: string): BoxRegistration | null {\n if (token.length === 0) return null;\n for (const reg of this.map.values()) {\n if (reg.token === token) return reg;\n }\n return null;\n }\n\n get(boxId: string): BoxRegistration | undefined {\n return this.map.get(boxId);\n }\n\n list(): BoxRegistration[] {\n return [...this.map.values()];\n }\n\n size(): number {\n return this.map.size;\n }\n}\n\nexport class EventBuffer {\n private readonly buf: RelayEvent[] = [];\n private nextId = 1;\n constructor(private readonly capacity: number = RELAY_EVENT_RING_SIZE) {}\n\n append(input: Omit<RelayEvent, 'id' | 'receivedAt'>): RelayEvent {\n const ev: RelayEvent = {\n id: this.nextId++,\n receivedAt: new Date().toISOString(),\n ...input,\n };\n this.buf.push(ev);\n if (this.buf.length > this.capacity) this.buf.shift();\n return ev;\n }\n\n /** Returns events with id > since. If `box` is given, filters to that box. */\n since(since: number, box?: string): RelayEvent[] {\n const out: RelayEvent[] = [];\n for (const ev of this.buf) {\n if (ev.id <= since) continue;\n if (box && ev.boxId !== box) continue;\n out.push(ev);\n }\n return out;\n }\n\n all(): RelayEvent[] {\n return this.buf.slice();\n }\n\n size(): number {\n return this.buf.length;\n }\n}\n","import { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { normalizeAgentStatus } from '@agentbox/core';\n\n/**\n * A box status snapshot as received from the in-box daemon. The relay treats\n * it structurally (it has no dep on `@agentbox/ctl`); the rich type lives in\n * `@agentbox/ctl` (`BoxStatus`) and is what the host CLI parses back.\n */\nexport type BoxStatusSnapshot = Record<string, unknown>;\n\n/**\n * Mirrors `sanitizeMnemonic` in @agentbox/config — duplicated here so the relay\n * stays dep-free. Two source-of-truth files; the schema-drift-style guarantee\n * is that boxes only land in `<id>-<mnemonic>/` if both impls agree.\n */\nfunction sanitizeMnemonic(raw: string): string {\n return (\n raw\n .toLowerCase()\n .replace(/-/g, '_')\n .replace(/[^a-z0-9_]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 32) || 'unnamed'\n );\n}\n\n/**\n * Mirrors `boxRunDirFor` / `boxDirSegment` in @agentbox/sandbox-docker — kept\n * in sync by hand. When `projectIndex` (`agentbox list`'s `N`) is set the\n * segment is `<id>-<n>-<mnemonic>` so directories sort cleanly within a\n * project; legacy (pre-feature) boxes register without it and fall back to\n * the original `<id>-<mnemonic>` shape.\n */\nfunction boxRunDirFor(boxId: string, name: string, projectIndex?: number): string {\n const mnemonic = sanitizeMnemonic(name);\n const segment =\n typeof projectIndex === 'number' && Number.isFinite(projectIndex) && projectIndex > 0\n ? `${boxId}-${String(projectIndex)}-${mnemonic}`\n : `${boxId}-${mnemonic}`;\n return join(homedir(), '.agentbox', 'boxes', segment);\n}\n\nfunction boxStatusPathFor(boxId: string, name: string, projectIndex?: number): string {\n return join(boxRunDirFor(boxId, name, projectIndex), 'status.json');\n}\n\n/**\n * Structural guard: a valid box-status payload is an object with `schema === 1`\n * and a non-empty `boxId` string. The relay persists it verbatim; the host\n * reader does the strict typing.\n */\nexport function isValidBoxStatus(payload: unknown): payload is BoxStatusSnapshot {\n if (typeof payload !== 'object' || payload === null) return false;\n const o = payload as Record<string, unknown>;\n return o.schema === 1 && typeof o.boxId === 'string' && o.boxId.length > 0;\n}\n\n/**\n * Fold an incoming snapshot's agent status into the keyed map, in place.\n *\n * Run at INGESTION, so the memory store, the `status.json` file and the\n * `box-status` SSE broadcast all carry the current shape and no downstream\n * reader has to know two. The producer is baked into the box image, so a box\n * created from an older snapshot posts the old named blocks for as long as it\n * lives, and no host release can change that.\n *\n * The named blocks are LEFT IN PLACE, not stripped: a hub or CLI older than this\n * build is still reading them, and the current producer writes them itself as a\n * derived mirror. Normalizing only ever adds `agents`.\n *\n * `schema` deliberately does not move — see `AgentStatusMap`'s note. Both this\n * guard and the host's `readBoxStatus` reject anything but 1, so bumping it\n * would blank every field on every existing reader rather than degrade.\n */\nexport function normalizeBoxStatus(payload: BoxStatusSnapshot): BoxStatusSnapshot {\n const agents = normalizeAgentStatus(payload);\n if (Object.keys(agents).length === 0) return payload;\n return { ...payload, agents };\n}\n\n/**\n * In-memory latest-status map plus a durable per-box file at\n * `~/.agentbox/boxes/<id>/status.json`. The relay is a single process so it is\n * the single writer; the atomic tmp+rename means the host CLI never reads a\n * torn file. The on-disk copy is what makes status survive box pause/stop,\n * relay restart, and host reboot.\n */\nexport class BoxStatusStore {\n private readonly map = new Map<string, BoxStatusSnapshot>();\n\n get(boxId: string): BoxStatusSnapshot | undefined {\n return this.map.get(boxId);\n }\n\n /**\n * Update the in-memory entry and best-effort persist it to disk. `name` is\n * the box's user-facing name (from the registry); `projectIndex` is the\n * 1-based per-project `N`. Together they form the on-disk dir\n * `~/.agentbox/boxes/<id>-<n>-<mnemonic>/status.json` (or\n * `<id>-<mnemonic>/` if N is absent — legacy boxes).\n */\n async set(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n this.map.set(boxId, status);\n const target = boxStatusPathFor(boxId, name, projectIndex);\n const tmp = `${target}.${String(process.pid)}.tmp`;\n try {\n await mkdir(boxRunDirFor(boxId, name, projectIndex), { recursive: true });\n await writeFile(tmp, JSON.stringify(status), 'utf8');\n await rename(tmp, target);\n } catch {\n await rm(tmp, { force: true }).catch(() => {});\n }\n }\n\n /** Drop the in-memory entry (the on-disk file is wiped with the box dir). */\n delete(boxId: string): void {\n this.map.delete(boxId);\n }\n\n /** Every box's latest snapshot in one pass (backs `Store.listStatuses`). */\n list(): Array<{ boxId: string; status: BoxStatusSnapshot }> {\n return [...this.map.entries()].map(([boxId, status]) => ({ boxId, status }));\n }\n}\n","import { BoxRegistry, EventBuffer } from '../registry.js';\nimport { BoxStatusStore } from '../status-store.js';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\nexport interface MemoryStoreParts {\n registry?: BoxRegistry;\n events?: EventBuffer;\n statusStore?: BoxStatusStore;\n}\n\n/**\n * In-memory {@link Store} — the laptop loopback relay default and the test\n * default. It wraps the original `BoxRegistry` / `EventBuffer` /\n * `BoxStatusStore` instances verbatim, so it is behaviorally identical to the\n * pre-seam relay (status still persists to `~/.agentbox/boxes/<id>/status.json`\n * via `BoxStatusStore.set`). The wrapped instances are exposed so the relay\n * handle can keep handing them to the autopause / queue loops and the unit\n * tests, which read them synchronously.\n */\nexport class MemoryStore implements Store {\n readonly registry: BoxRegistry;\n readonly events: EventBuffer;\n readonly statusStore: BoxStatusStore;\n private readonly prompts = new Map<string, PromptRow>();\n private readonly createJobs = new Map<string, CreateJobRow>();\n\n constructor(parts: MemoryStoreParts = {}) {\n this.registry = parts.registry ?? new BoxRegistry();\n this.events = parts.events ?? new EventBuffer();\n this.statusStore = parts.statusStore ?? new BoxStatusStore();\n }\n\n registerBox(reg: BoxRegistration): Promise<void> {\n this.registry.register(reg);\n return Promise.resolve();\n }\n\n getBox(boxId: string): Promise<BoxRegistration | undefined> {\n return Promise.resolve(this.registry.get(boxId));\n }\n\n authenticateBox(token: string): Promise<BoxRegistration | null> {\n return Promise.resolve(this.registry.authenticate(token));\n }\n\n listBoxes(): Promise<BoxRegistration[]> {\n return Promise.resolve(this.registry.list());\n }\n\n forgetBox(boxId: string): Promise<boolean> {\n return Promise.resolve(this.registry.forget(boxId));\n }\n\n countBoxes(): Promise<number> {\n return Promise.resolve(this.registry.size());\n }\n\n appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n return Promise.resolve(this.events.append(input));\n }\n\n listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n return Promise.resolve(this.events.since(since, boxId));\n }\n\n countEvents(): Promise<number> {\n return Promise.resolve(this.events.size());\n }\n\n setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n return this.statusStore.set(boxId, name, projectIndex, status);\n }\n\n getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n return Promise.resolve(this.statusStore.get(boxId));\n }\n\n deleteStatus(boxId: string): Promise<void> {\n this.statusStore.delete(boxId);\n return Promise.resolve();\n }\n\n listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n return Promise.resolve(this.statusStore.list());\n }\n\n createPrompt(row: PromptRow): Promise<void> {\n this.prompts.set(row.id, { ...row });\n return Promise.resolve();\n }\n\n getPrompt(promptId: string): Promise<PromptRow | null> {\n const row = this.prompts.get(promptId);\n return Promise.resolve(row ? { ...row } : null);\n }\n\n answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const row = this.prompts.get(promptId);\n if (!row || row.status !== 'pending') return Promise.resolve(false);\n row.status = 'answered';\n row.answer = answer;\n row.cancelled = cancelled;\n return Promise.resolve(true);\n }\n\n listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const out: PromptRow[] = [];\n for (const row of this.prompts.values()) {\n if (row.boxId === boxId && row.status === 'pending') out.push({ ...row });\n }\n return Promise.resolve(out);\n }\n\n setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n const row = this.prompts.get(promptId);\n if (row) row.result = result;\n return Promise.resolve();\n }\n\n enqueueCreateJob(job: CreateJobRow): Promise<void> {\n this.createJobs.set(job.id, { ...job });\n return Promise.resolve();\n }\n\n getCreateJob(id: string): Promise<CreateJobRow | null> {\n const job = this.createJobs.get(id);\n return Promise.resolve(job ? { ...job } : null);\n }\n\n listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n const wanted = opts?.status;\n const rows = [...this.createJobs.values()]\n .filter((j) => !wanted || wanted.includes(j.status))\n .sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n .map((j) => ({ ...j }));\n return Promise.resolve(opts?.limit ? rows.slice(0, opts.limit) : rows);\n }\n\n claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n // Oldest queued first; single-process so no real concurrency to guard.\n const queued = [...this.createJobs.values()]\n .filter((j) => j.status === 'queued')\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n const job = queued[0];\n if (!job) return Promise.resolve(null);\n job.status = 'running';\n job.claimedBy = workerId;\n job.startedAt = new Date().toISOString();\n return Promise.resolve({ ...job });\n }\n\n completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n const job = this.createJobs.get(id);\n if (job) {\n job.status = status;\n job.result = result;\n job.finishedAt = new Date().toISOString();\n }\n return Promise.resolve();\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { ServerResponse } from 'node:http';\nimport type { PromptAnswerBody, PromptAskEvent } from './types.js';\n\n/**\n * Resolution shape passed back through `askPrompt`'s Promise. Mirrors the\n * shape the wrapper POSTs to `/admin/prompts/answer` minus the id (the\n * caller already knows it).\n */\nexport interface PromptResolution {\n answer: 'y' | 'n';\n cancelled?: boolean;\n /**\n * `kind: 'open-link'` only: the answering client opened the URL itself, so\n * the host must not open it again. See {@link PromptAnswerBody.openedByClient}.\n */\n openedByClient?: boolean;\n}\n\ninterface PendingPromptEntry {\n ev: PromptAskEvent;\n boxId: string;\n resolve: (r: PromptResolution) => void;\n createdAt: string;\n}\n\n/**\n * In-memory pending prompts map. The relay's host-action handlers (git push,\n * cp.*, download.*) put a pending entry here and await the Promise; the\n * wrapper's POST to `/admin/prompts/answer` resolves it. Entries live for\n * however long the user takes — per the design we block indefinitely until\n * a wrapper attaches and answers.\n */\n/**\n * Per-box auto-approve policy, wired by the relay server once the registry +\n * event buffer are available. `shouldAutoApprove` reflects the box's\n * `autoApproveHostActions` registration flag; `audit` records the bypass to\n * the relay event ring buffer so it stays observable. Lives on\n * {@link PendingPrompts} because that instance is already threaded into every\n * `askPrompt` call site (host + cloud), so no handler signatures change.\n */\nexport interface AutoApprovePolicy {\n shouldAutoApprove(boxId: string): boolean;\n audit(boxId: string, params: Omit<PromptAskEvent, 'id'>, reason?: string): void;\n}\n\n/** A pending approval, flattened for listing across all boxes (hub UI). */\nexport interface PendingApproval {\n id: string;\n boxId: string;\n ev: PromptAskEvent;\n createdAt: string;\n}\n\nexport class PendingPrompts {\n private readonly entries = new Map<string, PendingPromptEntry>();\n private autoApprove: AutoApprovePolicy | null = null;\n private onChange: (() => void) | null = null;\n\n /** Install the per-box auto-approve policy (relay server, once at startup). */\n setAutoApprovePolicy(policy: AutoApprovePolicy): void {\n this.autoApprove = policy;\n }\n\n /**\n * Install a change hook fired whenever the pending set is mutated (add /\n * resolve). Wired by the relay server to the hub notifier so the embedded UI\n * pushes an update to connected browsers.\n */\n setOnChange(fn: () => void): void {\n this.onChange = fn;\n }\n\n /**\n * True when this box opted into `box.autoApproveHostActions`. Records the\n * bypass to the audit sink as a side effect so the caller short-circuits\n * with a trail. Returns false when no policy is installed.\n */\n consumeAutoApprove(boxId: string, params: Omit<PromptAskEvent, 'id'>): boolean {\n if (!this.autoApprove || !this.autoApprove.shouldAutoApprove(boxId)) return false;\n this.autoApprove.audit(boxId, params);\n return true;\n }\n\n /**\n * Record a *safe-subset* auto-approval (opening a PR, a contained file copy,\n * a sanctioned-branch push, …) to the audit sink WITHOUT the blanket\n * `autoApproveHostActions` opt-in. The handler already decided the action is\n * safe under `box.autoApproveSafeHostActions`; this just leaves the same\n * `host-action-auto-approved` trail a full opt-in would, tagged with `reason`.\n * No-op when no policy is installed (e.g. the stateless poll plane).\n */\n noteAutoApprove(boxId: string, params: Omit<PromptAskEvent, 'id'>, reason: string): void {\n this.autoApprove?.audit(boxId, params, reason);\n }\n\n add(boxId: string, ev: PromptAskEvent): Promise<PromptResolution> {\n return new Promise<PromptResolution>((resolve) => {\n this.entries.set(ev.id, {\n ev,\n boxId,\n resolve,\n createdAt: new Date().toISOString(),\n });\n this.onChange?.();\n });\n }\n\n /**\n * Idempotent: returns true if a pending entry was found + resolved, false\n * otherwise. The /admin/prompts/answer handler uses the bool to decide\n * 204 vs 404 — the wrapper treats both as \"we're done.\"\n *\n * This bool is also the CLAIM primitive for `open-link` prompts: several\n * surfaces (footer, dashboard, tray, hub web) may race to open the same\n * link, and only the first `resolve` wins. Every client therefore claims\n * BEFORE it opens — a loser sees 404 and opens nothing.\n */\n resolve(id: string, answer: 'y' | 'n', cancelled?: boolean, openedByClient?: boolean): boolean {\n const entry = this.entries.get(id);\n if (!entry) return false;\n this.entries.delete(id);\n entry.resolve({ answer, cancelled, openedByClient });\n this.onChange?.();\n return true;\n }\n\n /**\n * Snapshot of all pending prompts for a given box; used to flush the\n * backlog to a newly-attached SSE subscriber.\n */\n forBox(boxId: string): PromptAskEvent[] {\n const out: PromptAskEvent[] = [];\n for (const entry of this.entries.values()) {\n if (entry.boxId === boxId) out.push(entry.ev);\n }\n return out;\n }\n\n /**\n * Snapshot of every pending prompt across all boxes, with its boxId and\n * enqueue time — the hub's Approvals view lists these.\n */\n all(): PendingApproval[] {\n const out: PendingApproval[] = [];\n for (const entry of this.entries.values()) {\n out.push({ id: entry.ev.id, boxId: entry.boxId, ev: entry.ev, createdAt: entry.createdAt });\n }\n return out;\n }\n\n /** boxId that owns a pending prompt id, or null when unknown. */\n boxFor(id: string): string | null {\n const entry = this.entries.get(id);\n return entry ? entry.boxId : null;\n }\n\n size(): number {\n return this.entries.size;\n }\n}\n\n/** A callback subscriber to a box's prompt/notice broadcasts. */\nexport type PromptListener = (event: string, data: unknown) => void;\n\n/**\n * Tracks the set of host-side wrappers currently subscribed per box. Two kinds\n * of subscriber exist:\n * - raw `ServerResponse` SSE writers — the relay's own `/admin/prompts/stream`\n * route (in-process on the same server).\n * - callback `PromptListener`s — the hub's `/api/v1` prompt stream, which is a\n * Next route that can't hold the relay's `ServerResponse` directly and\n * receives the same events via a callback instead.\n *\n * `broadcast` writes to both so the user can answer from whichever attached\n * window (footer or web-driven stream) they happen to be in.\n */\nexport class PromptSubscribers {\n private readonly byBox = new Map<string, Set<ServerResponse>>();\n private readonly listenersByBox = new Map<string, Set<PromptListener>>();\n private durableFloor = 0;\n\n add(boxId: string, res: ServerResponse): void {\n let set = this.byBox.get(boxId);\n if (!set) {\n set = new Set();\n this.byBox.set(boxId, set);\n }\n set.add(res);\n }\n\n remove(boxId: string, res: ServerResponse): void {\n const set = this.byBox.get(boxId);\n if (!set) return;\n set.delete(res);\n if (set.size === 0) this.byBox.delete(boxId);\n }\n\n /**\n * Register a callback subscriber for a box; returns an unsubscribe. Used by\n * the hub's `/api/v1` prompt-stream route (a Next route, reached via a\n * globalThis seam) so its stream gets the same `prompt-ask`/`prompt-resolved`/\n * `notice-*` events the footer's admin stream does.\n */\n addListener(boxId: string, fn: PromptListener): () => void {\n let set = this.listenersByBox.get(boxId);\n if (!set) {\n set = new Set();\n this.listenersByBox.set(boxId, set);\n }\n set.add(fn);\n return () => {\n const s = this.listenersByBox.get(boxId);\n if (!s) return;\n s.delete(fn);\n if (s.size === 0) this.listenersByBox.delete(boxId);\n };\n }\n\n forBox(boxId: string): ServerResponse[] {\n const set = this.byBox.get(boxId);\n return set ? Array.from(set) : [];\n }\n\n /**\n * Set a process-wide floor added to every box's {@link count}. This is how the\n * always-on hub declares itself the *durable subscriber*: when the floor is 1,\n * a pending prompt is always answerable (the web UI + `/api/v1/approvals/:id/\n * answer` never go away), so a host-action gate (e.g. git.push) parks the\n * prompt instead of auto-denying when no wrapper is attached. Gated to the\n * control-box profile by the caller — a plain local hub keeps floor 0 (the\n * user is present; an unattended local box shouldn't wedge on a blocked push).\n */\n setDurableFloor(n: number): void {\n this.durableFloor = Math.max(0, n);\n }\n\n /**\n * How many subscribers a box has: raw SSE writers + callback listeners + the\n * durable floor. The host-action no-subscriber gate reads this to decide\n * whether a confirm can be surfaced-and-answered (park) or must fall back to\n * its `*_NO_SUB` policy (auto-deny by default). Counting listeners is\n * load-bearing: the footer moved from a `ServerResponse` on `/admin/prompts/\n * stream` to a callback on the `/api/v1` stream, so a `forBox().length` check\n * would no longer see an attached footer and would silently auto-deny.\n */\n count(boxId: string): number {\n const responses = this.byBox.get(boxId)?.size ?? 0;\n const listeners = this.listenersByBox.get(boxId)?.size ?? 0;\n return responses + listeners + this.durableFloor;\n }\n\n /**\n * Fire-and-forget broadcast to both SSE writers and callback listeners. Writes\n * that fail (closed socket) are swallowed — the route's `close` handler already\n * deregisters the dead subscriber; a throwing listener is isolated the same way.\n */\n broadcast(boxId: string, event: string, data: unknown): void {\n const set = this.byBox.get(boxId);\n if (set) {\n const payload = `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n for (const res of set) {\n try {\n res.write(payload);\n } catch {\n /* dead socket; close handler will deregister */\n }\n }\n }\n const listeners = this.listenersByBox.get(boxId);\n if (listeners) {\n for (const fn of listeners) {\n try {\n fn(event, data);\n } catch {\n /* an errant listener must not take the broadcast (or its peers) down */\n }\n }\n }\n }\n}\n\n/**\n * Internal API used by handleGitRpc / handleCpRpc / handleDownloadRpc and the\n * `browser.open` host-mirror offer. Generates a UUID, adds a pending entry,\n * broadcasts the SSE event, and awaits the answer. Respects\n * `process.env.AGENTBOX_PROMPT === 'off'` — auto-accepts without broadcasting\n * (useful for headless scripts and tests) — and the per-box\n * `box.autoApproveHostActions` policy (auto-accepts with an audit event).\n *\n * `opts.ttlMs` makes the prompt auto-expire: if no answer arrives in time it\n * resolves to its `defaultAnswer` (cancelled) and a `prompt-resolved` event is\n * broadcast so attached wrappers clear it. Used for optional, non-blocking\n * prompts that must not linger when nobody answers; omit it for the\n * block-until-answered prompts that gate a paused in-box RPC.\n */\nexport async function askPrompt(\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n boxId: string,\n params: Omit<PromptAskEvent, 'id'>,\n opts?: { ttlMs?: number },\n): Promise<PromptResolution> {\n if (process.env.AGENTBOX_PROMPT === 'off') {\n return { answer: 'y' };\n }\n // Per-box opt-in: `box.autoApproveHostActions` resolves the confirm to 'y'\n // without surfacing a prompt, but records an audit event (inside\n // consumeAutoApprove) so the bypass is never silent.\n if (prompts.consumeAutoApprove(boxId, params)) {\n return { answer: 'y' };\n }\n const ev: PromptAskEvent = { id: randomUUID(), ...params };\n const promise = prompts.add(boxId, ev);\n subscribers.broadcast(boxId, 'prompt-ask', ev);\n if (opts?.ttlMs !== undefined && opts.ttlMs > 0) {\n const timer = setTimeout(() => {\n if (prompts.resolve(ev.id, params.defaultAnswer ?? 'n', true)) {\n subscribers.broadcast(boxId, 'prompt-resolved', { id: ev.id });\n }\n }, opts.ttlMs);\n if (typeof timer.unref === 'function') timer.unref();\n void promise.then(() => {\n clearTimeout(timer);\n });\n }\n return promise;\n}\n\n/** Helper for the answer body — used by the relay server to validate. */\nexport function isPromptAnswerBody(v: unknown): v is PromptAnswerBody {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n if (typeof o.id !== 'string' || o.id.length === 0) return false;\n if (o.answer !== 'y' && o.answer !== 'n') return false;\n if (o.cancelled !== undefined && typeof o.cancelled !== 'boolean') return false;\n if (o.openedByClient !== undefined && typeof o.openedByClient !== 'boolean') return false;\n return true;\n}\n","import { randomUUID } from 'node:crypto';\nimport { askPrompt, type PendingPrompts, type PromptSubscribers } from './prompts.js';\nimport type { Store } from './store/store.js';\nimport type { PromptAskEvent } from './types.js';\n\n/**\n * How the relay obtains host-action approval:\n * - 'block' — the laptop loopback relay (a long-lived process): the `/rpc`\n * handler blocks on an in-process `PendingPrompts` Promise until the human\n * answers (today's behavior, unchanged).\n * - 'poll' — the hosted control plane (serverless / stateless per request):\n * the gate parks a prompt row in the Store and returns immediately; `/rpc`\n * replies `202 {promptId}` and the box polls `/rpc/status/:id` for the\n * verdict + result.\n */\nexport type PromptMode = 'block' | 'poll';\n\nexport type ApprovalGate =\n | { kind: 'allow' }\n | { kind: 'deny' }\n | { kind: 'pending'; promptId: string };\n\nexport interface GateDeps {\n mode: PromptMode;\n store: Store;\n /** Required for block mode (the in-process blocking wait). */\n prompts?: PendingPrompts;\n /** Optional: SSE fan-out to an attached human dashboard. Absent on the stateless plane. */\n subscribers?: PromptSubscribers;\n}\n\n/**\n * Decide whether a host action may proceed. The caller has already cleared the\n * fast paths that never prompt at all (agentbox/* branch, valid host-initiated\n * token, read-only op). `promptParams` is the confirm to show the human;\n * `method`/`params` are persisted on the poll-mode row so the approved action\n * can be re-dispatched when the box polls.\n *\n * - 'block': returns allow/deny once the human answers (or AGENTBOX_PROMPT=off\n * / autoApprove resolves it). Behaviorally identical to the pre-poll relay.\n * - 'poll': returns allow when no human is needed (AGENTBOX_PROMPT=off /\n * autoApprove, audited), else parks a pending row and returns its promptId.\n */\nexport async function gateApproval(\n deps: GateDeps,\n boxId: string,\n method: string,\n params: unknown,\n promptParams: Omit<PromptAskEvent, 'id'>,\n): Promise<ApprovalGate> {\n if (deps.mode === 'block') {\n // askPrompt handles AGENTBOX_PROMPT=off + autoApprove (with audit) + the\n // blocking wait, exactly as before. Block mode requires in-process state.\n if (!deps.prompts || !deps.subscribers) return { kind: 'deny' };\n const verdict = await askPrompt(deps.prompts, deps.subscribers, boxId, promptParams);\n return verdict.answer === 'y' && !verdict.cancelled ? { kind: 'allow' } : { kind: 'deny' };\n }\n // poll mode: store-based fast paths (works on the stateless hosted plane, no\n // in-process registry/prompts), then park a row the box will poll for.\n if (process.env.AGENTBOX_PROMPT === 'off') return { kind: 'allow' };\n const box = await deps.store.getBox(boxId);\n if (box?.autoApproveHostActions) {\n // Audited bypass — still observable in the event feed.\n await deps.store.appendEvent({\n boxId,\n type: 'host-action-auto-approved',\n payload: {\n command: promptParams.context?.command,\n argv: promptParams.context?.argv,\n message: promptParams.message,\n },\n });\n return { kind: 'allow' };\n }\n const promptId = randomUUID();\n const ev: PromptAskEvent = { id: promptId, ...promptParams };\n await deps.store.createPrompt({\n id: promptId,\n boxId,\n ev,\n method,\n params,\n status: 'pending',\n createdAt: new Date().toISOString(),\n });\n // Best-effort SSE for an attached human dashboard (no-op when none / on the\n // stateless plane); the box itself never relies on SSE — it polls /rpc/status.\n deps.subscribers?.broadcast(boxId, 'prompt-ask', ev);\n return { kind: 'pending', promptId };\n}\n","import { existsSync } from 'node:fs';\nimport type { BoxRegistration, BoxWorktree } from './types.js';\n\n/**\n * Resolve `containerPath` (a path inside the box) to the registered worktree\n * whose `hostMainRepo` + `branch` the relay should act on. `/workspace` maps to\n * the root repo; `/workspace/<sub>` maps to a nested repo when registered\n * (longest prefix wins). Pure — shared by the node relay (server.ts) and the\n * hosted-plane handler (core/handler.ts).\n */\nexport function resolveWorktree(reg: BoxRegistration, containerPath: string): BoxWorktree | null {\n const trees = reg.worktrees ?? [];\n if (trees.length === 0) return null;\n const exact = trees.find((w) => w.containerPath === containerPath);\n if (exact) return exact;\n const prefixMatches = trees\n .filter(\n (w) => containerPath === w.containerPath || containerPath.startsWith(w.containerPath + '/'),\n )\n .sort((a, b) => b.containerPath.length - a.containerPath.length);\n return prefixMatches[0] ?? trees.find((w) => w.containerPath === '/workspace') ?? null;\n}\n\n/**\n * Reject host-side git RPCs against a worktree with no usable host repo. A box\n * created by the control-box worker registers its `hostMainRepo` as the\n * create-time seed clone — a temp dir deleted after create — so `git -C <that>`\n * would fail cryptically. Returns an actionable error string for such a\n * worktree, or `null` when the host repo exists. Pure aside from the fs check,\n * so it is unit-testable with a real/fake directory.\n */\nexport function hostRepoUnavailableReason(\n worktree: BoxWorktree,\n boxId: string,\n op: string,\n): string | null {\n if (worktree.hostMainRepo.length > 0 && existsSync(worktree.hostMainRepo)) return null;\n return (\n `host-side ${op} is unavailable for box ${boxId}: its host repo ` +\n `(${worktree.hostMainRepo || '<unset>'}) does not exist on this host. ` +\n `Boxes created by the control-box worker have no host working copy — ` +\n `push from inside the box (leased) or adopt the box on this host first.`\n );\n}\n","/**\n * Pure GitHub remote-URL helpers: parse a remote, rewrite it to carry a token\n * over HTTPS, and derive the `gh --repo` slug. Shared by the control plane's\n * GitHub-App token leasing (`lease.ts`) and the cloud git.push path.\n */\n\n/** A remote URL split into its parts. `scheme` is null for the scp-like form. */\nexport interface ParsedGitRemote {\n host: string;\n path: string;\n /** Lowercased URL scheme (`https`, `ssh`, …); null for `git@host:owner/repo`. */\n scheme: string | null;\n}\n\n/**\n * Parse any GitHub remote URL (scp-like `git@host:owner/repo`, `ssh://…`, or\n * `https://…`, with or without embedded creds) into `{ host, path, scheme }`.\n * Throws on an unrecognized shape.\n */\nexport function parseGitRemote(origin: string): ParsedGitRemote {\n const trimmed = origin.trim();\n if (trimmed.length === 0) throw new Error('empty git remote URL');\n\n // URL form first: scheme://[user@]host[:port]/path. Matching this before the\n // scp branch avoids misreading `https://github.com/...` as scp `https:...`.\n const urlForm = /^([a-z][a-z0-9+.-]*):\\/\\/(?:[^@/]+@)?([^/:]+)(?::\\d+)?\\/(.+)$/i.exec(trimmed);\n const scpForm = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(trimmed);\n let host: string;\n let path: string;\n let scheme: string | null;\n if (urlForm) {\n scheme = urlForm[1]!.toLowerCase();\n host = urlForm[2]!;\n path = urlForm[3]!;\n } else if (scpForm && !/^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed)) {\n scheme = null;\n host = scpForm[1]!;\n path = scpForm[2]!;\n } else {\n throw new Error(`unrecognized git remote URL: ${origin}`);\n }\n return { host, path: path.replace(/^\\/+/, ''), scheme };\n}\n\n/**\n * Rewrite any GitHub remote URL into an HTTPS URL carrying the PAT as\n * `x-access-token`. Throws on an unrecognized shape.\n */\nexport function toAuthedHttpsUrl(origin: string, token: string): string {\n const { host, path } = parseGitRemote(origin);\n return `https://x-access-token:${token}@${host}/${path}`;\n}\n\n/**\n * Rewrite any GitHub remote URL to plain HTTPS, dropping embedded credentials.\n *\n * For a machine that authenticates git through a credential helper rather than\n * an SSH key — the hub in `hub.gitAuth=gh` mode — an scp-form\n * `git@github.com:owner/repo` origin is unusable: ssh fails at host-key\n * verification (no `known_hosts` entry) before it ever reaches auth, so the\n * helper never gets a say. Same URL over HTTPS is exactly what the helper\n * covers.\n */\nexport function toHttpsUrl(origin: string): string {\n const { host, path } = parseGitRemote(origin);\n return `https://${host}/${path}`;\n}\n\n/**\n * The `[HOST/]OWNER/REPO` slug `gh --repo` expects, derived from a remote URL.\n * github.com is implicit (just `OWNER/REPO`); enterprise hosts are prefixed.\n */\nexport function repoSlugFromRemote(origin: string): string {\n const { host, path } = parseGitRemote(origin);\n const repo = path.replace(/\\.git$/, '');\n return host.toLowerCase() === 'github.com' ? repo : `${host}/${repo}`;\n}\n\n/** The gh host a remote points at, or null when it needs no `GH_HOST` hint. */\nexport interface GhRemoteHost {\n /** Lowercased hostname from the remote — NOT github.com. */\n host: string;\n /**\n * True when `host` could be an `~/.ssh/config` alias (`git@github.com-work:o/r`),\n * i.e. anything but an http(s) URL — there is no aliasing layer between an\n * HTTPS URL and the request it makes, so those hosts are authoritative.\n */\n aliasable: boolean;\n}\n\n/**\n * The host `gh` must be pointed at for a remote, or `null` when that is\n * github.com (gh's own default — no hint needed) or the URL isn't a\n * recognizable remote (a local mirror path, junk).\n */\nexport function ghHostFromRemote(origin: string | undefined): GhRemoteHost | null {\n const trimmed = origin?.trim() ?? '';\n if (trimmed.length === 0) return null;\n let parsed: ParsedGitRemote;\n try {\n parsed = parseGitRemote(trimmed);\n } catch {\n return null;\n }\n const host = parsed.host.toLowerCase();\n if (host === 'github.com') return null;\n return { host, aliasable: parsed.scheme !== 'https' && parsed.scheme !== 'http' };\n}\n","import { parseGitRemote, repoSlugFromRemote, toAuthedHttpsUrl } from './git-pat.js';\nimport type { GitHubAppLeaser } from './github-app.js';\nimport type { BoxRegistration, GitRpcResult } from './types.js';\n\n/**\n * Mint a repo-scoped GitHub-App installation token for a box and package it as\n * a `{exitCode,stdout,stderr}` result whose `stdout` is the lease JSON\n * (`{ token, expiresAt, remoteUrl, repo }`). Shared by the node relay\n * (server.ts) and the hosted-plane handler (core/handler.ts).\n *\n * The repo is resolved from the box's REGISTERED origin URL — never from\n * box-supplied params — so a box can only ever lease a token for its own repo.\n */\nexport async function leaseTokenResult(\n leaser: GitHubAppLeaser | null,\n reg: BoxRegistration,\n): Promise<GitRpcResult> {\n if (!leaser) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'git.lease-token: no GitHub App configured on this relay\\n',\n };\n }\n const origin = reg.originUrl;\n if (!origin) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `git.lease-token: box ${reg.boxId} has no registered origin URL\\n`,\n };\n }\n let owner = '';\n let repo = '';\n let slug = '';\n try {\n const { path } = parseGitRemote(origin);\n const [o, r] = path.replace(/\\.git$/, '').split('/');\n owner = o ?? '';\n repo = r ?? '';\n slug = repoSlugFromRemote(origin);\n } catch {\n return { exitCode: 65, stdout: '', stderr: `git.lease-token: unrecognized origin ${origin}\\n` };\n }\n if (!owner || !repo) {\n return {\n exitCode: 65,\n stdout: '',\n stderr: `git.lease-token: cannot derive owner/repo from ${origin}\\n`,\n };\n }\n try {\n const leased = await leaser.leaseRepoToken(owner, repo);\n const payload = {\n token: leased.token,\n expiresAt: leased.expiresAt,\n remoteUrl: toAuthedHttpsUrl(origin, leased.token),\n repo: slug,\n };\n return { exitCode: 0, stdout: JSON.stringify(payload), stderr: '' };\n } catch (err) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `git.lease-token: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n}\n","import type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { PromptRow, Store } from './store.js';\n\n/**\n * A tiny RPC envelope over the {@link Store} interface, so a federated laptop\n * relay can back its state with a remote (hosted) Store over HTTP. The hosted\n * plane exposes `POST /admin/store` (admin-gated) and applies the op via\n * {@link applyStoreOp}; {@link RemoteStore} is the client that posts these.\n *\n * Generic-but-typed: a single switch keeps the dispatch type-safe (no `any`)\n * and the method names are an explicit allow-list — the endpoint can never\n * invoke an arbitrary property of the store object.\n */\nexport interface StoreRpcRequest {\n method: string;\n args: unknown[];\n}\n\nexport interface StoreRpcResponse {\n /** Method return value (already JSON-safe — every Store method returns plain data). */\n result: unknown;\n}\n\n/** True when `method` is a dispatchable Store op. */\nexport function isStoreRpcMethod(method: string): boolean {\n return STORE_RPC_METHODS.has(method);\n}\n\nconst STORE_RPC_METHODS = new Set<string>([\n 'registerBox',\n 'getBox',\n 'authenticateBox',\n 'listBoxes',\n 'forgetBox',\n 'countBoxes',\n 'appendEvent',\n 'listEvents',\n 'countEvents',\n 'setStatus',\n 'getStatus',\n 'deleteStatus',\n 'listStatuses',\n 'createPrompt',\n 'getPrompt',\n 'answerPrompt',\n 'listPendingPrompts',\n 'setPromptResult',\n]);\n\n/** Apply a store op by name with typed argument coercion. Throws on unknown method. */\nexport function applyStoreOp(store: Store, method: string, args: unknown[]): Promise<unknown> {\n switch (method) {\n case 'registerBox':\n return store.registerBox(args[0] as BoxRegistration);\n case 'getBox':\n return store.getBox(args[0] as string);\n case 'authenticateBox':\n return store.authenticateBox(args[0] as string);\n case 'listBoxes':\n return store.listBoxes();\n case 'forgetBox':\n return store.forgetBox(args[0] as string);\n case 'countBoxes':\n return store.countBoxes();\n case 'appendEvent':\n return store.appendEvent(args[0] as Omit<RelayEvent, 'id' | 'receivedAt'>);\n case 'listEvents':\n return store.listEvents(args[0] as number, args[1] as string | undefined);\n case 'countEvents':\n return store.countEvents();\n case 'setStatus':\n return store.setStatus(\n args[0] as string,\n args[1] as string,\n args[2] as number | undefined,\n args[3] as BoxStatusSnapshot,\n );\n case 'getStatus':\n return store.getStatus(args[0] as string);\n case 'deleteStatus':\n return store.deleteStatus(args[0] as string);\n case 'listStatuses':\n return store.listStatuses();\n case 'createPrompt':\n return store.createPrompt(args[0] as PromptRow);\n case 'getPrompt':\n return store.getPrompt(args[0] as string);\n case 'answerPrompt':\n return store.answerPrompt(\n args[0] as string,\n args[1] as 'y' | 'n',\n args[2] as boolean | undefined,\n );\n case 'listPendingPrompts':\n return store.listPendingPrompts(args[0] as string);\n case 'setPromptResult':\n return store.setPromptResult(args[0] as string, args[1] as GitRpcResult);\n default:\n throw new Error(`unknown store op: ${method}`);\n }\n}\n","/**\n * The `/admin/store` generic-Store RPC surface, as a framework-agnostic\n * dispatcher mounted by BOTH relay front-ends: the hosted-plane handler\n * (`core/handler.ts`, Next/Vercel) and the relay daemon (`server.ts`, node:http\n * — what the control box actually runs). One implementation, one gate, both\n * profiles, so a PC's {@link RemoteStore} works against the control box exactly\n * as against the hosted plane.\n *\n * Like custody / remote-boxes, the **admin bearer is the only proof** — never\n * loopback (the control box sits behind Caddy on the same host, so every proxied\n * request looks loopback). Missing admin token → 503 (not configured); wrong\n * token → 401. The method name is an explicit allow-list ({@link isStoreRpcMethod}),\n * so the endpoint can never invoke an arbitrary property of the store object.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\nimport type { Store } from './store.js';\nimport { applyStoreOp, isStoreRpcMethod, type StoreRpcRequest } from './store-rpc.js';\n\n/** Structurally identical to `RelayResponse` in `core/handler.ts` (kept local to avoid a cycle). */\nexport interface StoreRpcRouteResponse {\n status: number;\n body?: unknown;\n}\n\nexport interface StoreRpcRouteRequest {\n method: string;\n /** URL pathname, e.g. `/admin/store`. */\n path: string;\n /** Bearer token as presented ('' when absent). */\n bearer: string;\n /** Raw request body ('' for GET). */\n bodyText: string;\n}\n\nexport interface StoreRpcRouteDeps {\n store: Store;\n /** Admin bearer. Empty/absent → not configured (503). */\n adminToken?: string;\n log?: (line: string) => void;\n}\n\nexport const STORE_RPC_PATH = '/admin/store';\n\n/** True when `path` addresses the generic-Store RPC surface. */\nexport function isStoreRpcPath(path: string): boolean {\n return path === STORE_RPC_PATH;\n}\n\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\nfunction parseJson<T>(text: string): T | null {\n if (text.length === 0) return null;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Dispatch one `/admin/store` request. Returns `null` when `req.path` is not the\n * store-RPC path, so a host router falls through to its own routes unchanged.\n */\nexport async function handleStoreRpcRequest(\n req: StoreRpcRouteRequest,\n deps: StoreRpcRouteDeps,\n): Promise<StoreRpcRouteResponse | null> {\n if (!isStoreRpcPath(req.path)) return null;\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'control plane not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n if (req.method !== 'POST') {\n return { status: 405, body: { error: 'method not allowed' } };\n }\n const body = parseJson<StoreRpcRequest>(req.bodyText);\n if (!body || typeof body.method !== 'string' || !Array.isArray(body.args)) {\n return { status: 400, body: { error: 'expected {method, args}' } };\n }\n if (!isStoreRpcMethod(body.method)) {\n return { status: 400, body: { error: `unknown store op: ${body.method}` } };\n }\n const result = await applyStoreOp(deps.store, body.method, body.args);\n return { status: 200, body: { result: result ?? null } };\n}\n","/**\n * Custody — the control box's copy of what a box needs but the box may not\n * mint for itself: agent login credentials, per-project secrets/envs, and the\n * per-box SSH key material a host minted. The PC stays the source of truth\n * (roadmap §4, \"custody + reach\"); this is the copy the always-on hub holds so\n * a box created from either side is usable from both.\n *\n * The seam is deliberately **path-and-bytes shaped** — no file handles, no\n * streams, no directory semantics leaking through — so the filesystem backend\n * can be swapped for a blob store (key = path, `sha256` = object metadata)\n * without touching a caller. Payloads are small by construction (credentials,\n * `.env` files, SSH keys); the relay's 1 MiB body cap is the ceiling.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { Readable } from 'node:stream';\nimport { agentIds } from '@agentbox/sandbox-core';\n\n/**\n * Top-level custody scopes. Anything else is rejected by {@link normalizeCustodyPath}.\n * `prepared` holds each provider's bake record (`<provider>-prepared.json`), so a\n * base baked on either side is visible to both.\n */\nexport const CUSTODY_SCOPES = ['agents', 'projects', 'boxes', 'prepared'] as const;\nexport type CustodyScope = (typeof CUSTODY_SCOPES)[number];\n\n/** Metadata for one stored entry. `sha256` is the ONLY change signal (never `updatedAt`). */\nexport interface CustodyEntry {\n /** Custody-relative path, e.g. `agents/claude/.credentials.json`. */\n path: string;\n size: number;\n /** Hex sha256 of the stored bytes. */\n sha256: string;\n /** POSIX mode of the stored value (filesystem backend: 0o600). */\n mode: number;\n /** ISO timestamp of the last *write*. Informational — hash-skipped puts leave it alone. */\n updatedAt: string;\n}\n\n/** {@link CustodyStore.put} result. `changed: false` means the bytes were already there. */\nexport interface CustodyPutResult extends CustodyEntry {\n changed: boolean;\n}\n\nexport interface CustodyStore {\n /**\n * Store `data` at `path`. Content-addressed skip: when the stored bytes\n * already hash to the same digest, nothing is written and `changed` is false.\n */\n put(path: string, data: Buffer): Promise<CustodyPutResult>;\n /** Fetch bytes + metadata, or null when absent. */\n get(path: string): Promise<{ entry: CustodyEntry; data: Buffer } | null>;\n /** Metadata only (the value never leaves the store). */\n stat(path: string): Promise<CustodyEntry | null>;\n /** The manifest: every entry whose path starts with `prefix` (all entries when omitted). */\n list(prefix?: string): Promise<CustodyEntry[]>;\n /** Remove one entry. Returns false when it wasn't there. */\n delete(path: string): Promise<boolean>;\n\n /**\n * Streaming counterparts of {@link put} / {@link get}, for payloads too large\n * to hold in memory twice.\n *\n * The rest of this seam is deliberately path-and-bytes shaped, and for\n * credentials / `.env` / SSH keys — all small by construction — that is the\n * right contract. A project's `carry:` material breaks the assumption: it is\n * whatever the user asked to be copied into their box, bounded only by\n * `box.cpMaxBytes` (100 MiB). Buffering that as base64 inside a JSON envelope\n * costs roughly six times the payload in peak memory on both ends, which a\n * 4 GB control box does not have to spare.\n *\n * So this pair is the explicit escape hatch rather than a replacement:\n * `put`/`get` stay the simple API, these carry the big objects.\n */\n putStream(path: string, body: Readable, opts?: { maxBytes?: number }): Promise<CustodyPutResult>;\n /**\n * Stream bytes out. Returns the metadata plus a readable, or null when absent.\n * The caller MUST consume or destroy `data`.\n */\n getStream(path: string): Promise<{ entry: CustodyEntry; data: Readable } | null>;\n}\n\n/** Thrown by {@link CustodyStore.putStream} when the body exceeds `maxBytes`. */\nexport class CustodyTooLargeError extends Error {\n constructor(readonly maxBytes: number) {\n super(`payload exceeds the custody blob cap of ${String(maxBytes)} bytes`);\n this.name = 'CustodyTooLargeError';\n }\n}\n\n/** A rejected custody path (bad scope, traversal, illegal segment). Handlers map this to 400. */\nexport class CustodyPathError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CustodyPathError';\n }\n}\n\nconst SEGMENT_RE = /^[A-Za-z0-9._-]+$/;\nconst MAX_SEGMENTS = 6;\nconst MAX_PATH_LENGTH = 256;\n\n/** Hex sha256 of `data` — the store's change signal and the CLI's skip check. */\nexport function custodyDigest(data: Buffer): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * Validate + canonicalize a custody path. Fail-closed: every segment must be a\n * plain name (`.`/`..` and separators rejected, so no traversal can escape the\n * root even before the backend resolves it), the first segment must be a known\n * scope, and `agents/` accepts only the three known agent ids.\n */\nexport function normalizeCustodyPath(raw: string): string {\n const trimmed = raw.replace(/^\\/+/, '').replace(/\\/+$/, '');\n if (trimmed.length === 0) throw new CustodyPathError('empty custody path');\n if (trimmed.length > MAX_PATH_LENGTH) {\n throw new CustodyPathError(`custody path too long (max ${String(MAX_PATH_LENGTH)} chars)`);\n }\n const segments = trimmed.split('/');\n if (segments.length < 2) {\n throw new CustodyPathError(`custody path needs a scope and a name: '${raw}'`);\n }\n if (segments.length > MAX_SEGMENTS) {\n throw new CustodyPathError(`custody path too deep (max ${String(MAX_SEGMENTS)} segments)`);\n }\n for (const seg of segments) {\n if (seg === '.' || seg === '..' || !SEGMENT_RE.test(seg)) {\n throw new CustodyPathError(`illegal custody path segment: '${seg}'`);\n }\n }\n const scope = segments[0] as CustodyScope;\n if (!CUSTODY_SCOPES.includes(scope)) {\n throw new CustodyPathError(\n `unknown custody scope '${scope}' (expected ${CUSTODY_SCOPES.join(' | ')})`,\n );\n }\n // Registry, not a hand-copied list: a local one silently rejected every agent\n // added after it was written.\n if (scope === 'agents' && !agentIds().includes(segments[1]!)) {\n throw new CustodyPathError(\n `unknown agent '${segments[1]!}' (expected ${agentIds().join(' | ')})`,\n );\n }\n return segments.join('/');\n}\n\n/**\n * Validate a manifest prefix. Looser than a full path (a bare scope like\n * `agents` or a partial `boxes/abc` is legal) but the same anti-traversal rules\n * apply, so a listing can never walk out of the root.\n */\nexport function normalizeCustodyPrefix(raw: string): string {\n const trimmed = raw.replace(/^\\/+/, '').replace(/\\/+$/, '');\n if (trimmed.length === 0) return '';\n if (trimmed.length > MAX_PATH_LENGTH) {\n throw new CustodyPathError(`custody prefix too long (max ${String(MAX_PATH_LENGTH)} chars)`);\n }\n const segments = trimmed.split('/');\n if (segments.length > MAX_SEGMENTS) {\n throw new CustodyPathError(`custody prefix too deep (max ${String(MAX_SEGMENTS)} segments)`);\n }\n for (const seg of segments) {\n if (seg === '.' || seg === '..' || !SEGMENT_RE.test(seg)) {\n throw new CustodyPathError(`illegal custody prefix segment: '${seg}'`);\n }\n }\n if (!CUSTODY_SCOPES.includes(segments[0] as CustodyScope)) {\n throw new CustodyPathError(\n `unknown custody scope '${segments[0]!}' (expected ${CUSTODY_SCOPES.join(' | ')})`,\n );\n }\n return segments.join('/');\n}\n","/**\n * The custody HTTP surface, as a framework-agnostic dispatcher mounted by BOTH\n * relay front-ends: the hosted-plane handler (`core/handler.ts`, Next) and the\n * relay daemon (`server.ts`, node:http — what the control box actually runs).\n * One implementation, one gate, both profiles.\n *\n * Gating is the caller's job with one hard rule, enforced here rather than by\n * each host router: **the admin bearer is the only proof**. `server.ts` treats\n * loopback as admin, but on the control box the hub sits behind Caddy on the\n * same host, so every proxied request looks loopback — accepting that here\n * would publish the credential store. Missing admin token or missing custody\n * store → 503 (not configured); wrong token → 401.\n *\n * Values never appear in a log line: only path, size, and the changed flag.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\nimport type { Readable } from 'node:stream';\nimport {\n CustodyPathError,\n CustodyTooLargeError,\n normalizeCustodyPath,\n normalizeCustodyPrefix,\n type CustodyEntry,\n type CustodyStore,\n} from './store.js';\n\n/** Structurally identical to `RelayResponse` in `core/handler.ts` (kept local to avoid a cycle). */\nexport interface CustodyResponse {\n status: number;\n body?: unknown;\n}\n\nexport interface CustodyRequest {\n method: string;\n /** URL pathname, e.g. `/admin/custody/agents/claude/.credentials.json`. */\n path: string;\n query: URLSearchParams;\n /** Bearer token as presented ('' when absent). */\n bearer: string;\n /** Raw request body ('' for GET/DELETE). */\n bodyText: string;\n}\n\nexport interface CustodyRouteDeps {\n /** Wired by the control box / hub. Absent → custody is not enabled here (503). */\n custody?: CustodyStore | null;\n /** Admin bearer. Empty/absent → custody is not configured (503). */\n adminToken?: string;\n log?: (line: string) => void;\n}\n\nexport const CUSTODY_PATH_PREFIX = '/admin/custody';\n\n/** True when `path` addresses the custody surface (so a router can dispatch it here). */\nexport function isCustodyPath(path: string): boolean {\n return path === CUSTODY_PATH_PREFIX || path.startsWith(`${CUSTODY_PATH_PREFIX}/`);\n}\n\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\n/**\n * Dispatch one custody request. Returns `null` when `req.path` is not a custody\n * path, so a host router can fall through to its own routes unchanged.\n */\nexport async function handleCustodyRequest(\n req: CustodyRequest,\n deps: CustodyRouteDeps,\n): Promise<CustodyResponse | null> {\n if (!isCustodyPath(req.path)) return null;\n const log = deps.log ?? (() => {});\n\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'custody not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n const store = deps.custody;\n if (!store) {\n return { status: 503, body: { error: 'custody store not enabled on this relay' } };\n }\n\n try {\n if (req.path === CUSTODY_PATH_PREFIX) {\n if (req.method !== 'GET') return { status: 405, body: { error: 'method not allowed' } };\n const rawPrefix = req.query.get('prefix');\n const prefix = rawPrefix ? normalizeCustodyPrefix(rawPrefix) : undefined;\n const entries = await store.list(prefix);\n return { status: 200, body: { entries } };\n }\n\n const path = normalizeCustodyPath(\n decodeURIComponent(req.path.slice(`${CUSTODY_PATH_PREFIX}/`.length)),\n );\n\n if (req.method === 'PUT') {\n let parsed: { data?: unknown };\n try {\n parsed = JSON.parse(req.bodyText.length === 0 ? '{}' : req.bodyText) as { data?: unknown };\n } catch {\n return { status: 400, body: { error: 'expected JSON {data: <base64>}' } };\n }\n if (typeof parsed.data !== 'string') {\n return { status: 400, body: { error: 'expected {data: <base64>}' } };\n }\n const buf = Buffer.from(parsed.data, 'base64');\n // base64 decoding is lenient (it drops junk rather than throwing), so\n // round-trip it: a value that doesn't re-encode identically was not\n // base64 and would be stored silently truncated.\n if (buf.toString('base64') !== parsed.data.replace(/\\s+/g, '')) {\n return { status: 400, body: { error: 'data is not valid base64' } };\n }\n const result = await store.put(path, buf);\n log(\n `custody put ${path} (${String(result.size)} bytes, ${result.changed ? 'changed' : 'unchanged'})`,\n );\n return { status: 200, body: result };\n }\n\n if (req.method === 'GET') {\n const found = await store.get(path);\n if (!found) return { status: 404, body: { error: 'no such custody entry' } };\n log(`custody get ${path} (${String(found.entry.size)} bytes)`);\n return { status: 200, body: { ...found.entry, data: found.data.toString('base64') } };\n }\n\n if (req.method === 'DELETE') {\n const hit = await store.delete(path);\n if (!hit) return { status: 404, body: { error: 'no such custody entry' } };\n log(`custody delete ${path}`);\n return { status: 204 };\n }\n\n return { status: 405, body: { error: 'method not allowed' } };\n } catch (err) {\n if (err instanceof CustodyPathError) return { status: 400, body: { error: err.message } };\n const msg = err instanceof Error ? err.message : String(err);\n log(`custody error: ${msg}`);\n return { status: 500, body: { error: `custody: ${msg}` } };\n }\n}\n\n/**\n * The BLOB surface: the same store, addressed the same way, but moving raw\n * `application/octet-stream` bytes instead of base64 inside a JSON envelope.\n *\n * Deliberately a second endpoint rather than a content-type branch on the first.\n * The JSON API is the easy, general-purpose one — a curl and a base64 is all any\n * consumer needs for a credential or a `.env`, and it stays exactly as it was.\n * This one is the advanced path for objects big enough that buffering them twice\n * matters: a project's `carry:` material can run to `box.cpMaxBytes` (100 MiB),\n * where the JSON envelope costs ~6x the payload in peak memory across both ends.\n *\n * Keeping them separate also means there is no wire to break: an older hub\n * simply 404s this prefix, which a client can detect and report precisely.\n */\nexport const CUSTODY_BLOB_PATH_PREFIX = '/admin/custody-blob';\n\n/** True when `path` addresses the blob surface. Disjoint from {@link isCustodyPath}. */\nexport function isCustodyBlobPath(path: string): boolean {\n return path.startsWith(`${CUSTODY_BLOB_PATH_PREFIX}/`);\n}\n\nexport interface CustodyBlobRequest {\n method: string;\n /** URL pathname, e.g. `/admin/custody-blob/projects/acme__web/seed/carry.tar.gz`. */\n path: string;\n bearer: string;\n /** Request body for PUT. Absent for GET/DELETE. */\n body?: Readable;\n /** Cap enforced while streaming (`relay.custodyMaxBlobBytes`). */\n maxBytes?: number;\n}\n\n/**\n * A blob response. `stream` is set only for a successful GET, and the caller\n * owns piping it; everything else is a small JSON `body` exactly like the JSON\n * surface, so error handling is identical on both.\n */\nexport interface CustodyBlobResponse {\n status: number;\n body?: unknown;\n stream?: Readable;\n /** Metadata for a GET, so the host router can set content-length / digest headers. */\n entry?: CustodyEntry;\n}\n\nexport async function handleCustodyBlobRequest(\n req: CustodyBlobRequest,\n deps: CustodyRouteDeps,\n): Promise<CustodyBlobResponse | null> {\n if (!isCustodyBlobPath(req.path)) return null;\n const log = deps.log ?? (() => {});\n\n // Same gate as the JSON surface, for the same reason: on the control box every\n // proxied request looks loopback, so the admin bearer is the only proof.\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'custody not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n const store = deps.custody;\n if (!store) {\n return { status: 503, body: { error: 'custody store not enabled on this relay' } };\n }\n\n try {\n const path = normalizeCustodyPath(\n decodeURIComponent(req.path.slice(`${CUSTODY_BLOB_PATH_PREFIX}/`.length)),\n );\n\n if (req.method === 'PUT') {\n if (!req.body) return { status: 400, body: { error: 'expected a request body' } };\n const result = await store.putStream(path, req.body, { maxBytes: req.maxBytes });\n log(\n `custody blob put ${path} (${String(result.size)} bytes, ${result.changed ? 'changed' : 'unchanged'})`,\n );\n return { status: 200, body: result };\n }\n\n if (req.method === 'GET') {\n const found = await store.getStream(path);\n if (!found) return { status: 404, body: { error: 'no such custody entry' } };\n log(`custody blob get ${path} (${String(found.entry.size)} bytes)`);\n return { status: 200, stream: found.data, entry: found.entry };\n }\n\n return { status: 405, body: { error: 'method not allowed' } };\n } catch (err) {\n if (err instanceof CustodyPathError) return { status: 400, body: { error: err.message } };\n if (err instanceof CustodyTooLargeError) {\n // 413, and the message names the key — an operator hitting this needs to\n // know it is a configured cap, not a broken upload.\n return {\n status: 413,\n body: {\n error: `${err.message}. Raise \\`relay.custodyMaxBlobBytes\\` here and AGENTBOX_CUSTODY_MAX_BLOB_BYTES on the control box.`,\n },\n };\n }\n const msg = err instanceof Error ? err.message : String(err);\n log(`custody blob error: ${msg}`);\n return { status: 500, body: { error: `custody: ${msg}` } };\n }\n}\n","/**\n * The `/remote/boxes` create-queue surface, as a framework-agnostic dispatcher\n * mounted by BOTH relay front-ends: the hosted-plane handler (`core/handler.ts`,\n * Next/Vercel) and the relay daemon (`server.ts`, node:http — what the control\n * box actually runs). One implementation, one gate, both profiles.\n *\n * Like custody, the **admin bearer is the only proof** — never loopback (the\n * control box sits behind Caddy on the same host, so every proxied request looks\n * loopback). Missing admin token → 503 (not configured); wrong token → 401; a\n * store without the create-job queue → 501.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { rm } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { timingSafeEqual } from 'node:crypto';\nimport type { CustodyStore } from './custody/store.js';\nimport type { CreateJobRequest, Store } from './store/store.js';\n\n/** Structurally identical to `RelayResponse` in `core/handler.ts` (kept local to avoid a cycle). */\nexport interface RemoteBoxesResponse {\n status: number;\n body?: unknown;\n}\n\nexport interface RemoteBoxesRequest {\n method: string;\n /** URL pathname, e.g. `/remote/boxes` or `/remote/boxes/<jobId>`. */\n path: string;\n /** Bearer token as presented ('' when absent). */\n bearer: string;\n /** Raw request body ('' for GET). */\n bodyText: string;\n /** Query params, for the log tail's `?offset=`. Absent → treated as empty. */\n query?: URLSearchParams;\n}\n\nexport interface RemoteBoxesDeps {\n store: Store;\n /** Admin bearer. Empty/absent → not configured (503). */\n adminToken?: string;\n /**\n * Providers this plane can CREATE boxes on. `undefined`/empty → all allowed\n * (the full-host control box). A serverless plane sets the SDK-native set.\n */\n createProviders?: string[];\n /**\n * The custody store, if wired. A reap (`DELETE`) also removes the box's\n * `boxes/<sandboxId>/` SSH-key subtree from here so a destroyed box leaves no\n * key material behind. Absent → the reap only clears the registration/status.\n */\n custody?: CustodyStore | null;\n /**\n * Tail of a job's progress log, by byte offset. Wired by the relay daemon\n * (which runs on the same host as the worker writing the file) and omitted by\n * the serverless plane, where there is no such file — absent → 501, and a\n * polling client falls back to status-only progress.\n */\n readJobLog?: (jobId: string, offset: number) => Promise<{ lines: string[]; offset: number }>;\n log?: (line: string) => void;\n}\n\nexport const REMOTE_BOXES_PREFIX = '/remote/boxes';\n\n/**\n * A job id we are willing to hand to a path-building reader.\n *\n * Enforced HERE, at the trust boundary, not only inside the one reader that\n * builds a path today: `readJobLog` is injectable, and a future implementation\n * that forgot the check would inherit a path traversal straight off the URL.\n */\nexport function isSafeJobId(id: string): boolean {\n return id.length > 0 && id.length <= 128 && /^[A-Za-z0-9._-]+$/.test(id);\n}\n\n/** True when `path` addresses the create-queue surface. */\nexport function isRemoteBoxesPath(path: string): boolean {\n return path === REMOTE_BOXES_PREFIX || path.startsWith(`${REMOTE_BOXES_PREFIX}/`);\n}\n\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\nfunction parseJson<T>(text: string): T | null {\n if (text.length === 0) return {} as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Dispatch one `/remote/boxes` request. Returns `null` when `req.path` is not a\n * create-queue path, so a host router falls through to its own routes unchanged.\n */\nexport async function handleRemoteBoxesRequest(\n req: RemoteBoxesRequest,\n deps: RemoteBoxesDeps,\n): Promise<RemoteBoxesResponse | null> {\n if (!isRemoteBoxesPath(req.path)) return null;\n const log = deps.log ?? (() => {});\n const { store } = deps;\n\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'control plane not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n\n if (req.method === 'POST' && req.path === REMOTE_BOXES_PREFIX) {\n if (!store.enqueueCreateJob) {\n return { status: 501, body: { error: 'create-job queue not available on this store' } };\n }\n const body = parseJson<CreateJobRequest>(req.bodyText);\n if (!body || typeof body.repoUrl !== 'string' || typeof body.provider !== 'string') {\n return {\n status: 400,\n body: { error: 'expected {repoUrl, provider, branch?, name?, agent?, prompt?}' },\n };\n }\n const allowed = deps.createProviders;\n if (allowed && allowed.length > 0 && !allowed.includes(body.provider)) {\n return {\n status: 400,\n body: {\n error: `provider '${body.provider}' is not supported by this control plane (allowed: ${allowed.join(', ')})`,\n },\n };\n }\n const id = randomUUID();\n await store.enqueueCreateJob({\n id,\n status: 'queued',\n request: {\n repoUrl: body.repoUrl,\n provider: body.provider,\n branch: body.branch,\n name: body.name,\n agent: body.agent,\n prompt: body.prompt,\n },\n createdAt: new Date().toISOString(),\n });\n log(`enqueued create job ${id} (${body.provider} ${body.repoUrl})`);\n return { status: 202, body: { jobId: id } };\n }\n\n // The queue's own listing. Without it the create queue is addressable only by\n // job id, so a PC that enqueued a background run can't see what else is in\n // flight — `agentbox queue list` would show its local jobs and nothing else.\n if (req.method === 'GET' && req.path === REMOTE_BOXES_PREFIX) {\n if (!store.listCreateJobs) {\n return { status: 501, body: { error: 'create-job queue not available on this store' } };\n }\n const jobs = await store.listCreateJobs({ limit: 100 });\n return { status: 200, body: { jobs } };\n }\n\n // A job's progress log, by byte offset. The worker's per-step lines (clone,\n // seed, the provider's own create output) exist only as a file on the plane\n // that ran the job — without this the PC's `create --via-hub` / `<provider>\n // claude` sits on one static \"running\" line for the minutes a cloud create\n // takes, because the job row carries a status and nothing else.\n if (req.method === 'GET' && req.path.endsWith('/logs')) {\n const id = decodeURIComponent(\n req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length, -'/logs'.length),\n );\n if (id.length === 0) return { status: 404, body: { error: 'no such job' } };\n if (!isSafeJobId(id)) return { status: 400, body: { error: 'invalid job id' } };\n if (!deps.readJobLog) {\n return { status: 501, body: { error: 'job logs not available on this plane' } };\n }\n const offset = Number.parseInt(req.query?.get('offset') ?? '0', 10);\n const tail = await deps.readJobLog(id, Number.isFinite(offset) ? offset : 0);\n return { status: 200, body: tail };\n }\n\n if (req.method === 'GET' && req.path.startsWith(`${REMOTE_BOXES_PREFIX}/`)) {\n if (!store.getCreateJob) {\n return { status: 501, body: { error: 'create-job queue not available on this store' } };\n }\n const id = decodeURIComponent(req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length));\n const job = await store.getCreateJob(id);\n return job ? { status: 200, body: job } : { status: 404, body: { error: 'no such job' } };\n }\n\n // Reap a control-plane box's state from the control box: registration + status\n // + its SSH-key custody subtree. NOT the cloud resource — that teardown needs\n // provider creds + a reconstructed BoxRecord (the hub backend does it when it\n // can). The PC drives this via `hub boxes rm`; the hub UI's Destroy\n // button reaps a Store-registered box the same way.\n if (req.method === 'DELETE' && req.path.startsWith(`${REMOTE_BOXES_PREFIX}/`)) {\n const boxId = decodeURIComponent(req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length));\n if (boxId.length === 0) return { status: 404, body: { error: 'no such box' } };\n const reg = await store.getBox(boxId);\n const existed = await store.forgetBox(boxId);\n await store.deleteStatus(boxId);\n let custodyRemoved = 0;\n if (deps.custody) {\n // Keyed by sandboxId on disk + in custody; fall back to boxId for\n // registrations minted before sandboxId was carried.\n const key = reg?.sandboxId ?? boxId;\n const entries = await deps.custody.list(`boxes/${key}`).catch(() => []);\n for (const e of entries) {\n if (await deps.custody.delete(e.path).catch(() => false)) custodyRemoved += 1;\n }\n }\n // The control box also holds its OWN copy of a box it built: a `state.json`\n // record and the per-box SSH key dir the provider minted. Reaping only the\n // Store left those behind, so a box destroyed from the PC kept showing as\n // `running` in `hub boxes list`, the dashboard and the tray (both read local\n // state first, and a cloud row renders from `cloud.lastState` with no live\n // probe), with its private key still on disk.\n const localRemoved = await reapLocalBoxState(boxId, reg?.sandboxId, log);\n if (!existed && !reg && custodyRemoved === 0 && !localRemoved) {\n return { status: 404, body: { error: 'no such box' } };\n }\n log(\n `reaped box ${boxId} (registration=${String(existed)}, custody=${String(custodyRemoved)}, local=${String(localRemoved)})`,\n );\n return { status: 200, body: { boxId, removed: existed, custodyRemoved, localRemoved } };\n }\n\n return { status: 405, body: { error: 'method not allowed' } };\n}\n\n/**\n * Drop the control box's own record of a box whose cloud resource is already\n * gone: the `state.json` entry and the per-box SSH key dir the provider minted.\n *\n * Scoped to exactly this box's sandbox id — never a sweep. `prune --all`\n * enumerates box dirs by the docker-shaped `<id>-<n>-<mnemonic>` run-dir name,\n * which a VPS provider's sandboxId-keyed dir never matches, so a broad cleanup\n * there would delete a LIVE box's private key.\n *\n * Best-effort and idempotent: this runs on a plain relay too, where there is no\n * local record to remove.\n */\nasync function reapLocalBoxState(\n boxId: string,\n sandboxId: string | undefined,\n log: (line: string) => void,\n): Promise<boolean> {\n let removed = false;\n try {\n const { mutateState, readState, boxSshDirForProvider } = await import('@agentbox/sandbox-core');\n const state = await readState();\n const record = state.boxes.find((b) => b.id === boxId);\n if (record) {\n await mutateState((s) => ({ ...s, boxes: s.boxes.filter((b) => b.id !== boxId) }));\n removed = true;\n const key = record.cloud?.sandboxId ?? sandboxId;\n const provider = record.provider;\n if (key && provider) {\n const sshDir = boxSshDirForProvider(provider, key);\n // `<...>/boxes/<sandboxId>/ssh` — take the box dir, not just the keys.\n if (sshDir) await rm(dirname(sshDir), { recursive: true, force: true }).catch(() => {});\n }\n }\n } catch (err) {\n log(`local reap for ${boxId} failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n return removed;\n}\n","import type { BoxRegistry, EventBuffer } from '../registry.js';\nimport type { BoxStatusSnapshot, BoxStatusStore } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\nexport interface WriteThroughParts {\n registry: BoxRegistry;\n events: EventBuffer;\n statusStore: BoxStatusStore;\n}\n\n/** A durable store that also exposes the optional retention sweeps. */\ninterface StoreWithStatuses extends Store {\n prunePrompts?(beforeIso: string): Promise<number>;\n pruneCreateJobs?(beforeIso: string): Promise<number>;\n}\n\n/**\n * Wraps a durable {@link Store} (SQLite / Postgres) and mirrors every mutating\n * call into the in-process `BoxRegistry` / `EventBuffer` / `BoxStatusStore` the\n * relay handle exposes.\n *\n * Why this exists: the daemon's background loops (autopause, cloud-keepalive,\n * queue) and the hub backend read those concrete instances *synchronously*, not\n * the async `Store`. On the laptop that is fine — `MemoryStore` IS those\n * instances. But a control box injects a durable store, and without this wrapper\n * the handlers would write to SQLite while the instances stay empty, so\n * cloud-keepalive would never see a box and the hub UI would show no status.\n *\n * The durable store stays the source of truth (it survives restarts); the\n * in-memory instances are a within-process cache kept in lock-step by\n * write-through + a one-time {@link hydrate} on boot. The control box runs a\n * single hub process (SQLite single-writer, per phase 1), so no other writer can\n * make the mirror stale. Reads are pure delegation to the durable store.\n */\nexport class WriteThroughStore implements Store {\n private readonly inner: StoreWithStatuses;\n private readonly registry: BoxRegistry;\n private readonly events: EventBuffer;\n private readonly statusStore: BoxStatusStore;\n\n constructor(inner: Store, parts: WriteThroughParts) {\n this.inner = inner;\n this.registry = parts.registry;\n this.events = parts.events;\n this.statusStore = parts.statusStore;\n }\n\n /**\n * Load the durable store's boxes + statuses into the in-memory instances, once\n * at boot, so the loops start against a populated registry after a restart.\n * Events are a ring buffer (ephemeral) and are not hydrated.\n */\n async hydrate(): Promise<void> {\n for (const reg of await this.inner.listBoxes()) this.registry.register(reg);\n for (const { boxId, status } of await this.inner.listStatuses()) {\n const reg = this.registry.get(boxId);\n await this.statusStore.set(boxId, reg?.name ?? boxId, reg?.projectIndex, status);\n }\n }\n\n migrate(): Promise<void> {\n return this.inner.migrate?.() ?? Promise.resolve();\n }\n\n // --- boxes ---\n\n async registerBox(reg: BoxRegistration): Promise<void> {\n await this.inner.registerBox(reg);\n this.registry.register(reg);\n }\n\n getBox(boxId: string): Promise<BoxRegistration | undefined> {\n return this.inner.getBox(boxId);\n }\n\n authenticateBox(token: string): Promise<BoxRegistration | null> {\n return this.inner.authenticateBox(token);\n }\n\n listBoxes(): Promise<BoxRegistration[]> {\n return this.inner.listBoxes();\n }\n\n async forgetBox(boxId: string): Promise<boolean> {\n const existed = await this.inner.forgetBox(boxId);\n this.registry.forget(boxId);\n return existed;\n }\n\n countBoxes(): Promise<number> {\n return this.inner.countBoxes();\n }\n\n // --- events ---\n\n async appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n const ev = await this.inner.appendEvent(input);\n // The mirror ring keeps its own id sequence; the loops only read box/type/ts,\n // never cross-reference the durable id, so the divergence is harmless.\n this.events.append(input);\n return ev;\n }\n\n listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n return this.inner.listEvents(since, boxId);\n }\n\n countEvents(): Promise<number> {\n return this.inner.countEvents();\n }\n\n // --- status ---\n\n async setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n await this.inner.setStatus(boxId, name, projectIndex, status);\n await this.statusStore.set(boxId, name, projectIndex, status);\n }\n\n getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n return this.inner.getStatus(boxId);\n }\n\n async deleteStatus(boxId: string): Promise<void> {\n await this.inner.deleteStatus(boxId);\n this.statusStore.delete(boxId);\n }\n\n listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n return this.inner.listStatuses();\n }\n\n // --- prompt mailbox (pure delegation; no in-memory mirror the loops read) ---\n\n createPrompt(row: PromptRow): Promise<void> {\n return this.inner.createPrompt(row);\n }\n\n getPrompt(promptId: string): Promise<PromptRow | null> {\n return this.inner.getPrompt(promptId);\n }\n\n answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n return this.inner.answerPrompt(promptId, answer, cancelled);\n }\n\n listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n return this.inner.listPendingPrompts(boxId);\n }\n\n setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n return this.inner.setPromptResult(promptId, result);\n }\n\n // --- box-create job queue (pure delegation) ---\n\n enqueueCreateJob(job: CreateJobRow): Promise<void> {\n if (!this.inner.enqueueCreateJob) return Promise.resolve();\n return this.inner.enqueueCreateJob(job);\n }\n\n getCreateJob(id: string): Promise<CreateJobRow | null> {\n return this.inner.getCreateJob?.(id) ?? Promise.resolve(null);\n }\n\n listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n return this.inner.listCreateJobs?.(opts) ?? Promise.resolve([]);\n }\n\n claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n return this.inner.claimNextCreateJob?.(workerId) ?? Promise.resolve(null);\n }\n\n completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n if (!this.inner.completeCreateJob) return Promise.resolve();\n return this.inner.completeCreateJob(id, status, result);\n }\n\n // --- retention (forwarded; blocker B) ---\n\n prunePrompts(beforeIso: string): Promise<number> {\n return this.inner.prunePrompts?.(beforeIso) ?? Promise.resolve(0);\n }\n\n pruneCreateJobs(beforeIso: string): Promise<number> {\n return this.inner.pruneCreateJobs?.(beforeIso) ?? Promise.resolve(0);\n }\n}\n","import { createSign } from 'node:crypto';\n\n/**\n * GitHub App token leasing for the hosted control plane.\n *\n * The control plane holds only the App's private key + id — never a long-lived\n * PAT and never a box's repo. On an approved push it mints a short-lived\n * **installation access token** scoped to the SINGLE box repo (minimal perms)\n * and hands it to the box, which pushes to GitHub directly. GitHub installation\n * tokens always expire in ≤1h and are repo-scoped, so a compromised box yields\n * at most a 1h single-repo credential. The token is never persisted (in-memory\n * cache only; re-minted on a cold start — two cheap API calls).\n *\n * `fetch` (Node 20+) is used directly — no SDK dependency.\n */\n\nexport interface GitHubAppConfig {\n appId: string;\n privateKeyPem: string;\n /** API base; defaults to https://api.github.com (override for GHES). */\n apiBaseUrl?: string;\n}\n\nexport interface LeasedToken {\n token: string;\n /** ISO-8601 expiry as returned by GitHub. */\n expiresAt: string;\n}\n\n/**\n * Load the App config from the environment, or null when not configured.\n * `GITHUB_APP_PRIVATE_KEY` may be a raw PEM or base64-encoded PEM (env-friendly).\n */\nexport function loadGitHubAppConfig(): GitHubAppConfig | null {\n const appId = process.env.GITHUB_APP_ID;\n let key = process.env.GITHUB_APP_PRIVATE_KEY;\n if (!appId || !key) return null;\n if (!key.includes('BEGIN')) {\n try {\n key = Buffer.from(key, 'base64').toString('utf8');\n } catch {\n return null;\n }\n }\n const apiBaseUrl = process.env.GITHUB_API_URL || undefined;\n return { appId, privateKeyPem: key, apiBaseUrl };\n}\n\nfunction b64url(input: string | Buffer): string {\n return Buffer.from(input).toString('base64url');\n}\n\n/**\n * Mint the App JWT (RS256). `exp` is well under GitHub's 10-minute ceiling;\n * `iat` is backdated 60s to tolerate clock skew. Exported for unit testing.\n */\nexport function appJwt(cfg: GitHubAppConfig, nowMs: number = Date.now()): string {\n const now = Math.floor(nowMs / 1000);\n const header = b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));\n const payload = b64url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: cfg.appId }));\n const signingInput = `${header}.${payload}`;\n const signature = createSign('RSA-SHA256').update(signingInput).sign(cfg.privateKeyPem);\n return `${signingInput}.${b64url(signature)}`;\n}\n\ntype FetchLike = typeof fetch;\n\nexport interface GitHubAppLeaserOptions {\n /** Inject a fetch impl (tests). Defaults to the global fetch. */\n fetchImpl?: FetchLike;\n /** Inject a clock (tests). Defaults to Date.now. */\n now?: () => number;\n}\n\ninterface CacheEntry {\n token: string;\n expiresAt: string;\n expiresAtMs: number;\n}\n\nconst RENEW_BEFORE_MS = 5 * 60 * 1000; // re-mint when <5 min of life remains\n\n/**\n * Leases (and caches) repo-scoped installation tokens. One instance per relay\n * server. The cache key is `owner/repo`; a token is reused until it is within\n * RENEW_BEFORE_MS of expiry.\n */\nexport class GitHubAppLeaser {\n private readonly cfg: GitHubAppConfig;\n private readonly fetchImpl: FetchLike;\n private readonly now: () => number;\n private readonly apiBase: string;\n private readonly cache = new Map<string, CacheEntry>();\n private readonly installationIds = new Map<string, number>();\n\n constructor(cfg: GitHubAppConfig, opts: GitHubAppLeaserOptions = {}) {\n this.cfg = cfg;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n this.now = opts.now ?? Date.now;\n this.apiBase = (cfg.apiBaseUrl ?? 'https://api.github.com').replace(/\\/$/, '');\n }\n\n private headers(jwt: string): Record<string, string> {\n return {\n Authorization: `Bearer ${jwt}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'agentbox-relay',\n };\n }\n\n /**\n * Resolve the installation id for `owner/repo`, or null when the App is not\n * installed on it (404). Caches positive lookups. Non-404 errors throw.\n */\n private async lookupInstallationId(owner: string, repo: string): Promise<number | null> {\n const key = `${owner}/${repo}`;\n const cached = this.installationIds.get(key);\n if (cached !== undefined) return cached;\n const jwt = appJwt(this.cfg, this.now());\n const res = await this.fetchImpl(`${this.apiBase}/repos/${owner}/${repo}/installation`, {\n headers: this.headers(jwt),\n });\n if (res.status === 404) return null;\n if (!res.ok) {\n throw new Error(`GET installation for ${key} → ${String(res.status)}`);\n }\n const body = (await res.json()) as { id?: number };\n if (typeof body.id !== 'number') throw new Error('installation response missing id');\n this.installationIds.set(key, body.id);\n return body.id;\n }\n\n private async installationId(owner: string, repo: string): Promise<number> {\n const id = await this.lookupInstallationId(owner, repo);\n if (id === null) throw new Error(`GitHub App is not installed on ${owner}/${repo}`);\n return id;\n }\n\n /** Whether the App is installed on `owner/repo` — no token is minted. */\n async isRepoInstalled(owner: string, repo: string): Promise<boolean> {\n return (await this.lookupInstallationId(owner, repo)) !== null;\n }\n\n /**\n * Mint (or return a cached) installation token scoped to the single repo with\n * `contents: write` + `pull_requests: write`. Throws on any GitHub error.\n */\n async leaseRepoToken(owner: string, repo: string): Promise<LeasedToken> {\n const key = `${owner}/${repo}`;\n const cached = this.cache.get(key);\n if (cached && cached.expiresAtMs - this.now() > RENEW_BEFORE_MS) {\n return { token: cached.token, expiresAt: cached.expiresAt };\n }\n const id = await this.installationId(owner, repo);\n const jwt = appJwt(this.cfg, this.now());\n const res = await this.fetchImpl(\n `${this.apiBase}/app/installations/${String(id)}/access_tokens`,\n {\n method: 'POST',\n headers: { ...this.headers(jwt), 'Content-Type': 'application/json' },\n body: JSON.stringify({\n repositories: [repo],\n permissions: { contents: 'write', pull_requests: 'write' },\n }),\n },\n );\n if (!res.ok) {\n throw new Error(`failed to mint installation token for ${key} (→ ${String(res.status)})`);\n }\n const body = (await res.json()) as { token?: string; expires_at?: string };\n if (!body.token || !body.expires_at)\n throw new Error('access_tokens response missing token/expires_at');\n this.cache.set(key, {\n token: body.token,\n expiresAt: body.expires_at,\n expiresAtMs: Date.parse(body.expires_at),\n });\n return { token: body.token, expiresAt: body.expires_at };\n }\n}\n","import { spawn } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport { mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { closeSync, existsSync, openSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type GitPushMode,\n type UserConfig,\n} from '@agentbox/config';\nimport { readState, STATE_DIR, STATE_FILE } from '@agentbox/sandbox-core';\nimport { normalizeAgentStatus, pickPrimaryAgent } from '@agentbox/core';\nimport type {\n AgentActivityState,\n BoxRecord,\n QueueAgentKind,\n ResolvedCarryEntry,\n} from '@agentbox/core';\nimport type { BoxRegistry } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\nexport const QUEUE_DIR = join(STATE_DIR, 'queue');\n\n/**\n * Concurrency ceiling for `kind: 'prepare'` (image-bake) jobs, applied **per\n * provider lane** — a separate gate from box creation. Two bakes of the same\n * provider would race on that provider's prepared-state marker and its\n * `box.image<Provider>` pin, so a provider bakes one at a time and a second\n * request for it queues. Different providers share nothing and bake in parallel.\n *\n * The lane key is `job.providerName` verbatim, so a remote-docker `docker:<alias>`\n * bake gets its own lane per host — those run on different machines entirely.\n */\n\nexport const PREPARE_MAX_CONCURRENT_PER_PROVIDER = 1;\n\nexport type QueueJobStatus = 'queued' | 'running' | 'done' | 'failed' | 'cancelled';\nexport type { QueueAgentKind };\n\n/**\n * Host-terminal targeting captured on the submitting host when `queue.openIn`\n * is not `none`, carried on the job so the worker can open a fresh terminal\n * onto the box the moment it is ready. The relay treats this as opaque\n * pass-through; the CLI worker (`_run-queued-job`) is what reads and acts on it.\n *\n * The targeting is captured at submit time because the relay daemon is\n * long-lived and idempotent — its own env reflects whatever terminal first\n * started it, not this submit's terminal.\n */\nexport interface QueueJobOpenTerminal {\n host: 'tmux' | 'cmux' | 'herdr' | 'iterm2';\n mode: 'split' | 'window' | 'tab';\n /** Submitting shell's cwd, so the new pane resolves project-scoped refs. */\n cwd: string;\n /** tmux server socket (`$TMUX`) + the pane to split (`$TMUX_PANE`). */\n tmuxSocket?: string;\n tmuxPane?: string;\n /** cmux control socket (`$CMUX_SOCKET_PATH`) + bundled CLI path. */\n cmuxSocket?: string;\n cmuxBundledCli?: string;\n /** Submitting surface + workspace UUIDs (`$CMUX_SURFACE_ID` /\n * `$CMUX_WORKSPACE_ID`), so the worker can split the original pane (or, failing\n * that, the parent workspace) instead of opening a new top-level workspace. */\n cmuxSurfaceId?: string;\n cmuxWorkspaceId?: string;\n /** Herdr session socket (`$HERDR_SOCKET_PATH`) + submitting pane/workspace ids\n * (`$HERDR_PANE_ID` / `$HERDR_WORKSPACE_ID`), so the worker can split the\n * original pane / add a tab in the parent workspace. */\n herdrSocket?: string;\n herdrPaneId?: string;\n herdrWorkspaceId?: string;\n}\n\n/** On-disk job manifest. Read/written under `~/.agentbox/queue/<id>.json`. */\nexport interface QueueJob {\n id: string;\n /**\n * What the worker does with this job. `create` (default when absent) builds a\n * box. `prepare` bakes a provider's base image — it produces an artifact, not\n * a box, so it is excluded from the box/working concurrency gates and never\n * surfaces as a box in the dashboard. Prepare jobs carry `prepare` (not the\n * agent/create fields, which hold inert placeholders).\n */\n kind?: 'create' | 'prepare';\n agent: QueueAgentKind;\n status: QueueJobStatus;\n /** Friendly box name the worker should create the box under. */\n boxName: string;\n providerName: string;\n /** Original initial-prompt text the user passed via `-i`. */\n prompt: string;\n /** Extra argv tokens passed after `--`. */\n agentArgs: string[];\n /**\n * \"Just create the box, don't start an agent\" (like `agentbox create`). When\n * true the worker builds the box and stops — no agent session, no prompt.\n * `agent` still holds a value (required by the type) but is ignored.\n */\n noAgent?: boolean;\n /**\n * Seed the agent's first turn with the setup-wizard prompt (generate\n * `agentbox.yaml`) — set by the hub when the project has no `agentbox.yaml`\n * and no default snapshot. Inert when `noAgent` (no agent to run it).\n */\n setupWizard?: boolean;\n /**\n * A FOREGROUND create (an interactive `agentbox create` a human is watching),\n * as opposed to a background `-i` run. The scheduler starts foreground jobs in\n * their own lane, ungated by `queue.maxConcurrent` — that gate bounds background\n * fan-out, and making an interactive command sit `queued` behind unrelated `-i`\n * jobs would be a worse regression than the inline path it replaces. Its box\n * still counts in the running total once live (honest occupancy); it is just\n * never blocked. See {@link selectNextRunnableForeground}.\n */\n foreground?: boolean;\n /** Workspace + create-time options the worker reconstructs from. */\n createOpts: QueueJobCreateOpts;\n /** Per-job concurrency ceiling (--max-running override, else the global). */\n maxConcurrent: number;\n /**\n * Per-job working-agent ceiling (--max-working override, else the global\n * `queue.maxWorking`). Only consulted when the working-agent gate is active\n * (`queue.maxWorking > 0`). Absent → use the global.\n */\n maxWorking?: number;\n /**\n * Box id the worker created for this job, written back to the manifest as\n * soon as `createBox` returns (before the agent session starts). Lets the\n * working-agent counter join a `running` manifest to its live box status and\n * avoid double-counting the in-flight startup slot once the box registers.\n */\n boxId?: string;\n /**\n * Host-terminal targeting for `queue.openIn`. Set at submit time when the\n * submitting shell ran inside a supported terminal; absent → open nothing.\n */\n openTerminal?: QueueJobOpenTerminal;\n createdAt: string;\n startedAt?: string;\n finishedAt?: string;\n /** Per-job log file path the worker writes to. */\n logPath: string;\n /** PID of the running worker. */\n pid?: number;\n /** Free-form context attached on terminal status flips. */\n reason?: string;\n /** Exit code of the worker process (only set on done/failed). */\n exitCode?: number;\n /**\n * Interactive Claude re-login sub-state. Set by the worker when it detects an\n * expired/dead Claude login during create and drives a browser re-login in a\n * throwaway docker container (job stays `running` meanwhile). The hub API/UI\n * read `phase`/`url`/`error` to surface the flow; the code endpoint writes\n * `code` back, which the worker consumes and clears. Absent for the normal\n * (creds-OK) path.\n */\n login?: QueueJobLogin;\n /** Bake options for a `kind: 'prepare'` job (see {@link QueueJobPrepare}). */\n prepare?: QueueJobPrepare;\n}\n\n/**\n * Claude re-login sub-state carried on a create job. Written **only by the create\n * worker** (worker → UI): `phase`/`url`/`error`/`lastError`. The reverse channel\n * (the pasted OAuth code, UI → worker) rides a separate file — see\n * {@link queueLoginCodePath} — so the two sides never read-modify-write the same\n * object and can't lose each other's updates.\n */\nexport interface QueueJobLogin {\n required: boolean;\n phase: 'starting' | 'awaiting-code' | 'exchanging' | 'done' | 'error';\n /** OAuth approval URL the user must open; present from `awaiting-code` onward. */\n url?: string;\n /** Terminal failure reason (with `phase: 'error'`). */\n error?: string;\n /** A recoverable note (e.g. a rejected code) — the flow stays usable. */\n lastError?: string;\n}\n\n/**\n * Options for a `kind: 'prepare'` job: bake a provider's base image. The worker\n * (`_run-queued-prepare`) passes these into `provider.prepare`, filling any that\n * are absent from the hub's own effective config, and streams progress to the\n * job log. These are the bake INPUTS (not routing) — the CLI's `--build` /\n * `--size` / `--location` / `--name` flags ride here so one route serves every\n * bake shape.\n */\nexport interface QueueJobPrepare {\n /** Rebuild even if the base image/snapshot already exists. */\n force?: boolean;\n /** Each agent's declared settings (falls back to the effective config). */\n agentSettings?: Readonly<Record<string, Readonly<Record<string, string | boolean>>>>;\n /** Agents to bake into the base. Omitted/empty = agentless. */\n agents?: string[];\n /** Force a local docker build instead of pulling the registry base (`--build`). */\n build?: boolean;\n /** Bake-time VM size for the fixed-resource providers (daytona `cpu-mem-disk`, e2b `cpu-mem`). */\n size?: string;\n /** Bake datacenter / region (hetzner / digitalocean / daytona). */\n location?: string;\n /** Snapshot name (daytona; defaults to `agentbox-base-<timestamp>` when absent). */\n name?: string;\n}\n\n/**\n * Minimal subset of CLI create flags the queued worker needs to reconstruct\n * the box. Kept narrow on purpose: anything that only changes interactive\n * attach behavior is irrelevant for the background path.\n */\nexport interface QueueJobCreateOpts {\n workspace: string;\n name?: string;\n hostSnapshot?: boolean;\n snapshot?: string;\n /** Base ref the box's per-box `agentbox/<name>` branch forks from (branch / tag\n * / SHA). Absent → the host's HEAD. Mirrors the CLI's `--from-branch`. */\n fromBranch?: string;\n image?: string;\n withPlaywright?: boolean;\n withEnv?: boolean;\n vnc?: boolean;\n /** `--persistent` / `--no-persistent`: always-on box (config `box.persistent`). */\n persistent?: boolean;\n /** Other agents' host logins to seed as model auth (`--model-auth`; service agents). */\n borrowCredentials?: string[];\n /** `--no-resync` → false; resync the box with the host on (checkpoint) create. */\n resync?: boolean;\n sharedDockerCache?: boolean;\n portless?: boolean;\n sessionName?: string;\n /** Per-box override of `<agent>.dangerouslySkipPermissions` (`--no-...`). */\n dangerouslySkipPermissions?: boolean;\n memory?: string;\n cpus?: string;\n pidsLimit?: string;\n disk?: string;\n /**\n * carry: entries the submitter resolved + approved on the host (the same gate\n * the foreground create runs). Plain host-path metadata — serialized into the\n * job and applied by the worker, which reads the host files at create time.\n */\n carry?: ResolvedCarryEntry[];\n // ── Fields the foreground `agentbox create` conversion carries so the queue\n // worker builds the same box the old inline path did (audit: every create\n // flag has a home; a dropped one is an invisible capability regression). ──\n /** `--build` / `--no-pull`: force a local docker base build (→ allowPull:false). */\n build?: boolean;\n /** `box.imageRegistry`: GHCR ref the base is pulled from (docker + daytona). */\n imageRegistry?: string;\n /** `--with-env` / wizard picks: gitignore-bypassing env/config files to copy in. */\n envFiles?: string[];\n /** `--no-credential-sync` → false: the in-box refreshed-token fan-out watcher. */\n credentialSync?: boolean;\n /** `--bundle-depth`: cap commits in the cloud-seed git bundle (0 = full). */\n bundleDepth?: number;\n /** `-b`/`--use-branch`: reuse an existing branch instead of forking agentbox/<name>. */\n useBranch?: string;\n /** `git.pushMode` (`--dangerously-with-credentials` → 'direct'); cloud only. */\n gitPushMode?: GitPushMode;\n /** `--size`: VM size for cloud providers (hetzner type / daytona cpu-mem-disk / vercel vCPU). */\n size?: string;\n /** `--location`: datacenter/region (hetzner / digitalocean). */\n location?: string;\n /** `--inbound`: VPS firewall access policy (locked | open | CIDR list). */\n inbound?: string;\n /** `--remote-host`: SSH destination whose docker engine runs a remote-docker box. */\n remoteHost?: string;\n /**\n * Put a backed-up bot's IDENTITY back once the box is up. Set only by the\n * hub's restore route — never from the wire, and never by a plain create.\n *\n * The workspace half needs nothing here: the staged bundle tree IS the job's\n * `workspace`, so it rides the ordinary create. The state half cannot, because\n * it belongs inside the agent's own config dir — so the worker waits for the\n * service to report ready ON ITS OWN, stops it, pushes `<bundleDir>/state` in,\n * and restarts it. That ordering is forced by a `run_once: marker` onboard\n * task whose marker lives on the box ROOTFS: it fires on every fresh box no\n * matter what the config volume holds, so letting it run and THEN replacing\n * what it wrote is the only sequence that survives later boots.\n */\n restore?: {\n /** Absolute bundle dir on the host running the worker (`…/bots/<bot>/<stamp>`). */\n bundleDir: string;\n /** The agent whose state dir the bundle carries. */\n agent: string;\n };\n}\n\nexport interface QueueConfig {\n enabled: boolean;\n maxConcurrent: number;\n /** Max concurrently-working agents before `-i` jobs queue. 0 = disabled (use the running-box gate). */\n maxWorking: number;\n /** Debounce: ms an agent must stay non-working before it frees its working slot. */\n idleGraceMs: number;\n}\n\n/**\n * Global+built-in queue config (mirrors `loadAutopauseConfig`): re-read every\n * tick so `agentbox config set --global queue.*` takes effect without a relay\n * restart. Project/workspace layers are intentionally ignored — the relay is\n * host-wide.\n */\nexport async function loadQueueConfig(): Promise<QueueConfig> {\n const d = BUILT_IN_DEFAULTS.queue;\n let global: Partial<UserConfig> = {};\n try {\n global = parseUserConfig(await readFile(GLOBAL_CONFIG_FILE, 'utf8'), GLOBAL_CONFIG_FILE);\n } catch {\n // ENOENT / parse error → built-in defaults.\n }\n const q = global.queue ?? {};\n return {\n enabled: q.enabled ?? d.enabled,\n maxConcurrent: q.maxConcurrent ?? d.maxConcurrent,\n maxWorking: q.maxWorking ?? d.maxWorking,\n idleGraceMs: (q.idleGraceSeconds ?? d.idleGraceSeconds) * 1_000,\n };\n}\n\n/**\n * Atomically write a job manifest. Writes to a sibling `.tmp` file then renames\n * — readers never see a half-written JSON file. Idempotent: missing queue dir\n * is created as needed.\n */\nexport async function writeJob(job: QueueJob): Promise<void> {\n await mkdir(QUEUE_DIR, { recursive: true });\n const final = join(QUEUE_DIR, `${job.id}.json`);\n const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(job, null, 2) + '\\n', 'utf8');\n await rename(tmp, final);\n}\n\nexport interface EnqueueQueueJobInput {\n agent: QueueAgentKind;\n boxName: string;\n providerName: string;\n prompt: string;\n agentArgs: string[];\n createOpts: QueueJobCreateOpts;\n /**\n * \"Just create the box, don't start an agent\" (like `agentbox create`). The\n * worker runs createBox() then stops — no agent session. `agent` is still\n * required by the type but is ignored by the worker when this is set.\n */\n noAgent?: boolean;\n /** Seed the setup-wizard prompt as the agent's first turn (hub create path). */\n setupWizard?: boolean;\n /** A FOREGROUND create — starts in the ungated lane (see {@link QueueJob.foreground}). */\n foreground?: boolean;\n /** Per-invocation override of queue.maxConcurrent. */\n maxRunningOverride?: number;\n /** Per-invocation override of queue.maxWorking. */\n maxWorkingOverride?: number;\n /** Host-terminal targeting captured at submit time (CLI `queue.openIn`). */\n openTerminal?: QueueJobOpenTerminal;\n}\n\nexport interface EnqueueQueueJobResult {\n job: QueueJob;\n /** Cross-provider running count at the time of enqueue (informational). */\n runningCount: number;\n /** Effective ceiling used for the job (override or global). */\n maxConcurrent: number;\n}\n\n/**\n * Build a queued-job manifest and write it to `~/.agentbox/queue/<id>.json`.\n * Pure + transport-free: it does NOT ensure a relay is running and does NOT\n * poke the scheduler — callers do that (the CLI via `POST /admin/queue/enqueue`\n * after `ensureRelay`; the embedded hub via its in-process queue poke). Kept in\n * `@agentbox/relay` so both the CLI `submitQueueJob` wrapper and the hub backend\n * share one manifest-builder without the hub importing `apps/cli`. The scheduler\n * (`startQueueLoop`) picks the manifest up on its next tick regardless.\n */\nexport async function enqueueQueueJob(input: EnqueueQueueJobInput): Promise<EnqueueQueueJobResult> {\n const cfg = await loadQueueConfig();\n const ceiling =\n typeof input.maxRunningOverride === 'number' && input.maxRunningOverride > 0\n ? input.maxRunningOverride\n : cfg.maxConcurrent;\n const maxWorking =\n typeof input.maxWorkingOverride === 'number' && input.maxWorkingOverride > 0\n ? input.maxWorkingOverride\n : undefined;\n\n const id = randomBytes(9).toString('hex');\n const job: QueueJob = {\n id,\n agent: input.agent,\n status: 'queued',\n boxName: input.boxName,\n providerName: input.providerName,\n prompt: input.prompt,\n agentArgs: input.agentArgs,\n ...(input.noAgent ? { noAgent: true } : {}),\n ...(input.setupWizard ? { setupWizard: true } : {}),\n ...(input.foreground ? { foreground: true } : {}),\n createOpts: input.createOpts,\n maxConcurrent: ceiling,\n ...(maxWorking !== undefined ? { maxWorking } : {}),\n ...(input.openTerminal !== undefined ? { openTerminal: input.openTerminal } : {}),\n createdAt: new Date().toISOString(),\n logPath: queueLogPath(id),\n };\n await writeJob(job);\n\n let runningCount = 0;\n try {\n runningCount = await defaultCountRunningBoxes();\n } catch {\n runningCount = 0;\n }\n\n return { job, runningCount, maxConcurrent: ceiling };\n}\n\nexport interface EnqueuePrepareJobInput {\n /** Provider to bake (docker | daytona | hetzner | vercel | e2b | plugin). */\n providerName: string;\n /** Rebuild even if the base already exists. */\n force?: boolean;\n /** Each agent's declared settings (else the effective config decides). */\n agentSettings?: Readonly<Record<string, Readonly<Record<string, string | boolean>>>>;\n /** Agents to bake into the base. */\n agents?: string[];\n /** Force a local docker build instead of pulling the registry base (`--build`). */\n build?: boolean;\n /** Bake-time VM size (else the effective config's `box.size<Provider>` decides). */\n size?: string;\n /** Bake datacenter / region (else the provider's `box.<...>Location/Region` decides). */\n location?: string;\n /** Snapshot name (daytona; the provider defaults it when absent). */\n name?: string;\n /** Host dir used for config resolution; the worker defaults it if absent. */\n workspace?: string;\n}\n\n/**\n * Build a `kind: 'prepare'` manifest and write it to the queue. Like\n * {@link enqueueQueueJob} this is transport-free — the caller pokes the\n * scheduler. The agent/create fields carry inert placeholders (the prepare\n * worker only reads `providerName` + `prepare`); the job is scheduled in its\n * provider's own lane (see {@link PREPARE_MAX_CONCURRENT_PER_PROVIDER}) and never\n * surfaces as a box.\n */\nexport async function enqueuePrepareJob(input: EnqueuePrepareJobInput): Promise<{ job: QueueJob }> {\n const id = randomBytes(9).toString('hex');\n const prepare: QueueJobPrepare = {\n ...(input.force ? { force: true } : {}),\n ...(input.agentSettings ? { agentSettings: input.agentSettings } : {}),\n ...(input.agents ? { agents: input.agents } : {}),\n ...(input.build ? { build: true } : {}),\n ...(input.size ? { size: input.size } : {}),\n ...(input.location ? { location: input.location } : {}),\n ...(input.name ? { name: input.name } : {}),\n };\n const job: QueueJob = {\n id,\n kind: 'prepare',\n agent: 'claude-code', // placeholder — ignored for prepare\n status: 'queued',\n boxName: '',\n providerName: input.providerName,\n prompt: '',\n agentArgs: [],\n createOpts: { workspace: input.workspace ?? process.cwd() },\n prepare,\n maxConcurrent: PREPARE_MAX_CONCURRENT_PER_PROVIDER,\n createdAt: new Date().toISOString(),\n logPath: queueLogPath(id),\n };\n await writeJob(job);\n return { job };\n}\n\n/** Read a single job manifest by id. Returns null when missing. */\nexport async function readJob(id: string): Promise<QueueJob | null> {\n try {\n const raw = await readFile(join(QUEUE_DIR, `${id}.json`), 'utf8');\n return JSON.parse(raw) as QueueJob;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n}\n\n/** Best-effort delete of a job manifest. ENOENT is not an error. */\nexport async function deleteJob(id: string): Promise<void> {\n try {\n await unlink(join(QUEUE_DIR, `${id}.json`));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n}\n\n/**\n * Read every job manifest in the queue dir. Skips temp files (atomic-rename\n * leftovers) and entries that fail to parse — the loop must never crash on a\n * malformed file. Sorted by `createdAt` ascending for FIFO selection.\n */\nexport async function loadQueue(): Promise<QueueJob[]> {\n let entries: string[];\n try {\n entries = await readdir(QUEUE_DIR);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: QueueJob[] = [];\n for (const name of entries) {\n if (!name.endsWith('.json')) continue;\n try {\n const raw = await readFile(join(QUEUE_DIR, name), 'utf8');\n out.push(JSON.parse(raw) as QueueJob);\n } catch {\n // skip malformed — surfaced via tick log if it stays put\n }\n }\n out.sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));\n return out;\n}\n\n/**\n * Pure selector: pick the oldest queued job that can start given the current\n * cross-provider running count. Per-job `maxConcurrent` ceiling wins (a job\n * with `--max-running 3` starts even when the global cap is 1). Returns null\n * when nothing can start right now.\n */\nexport function selectNextRunnable(jobs: QueueJob[], runningCount: number): QueueJob | null {\n // jobs is FIFO by createdAt already (loadQueue sorts).\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue; // prepare has its own lane\n if (j.foreground) continue; // foreground has its own lane (ungated)\n if (runningCount < j.maxConcurrent) return j;\n }\n return null;\n}\n\n/**\n * Pure selector for the FOREGROUND lane: the oldest queued foreground create.\n * Ungated — a foreground create is an interactive command a human is watching\n * (inherently one per terminal), so it must never sit `queued` behind background\n * `-i` jobs that happen to fill `queue.maxConcurrent`. Independent of the box and\n * working gates, exactly like {@link selectNextRunnablePrepare}. Its box counts\n * toward the running total once live (honest occupancy) but is never blocked.\n */\nexport function selectNextRunnableForeground(jobs: QueueJob[]): QueueJob | null {\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue;\n if (!j.foreground) continue;\n return j;\n }\n return null;\n}\n\n/**\n * Count running prepare jobs per provider lane (keyed by `providerName`). Dead\n * workers are skipped so a crashed bake doesn't wedge its provider's lane.\n */\nexport function countRunningPrepareJobsByProvider(jobs: QueueJob[]): Map<string, number> {\n const byProvider = new Map<string, number>();\n for (const j of jobs) {\n if (j.kind !== 'prepare') continue;\n if (j.status !== 'running') continue;\n if (typeof j.pid === 'number' && !processAlive(j.pid)) continue;\n byProvider.set(j.providerName, (byProvider.get(j.providerName) ?? 0) + 1);\n }\n return byProvider;\n}\n\n/**\n * Pure selector for the prepare (image-bake) lane: the oldest queued prepare job\n * whose provider lane is under {@link PREPARE_MAX_CONCURRENT_PER_PROVIDER}. A job\n * whose lane is busy is skipped, not blocking — so a queued e2b bake starts while\n * a docker bake runs. Independent of the box gates.\n */\nexport function selectNextRunnablePrepare(\n jobs: QueueJob[],\n runningByProvider: Map<string, number>,\n): QueueJob | null {\n for (const j of jobs) {\n if (j.kind !== 'prepare') continue;\n if (j.status !== 'queued') continue;\n const running = runningByProvider.get(j.providerName) ?? 0;\n if (running >= PREPARE_MAX_CONCURRENT_PER_PROVIDER) continue;\n return j;\n }\n return null;\n}\n\n// ---- working-agent gate ---------------------------------------------------\n//\n// When `queue.maxWorking > 0` the scheduler caps the number of *working*\n// (quota-consuming) agents instead of running boxes. The signal is each box's\n// live activity state in the relay's BoxStatusStore (fed for docker and cloud\n// alike). A box that has finished thinking and is waiting for the user no\n// longer occupies a slot, so the next queued job starts — without pausing the\n// finished box.\n\n/**\n * Activity union the working gate reasons about. Was a hand-kept copy of the\n * ctl union — the relay cannot import `@agentbox/ctl` (ctl depends on the relay,\n * not the reverse), which is exactly why the shared contract now lives in\n * `@agentbox/core` instead of being transcribed here.\n */\nexport type WorkingAgentState = AgentActivityState;\n\n/**\n * Boot window during which a freshly-created box (agent not yet reporting a\n * state) still counts as occupying a slot. Must exceed worst-case box\n * create + session launch before the first `working` hook fires, or a burst\n * of queued jobs would over-start before any reports working. Internal\n * constant, not user-tunable (it's a correctness guard, not a preference).\n */\nexport const STARTUP_GRACE_MS = 90_000;\n\n/** One box's facts the pure working-slot predicate reasons about. No I/O, no clock. */\nexport interface WorkingSlotEntry {\n /** boxId (registered box) — for logging/debug only. */\n key: string;\n /** Most-recent active-agent state across claude/codex/opencode, or null when no snapshot. */\n agentState: WorkingAgentState | null;\n /** ms since that agent's `updatedAt` (now - updatedAt), or null. */\n sinceUpdateMs: number | null;\n /** ms since the box was created (now - box.createdAt), or null. */\n sinceCreateMs: number | null;\n}\n\n/**\n * Pure predicate: does this box occupy a working slot right now?\n * - working/compacting → yes (actively consuming quota)\n * - unknown/no-snapshot, booting → yes while within {@link STARTUP_GRACE_MS}\n * - idle/waiting/end-plan/question→ yes only while within the debounce window\n * (`now - updatedAt < idleGraceMs`); this absorbs brief idle flaps between\n * turns so a slot isn't freed-then-reclaimed in a thrash.\n * - error, or anything past its window → no (slot frees).\n */\nexport function occupiesWorkingSlot(e: WorkingSlotEntry, idleGraceMs: number): boolean {\n if (e.agentState === 'working' || e.agentState === 'compacting') return true;\n if (\n (e.agentState === null || e.agentState === 'unknown') &&\n e.sinceCreateMs !== null &&\n e.sinceCreateMs < STARTUP_GRACE_MS\n ) {\n return true;\n }\n if (\n (e.agentState === 'idle' ||\n e.agentState === 'waiting' ||\n e.agentState === 'end-plan' ||\n e.agentState === 'question') &&\n e.sinceUpdateMs !== null &&\n e.sinceUpdateMs < idleGraceMs\n ) {\n return true;\n }\n return false;\n}\n\nexport function countWorkingSlots(entries: WorkingSlotEntry[], idleGraceMs: number): number {\n return entries.reduce((n, e) => (occupiesWorkingSlot(e, idleGraceMs) ? n + 1 : n), 0);\n}\n\n/**\n * Pure selector mirroring {@link selectNextRunnable} but for the working-agent\n * gate: pick the oldest queued job whose effective working ceiling (per-job\n * `maxWorking`, else the global) is above the current working count.\n */\nexport function selectNextRunnableByWorking(\n jobs: QueueJob[],\n workingCount: number,\n globalMaxWorking: number,\n): QueueJob | null {\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue; // prepare has its own lane\n if (j.foreground) continue; // foreground has its own lane (ungated)\n const ceil =\n typeof j.maxWorking === 'number' && j.maxWorking > 0 ? j.maxWorking : globalMaxWorking;\n if (workingCount < ceil) return j;\n }\n return null;\n}\n\n/**\n * Pick the active agent's state from a box-status snapshot. `claude` is always\n * present (codex/opencode are additive), so prefer whichever agent reports a\n * quota-consuming state, else the most-recently-updated one. Returns nulls\n * when no snapshot / no recognizable state.\n */\nexport function readActiveAgent(snap: Record<string, unknown> | undefined): {\n state: WorkingAgentState | null;\n updatedAt: string | null;\n} {\n // Through the normalizer: a box whose baked ctl still posts the old named\n // blocks must gate the queue exactly like a current one, and an agent added\n // after that box was baked must not read as \"this box is idle\" and let a\n // second job start on top of it.\n const picked = pickPrimaryAgent(normalizeAgentStatus(snap));\n if (!picked) return { state: null, updatedAt: null };\n return { state: picked.entry.state, updatedAt: picked.entry.updatedAt };\n}\n\nfunction msSince(iso: string | null | undefined): number | null {\n if (!iso) return null;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : Date.now() - t;\n}\n\nexport type RunningCountFn = () => Promise<number>;\nexport type CountWorkingFn = (idleGraceMs: number) => Promise<number>;\n\nexport interface QueueLoopDeps {\n log: (line: string) => void;\n /** Injectable; defaults to global-config loader. */\n loadConfig?: () => Promise<QueueConfig>;\n /** Injectable; defaults to docker inspect + cloud-as-running (see {@link defaultCountRunningBoxes}). */\n countRunning?: RunningCountFn;\n /**\n * Injectable working-agent counter (used when `queue.maxWorking > 0`).\n * Defaults to {@link defaultCountWorkingBoxes} over `registry` + `statusStore`.\n */\n countWorking?: CountWorkingFn;\n /** The relay's box registry; required (with `statusStore`) for the working gate. */\n registry?: Pick<BoxRegistry, 'list'>;\n /** The relay's box-status store; required (with `registry`) for the working gate. */\n statusStore?: Pick<BoxStatusStore, 'get'>;\n /** Injectable; defaults to `spawn detached node <cliEntry> _run-queued-job <id>`. */\n spawnWorker?: (job: QueueJob) => Promise<number | null>;\n /** Hook invoked when a manifest's status flips. Tests inject to assert. */\n onStatusChange?: (job: QueueJob) => void;\n intervalMs?: number;\n}\n\nexport interface QueueLoopHandle {\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 2_000;\n\n/**\n * Periodic queue scheduler. Runs alongside the autopause loop in the host\n * relay: every tick, count running boxes, pick the oldest startable queued\n * job, atomically flip it to `running`, then spawn the worker. Worker\n * crash/reboot recovery: on relay start, any `running` manifest whose PID\n * is no longer alive gets flipped to `failed` (the slot is recouped\n * automatically because we count live provider state, not manifests).\n */\nexport function startQueueLoop(deps: QueueLoopDeps): QueueLoopHandle {\n const loadConfig = deps.loadConfig ?? loadQueueConfig;\n const countRunning = deps.countRunning ?? defaultCountRunningBoxes;\n const spawnWorker = deps.spawnWorker ?? defaultSpawnWorker;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { log, onStatusChange } = deps;\n\n const countWorking: CountWorkingFn | null =\n deps.countWorking ??\n (deps.registry && deps.statusStore\n ? (idleGraceMs) => defaultCountWorkingBoxes(deps.registry!, deps.statusStore!, idleGraceMs)\n : null);\n\n let ticking = false;\n let stopped = false;\n let warnedNoWorkingDeps = false;\n let lastSweepAt = 0;\n let inFlight: Promise<void> = recoverOrphanedWorkers(log, onStatusChange).catch((err) => {\n log(`queue: orphan recovery failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n // NOTE: `cfg.enabled` gates only the BACKGROUND box/working lane below (it\n // bounds background `-i` fan-out). The foreground lane (an interactive\n // `agentbox create`, which now enqueues through the hub) and the prepare\n // lane must run regardless — a disabled background queue must not wedge an\n // interactive create at `queued`. Hygiene (sweep/recover) also runs always.\n\n // Throttled hygiene sweep of stale terminal manifests (runs regardless of\n // whether anything is queued, so a finished burst gets cleaned up).\n const now = Date.now();\n if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {\n lastSweepAt = now;\n await sweepTerminalJobs(log, now).catch((err) => {\n log(`queue: sweep failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n }\n\n // Flip jobs whose worker died mid-flight to `failed`. Must run before the\n // no-queued-work early return below, or a dead worker with nothing else\n // queued is never noticed — which is precisely the case that leaves a UI\n // progress card waiting on a job that will never finish.\n await recoverOrphanedWorkers(log, onStatusChange, true).catch((err) => {\n log(`queue: orphan reap failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n\n const jobs = await loadQueue();\n const hasQueued = jobs.some((j) => j.status === 'queued');\n if (!hasQueued) return;\n\n // Working-agent gate when `queue.maxWorking > 0` and the relay wired in\n // its registry + status store; otherwise the legacy running-box gate.\n let gateByWorking = cfg.maxWorking > 0;\n if (gateByWorking && !countWorking) {\n gateByWorking = false;\n if (!warnedNoWorkingDeps) {\n warnedNoWorkingDeps = true;\n log('queue: maxWorking set but registry/statusStore not wired; using running-box gate');\n }\n }\n\n // Start as many slots as we can in one tick — picking one per tick would\n // mean a 2s lag per job after a slot frees, which adds up when a burst\n // of jobs queues against a freshly-cleared pool. Gated by `cfg.enabled`:\n // when the background queue is off, this lane starts nothing (the foreground\n // + prepare lanes below still run).\n while (!stopped && cfg.enabled) {\n let occupancy: number;\n let next: QueueJob | null;\n if (gateByWorking && countWorking) {\n occupancy = await countWorking(cfg.idleGraceMs);\n const fresh = await loadQueue();\n next = selectNextRunnableByWorking(fresh, occupancy, cfg.maxWorking);\n } else {\n occupancy = await countRunning();\n const fresh = await loadQueue();\n next = selectNextRunnable(fresh, occupancy);\n }\n if (!next) break;\n // Atomic claim: re-read to make sure no other process already started\n // it (the relay is the only writer of status: running, but a\n // future-second-relay scenario would clobber here without this read).\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n const ceil = gateByWorking\n ? typeof updated.maxWorking === 'number' && updated.maxWorking > 0\n ? updated.maxWorking\n : cfg.maxWorking\n : updated.maxConcurrent;\n log(\n `queue: started job ${updated.id} (${updated.agent}) as pid ${String(pid)}; ${gateByWorking ? 'working' : 'running'} ${String(occupancy + 1)}/${String(ceil)}`,\n );\n } else {\n log(`queue: started job ${updated.id} (${updated.agent}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for job ${updated.id} failed: ${msg}`);\n }\n }\n\n // Foreground lane — an interactive `agentbox create` a human is watching.\n // Ungated by `queue.maxConcurrent` (that gate bounds background `-i` fan-out);\n // a foreground create must start immediately, not sit `queued` behind unrelated\n // background jobs. Start every queued foreground create this tick — there is\n // inherently one per terminal, and each was launched by a present human.\n while (!stopped) {\n const fresh = await loadQueue();\n const next = selectNextRunnableForeground(fresh);\n if (!next) break;\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n log(\n `queue: started foreground job ${updated.id} (${updated.agent}) as pid ${String(pid)}`,\n );\n } else {\n log(`queue: started foreground job ${updated.id} (${updated.agent}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for foreground job ${updated.id} failed: ${msg}`);\n }\n }\n\n // Prepare (image-bake) lanes — independent of the box/working gates. A bake\n // produces an artifact, not a box, so it neither counts against nor is\n // blocked by running boxes. One lane per provider: the recount below sees\n // the job just claimed, so a single tick starts at most one bake per\n // provider and as many providers as have queued work.\n while (!stopped) {\n const fresh = await loadQueue();\n const runningByProvider = countRunningPrepareJobsByProvider(fresh);\n const next = selectNextRunnablePrepare(fresh, runningByProvider);\n if (!next) break;\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n log(\n `queue: started prepare job ${updated.id} (${updated.providerName}) as pid ${String(pid)}; ${updated.providerName} lane ${String((runningByProvider.get(updated.providerName) ?? 0) + 1)}/${String(PREPARE_MAX_CONCURRENT_PER_PROVIDER)}`,\n );\n } else {\n log(`queue: started prepare job ${updated.id} (${updated.providerName}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for prepare job ${updated.id} failed: ${msg}`);\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log(`queue: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n /** Inject manual ticks (after enqueue HTTP). Caller is fire-and-forget. */\n function poke(): void {\n if (stopped) return;\n inFlight = tick();\n }\n\n // Expose poke on the handle in addition to stop, so the HTTP enqueue route\n // can trigger an immediate scheduling pass without waiting for the timer.\n const handle: QueueLoopHandle & { poke: () => void } = {\n poke,\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return handle;\n}\n\n/**\n * Scrub `running` manifests whose PID is no longer alive — usually after a\n * host reboot or a relay crash mid-flight. The slot is recouped automatically\n * because `countRunning` reads live provider state, but the manifest must be\n * advanced or `agentbox queue list` keeps lying about what's in progress.\n *\n * `requirePid` distinguishes the two callers:\n * - startup (`false`): a `running` manifest with no PID at all was orphaned by a\n * relay that died between marking the job running and recording the PID. There\n * is no worker to wait for, so fail it.\n * - every tick (`true`): only reap a PID we know is dead. A `running` job whose\n * PID isn't written *yet* is in the spawn window of the current tick — reaping\n * that would kill jobs as they start.\n *\n * Running this per-tick is what makes a worker that dies mid-flight visible. It\n * used to run only at startup, so a crashed worker left the job `running`\n * forever: no terminal status, no SSE `end`, and a UI progress card that waits\n * on a job that is never coming back.\n */\nasync function recoverOrphanedWorkers(\n log: (line: string) => void,\n onChange?: (job: QueueJob) => void,\n requirePid = false,\n): Promise<void> {\n const jobs = await loadQueue();\n for (const j of jobs) {\n if (j.status !== 'running') continue;\n if (typeof j.pid === 'number' ? processAlive(j.pid) : requirePid) continue;\n const failed: QueueJob = {\n ...j,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: 'worker-died',\n };\n await writeJob(failed);\n onChange?.(failed);\n log(`queue: recovered orphan job ${j.id} (pid ${String(j.pid ?? '?')} not alive) -> failed`);\n }\n}\n\n/** Terminal job manifests older than this are swept so `queue list` and the\n * scheduler don't accumulate unbounded done/failed/cancelled entries (they\n * never gate concurrency, but they pollute listings and were never cleaned). */\nexport const TERMINAL_RETENTION_MS = 60 * 60 * 1_000;\nconst SWEEP_INTERVAL_MS = 60 * 1_000;\nconst TERMINAL_STATUSES: readonly QueueJobStatus[] = ['done', 'failed', 'cancelled'];\n\n/**\n * Delete terminal (done/failed/cancelled) job manifests whose terminal flip is\n * older than {@link TERMINAL_RETENTION_MS}. Recent terminal jobs are kept so\n * `agentbox queue list` still shows just-finished history. Best-effort: a\n * delete failure is logged-by-omission and retried next sweep.\n */\nasync function sweepTerminalJobs(log: (line: string) => void, now: number): Promise<void> {\n const jobs = await loadQueue();\n let swept = 0;\n for (const j of jobs) {\n if (!TERMINAL_STATUSES.includes(j.status)) continue;\n const since = Date.parse(j.finishedAt ?? j.createdAt);\n if (Number.isNaN(since) || now - since < TERMINAL_RETENTION_MS) continue;\n await deleteJob(j.id);\n swept += 1;\n }\n if (swept > 0) log(`queue: swept ${String(swept)} stale terminal manifest(s)`);\n}\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Count concurrently *working* agents for the working-agent gate. Computed\n * fresh each call from in-memory relay state (no docker shell-out, no cache):\n * - one {@link WorkingSlotEntry} per registered box, from its live status\n * snapshot (`statusStore`) and creation time (`registry`), scored by\n * {@link occupiesWorkingSlot};\n * - plus each `running` queue job whose box hasn't registered yet (in-flight\n * create), so a burst can't over-start before the first box reports. A job\n * whose `boxId` is already in the registry is counted via its box entry\n * (no double count); a job whose worker PID is dead is skipped (the box,\n * if it exists, is counted via the registry).\n */\nexport async function defaultCountWorkingBoxes(\n registry: Pick<BoxRegistry, 'list'>,\n statusStore: Pick<BoxStatusStore, 'get'>,\n idleGraceMs: number,\n): Promise<number> {\n const boxes = registry.list();\n const registeredIds = new Set(boxes.map((b) => b.boxId));\n const entries: WorkingSlotEntry[] = boxes.map((b) => {\n const active = readActiveAgent(statusStore.get(b.boxId));\n return {\n key: b.boxId,\n agentState: active.state,\n sinceUpdateMs: msSince(active.updatedAt),\n sinceCreateMs: msSince(b.createdAt),\n };\n });\n const count = countWorkingSlots(entries, idleGraceMs);\n\n let jobs: QueueJob[];\n try {\n jobs = await loadQueue();\n } catch {\n return count;\n }\n return count + countInFlightCreateJobs(jobs, registeredIds);\n}\n\n/**\n * Count `running` queue jobs whose box isn't yet accounted for elsewhere — an\n * in-flight create that occupies a concurrency slot before its box exists.\n * Shared by both gates: the caller passes the set of box ids it already counted\n * (relay registry ids for the working gate, state.json ids for the running\n * gate), so a job is added only while its box is invisible to that source. A\n * job whose worker pid is dead is skipped (its box, if any, is counted directly;\n * the orphan-recovery sweep flips the stale manifest to `failed`).\n */\nexport function countInFlightCreateJobs(jobs: QueueJob[], accountedBoxIds: Set<string>): number {\n let n = 0;\n for (const j of jobs) {\n if (j.kind === 'prepare') continue; // a bake is not a box\n if (j.status !== 'running') continue;\n if (j.boxId && accountedBoxIds.has(j.boxId)) continue; // counted via its box\n if (typeof j.pid === 'number' && !processAlive(j.pid)) continue; // dead worker\n n += 1;\n }\n return n;\n}\n\nconst RUNNING_COUNT_CACHE_MS = 3_000;\nlet boxStateCache: { boxCount: number; stateIds: Set<string>; expiresAt: number } | null = null;\n\n/**\n * Cross-provider count of boxes whose runtime state is `running`, plus the\n * in-flight queue jobs whose box isn't in `state.json` yet.\n *\n * The box-state portion reads `~/.agentbox/state.json`, then per-provider:\n * - docker: `docker inspect --format {{.State.Status}}` shell-out (cheap).\n * - non-docker (daytona/hetzner/…): counted as running unless the record's\n * `lastState` says the host itself paused it. Cloud providers don't expose\n * a cheap synchronous probe (the queue loop would pay an SDK round-trip per\n * box per tick), so this is the same host-driven state `agentbox list`\n * shows — a platform-side stop is not seen, which only ever over-counts.\n * Before this, a `stop`ped cloud box held its slot until destroyed, and\n * three finished cloud boxes kept two queued jobs waiting indefinitely.\n * That portion is cached for 3s so multiple slot decisions in one tick share it.\n *\n * The in-flight term is recomputed every call (a cheap `loadQueue` fs read), NOT\n * cached: a job the scheduler just flipped to `running` hasn't created its box\n * yet (~25s on cloud, image pull on docker), so it's absent from `state.json`.\n * Without counting it, the per-tick \"start as many as fit\" loop would re-select\n * the same free slot for the next job and over-start past `--max-running`.\n */\nexport async function defaultCountRunningBoxes(): Promise<number> {\n const { boxCount, stateIds } = await cachedBoxState();\n let jobs: QueueJob[];\n try {\n jobs = await loadQueue();\n } catch {\n return boxCount;\n }\n return boxCount + countInFlightCreateJobs(jobs, stateIds);\n}\n\nasync function cachedBoxState(): Promise<{ boxCount: number; stateIds: Set<string> }> {\n const now = Date.now();\n if (boxStateCache && boxStateCache.expiresAt > now) {\n return { boxCount: boxStateCache.boxCount, stateIds: boxStateCache.stateIds };\n }\n const fresh = await uncachedBoxStateCount();\n boxStateCache = { ...fresh, expiresAt: now + RUNNING_COUNT_CACHE_MS };\n return fresh;\n}\n\n/** Running-box count from `state.json` plus the set of those boxes' ids (for\n * in-flight-job dedup). Read errors / no boxes → zero and an empty set. */\nasync function uncachedBoxStateCount(): Promise<{ boxCount: number; stateIds: Set<string> }> {\n let boxes: BoxRecord[];\n try {\n boxes = (await readState(STATE_FILE)).boxes;\n } catch {\n return { boxCount: 0, stateIds: new Set() };\n }\n const stateIds = new Set(boxes.map((b) => b.id));\n if (boxes.length === 0) return { boxCount: 0, stateIds };\n\n let boxCount = 0;\n const dockerBoxes: BoxRecord[] = [];\n for (const b of boxes) {\n const provider = b.provider ?? 'docker';\n if (provider === 'docker') {\n dockerBoxes.push(b);\n } else if (cloudBoxCountsAsRunning(b)) {\n boxCount += 1;\n }\n }\n if (dockerBoxes.length > 0) {\n const states = await Promise.all(dockerBoxes.map((b) => inspectDockerState(b.container)));\n for (const s of states) {\n if (s === 'running') boxCount += 1;\n }\n }\n return { boxCount, stateIds };\n}\n\n/**\n * Whether a non-docker box occupies a queue slot: yes unless agentbox itself\n * paused it (`cloud.lastState`). Absent (a pre-feature record) counts as\n * running, matching that field's own default.\n */\nexport function cloudBoxCountsAsRunning(box: Pick<BoxRecord, 'cloud'>): boolean {\n return box.cloud?.lastState !== 'paused';\n}\n\nfunction inspectDockerState(containerName: string): Promise<'running' | 'other'> {\n return new Promise<'running' | 'other'>((resolveP) => {\n const child = spawn('docker', ['inspect', '--format', '{{.State.Status}}', containerName], {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let out = '';\n let settled = false;\n const finish = (state: 'running' | 'other'): void => {\n if (settled) return;\n settled = true;\n resolveP(state);\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish('other');\n }, 10_000);\n child.stdout?.on('data', (c: Buffer) => {\n out += c.toString('utf8');\n });\n child.on('error', () => {\n clearTimeout(timer);\n finish('other');\n });\n child.on('close', () => {\n clearTimeout(timer);\n finish(out.trim() === 'running' ? 'running' : 'other');\n });\n });\n}\n\n/**\n * Default worker spawner: detached `node <cliEntry> _run-queued-job <id>`,\n * with stdout/stderr appended to the job's `logPath`. The CLI entry is set by\n * `ensureRelay` via `AGENTBOX_CLI_ENTRY` (the same hook checkpoint/cp/download\n * RPCs already use). Returns the worker PID, or null when the spawn produced\n * no PID (treated as a soft failure — the loop's catch turns it into a\n * `failed` manifest).\n */\nasync function defaultSpawnWorker(job: QueueJob): Promise<number | null> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry || !existsSync(entry)) {\n throw new Error(\n `AGENTBOX_CLI_ENTRY not set or missing (${String(entry)}); cannot spawn queue worker`,\n );\n }\n await mkdir(join(STATE_DIR, 'logs'), { recursive: true });\n const fd = openSync(job.logPath, 'a');\n // A prepare (image-bake) job runs a different worker; both stream to logPath.\n const command = job.kind === 'prepare' ? '_run-queued-prepare' : '_run-queued-job';\n // Pin an explicit cwd. Without one the worker inherits the daemon's, and this\n // daemon is long-lived while its own directory is not: `npm install -g` (what\n // `self-update` runs) replaces the package tree, so a relay/hub that keeps\n // running across an update sits in a deleted directory. The child then dies on\n // `process.cwd()` at startup — `ENOENT: uv_cwd` — before any of our code runs,\n // which reads as a create that hangs with a Node stack trace for a status line.\n // STATE_DIR is ours and always exists; the worker takes its workspace from the\n // job manifest, never from cwd.\n const child = spawn(process.execPath, [entry, command, job.id], {\n detached: true,\n stdio: ['ignore', fd, fd],\n env: process.env,\n cwd: STATE_DIR,\n });\n child.unref();\n // The fd stays open in the child; close our own copy.\n try {\n closeSync(fd);\n } catch {\n /* the child still holds its own fd */\n }\n return typeof child.pid === 'number' ? child.pid : null;\n}\n\n/** Re-export the path for callers (CLI submit helper, tests). */\nexport const QUEUE_LOGS_DIR = join(STATE_DIR, 'logs');\n\n/** Build the per-job log path. Kept here so submit + worker agree on layout. */\nexport function queueLogPath(id: string): string {\n return join(QUEUE_LOGS_DIR, `queue-${id}.log`);\n}\n\n/**\n * The UI → worker channel for a Claude re-login code: a dedicated file next to\n * the manifest. Only the hub writes it ({@link writeQueueLoginCode}); only the\n * worker reads+consumes it ({@link takeQueueLoginCode}). Keeping it out of the\n * job manifest avoids a cross-process read-modify-write race with the worker's\n * `login` (phase/url) writes.\n */\nexport function queueLoginCodePath(id: string): string {\n return join(QUEUE_DIR, `${id}.login-code`);\n}\n\n/** Hub side: deliver the pasted OAuth approval code to a job, written atomically. */\nexport async function writeQueueLoginCode(id: string, code: string): Promise<void> {\n await mkdir(QUEUE_DIR, { recursive: true });\n const final = queueLoginCodePath(id);\n const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, code.trim(), { mode: 0o600 });\n await rename(tmp, final);\n}\n\n/** Worker side: read + consume the pending code (deleting it); null when none. */\nexport async function takeQueueLoginCode(id: string): Promise<string | null> {\n try {\n const code = (await readFile(queueLoginCodePath(id), 'utf8')).trim();\n await unlink(queueLoginCodePath(id)).catch(() => {});\n return code.length > 0 ? code : null;\n } catch {\n return null;\n }\n}\n\n/** Wait briefly for a file to appear (queue manifest after enqueue HTTP). */\nexport async function waitForFile(path: string, timeoutMs = 1_000): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (existsSync(path)) return true;\n await delay(25);\n }\n return existsSync(path);\n}\n","import type { CreateJobRequest, Store } from './store/store.js';\n\n/**\n * A resolved `carry:` entry, spelled structurally so the relay core stays free\n * of a dependency on @agentbox/core's `ResolvedCarryEntry`. The provider on the\n * other end takes the real type; this is only a pass-through.\n */\nexport interface CarryEntryLike {\n rawSrc: string;\n rawDest: string;\n absSrc: string;\n absDest: string;\n kind: 'file' | 'dir';\n optional: boolean;\n mode?: number;\n user?: number;\n exclude?: string[];\n replaceEnvs?: boolean;\n replace?: unknown[];\n symlinkInfo?: 'safe' | 'outside-home';\n}\n\n/**\n * The actual box-creation step, injected by the deploy target. On a self-host\n * worker / Vercel cron this provisions a cloud box and seeds its workspace by\n * cloning `request.repoUrl` with a leased GitHub-App token (origin-clone — no\n * host bundle). Kept injectable so the worker loop is unit-testable without a\n * live cloud, and so the heavy provider wiring lives outside the relay core.\n */\nexport type CreateBoxFn = (\n request: CreateJobRequest,\n jobId: string,\n) => Promise<{ boxId: string; agentStartError?: string }>;\n\n/**\n * Side-effecting steps a {@link makeControlPlaneCreateBox} needs, all injected\n * so the orchestration is unit-testable without a cloud or GitHub. The worker\n * (laptop `hub worker`, or the resident hub worker) clones the repo\n * LOCALLY with a leased GitHub-App token and hands the fresh checkout to the\n * normal, tested `provider.create()` as the workspace — origin-clone seeding\n * without touching the host-coupled create flow.\n */\nexport interface CreateBoxDeps {\n /** Mint an authed HTTPS remote URL for the repo (App lease → x-access-token URL). */\n leaseRemoteUrl(repoUrl: string): Promise<string>;\n /**\n * Clone `authedUrl` into `dest` (checking out `branch` when given), then scrub\n * the remote back to the bare `repoUrl`.\n */\n cloneRepo(authedUrl: string, repoUrl: string, dest: string, branch?: string): Promise<void>;\n /**\n * Provision the cloud box from the local checkout. Returns the new box id, and\n * `agentStartError` when the box was created but starting the agent in-box\n * failed (a background `-i` run) — the caller fails the job WITH the box id so\n * the box is preserved for adopt/attach.\n */\n createBox(opts: {\n workspacePath: string;\n name: string | undefined;\n /** Approved `carry:` entries, staged locally by {@link CreateBoxDeps.fetchSeedMaterial}. */\n carry?: CarryEntryLike[];\n /**\n * The repo this checkout came from. `workspacePath` is a per-job temp clone\n * the worker deletes on the way out, so it is the only durable identity the\n * box has — used to name the box after the repo rather than after that\n * directory.\n */\n repoUrl: string;\n provider: string;\n /**\n * Agent the box is being created for. Registered on the control plane so a\n * PC adopting this box knows which agent to relaunch. When `prompt` is set\n * the worker also STARTS this agent detached in the box.\n */\n agent?: string;\n /** Seed prompt for a background `-i` run — present ⇒ start the agent in-box. */\n prompt?: string;\n /** Fully-processed agent args (post-`--`, incl. skip-permissions). */\n agentArgs?: string[];\n /** Start the agent in-box even with no `prompt` (a hub web-UI create). */\n startAgent?: boolean;\n /** Box-shaping flags the CLI resolved (snapshot/image/withEnv/...); see CreateJobRequestOpts. */\n opts?: CreateJobRequest['opts'];\n onLog?: (line: string) => void;\n }): Promise<{ id: string; agentStartError?: string }>;\n /** Make a per-job temp dir path. */\n tmpDir(jobId: string): string;\n /** Remove the temp checkout (best-effort). */\n cleanup(dir: string): Promise<void>;\n /**\n * Overlay the project's custody seed material (untracked files + env/secrets\n * a PC pushed) onto the fresh checkout at `dest`. A clone can only ever carry\n * committed state, so without this a hub-created box is missing exactly the\n * local files that make the project runnable.\n *\n * Optional and best-effort: a worker with no custody store (or a project that\n * was never pushed) simply creates the box from the bare clone, as before.\n * Returns what it applied, for the job log.\n */\n fetchSeedMaterial?(\n repoUrl: string,\n dest: string,\n ): Promise<{\n files: number;\n capturedAt?: string;\n repoHeadSha?: string;\n /**\n * Approved `carry:` entries staged on this machine, with `absSrc` pointing\n * at the staging dir. Passed straight to {@link CreateBoxDeps.createBox} so\n * the provider applies them exactly as it does for a local create.\n */\n carry?: CarryEntryLike[];\n } | null>;\n log?: (line: string) => void;\n /**\n * Per-job logger, preferred over {@link log} when present. The hub web UI\n * streams a create's progress from a per-job log file, so a job driven from\n * there needs its lines addressable by job id rather than interleaved into one\n * worker-wide log.\n */\n logFor?(jobId: string): (line: string) => void;\n}\n\n/** Runs `git <args>` with optional extra env + timeout; rejects on non-zero. */\nexport type CloneRepoRunGit = (\n args: string[],\n env?: Record<string, string>,\n timeoutMs?: number,\n) => Promise<void>;\n\n/** The GitHub/GitLab-convention LFS API endpoint for a clone URL: `<repo>.git/info/lfs`. */\nfunction lfsEndpointFor(cloneUrl: string): string {\n return `${cloneUrl.replace(/\\.git$/, '')}.git/info/lfs`;\n}\n\n/**\n * Clone `authedUrl` into `dest` robustly against **git-LFS**. A worker (control\n * box / laptop) clones with a leased token, and LFS reuses that token over HTTPS\n * (the standard CI path — verified). But the worker's git environment can resolve\n * an *SSH* LFS batch endpoint — e.g. a `git@github.com: insteadOf` rewrite (the\n * git-identity seeding configures such rewrites) makes git-lfs try SSH — and then\n * it hard-fails the create at the smudge step (`ssh_askpass ... Host key\n * verification failed`). To make the LFS fetch deterministic over HTTPS:\n * 1. clone with `GIT_LFS_SKIP_SMUDGE=1` — the checkout comes down with LFS\n * **pointer files**, so the clone can't fail on LFS transport at all;\n * 2. `git lfs pull` with `lfs.url` FORCED to the authed HTTPS endpoint — the\n * embedded `x-access-token:<token>@` userinfo both authenticates the fetch\n * AND dodges an `https://github.com/ → ssh` insteadOf rewrite (that prefix no\n * longer matches once the userinfo is present), so the real bytes come down\n * over HTTPS. Best-effort + non-interactive + timed: a token that genuinely\n * can't read LFS is left as pointers with a log line, not a failed create;\n * 3. scrub the leased token from `origin` (leave the box on the bare repo URL).\n *\n * Shared by both worker impls (`apps/hub` resident worker, `apps/cli control-plane\n * worker`) via an injected git-runner so it stays runtime-agnostic.\n */\nexport async function cloneRepoWithLfs(\n runGit: CloneRepoRunGit,\n authedUrl: string,\n repoUrl: string,\n dest: string,\n branch?: string,\n log: (line: string) => void = () => {},\n): Promise<void> {\n await runGit(\n branch ? ['clone', '--branch', branch, authedUrl, dest] : ['clone', authedUrl, dest],\n {\n GIT_LFS_SKIP_SMUDGE: '1',\n },\n );\n // Fetch the real LFS bytes over the forced HTTPS endpoint (best-effort). A repo\n // with no LFS makes this a fast no-op. `-c lfs.url` overrides remote/insteadOf\n // resolution; the token is passed on the argv (ephemeral), never written to the\n // box's config — origin is scrubbed to the bare URL below regardless.\n try {\n await runGit(\n ['-C', dest, '-c', `lfs.url=${lfsEndpointFor(authedUrl)}`, 'lfs', 'pull'],\n {\n GIT_TERMINAL_PROMPT: '0',\n GIT_SSH_COMMAND: 'ssh -o BatchMode=yes -o StrictHostKeyChecking=no',\n },\n 120_000,\n );\n } catch (err) {\n log(\n `git-lfs objects left as pointers (fetch failed): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n await runGit(['-C', dest, 'remote', 'set-url', 'origin', repoUrl]);\n}\n\n/**\n * Build a {@link CreateBoxFn} from injected side-effecting steps: lease a push\n * token, clone the repo locally, provision the box from that checkout, clean up.\n */\nexport function makeControlPlaneCreateBox(deps: CreateBoxDeps): CreateBoxFn {\n return async (request, jobId) => {\n const log = deps.logFor?.(jobId) ?? deps.log ?? (() => {});\n const dir = deps.tmpDir(jobId);\n try {\n log(`leasing a push token for ${request.repoUrl}`);\n const authedUrl = await deps.leaseRemoteUrl(request.repoUrl);\n log(`cloning ${request.repoUrl}${request.branch ? `@${request.branch}` : ''} into ${dir}`);\n await deps.cloneRepo(authedUrl, request.repoUrl, dir, request.branch);\n let carry: CarryEntryLike[] | undefined;\n if (deps.fetchSeedMaterial) {\n try {\n const seed = await deps.fetchSeedMaterial(request.repoUrl, dir);\n carry = seed?.carry?.length ? seed.carry : undefined;\n if (seed && seed.files > 0) {\n // Report what the seed was captured from: it can lag the branch tip\n // (the PC pushes it on create), and a surprising box is much easier\n // to explain when the job log says how old its local files are.\n const from = [\n seed.repoHeadSha ? `at ${seed.repoHeadSha.slice(0, 8)}` : null,\n seed.capturedAt ? `captured ${seed.capturedAt}` : null,\n ]\n .filter(Boolean)\n .join(', ');\n log(\n `applied ${String(seed.files)} seed file(s) from custody${from ? ` (${from})` : ''}`,\n );\n }\n } catch (err) {\n // Untracked/env material is a convenience: the box is still usable\n // without it, so say so and carry on rather than failing a create the\n // user is waiting on. `carry:` is NOT in that category — those paths\n // were shown to the user and approved, so applyProjectSeed throws for\n // them and that throw must not be swallowed here.\n // Matched by NAME, not by message prefix: a tar/fs failure while\n // unpacking approved entries throws a generic error, and swallowing it\n // would build the box without those files — the exact bug the loud\n // path exists to prevent. `applyProjectSeed` wraps every carry failure\n // in `CarrySeedError` so this test can't miss one.\n if (err instanceof Error && err.name === 'CarrySeedError') throw err;\n const msg = err instanceof Error ? err.message : String(err);\n log(`seed material unavailable (continuing with a bare clone): ${msg}`);\n }\n }\n log(`provisioning ${request.provider} box from the clone`);\n const box = await deps.createBox({\n workspacePath: dir,\n name: request.name,\n repoUrl: request.repoUrl,\n provider: request.provider,\n ...(carry ? { carry } : {}),\n // Carry the job's agent through to the box record + its plane\n // registration, so an adopting PC relaunches the right agent instead of\n // guessing. Without this a hub-created box adopts with no `lastAgent`.\n agent: request.agent,\n // A background `-i` run seeds a prompt: the worker starts the agent\n // in-box with these. Absent ⇒ a \"cold\" create (create --via-hub /\n // foreground) that the PC attaches later.\n prompt: request.prompt,\n agentArgs: request.agentArgs,\n startAgent: request.startAgent,\n // Box-shaping flags the CLI resolved, so a control-box create isn't built\n // with defaults where the user asked for a snapshot / image / env / etc.\n opts: request.opts,\n onLog: log,\n });\n log(`created box ${box.id}`);\n return { boxId: box.id, agentStartError: box.agentStartError };\n } finally {\n await deps.cleanup(dir);\n }\n };\n}\n\n/**\n * Claim + run ONE queued create job. Returns the processed job id, or null when\n * the queue is empty (or the store has no create-job support). A throwing\n * `createBox` marks the job failed (never throws out of here).\n */\nexport async function drainOneCreateJob(\n store: Store,\n createBox: CreateBoxFn,\n workerId: string,\n): Promise<string | null> {\n if (!store.claimNextCreateJob || !store.completeCreateJob) return null;\n const job = await store.claimNextCreateJob(workerId);\n if (!job) return null;\n try {\n const { boxId, agentStartError } = await createBox(job.request, job.id);\n // The box was created; if starting the agent in-box failed, fail the job but\n // keep the box id so it's adoptable/attachable (the user re-logins + retries).\n if (agentStartError) {\n await store.completeCreateJob(job.id, 'failed', { boxId, error: agentStartError });\n } else {\n await store.completeCreateJob(job.id, 'done', { boxId });\n }\n } catch (err) {\n await store.completeCreateJob(job.id, 'failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n return job.id;\n}\n\n/**\n * Drain queued create jobs until the queue is empty or `max` is hit. Used by\n * the self-host worker loop and a Vercel cron tick. Returns the count processed.\n */\nexport async function drainCreateJobs(\n store: Store,\n createBox: CreateBoxFn,\n workerId: string,\n max = 10,\n): Promise<number> {\n let processed = 0;\n while (processed < max) {\n const id = await drainOneCreateJob(store, createBox, workerId);\n if (!id) break;\n processed++;\n }\n return processed;\n}\n","import { timingSafeEqual } from 'node:crypto';\nimport type { GitHubAppLeaser } from '../github-app.js';\nimport { leaseTokenResult } from '../lease.js';\nimport { gateApproval } from '../permission.js';\nimport { isValidBoxStatus, normalizeBoxStatus } from '../status-store.js';\nimport type { Store } from '../store/store.js';\nimport { handleStoreRpcRequest } from '../store/store-rpc-routes.js';\nimport { resolveWorktree } from '../worktree.js';\nimport { handleCustodyRequest, type CustodyRouteDeps } from '../custody/routes.js';\nimport { handleRemoteBoxesRequest } from '../remote-boxes.js';\nimport type { CustodyStore } from '../custody/store.js';\nimport { isScratchBranch } from '@agentbox/core';\nimport type {\n BoxRegistration,\n GitRpcParams,\n PostEventBody,\n PostRpcBody,\n RegisterBoxBody,\n} from '../types.js';\n\n/**\n * Framework-agnostic request/response dispatch for the HOSTED control plane\n * (the Next.js app on Vercel / self-host). It reuses the relay's shared\n * primitives — the {@link Store}, {@link gateApproval}, the GitHub-App leaser —\n * but is decoupled from node:http and from host execution: it never runs git\n * locally (no worktree on the hosted plane) and obtains approvals via the poll\n * mailbox, never by blocking. The long-lived laptop relay keeps using\n * `server.ts` (node:http, host execution, SSE); they share the same core\n * building blocks but not this handler.\n *\n * Host-local RPCs (cp/download/checkpoint, and the docker-style git.push/fetch)\n * are intentionally rejected here — they require a host, which the plane has\n * none of. Cloud boxes push via `git.lease-token` instead.\n */\nexport interface GenericRequest {\n method: string;\n /** URL pathname, e.g. \"/rpc\" or \"/rpc/status/<id>\". */\n path: string;\n query: URLSearchParams;\n /** The Bearer token, already extracted ('' when absent). */\n bearer: string;\n /** Raw request body (already read by the adapter; '' for GET). */\n bodyText: string;\n}\n\nexport interface RelayResponse {\n status: number;\n /** JSON-serializable body (omitted → empty response). */\n body?: unknown;\n}\n\nexport interface ControlPlaneDeps {\n store: Store;\n /** GitHub-App leaser for `git.lease-token`; null → leasing returns a clear error. */\n leaser: GitHubAppLeaser | null;\n /** Admin bearer gating `/admin/*` + `/remote/*`. Required (fail-closed). */\n adminToken: string;\n /**\n * Providers this plane can CREATE boxes on (gates `POST /remote/boxes`).\n * `undefined`/empty → all providers allowed. A serverless plane (Vercel, no\n * worker) sets this to the SDK-native set so it cleanly refuses providers\n * whose `create()` needs host execution (e.g. hetzner).\n */\n createProviders?: string[];\n /**\n * Custody store (agent creds / project secrets / box SSH keys). Absent →\n * `/admin/custody/*` fail-closes with 503. See `../custody/routes.ts`.\n */\n custody?: CustodyStore | null;\n log?: (line: string) => void;\n}\n\nfunction ok(body: unknown, status = 200): RelayResponse {\n return { status, body };\n}\nfunction err(status: number, error: string): RelayResponse {\n return { status, body: { error } };\n}\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\nfunction parseJson<T>(text: string): T | null {\n if (text.length === 0) return {} as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\nconst HOST_LOCAL_METHODS = new Set([\n 'git.push',\n 'git.fetch',\n 'cp.toHost',\n 'cp.fromHost',\n 'download.workspace',\n 'download.env',\n 'download.config',\n 'download.claude',\n 'checkpoint.create',\n]);\n\n/**\n * Dispatch one control-plane request. The hosted plane's gating is fixed:\n * `/admin/*` and `/remote/*` always require the admin bearer (never loopback),\n * and approvals are always poll-mode.\n */\nexport async function handleRelayRequest(\n req: GenericRequest,\n deps: ControlPlaneDeps,\n): Promise<RelayResponse> {\n const { store, leaser } = deps;\n const log = deps.log ?? (() => {});\n\n if (deps.adminToken.length === 0) {\n // Fail closed — a hosted plane with no admin token must never serve /admin/*.\n // 503 (not 500): a deploy that hasn't had its secrets set yet is \"not ready\",\n // not crashed. healthz is handled before this in the Web adapter (lib/plane.ts).\n return err(503, 'control plane not configured: admin token unset');\n }\n\n if (req.method === 'GET' && req.path === '/healthz') {\n return ok({\n ok: true,\n boxes: await store.countBoxes(),\n events: await store.countEvents(),\n controlPlane: true,\n });\n }\n\n const isAdmin = req.path.startsWith('/admin/') || req.path.startsWith('/remote/');\n if (isAdmin && !timingSafeEqualStr(req.bearer, deps.adminToken)) {\n return err(401, 'invalid admin token');\n }\n\n const custodyDeps: CustodyRouteDeps = { custody: deps.custody, adminToken: deps.adminToken, log };\n const custody = await handleCustodyRequest(req, custodyDeps);\n if (custody)\n return custody.body === undefined\n ? { status: custody.status }\n : ok(custody.body, custody.status);\n\n // --- box endpoints (per-box bearer) ---\n if (req.method === 'POST' && req.path === '/events') {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const body = parseJson<PostEventBody>(req.bodyText);\n if (!body || typeof body.type !== 'string' || body.type.length === 0) {\n return err(400, 'missing \"type\" string');\n }\n if (body.type === 'box-status') {\n if (!isValidBoxStatus(body.payload)) return err(400, 'invalid box-status payload');\n // Normalized at the door — see `normalizeBoxStatus`.\n await store.setStatus(\n reg.boxId,\n reg.name,\n reg.projectIndex,\n normalizeBoxStatus(body.payload),\n );\n return ok({ ok: true }, 202);\n }\n const ev = await store.appendEvent({\n boxId: reg.boxId,\n type: body.type,\n ts: typeof body.ts === 'string' ? body.ts : undefined,\n payload: body.payload,\n });\n return ok({ id: ev.id }, 202);\n }\n\n if (req.method === 'POST' && req.path === '/rpc') {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const body = parseJson<PostRpcBody>(req.bodyText);\n if (!body || typeof body.method !== 'string' || body.method.length === 0) {\n return err(400, 'missing \"method\" string');\n }\n log(`rpc box=${reg.boxId} method=${body.method}`);\n return dispatchRpc(reg, body.method, body.params, deps);\n }\n\n if (req.method === 'GET' && req.path.startsWith('/rpc/status/')) {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const promptId = decodeURIComponent(req.path.slice('/rpc/status/'.length));\n const row = await store.getPrompt(promptId);\n if (!row || row.boxId !== reg.boxId) return err(404, 'no such prompt');\n if (row.status === 'pending') return ok({ status: 'pending' });\n if (row.answer !== 'y' || row.cancelled) {\n return ok({\n status: 'done',\n result: { exitCode: 10, stdout: '', stderr: 'denied by user\\n' },\n });\n }\n const cached = row.result;\n const result = cached ?? (await runApproved(reg, row.method, leaser));\n if (!cached) await store.setPromptResult(promptId, result);\n return ok({ status: 'done', result });\n }\n\n // --- admin endpoints (admin bearer, checked above) ---\n if (req.method === 'POST' && req.path === '/admin/register-box') {\n const body = parseJson<RegisterBoxBody>(req.bodyText);\n if (!body || !body.boxId || !body.token || typeof body.name !== 'string') {\n return err(400, 'expected {boxId, token, name}');\n }\n const reg: BoxRegistration = {\n boxId: body.boxId,\n token: body.token,\n name: body.name,\n kind: body.kind === 'cloud' ? 'cloud' : 'docker',\n backend: body.backend || undefined,\n sandboxId: body.sandboxId || undefined,\n registeredAt: new Date().toISOString(),\n containerName: body.containerName || undefined,\n createdAt: body.createdAt || undefined,\n projectIndex:\n typeof body.projectIndex === 'number' && body.projectIndex > 0\n ? Math.trunc(body.projectIndex)\n : undefined,\n worktrees: Array.isArray(body.worktrees) ? body.worktrees : undefined,\n previewUrl: body.previewUrl || undefined,\n previewToken: body.previewToken || undefined,\n bridgeToken: body.bridgeToken || undefined,\n autoApproveHostActions: body.autoApproveHostActions === true,\n autoApproveSafeHostActions: body.autoApproveSafeHostActions !== false,\n originUrl: body.originUrl || undefined,\n };\n await store.registerBox(reg);\n log(`registered ${reg.kind ?? 'docker'} box ${reg.boxId} (${reg.name})`);\n return ok(null, 204);\n }\n\n if (req.method === 'POST' && req.path === '/admin/forget-box') {\n const body = parseJson<{ boxId?: string }>(req.bodyText);\n if (!body?.boxId) return err(400, 'expected {boxId}');\n await store.forgetBox(body.boxId);\n await store.deleteStatus(body.boxId);\n return ok(null, 204);\n }\n\n if (req.method === 'GET' && req.path === '/admin/box-status') {\n const box = req.query.get('box') ?? '';\n const status = box ? await store.getStatus(box) : undefined;\n return status ? ok(status) : err(404, 'no status for box');\n }\n\n if (req.method === 'GET' && req.path === '/admin/events') {\n const since = Number.parseInt(req.query.get('since') ?? '0', 10) || 0;\n const box = req.query.get('box') ?? undefined;\n return ok({ events: await store.listEvents(since, box ?? undefined) });\n }\n\n if (req.method === 'GET' && req.path === '/admin/app/repo-installed') {\n // Whether the GitHub App is installed on owner/repo — lets a CLI without a\n // local App key (a laptop pointed at this plane) decide whether to prompt\n // the user to authorize the repo. No token is minted.\n if (!leaser) return err(503, 'no GitHub App configured on this control plane');\n const owner = req.query.get('owner') ?? '';\n const repo = req.query.get('repo') ?? '';\n if (!owner || !repo) return err(400, 'missing owner/repo query params');\n try {\n return ok({ installed: await leaser.isRepoInstalled(owner, repo) });\n } catch (e) {\n return err(502, `installation check failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n if (req.method === 'GET' && req.path === '/admin/registry') {\n const redacted = (await store.listBoxes()).map((r) => ({\n boxId: r.boxId,\n name: r.name,\n kind: r.kind,\n registeredAt: r.registeredAt,\n projectIndex: r.projectIndex,\n originUrl: r.originUrl,\n }));\n return ok({ boxes: redacted });\n }\n\n if (req.method === 'GET' && req.path === '/admin/prompts') {\n const boxId = req.query.get('boxId') ?? '';\n if (boxId.length === 0) return err(400, 'missing boxId query param');\n const pending = (await store.listPendingPrompts(boxId)).map((r) => r.ev);\n return ok({ prompts: pending });\n }\n\n if (req.method === 'POST' && req.path === '/admin/prompts/answer') {\n const body = parseJson<{ id?: string; answer?: string; cancelled?: boolean }>(req.bodyText);\n if (!body?.id || (body.answer !== 'y' && body.answer !== 'n')) {\n return err(400, 'expected {id, answer:\"y\"|\"n\", cancelled?}');\n }\n const hit = await store.answerPrompt(body.id, body.answer, body.cancelled);\n return hit ? ok(null, 204) : err(404, 'no pending prompt with that id');\n }\n\n // Generic Store RPC for a federated laptop relay's RemoteStore — a shared\n // dispatcher mounted in both this hosted-plane handler and the relay daemon\n // (`server.ts`), so a PC's RemoteStore works against the control box and the\n // Vercel plane identically.\n const storeRpc = await handleStoreRpcRequest(req, { store, adminToken: deps.adminToken, log });\n if (storeRpc) {\n return storeRpc.body === undefined\n ? { status: storeRpc.status }\n : ok(storeRpc.body, storeRpc.status);\n }\n\n // Create-queue surface (`/remote/boxes`) — a shared dispatcher mounted in both\n // this hosted-plane handler and the relay daemon (`server.ts`), so the control\n // box and the Vercel plane serve identical enqueue/status semantics.\n const remote = await handleRemoteBoxesRequest(req, {\n store,\n adminToken: deps.adminToken,\n createProviders: deps.createProviders,\n custody: deps.custody,\n log,\n });\n if (remote)\n return remote.body === undefined ? { status: remote.status } : ok(remote.body, remote.status);\n\n return err(404, 'not found');\n}\n\nasync function dispatchRpc(\n reg: BoxRegistration,\n method: string,\n params: unknown,\n deps: ControlPlaneDeps,\n): Promise<RelayResponse> {\n if (method === 'git.lease-token') {\n const p = params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, p?.path ?? '/workspace');\n // Lease-token grants a *repo-scoped* push token — the box can then push any\n // branch with it, so (unlike the relay-driven git.push, where the relay\n // picks the exact branch) the sanctioned-branch auto-approve does NOT apply\n // here. Only the box's own scratch branch bypasses; everything else parks\n // for a human.\n const isAgentboxBranch = isScratchBranch(worktree?.branch);\n if (!isAgentboxBranch) {\n const gate = await gateApproval(\n { mode: 'poll', store: deps.store },\n reg.boxId,\n method,\n params,\n {\n kind: 'confirm',\n message: `Allow box ${reg.name} to lease a push token for ${reg.originUrl ?? 'its repo'}?`,\n detail: `branch ${worktree?.branch ?? '(unregistered)'}`,\n defaultAnswer: 'n',\n context: { command: 'git lease-token', cwd: p?.path },\n },\n );\n if (gate.kind === 'pending') return ok({ status: 'pending', promptId: gate.promptId }, 202);\n if (gate.kind === 'deny') {\n return ok({ exitCode: 10, stdout: '', stderr: 'denied by user\\n' }, 500);\n }\n }\n const result = await leaseTokenResult(deps.leaser, reg);\n return ok(result, result.exitCode === 0 ? 200 : 500);\n }\n\n if (method === 'browser.open') {\n // The box already opened it locally; just record the event (no host mirror).\n const p = params as { url?: unknown } | undefined;\n if (typeof p?.url === 'string') {\n await deps.store.appendEvent({\n boxId: reg.boxId,\n type: 'browser-open',\n payload: { url: p.url },\n });\n }\n return ok({ exitCode: 0, stdout: '', stderr: '' });\n }\n\n if (HOST_LOCAL_METHODS.has(method)) {\n return ok(\n {\n exitCode: 64,\n stdout: '',\n stderr: `${method}: not available on the hosted control plane (no host). Cloud boxes push via git.lease-token.\\n`,\n },\n 501,\n );\n }\n\n return ok({ error: 'rpc method not implemented', method }, 501);\n}\n\n/** Execute a poll-approved action on the hosted plane. Only leasing is parkable here. */\nasync function runApproved(\n reg: BoxRegistration,\n method: string,\n leaser: GitHubAppLeaser | null,\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n if (method === 'git.lease-token') return leaseTokenResult(leaser, reg);\n return { exitCode: 64, stdout: '', stderr: `relay: no approved-action executor for ${method}\\n` };\n}\n","import * as pg from 'drizzle-orm/pg-core';\nimport * as sq from 'drizzle-orm/sqlite-core';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, PromptAskEvent, RelayEvent } from '../types.js';\nimport type { CreateJobRow, PromptRow } from './store.js';\n\n/**\n * The relay core's persisted schema, in both dialects.\n *\n * Drizzle types a table (and therefore every query) to its dialect, so `pg-core`\n * and `sqlite-core` each need their own table objects — but the *logical* schema\n * is one: identical table names, identical column names, identical JSON payloads.\n * Only the physical types differ (jsonb/timestamptz/bigint-identity vs\n * text-json/text-ISO/integer-autoincrement), which is what lets the existing\n * Postgres tables stay byte-compatible with what the hand-written SQL created.\n *\n * Timestamps are written as JS-side values in both dialects rather than leaning\n * on a `now()` default, so the read mappers below are shared: they normalize\n * `Date | string` to ISO-8601 whichever driver produced the row.\n *\n * DDL lives here too (see PG_SCHEMA_SQL / SQLITE_SCHEMA_SQL). Drizzle only emits\n * DDL through drizzle-kit migration folders, and a folder of .sql files does not\n * survive tsup bundling into relay's `bin.cjs` or the hub's standalone build — so\n * the boot-time `CREATE TABLE IF NOT EXISTS` stays literal SQL, colocated with\n * the schema it must match. Every *query* is drizzle-built.\n */\n\n// --- postgres ---\n\nexport const pgBoxes = pg.pgTable('boxes', {\n boxId: pg.text('box_id').primaryKey(),\n token: pg.text('token').notNull(),\n originUrl: pg.text('origin_url'),\n data: pg.jsonb('data').$type<BoxRegistration>().notNull(),\n registeredAt: pg.timestamp('registered_at', { withTimezone: true }).notNull(),\n});\n\nexport const pgEvents = pg.pgTable('events', {\n id: pg.bigint('id', { mode: 'number' }).generatedAlwaysAsIdentity().primaryKey(),\n boxId: pg.text('box_id').notNull(),\n type: pg.text('type').notNull(),\n ts: pg.text('ts'),\n payload: pg.jsonb('payload'),\n receivedAt: pg.timestamp('received_at', { withTimezone: true }).notNull(),\n});\n\nexport const pgBoxStatus = pg.pgTable('box_status', {\n boxId: pg.text('box_id').primaryKey(),\n name: pg.text('name'),\n projectIndex: pg.integer('project_index'),\n status: pg.jsonb('status').$type<BoxStatusSnapshot>().notNull(),\n updatedAt: pg.timestamp('updated_at', { withTimezone: true }).notNull(),\n});\n\nexport const pgPrompts = pg.pgTable('prompts', {\n id: pg.text('id').primaryKey(),\n boxId: pg.text('box_id').notNull(),\n ev: pg.jsonb('ev').$type<PromptAskEvent>().notNull(),\n method: pg.text('method').notNull(),\n params: pg.jsonb('params'),\n status: pg.text('status').$type<PromptRow['status']>().notNull(),\n answer: pg.text('answer').$type<'y' | 'n'>(),\n cancelled: pg.boolean('cancelled'),\n result: pg.jsonb('result').$type<GitRpcResult>(),\n createdAt: pg.timestamp('created_at', { withTimezone: true }).notNull(),\n expiresAt: pg.timestamp('expires_at', { withTimezone: true }),\n});\n\nexport const pgCreateJobs = pg.pgTable('create_jobs', {\n id: pg.text('id').primaryKey(),\n status: pg.text('status').$type<CreateJobRow['status']>().notNull(),\n request: pg.jsonb('request').$type<CreateJobRow['request']>().notNull(),\n result: pg.jsonb('result').$type<NonNullable<CreateJobRow['result']>>(),\n claimedBy: pg.text('claimed_by'),\n createdAt: pg.timestamp('created_at', { withTimezone: true }).notNull(),\n startedAt: pg.timestamp('started_at', { withTimezone: true }),\n finishedAt: pg.timestamp('finished_at', { withTimezone: true }),\n});\n\n/** Idempotent DDL for the Postgres tables. Unchanged from the pre-drizzle store. */\nexport const PG_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS boxes (\n box_id text PRIMARY KEY,\n token text NOT NULL,\n origin_url text,\n data jsonb NOT NULL,\n registered_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);\n\nCREATE TABLE IF NOT EXISTS events (\n id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n box_id text NOT NULL,\n type text NOT NULL,\n ts text,\n payload jsonb,\n received_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);\n\nCREATE TABLE IF NOT EXISTS box_status (\n box_id text PRIMARY KEY,\n name text,\n project_index int,\n status jsonb NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n id text PRIMARY KEY,\n box_id text NOT NULL,\n ev jsonb NOT NULL,\n method text NOT NULL,\n params jsonb,\n status text NOT NULL DEFAULT 'pending',\n answer text,\n cancelled boolean,\n result jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz\n);\nCREATE INDEX IF NOT EXISTS prompts_box_pending_idx ON prompts (box_id) WHERE status = 'pending';\n\nCREATE TABLE IF NOT EXISTS create_jobs (\n id text PRIMARY KEY,\n status text NOT NULL DEFAULT 'queued',\n request jsonb NOT NULL,\n result jsonb,\n claimed_by text,\n created_at timestamptz NOT NULL DEFAULT now(),\n started_at timestamptz,\n finished_at timestamptz\n);\nCREATE INDEX IF NOT EXISTS create_jobs_queued_idx ON create_jobs (created_at) WHERE status = 'queued';\n`;\n\n// --- sqlite ---\n\nexport const sqliteBoxes = sq.sqliteTable(\n 'boxes',\n {\n boxId: sq.text('box_id').primaryKey(),\n token: sq.text('token').notNull(),\n originUrl: sq.text('origin_url'),\n data: sq.text('data', { mode: 'json' }).$type<BoxRegistration>().notNull(),\n registeredAt: sq.text('registered_at').notNull(),\n },\n (t) => [sq.index('boxes_token_idx').on(t.token)],\n);\n\nexport const sqliteEvents = sq.sqliteTable(\n 'events',\n {\n id: sq.integer('id').primaryKey({ autoIncrement: true }),\n boxId: sq.text('box_id').notNull(),\n type: sq.text('type').notNull(),\n ts: sq.text('ts'),\n payload: sq.text('payload', { mode: 'json' }),\n receivedAt: sq.text('received_at').notNull(),\n },\n (t) => [sq.index('events_box_idx').on(t.boxId, t.id)],\n);\n\nexport const sqliteBoxStatus = sq.sqliteTable('box_status', {\n boxId: sq.text('box_id').primaryKey(),\n name: sq.text('name'),\n projectIndex: sq.integer('project_index'),\n status: sq.text('status', { mode: 'json' }).$type<BoxStatusSnapshot>().notNull(),\n updatedAt: sq.text('updated_at').notNull(),\n});\n\nexport const sqlitePrompts = sq.sqliteTable(\n 'prompts',\n {\n id: sq.text('id').primaryKey(),\n boxId: sq.text('box_id').notNull(),\n ev: sq.text('ev', { mode: 'json' }).$type<PromptAskEvent>().notNull(),\n method: sq.text('method').notNull(),\n params: sq.text('params', { mode: 'json' }),\n status: sq.text('status').$type<PromptRow['status']>().notNull(),\n answer: sq.text('answer').$type<'y' | 'n'>(),\n cancelled: sq.integer('cancelled', { mode: 'boolean' }),\n result: sq.text('result', { mode: 'json' }).$type<GitRpcResult>(),\n createdAt: sq.text('created_at').notNull(),\n expiresAt: sq.text('expires_at'),\n },\n (t) => [sq.index('prompts_box_status_idx').on(t.boxId, t.status)],\n);\n\nexport const sqliteCreateJobs = sq.sqliteTable(\n 'create_jobs',\n {\n id: sq.text('id').primaryKey(),\n status: sq.text('status').$type<CreateJobRow['status']>().notNull(),\n request: sq.text('request', { mode: 'json' }).$type<CreateJobRow['request']>().notNull(),\n result: sq.text('result', { mode: 'json' }).$type<NonNullable<CreateJobRow['result']>>(),\n claimedBy: sq.text('claimed_by'),\n createdAt: sq.text('created_at').notNull(),\n startedAt: sq.text('started_at'),\n finishedAt: sq.text('finished_at'),\n },\n (t) => [sq.index('create_jobs_status_idx').on(t.status, t.createdAt)],\n);\n\n/** Idempotent DDL for the SQLite tables (mirror of {@link PG_SCHEMA_SQL}). */\nexport const SQLITE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS boxes (\n box_id text PRIMARY KEY,\n token text NOT NULL,\n origin_url text,\n data text NOT NULL,\n registered_at text NOT NULL\n);\nCREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);\n\nCREATE TABLE IF NOT EXISTS events (\n id integer PRIMARY KEY AUTOINCREMENT,\n box_id text NOT NULL,\n type text NOT NULL,\n ts text,\n payload text,\n received_at text NOT NULL\n);\nCREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);\n\nCREATE TABLE IF NOT EXISTS box_status (\n box_id text PRIMARY KEY,\n name text,\n project_index integer,\n status text NOT NULL,\n updated_at text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n id text PRIMARY KEY,\n box_id text NOT NULL,\n ev text NOT NULL,\n method text NOT NULL,\n params text,\n status text NOT NULL DEFAULT 'pending',\n answer text,\n cancelled integer,\n result text,\n created_at text NOT NULL,\n expires_at text\n);\nCREATE INDEX IF NOT EXISTS prompts_box_status_idx ON prompts (box_id, status);\n\nCREATE TABLE IF NOT EXISTS create_jobs (\n id text PRIMARY KEY,\n status text NOT NULL DEFAULT 'queued',\n request text NOT NULL,\n result text,\n claimed_by text,\n created_at text NOT NULL,\n started_at text,\n finished_at text\n);\nCREATE INDEX IF NOT EXISTS create_jobs_status_idx ON create_jobs (status, created_at);\n`;\n\n// --- shared row mappers (either dialect) ---\n\n/** A timestamp column as returned by pg (Date) or sqlite (ISO text). */\nexport type DbTimestamp = Date | string;\n\nexport function toIso(value: DbTimestamp): string {\n return value instanceof Date ? value.toISOString() : new Date(value).toISOString();\n}\n\nexport function toIsoOrUndefined(value: DbTimestamp | null): string | undefined {\n return value === null ? undefined : toIso(value);\n}\n\nexport interface EventRow {\n id: number;\n boxId: string;\n type: string;\n ts: string | null;\n payload: unknown;\n receivedAt: DbTimestamp;\n}\n\nexport function rowToEvent(r: EventRow): RelayEvent {\n return {\n id: Number(r.id),\n boxId: r.boxId,\n type: r.type,\n ts: r.ts ?? undefined,\n payload: r.payload ?? undefined,\n receivedAt: toIso(r.receivedAt),\n };\n}\n\nexport interface PromptDbRow {\n id: string;\n boxId: string;\n ev: PromptAskEvent;\n method: string;\n params: unknown;\n status: PromptRow['status'];\n answer: 'y' | 'n' | null;\n cancelled: boolean | null;\n result: GitRpcResult | null;\n createdAt: DbTimestamp;\n expiresAt: DbTimestamp | null;\n}\n\nexport function rowToPrompt(r: PromptDbRow): PromptRow {\n return {\n id: r.id,\n boxId: r.boxId,\n ev: r.ev,\n method: r.method,\n params: r.params ?? undefined,\n status: r.status,\n answer: r.answer ?? undefined,\n cancelled: r.cancelled ?? undefined,\n result: r.result ?? undefined,\n createdAt: toIso(r.createdAt),\n expiresAt: toIsoOrUndefined(r.expiresAt),\n };\n}\n\nexport interface CreateJobDbRow {\n id: string;\n status: CreateJobRow['status'];\n request: CreateJobRow['request'];\n result: NonNullable<CreateJobRow['result']> | null;\n claimedBy: string | null;\n createdAt: DbTimestamp;\n startedAt: DbTimestamp | null;\n finishedAt: DbTimestamp | null;\n}\n\nexport function rowToJob(r: CreateJobDbRow): CreateJobRow {\n return {\n id: r.id,\n status: r.status,\n request: r.request,\n result: r.result ?? undefined,\n claimedBy: r.claimedBy ?? undefined,\n createdAt: toIso(r.createdAt),\n startedAt: toIsoOrUndefined(r.startedAt),\n finishedAt: toIsoOrUndefined(r.finishedAt),\n };\n}\n","import { and, asc, desc, eq, gt, inArray, isNotNull, lt, lte, or } from 'drizzle-orm';\nimport type { NodePgDatabase } from 'drizzle-orm/node-postgres';\nimport type { Pool } from 'pg';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport { RELAY_EVENT_RING_SIZE } from '../types.js';\nimport {\n PG_SCHEMA_SQL,\n pgBoxStatus,\n pgBoxes,\n pgCreateJobs,\n pgEvents,\n pgPrompts,\n rowToEvent,\n rowToJob,\n rowToPrompt,\n} from './schema.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\n/**\n * Postgres-backed {@link Store} for the hosted control plane (Vercel-managed\n * Postgres, Neon, or a self-hosted Postgres beside the app). Queries are built\n * with drizzle over the shared schema in `./schema.ts` — the same schema the\n * SQLite store uses, so the two dialects cannot drift.\n *\n * `pg` (and drizzle's `node-postgres` driver, which statically imports it) is\n * loaded via a lazy dynamic import so the laptop relay / CLI bundle — which only\n * ever uses {@link MemoryStore} — never pulls it in (mirrors how host-actions.ts\n * lazy-loads the cloud SDKs; `pg` is in the relay tsup `external` list).\n */\n\nconst DEFAULT_EVENT_CAP = RELAY_EVENT_RING_SIZE;\n\nexport interface PostgresStoreOptions {\n /** Postgres connection string (e.g. `process.env.POSTGRES_URL`). */\n connectionString?: string;\n /** Inject a pre-built pool (tests / a shared app pool). Takes precedence over connectionString. */\n pool?: Pool;\n /**\n * Global event-row cap, mirroring the in-memory ring. Newest N kept by id;\n * older rows trimmed on append. 0 disables trimming. Default 1000.\n */\n eventCap?: number;\n}\n\nexport class PostgresStore implements Store {\n private readonly eventCap: number;\n private readonly connectionString?: string;\n private readonly injectedPool?: Pool;\n private poolPromise: Promise<Pool> | null = null;\n private dbPromise: Promise<NodePgDatabase> | null = null;\n\n constructor(opts: PostgresStoreOptions = {}) {\n this.connectionString = opts.connectionString;\n this.injectedPool = opts.pool;\n this.eventCap = opts.eventCap ?? DEFAULT_EVENT_CAP;\n }\n\n /** Lazily build (or reuse) the pg Pool. `pg` is imported on first use only. */\n private pool(): Promise<Pool> {\n if (this.injectedPool) return Promise.resolve(this.injectedPool);\n this.poolPromise ??= import('pg').then(\n ({ default: pg }) => new pg.Pool({ connectionString: this.connectionString }),\n );\n return this.poolPromise;\n }\n\n private db(): Promise<NodePgDatabase> {\n this.dbPromise ??= (async () => {\n const pool = await this.pool();\n const { drizzle } = await import('drizzle-orm/node-postgres');\n return drizzle(pool);\n })();\n return this.dbPromise;\n }\n\n /** Create the tables if absent. Call once on boot (idempotent). */\n async migrate(): Promise<void> {\n const pool = await this.pool();\n await pool.query(PG_SCHEMA_SQL);\n }\n\n /** Release the pool (tests / graceful shutdown). No-op for an injected pool. */\n async close(): Promise<void> {\n if (this.injectedPool) return;\n if (this.poolPromise) {\n const pool = await this.poolPromise;\n await pool.end();\n this.poolPromise = null;\n this.dbPromise = null;\n }\n }\n\n // --- boxes ---\n\n async registerBox(reg: BoxRegistration): Promise<void> {\n const db = await this.db();\n await db\n .insert(pgBoxes)\n .values({\n boxId: reg.boxId,\n token: reg.token,\n originUrl: reg.originUrl ?? null,\n data: reg,\n registeredAt: new Date(reg.registeredAt),\n })\n .onConflictDoUpdate({\n target: pgBoxes.boxId,\n set: { token: reg.token, originUrl: reg.originUrl ?? null, data: reg },\n });\n }\n\n async getBox(boxId: string): Promise<BoxRegistration | undefined> {\n const db = await this.db();\n const rows = await db.select({ data: pgBoxes.data }).from(pgBoxes).where(eq(pgBoxes.boxId, boxId));\n return rows[0]?.data;\n }\n\n async authenticateBox(token: string): Promise<BoxRegistration | null> {\n if (token.length === 0) return null;\n const db = await this.db();\n const rows = await db\n .select({ data: pgBoxes.data })\n .from(pgBoxes)\n .where(eq(pgBoxes.token, token))\n .limit(1);\n return rows[0]?.data ?? null;\n }\n\n async listBoxes(): Promise<BoxRegistration[]> {\n const db = await this.db();\n const rows = await db.select({ data: pgBoxes.data }).from(pgBoxes).orderBy(asc(pgBoxes.registeredAt));\n return rows.map((r) => r.data);\n }\n\n async forgetBox(boxId: string): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .delete(pgBoxes)\n .where(eq(pgBoxes.boxId, boxId))\n .returning({ boxId: pgBoxes.boxId });\n return rows.length > 0;\n }\n\n async countBoxes(): Promise<number> {\n const db = await this.db();\n return db.$count(pgBoxes);\n }\n\n // --- events ---\n\n async appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n const db = await this.db();\n const rows = await db\n .insert(pgEvents)\n .values({\n boxId: input.boxId,\n type: input.type,\n ts: input.ts ?? null,\n payload: input.payload ?? null,\n receivedAt: new Date(),\n })\n .returning({ id: pgEvents.id, receivedAt: pgEvents.receivedAt });\n const row = rows[0]!;\n if (this.eventCap > 0) {\n // Keep only the newest `eventCap` rows by id, matching the in-memory ring.\n await db.delete(pgEvents).where(lte(pgEvents.id, row.id - this.eventCap));\n }\n return {\n id: row.id,\n boxId: input.boxId,\n type: input.type,\n ts: input.ts,\n payload: input.payload,\n receivedAt: row.receivedAt.toISOString(),\n };\n }\n\n async listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n const db = await this.db();\n const where =\n boxId === undefined\n ? gt(pgEvents.id, since)\n : and(gt(pgEvents.id, since), eq(pgEvents.boxId, boxId));\n const rows = await db.select().from(pgEvents).where(where).orderBy(asc(pgEvents.id));\n return rows.map(rowToEvent);\n }\n\n async countEvents(): Promise<number> {\n const db = await this.db();\n return db.$count(pgEvents);\n }\n\n // --- status ---\n\n async setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n const db = await this.db();\n const updatedAt = new Date();\n await db\n .insert(pgBoxStatus)\n .values({ boxId, name, projectIndex: projectIndex ?? null, status, updatedAt })\n .onConflictDoUpdate({\n target: pgBoxStatus.boxId,\n set: { name, projectIndex: projectIndex ?? null, status, updatedAt },\n });\n }\n\n async getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n const db = await this.db();\n const rows = await db\n .select({ status: pgBoxStatus.status })\n .from(pgBoxStatus)\n .where(eq(pgBoxStatus.boxId, boxId));\n return rows[0]?.status;\n }\n\n async deleteStatus(boxId: string): Promise<void> {\n const db = await this.db();\n await db.delete(pgBoxStatus).where(eq(pgBoxStatus.boxId, boxId));\n }\n\n /**\n * All box status snapshots in one query (avoids N+1 over listBoxes +\n * per-box getStatus). Used by the hosted hub UI to render every box's live\n * status. Not on the Store interface — only the hosted stores need it.\n */\n async listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n const db = await this.db();\n return db.select({ boxId: pgBoxStatus.boxId, status: pgBoxStatus.status }).from(pgBoxStatus);\n }\n\n // --- prompt mailbox ---\n\n async createPrompt(row: PromptRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(pgPrompts)\n .values({\n id: row.id,\n boxId: row.boxId,\n ev: row.ev,\n method: row.method,\n params: row.params ?? null,\n status: row.status,\n answer: row.answer ?? null,\n cancelled: row.cancelled ?? null,\n result: row.result ?? null,\n createdAt: new Date(row.createdAt),\n expiresAt: row.expiresAt ? new Date(row.expiresAt) : null,\n })\n .onConflictDoNothing({ target: pgPrompts.id });\n }\n\n async getPrompt(promptId: string): Promise<PromptRow | null> {\n const db = await this.db();\n const rows = await db.select().from(pgPrompts).where(eq(pgPrompts.id, promptId));\n return rows[0] ? rowToPrompt(rows[0]) : null;\n }\n\n async answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .update(pgPrompts)\n .set({ status: 'answered', answer, cancelled: cancelled ?? null })\n .where(and(eq(pgPrompts.id, promptId), eq(pgPrompts.status, 'pending')))\n .returning({ id: pgPrompts.id });\n return rows.length > 0;\n }\n\n async listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const db = await this.db();\n const rows = await db\n .select()\n .from(pgPrompts)\n .where(and(eq(pgPrompts.boxId, boxId), eq(pgPrompts.status, 'pending')))\n .orderBy(asc(pgPrompts.createdAt));\n return rows.map(rowToPrompt);\n }\n\n async setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n const db = await this.db();\n await db.update(pgPrompts).set({ result }).where(eq(pgPrompts.id, promptId));\n }\n\n // --- box-create job queue ---\n\n async enqueueCreateJob(job: CreateJobRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(pgCreateJobs)\n .values({\n id: job.id,\n status: job.status,\n request: job.request,\n result: job.result ?? null,\n claimedBy: job.claimedBy ?? null,\n createdAt: new Date(job.createdAt),\n startedAt: job.startedAt ? new Date(job.startedAt) : null,\n finishedAt: job.finishedAt ? new Date(job.finishedAt) : null,\n })\n .onConflictDoNothing({ target: pgCreateJobs.id });\n }\n\n async getCreateJob(id: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n const rows = await db.select().from(pgCreateJobs).where(eq(pgCreateJobs.id, id));\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n const db = await this.db();\n const base = db.select().from(pgCreateJobs);\n const filtered = opts?.status?.length\n ? base.where(inArray(pgCreateJobs.status, opts.status))\n : base;\n const rows = await filtered.orderBy(desc(pgCreateJobs.createdAt)).limit(opts?.limit ?? 100);\n return rows.map(rowToJob);\n }\n\n async claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n // Atomic claim: lock the oldest queued row, skip ones a sibling worker holds.\n const oldestQueued = db\n .select({ id: pgCreateJobs.id })\n .from(pgCreateJobs)\n .where(eq(pgCreateJobs.status, 'queued'))\n .orderBy(asc(pgCreateJobs.createdAt))\n .limit(1)\n .for('update', { skipLocked: true });\n const rows = await db\n .update(pgCreateJobs)\n .set({ status: 'running', claimedBy: workerId, startedAt: new Date() })\n .where(inArray(pgCreateJobs.id, oldestQueued))\n .returning();\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n const db = await this.db();\n await db\n .update(pgCreateJobs)\n .set({ status, result, finishedAt: new Date() })\n .where(eq(pgCreateJobs.id, id));\n }\n\n // --- retention (timestamptz columns compare against a Date) ---\n\n async prunePrompts(beforeIso: string): Promise<number> {\n const db = await this.db();\n const before = new Date(beforeIso);\n const rows = await db\n .delete(pgPrompts)\n .where(\n or(\n and(eq(pgPrompts.status, 'answered'), lt(pgPrompts.createdAt, before)),\n and(isNotNull(pgPrompts.expiresAt), lt(pgPrompts.expiresAt, before)),\n ),\n )\n .returning({ id: pgPrompts.id });\n return rows.length;\n }\n\n async pruneCreateJobs(beforeIso: string): Promise<number> {\n const db = await this.db();\n const before = new Date(beforeIso);\n const rows = await db\n .delete(pgCreateJobs)\n .where(\n and(\n inArray(pgCreateJobs.status, ['done', 'failed']),\n isNotNull(pgCreateJobs.finishedAt),\n lt(pgCreateJobs.finishedAt, before),\n ),\n )\n .returning({ id: pgCreateJobs.id });\n return rows.length;\n }\n}\n","import { mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { STATE_DIR } from '@agentbox/config';\nimport { and, asc, desc, eq, gt, inArray, isNotNull, lt, lte, or } from 'drizzle-orm';\nimport type { SqliteRemoteDatabase } from 'drizzle-orm/sqlite-proxy';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport { RELAY_EVENT_RING_SIZE } from '../types.js';\nimport {\n SQLITE_SCHEMA_SQL,\n rowToEvent,\n rowToJob,\n rowToPrompt,\n sqliteBoxStatus,\n sqliteBoxes,\n sqliteCreateJobs,\n sqliteEvents,\n sqlitePrompts,\n} from './schema.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\n/**\n * SQLite-backed {@link Store} — the control box's default (a single always-on\n * process on a small VPS has no reason to run a Postgres container).\n *\n * Driver: `node:sqlite`'s `DatabaseSync` behind drizzle's `sqlite-proxy`\n * (bring-your-own-executor) driver. drizzle ships no `node:sqlite` driver, and\n * its `better-sqlite3` one would add a native dependency; `sqlite-proxy` gets the\n * same typed query builder over the exact driver the hub's better-auth already\n * uses (`~/.agentbox/hub/auth.db`), with no native build step. The executor\n * callback below is the whole adapter.\n *\n * `node:sqlite` (and the drizzle driver) are lazy dynamic imports so the laptop\n * CLI bundle never touches them, and so a Node < 22.5 host only fails if it\n * actually asks for a SQLite store.\n *\n * Concurrency: SQLite is single-writer. WAL + a busy timeout make concurrent\n * readers fine, but the design consequence (recorded in the plan) is that the\n * create worker must run in the hub *process*, not as a second container on the\n * same file.\n */\n\nconst DEFAULT_EVENT_CAP = RELAY_EVENT_RING_SIZE;\n\n/** Default DB path — sibling of the hub's better-auth `auth.db`. */\nexport const DEFAULT_SQLITE_STORE_PATH = join(STATE_DIR, 'hub', 'store.db');\n\n/** `node:sqlite` landed in 22.5 (the repo's engines floor is 20.10). */\nconst MIN_NODE_SQLITE = [22, 5] as const;\n\nexport interface SqliteStoreOptions {\n /** DB file path, or ':memory:' (tests). Default `~/.agentbox/hub/store.db`. */\n path?: string;\n /** Global event-row cap, mirroring the in-memory ring. 0 disables trimming. Default 1000. */\n eventCap?: number;\n}\n\n/** The subset of `node:sqlite`'s DatabaseSync this store drives. */\ninterface SqliteDatabase {\n exec(sql: string): void;\n prepare(sql: string): SqliteStatement;\n close(): void;\n}\ninterface SqliteStatement {\n run(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n setReturnArrays?: (enabled: boolean) => void;\n}\n\n/**\n * Load `node:sqlite` without any bundler seeing the specifier.\n *\n * It is a *prefix-only* builtin, so it is absent from `module.builtinModules` —\n * and vite 5 / vite-node decide \"is this a builtin?\" from that list, strip the\n * `node:`, and then try to load a package called `sqlite` from disk. A plain\n * `await import('node:sqlite')` therefore breaks every vitest run that touches\n * this store. Going through `createRequire` keeps the load a runtime concern of\n * Node's own resolver, which is the only one that gets this right.\n */\nfunction loadNodeSqlite(): typeof import('node:sqlite') {\n const require = createRequire(import.meta.url);\n return require('node:sqlite') as typeof import('node:sqlite');\n}\n\nfunction assertNodeSupportsSqlite(): void {\n const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);\n const ok = major > MIN_NODE_SQLITE[0] || (major === MIN_NODE_SQLITE[0] && minor >= MIN_NODE_SQLITE[1]);\n if (!ok) {\n throw new Error(\n `the SQLite store needs Node >= ${MIN_NODE_SQLITE[0]}.${MIN_NODE_SQLITE[1]} for node:sqlite (running ${process.versions.node}). ` +\n 'Upgrade Node, or point the hub at a Postgres store (POSTGRES_URL).',\n );\n }\n}\n\nexport class SqliteStore implements Store {\n private readonly path: string;\n private readonly eventCap: number;\n private raw: SqliteDatabase | null = null;\n private dbPromise: Promise<SqliteRemoteDatabase> | null = null;\n\n constructor(opts: SqliteStoreOptions = {}) {\n this.path = opts.path ?? DEFAULT_SQLITE_STORE_PATH;\n this.eventCap = opts.eventCap ?? DEFAULT_EVENT_CAP;\n }\n\n /**\n * Open the DB (creating the file + tables if absent) and wrap it in drizzle.\n * Lazy + memoized: the schema is always applied before the first query, so\n * callers never have to sequence `migrate()` themselves.\n */\n private db(): Promise<SqliteRemoteDatabase> {\n this.dbPromise ??= (async () => {\n assertNodeSupportsSqlite();\n const { DatabaseSync } = loadNodeSqlite();\n const { drizzle } = await import('drizzle-orm/sqlite-proxy');\n if (this.path !== ':memory:') mkdirSync(dirname(this.path), { recursive: true });\n const raw = new DatabaseSync(this.path) as unknown as SqliteDatabase;\n // WAL keeps readers off the writer's back; busy_timeout turns a concurrent\n // write into a short wait instead of an immediate SQLITE_BUSY throw.\n raw.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');\n raw.exec(SQLITE_SCHEMA_SQL);\n this.raw = raw;\n return drizzle(async (sql, params, method) => {\n const stmt = raw.prepare(sql);\n if (method === 'run') {\n stmt.run(...params);\n return { rows: [] };\n }\n // drizzle maps result columns positionally, so rows must be arrays.\n // node:sqlite grew setReturnArrays after 22.5 — fall back to key order\n // (our queries are single-table, so no duplicate-column collapse).\n let rows: unknown[][];\n if (typeof stmt.setReturnArrays === 'function') {\n stmt.setReturnArrays(true);\n rows = stmt.all(...params) as unknown[][];\n } else {\n rows = (stmt.all(...params) as Record<string, unknown>[]).map((r) => Object.values(r));\n }\n return method === 'get' ? { rows: rows[0] ?? [] } : { rows };\n });\n })();\n return this.dbPromise;\n }\n\n /** Open + apply the schema. Idempotent; `db()` does it lazily anyway. */\n async migrate(): Promise<void> {\n await this.db();\n }\n\n /** Close the underlying handle (tests / graceful shutdown). */\n async close(): Promise<void> {\n if (this.dbPromise) await this.dbPromise.catch(() => undefined);\n this.raw?.close();\n this.raw = null;\n this.dbPromise = null;\n }\n\n // --- boxes ---\n\n async registerBox(reg: BoxRegistration): Promise<void> {\n const db = await this.db();\n await db\n .insert(sqliteBoxes)\n .values({\n boxId: reg.boxId,\n token: reg.token,\n originUrl: reg.originUrl ?? null,\n data: reg,\n registeredAt: reg.registeredAt,\n })\n .onConflictDoUpdate({\n target: sqliteBoxes.boxId,\n set: { token: reg.token, originUrl: reg.originUrl ?? null, data: reg },\n });\n }\n\n async getBox(boxId: string): Promise<BoxRegistration | undefined> {\n const db = await this.db();\n const rows = await db\n .select({ data: sqliteBoxes.data })\n .from(sqliteBoxes)\n .where(eq(sqliteBoxes.boxId, boxId));\n return rows[0]?.data;\n }\n\n async authenticateBox(token: string): Promise<BoxRegistration | null> {\n if (token.length === 0) return null;\n const db = await this.db();\n const rows = await db\n .select({ data: sqliteBoxes.data })\n .from(sqliteBoxes)\n .where(eq(sqliteBoxes.token, token))\n .limit(1);\n return rows[0]?.data ?? null;\n }\n\n async listBoxes(): Promise<BoxRegistration[]> {\n const db = await this.db();\n const rows = await db\n .select({ data: sqliteBoxes.data })\n .from(sqliteBoxes)\n .orderBy(asc(sqliteBoxes.registeredAt));\n return rows.map((r) => r.data);\n }\n\n async forgetBox(boxId: string): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .delete(sqliteBoxes)\n .where(eq(sqliteBoxes.boxId, boxId))\n .returning({ boxId: sqliteBoxes.boxId });\n return rows.length > 0;\n }\n\n async countBoxes(): Promise<number> {\n const db = await this.db();\n return db.$count(sqliteBoxes);\n }\n\n // --- events ---\n\n async appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n const db = await this.db();\n const receivedAt = new Date().toISOString();\n const rows = await db\n .insert(sqliteEvents)\n .values({\n boxId: input.boxId,\n type: input.type,\n ts: input.ts ?? null,\n payload: input.payload ?? null,\n receivedAt,\n })\n .returning({ id: sqliteEvents.id });\n const id = rows[0]!.id;\n if (this.eventCap > 0) {\n // Keep only the newest `eventCap` rows by id, matching the in-memory ring.\n await db.delete(sqliteEvents).where(lte(sqliteEvents.id, id - this.eventCap));\n }\n return {\n id,\n boxId: input.boxId,\n type: input.type,\n ts: input.ts,\n payload: input.payload,\n receivedAt,\n };\n }\n\n async listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n const db = await this.db();\n const where =\n boxId === undefined\n ? gt(sqliteEvents.id, since)\n : and(gt(sqliteEvents.id, since), eq(sqliteEvents.boxId, boxId));\n const rows = await db.select().from(sqliteEvents).where(where).orderBy(asc(sqliteEvents.id));\n return rows.map(rowToEvent);\n }\n\n async countEvents(): Promise<number> {\n const db = await this.db();\n return db.$count(sqliteEvents);\n }\n\n // --- status ---\n\n async setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n const db = await this.db();\n const updatedAt = new Date().toISOString();\n await db\n .insert(sqliteBoxStatus)\n .values({ boxId, name, projectIndex: projectIndex ?? null, status, updatedAt })\n .onConflictDoUpdate({\n target: sqliteBoxStatus.boxId,\n set: { name, projectIndex: projectIndex ?? null, status, updatedAt },\n });\n }\n\n async getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n const db = await this.db();\n const rows = await db\n .select({ status: sqliteBoxStatus.status })\n .from(sqliteBoxStatus)\n .where(eq(sqliteBoxStatus.boxId, boxId));\n return rows[0]?.status;\n }\n\n async deleteStatus(boxId: string): Promise<void> {\n const db = await this.db();\n await db.delete(sqliteBoxStatus).where(eq(sqliteBoxStatus.boxId, boxId));\n }\n\n /** All box status snapshots in one query (see PostgresStore.listStatuses). */\n async listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n const db = await this.db();\n return db\n .select({ boxId: sqliteBoxStatus.boxId, status: sqliteBoxStatus.status })\n .from(sqliteBoxStatus);\n }\n\n // --- prompt mailbox ---\n\n async createPrompt(row: PromptRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(sqlitePrompts)\n .values({\n id: row.id,\n boxId: row.boxId,\n ev: row.ev,\n method: row.method,\n params: row.params ?? null,\n status: row.status,\n answer: row.answer ?? null,\n cancelled: row.cancelled ?? null,\n result: row.result ?? null,\n createdAt: row.createdAt,\n expiresAt: row.expiresAt ?? null,\n })\n .onConflictDoNothing({ target: sqlitePrompts.id });\n }\n\n async getPrompt(promptId: string): Promise<PromptRow | null> {\n const db = await this.db();\n const rows = await db.select().from(sqlitePrompts).where(eq(sqlitePrompts.id, promptId));\n return rows[0] ? rowToPrompt(rows[0]) : null;\n }\n\n async answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .update(sqlitePrompts)\n .set({ status: 'answered', answer, cancelled: cancelled ?? null })\n .where(and(eq(sqlitePrompts.id, promptId), eq(sqlitePrompts.status, 'pending')))\n .returning({ id: sqlitePrompts.id });\n return rows.length > 0;\n }\n\n async listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const db = await this.db();\n const rows = await db\n .select()\n .from(sqlitePrompts)\n .where(and(eq(sqlitePrompts.boxId, boxId), eq(sqlitePrompts.status, 'pending')))\n .orderBy(asc(sqlitePrompts.createdAt));\n return rows.map(rowToPrompt);\n }\n\n async setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n const db = await this.db();\n await db.update(sqlitePrompts).set({ result }).where(eq(sqlitePrompts.id, promptId));\n }\n\n // --- box-create job queue ---\n\n async enqueueCreateJob(job: CreateJobRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(sqliteCreateJobs)\n .values({\n id: job.id,\n status: job.status,\n request: job.request,\n result: job.result ?? null,\n claimedBy: job.claimedBy ?? null,\n createdAt: job.createdAt,\n startedAt: job.startedAt ?? null,\n finishedAt: job.finishedAt ?? null,\n })\n .onConflictDoNothing({ target: sqliteCreateJobs.id });\n }\n\n async getCreateJob(id: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n const rows = await db.select().from(sqliteCreateJobs).where(eq(sqliteCreateJobs.id, id));\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n const db = await this.db();\n const base = db.select().from(sqliteCreateJobs);\n const filtered = opts?.status?.length\n ? base.where(inArray(sqliteCreateJobs.status, opts.status))\n : base;\n const rows = await filtered\n .orderBy(desc(sqliteCreateJobs.createdAt))\n .limit(opts?.limit ?? 100);\n return rows.map(rowToJob);\n }\n\n async claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n // No SKIP LOCKED in SQLite — but the claim is one statement, and node:sqlite\n // executes it synchronously, so no second claimer can interleave between the\n // subquery and the update. The `status = 'queued'` guard is belt-and-braces.\n const oldestQueued = db\n .select({ id: sqliteCreateJobs.id })\n .from(sqliteCreateJobs)\n .where(eq(sqliteCreateJobs.status, 'queued'))\n .orderBy(asc(sqliteCreateJobs.createdAt))\n .limit(1);\n const rows = await db\n .update(sqliteCreateJobs)\n .set({ status: 'running', claimedBy: workerId, startedAt: new Date().toISOString() })\n .where(\n and(inArray(sqliteCreateJobs.id, oldestQueued), eq(sqliteCreateJobs.status, 'queued')),\n )\n .returning();\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n const db = await this.db();\n await db\n .update(sqliteCreateJobs)\n .set({ status, result, finishedAt: new Date().toISOString() })\n .where(eq(sqliteCreateJobs.id, id));\n }\n\n // --- retention (ISO strings compare lexicographically, matching the columns) ---\n\n async prunePrompts(beforeIso: string): Promise<number> {\n const db = await this.db();\n const rows = await db\n .delete(sqlitePrompts)\n .where(\n or(\n and(eq(sqlitePrompts.status, 'answered'), lt(sqlitePrompts.createdAt, beforeIso)),\n and(isNotNull(sqlitePrompts.expiresAt), lt(sqlitePrompts.expiresAt, beforeIso)),\n ),\n )\n .returning({ id: sqlitePrompts.id });\n return rows.length;\n }\n\n async pruneCreateJobs(beforeIso: string): Promise<number> {\n const db = await this.db();\n const rows = await db\n .delete(sqliteCreateJobs)\n .where(\n and(\n inArray(sqliteCreateJobs.status, ['done', 'failed']),\n isNotNull(sqliteCreateJobs.finishedAt),\n lt(sqliteCreateJobs.finishedAt, beforeIso),\n ),\n )\n .returning({ id: sqliteCreateJobs.id });\n return rows.length;\n }\n}\n","import { MemoryStore } from './memory-store.js';\nimport { PostgresStore } from './postgres-store.js';\nimport { SqliteStore } from './sqlite-store.js';\nimport type { Store } from './store.js';\n\nexport type { Store } from './store.js';\nexport { MemoryStore, type MemoryStoreParts } from './memory-store.js';\nexport { PostgresStore, type PostgresStoreOptions } from './postgres-store.js';\nexport { SqliteStore, type SqliteStoreOptions, DEFAULT_SQLITE_STORE_PATH } from './sqlite-store.js';\nexport { WriteThroughStore, type WriteThroughParts } from './write-through-store.js';\nexport { PG_SCHEMA_SQL, SQLITE_SCHEMA_SQL } from './schema.js';\n\n/**\n * Resolve a {@link Store} from a spec string. Used by the deploy adapters:\n * - undefined / 'memory' → in-memory (laptop relay, tests).\n * - 'postgres://…' / 'postgresql://…' → Postgres (hosted control plane).\n * - 'sqlite:<path>' / a bare path → SQLite (the control box default).\n * A federated laptop relay builds its RemoteStore directly (Phase 4b), not here.\n */\nexport function makeStore(spec?: string): Store {\n if (!spec || spec === 'memory') return new MemoryStore();\n if (spec.startsWith('postgres://') || spec.startsWith('postgresql://')) {\n return new PostgresStore({ connectionString: spec });\n }\n if (spec.startsWith('sqlite:')) {\n // Accept sqlite:/abs/path, sqlite:relative.db and sqlite://./file.db alike.\n const path = spec.slice('sqlite:'.length).replace(/^\\/\\//, '');\n if (!path) throw new Error(`store spec has no path: ${spec}`);\n return new SqliteStore({ path });\n }\n // A bare path (absolute, relative, or ':memory:') is a SQLite file.\n if (spec === ':memory:' || spec.startsWith('/') || spec.startsWith('.') || spec.endsWith('.db')) {\n return new SqliteStore({ path: spec });\n }\n throw new Error(`unknown store spec: ${spec}`);\n}\n","/**\n * Filesystem-backed {@link CustodyStore} — phase 2's backend: plain files under\n * `~/.agentbox/hub/custody/`, `0700` dirs / `0600` files. No sidecar manifest:\n * digests are computed from the bytes on read, so the manifest can never drift\n * from what is actually stored.\n *\n * `put`/`get` read the whole value into memory, which is right for what custody\n * was built to hold (credentials / `.env` / SSH keys — kilobytes). A project's\n * `carry:` material is the exception, so `putStream`/`getStream` pipe instead;\n * see the seam docs on {@link CustodyStore.putStream}.\n */\n\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { pipeline } from 'node:stream/promises';\nimport { Transform, type Readable } from 'node:stream';\nimport { STATE_DIR } from '@agentbox/config';\nimport {\n custodyDigest,\n CustodyTooLargeError,\n normalizeCustodyPath,\n normalizeCustodyPrefix,\n type CustodyEntry,\n type CustodyPutResult,\n type CustodyStore,\n} from './store.js';\n\n/** Where the control box keeps custody — sibling of `store.db` / `auth.db`. */\nexport const DEFAULT_CUSTODY_DIR = join(STATE_DIR, 'hub', 'custody');\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\nexport interface FsCustodyStoreOptions {\n /** Custody root. Defaults to {@link DEFAULT_CUSTODY_DIR}. */\n root?: string;\n}\n\nexport class FsCustodyStore implements CustodyStore {\n readonly root: string;\n\n constructor(opts: FsCustodyStoreOptions = {}) {\n this.root = opts.root ?? DEFAULT_CUSTODY_DIR;\n }\n\n async put(path: string, data: Buffer): Promise<CustodyPutResult> {\n const rel = normalizeCustodyPath(path);\n const abs = join(this.root, rel);\n const sha256 = custodyDigest(data);\n\n const existing = await this.readEntry(rel);\n if (existing && existing.entry.sha256 === sha256) {\n // Content-addressed skip: identical bytes are already stored, so the file\n // (and its mtime) is left untouched — an unchanged re-push is a no-op.\n return { ...existing.entry, changed: false };\n }\n\n await mkdir(dirname(abs), { recursive: true, mode: DIR_MODE });\n // Atomic: a reader (or a crash) never observes a half-written credential.\n const tmp = `${abs}.${randomBytes(6).toString('hex')}.tmp`;\n try {\n await writeFile(tmp, data, { mode: FILE_MODE });\n await chmod(tmp, FILE_MODE);\n await rename(tmp, abs);\n } catch (err) {\n await rm(tmp, { force: true });\n throw err;\n }\n const st = await stat(abs);\n return {\n path: rel,\n size: data.length,\n sha256,\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n changed: true,\n };\n }\n\n async get(path: string): Promise<{ entry: CustodyEntry; data: Buffer } | null> {\n return this.readEntry(normalizeCustodyPath(path));\n }\n\n async stat(path: string): Promise<CustodyEntry | null> {\n const found = await this.readEntry(normalizeCustodyPath(path));\n return found ? found.entry : null;\n }\n\n async list(prefix?: string): Promise<CustodyEntry[]> {\n const rel = prefix === undefined ? '' : normalizeCustodyPrefix(prefix);\n const entries: CustodyEntry[] = [];\n for (const found of await this.walk(this.root)) {\n // Prefix match on path segments — `agents/cl` must not match `agents/claude`.\n if (rel.length > 0 && found !== rel && !found.startsWith(`${rel}/`)) continue;\n const e = await this.readEntry(found);\n if (e) entries.push(e.entry);\n }\n entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n return entries;\n }\n\n async delete(path: string): Promise<boolean> {\n const rel = normalizeCustodyPath(path);\n const abs = join(this.root, rel);\n try {\n await rm(abs);\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;\n throw err;\n }\n }\n\n async putStream(\n path: string,\n body: Readable,\n opts: { maxBytes?: number } = {},\n ): Promise<CustodyPutResult> {\n const rel = normalizeCustodyPath(path);\n const abs = join(this.root, rel);\n await mkdir(dirname(abs), { recursive: true, mode: DIR_MODE });\n const tmp = `${abs}.${randomBytes(6).toString('hex')}.tmp`;\n\n const hash = createHash('sha256');\n let size = 0;\n // Cap while streaming, not after: the point of this path is never to hold\n // the whole payload, so an over-cap body must be cut off mid-flight rather\n // than measured once it has already landed.\n const meter = new Transform({\n transform(chunk: Buffer, _enc, cb) {\n size += chunk.length;\n if (opts.maxBytes !== undefined && size > opts.maxBytes) {\n cb(new CustodyTooLargeError(opts.maxBytes));\n return;\n }\n hash.update(chunk);\n cb(null, chunk);\n },\n });\n\n try {\n await pipeline(body, meter, createWriteStream(tmp, { mode: FILE_MODE }));\n } catch (err) {\n await rm(tmp, { force: true });\n throw err;\n }\n\n const sha256 = hash.digest('hex');\n const existing = await this.readEntryMeta(rel);\n if (existing && existing.sha256 === sha256) {\n // Same content-addressed skip `put` makes. The bytes still crossed the\n // wire (a stream can't be hashed before it arrives), but the stored file\n // and its mtime are left alone — the client's manifest pre-check is what\n // avoids the transfer itself.\n await rm(tmp, { force: true });\n return { ...existing, changed: false };\n }\n\n try {\n await chmod(tmp, FILE_MODE);\n await rename(tmp, abs);\n } catch (err) {\n await rm(tmp, { force: true });\n throw err;\n }\n const st = await stat(abs);\n return {\n path: rel,\n size,\n sha256,\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n changed: true,\n };\n }\n\n async getStream(path: string): Promise<{ entry: CustodyEntry; data: Readable } | null> {\n const rel = normalizeCustodyPath(path);\n const entry = await this.readEntryMeta(rel);\n if (!entry) return null;\n return { entry, data: createReadStream(join(this.root, rel)) };\n }\n\n /**\n * Metadata without holding the value. Digest still comes from the bytes (no\n * sidecar to drift), but they are hashed in a streaming pass and discarded,\n * so a 100 MiB entry costs a buffer's worth of memory rather than 100 MiB.\n */\n private async readEntryMeta(rel: string): Promise<CustodyEntry | null> {\n const abs = join(this.root, rel);\n try {\n const st = await stat(abs);\n if (!st.isFile()) return null;\n const hash = createHash('sha256');\n await pipeline(\n createReadStream(abs),\n new Transform({\n transform(chunk: Buffer, _enc, cb) {\n hash.update(chunk);\n cb();\n },\n }),\n );\n return {\n path: rel,\n size: st.size,\n sha256: hash.digest('hex'),\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n }\n\n private async readEntry(rel: string): Promise<{ entry: CustodyEntry; data: Buffer } | null> {\n const abs = join(this.root, rel);\n try {\n const [data, st] = await Promise.all([readFile(abs), stat(abs)]);\n return {\n entry: {\n path: rel,\n size: data.length,\n sha256: custodyDigest(data),\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n },\n data,\n };\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'EISDIR') return null;\n throw err;\n }\n }\n\n /** Custody-relative paths of every regular file under `dir` (tmp files skipped). */\n private async walk(dir: string): Promise<string[]> {\n let dirents;\n try {\n dirents = await readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: string[] = [];\n for (const d of dirents) {\n const abs = join(dir, d.name);\n if (d.isDirectory()) {\n out.push(...(await this.walk(abs)));\n } else if (d.isFile() && !d.name.endsWith('.tmp')) {\n out.push(relative(this.root, abs).split(sep).join('/'));\n }\n }\n return out;\n }\n}\n","import { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport {\n boxCarriedHostPaths,\n boxWorkspacePath,\n executeCloudAction,\n refreshCloudPreviewUrl,\n resolveHostPath,\n} from './host-actions.js';\nimport { canAutoApproveTransfer } from './safe-transfer.js';\nimport { offerBrowserOpen } from './open-link.js';\nimport { HostActionQueue } from './host-action-queue.js';\nimport { HostReachQueue, type HostReachUnreachable } from './host-reach.js';\nimport { cpCachePrefix } from './cp-cache.js';\nimport { describeCpCacheEntries, lookupCpCache, serveCpFromCache } from './cp-cache-serve.js';\nimport { cpOutboxPrefix, listCpOutbox, parkCpOutbox, removeCpOutboxItem } from './cp-outbox.js';\nimport { HubNotifier } from './hub-notifier.js';\nimport { BoxNotices } from './notices.js';\nimport { buildAgentDescriptors, projectSlugFromOriginUrl } from '@agentbox/sandbox-core';\nimport { registrationAgents } from './registration-to-record.js';\nimport {\n isSanctionedPushBranch,\n isScratchBranch,\n landRefspec,\n parseDownloadKind,\n resolveLandDest,\n resolveRemote,\n sanitizeGitArgs,\n upstreamRef,\n} from '@agentbox/core';\nimport {\n checkoutGuards,\n ghDestructiveTarget,\n ghRunContext,\n ghVerbArgv,\n injectPrCreateHead,\n PR_CREATE_NO_HEAD_REFUSAL,\n prCreateNeedsHead,\n refuseBlockedGhCall,\n refuseCheckoutByDefault,\n refuseGhApiInput,\n resolveGhTarget,\n runHostGh,\n type GhExecRpcParams,\n} from './gh.js';\nimport { hashRpcParams, HostInitiatedTokens } from './host-initiated.js';\nimport { GitHubAppLeaser, loadGitHubAppConfig, type GitHubAppConfig } from './github-app.js';\nimport { leaseTokenResult } from './lease.js';\nimport { gateApproval, type GateDeps, type PromptMode } from './permission.js';\nimport { resolveWorktree, hostRepoUnavailableReason } from './worktree.js';\nimport { adminGateAllows, timingSafeEqualStr } from './admin-gate.js';\nimport {\n handleCustodyBlobRequest,\n handleCustodyRequest,\n isCustodyBlobPath,\n} from './custody/routes.js';\nimport { handleRemoteBoxesRequest, isRemoteBoxesPath } from './remote-boxes.js';\nimport { readCreateJobLog } from './job-log-tail.js';\nimport { handleStoreRpcRequest, isStoreRpcPath } from './store/store-rpc-routes.js';\nimport type { CustodyStore } from './custody/store.js';\nimport {\n isValidToolName,\n loadGrantedTools,\n resolveProjectToolsFile,\n writeToolGrant,\n} from '@agentbox/config';\nimport {\n argvIsExplicitlyAllowed,\n refuseCredentialArgv,\n refuseDeniedArgv,\n refuseIfGhDisabled,\n renderToolList,\n renderToolListJson,\n hostToolInstalled,\n resolveToolGrant,\n runGrantedTool,\n toolRequestsEnabled,\n type ToolRequestRpcParams,\n} from './host-tools.js';\nimport { askPrompt, isPromptAnswerBody, PendingPrompts, PromptSubscribers } from './prompts.js';\nimport { BoxRegistry, EventBuffer } from './registry.js';\nimport { CREDENTIALS_UPDATED_EVENT, CredentialsFanout } from './credentials-fanout.js';\nimport { BoxStatusStore, isValidBoxStatus, normalizeBoxStatus } from './status-store.js';\nimport { MemoryStore } from './store/memory-store.js';\nimport { WriteThroughStore } from './store/write-through-store.js';\nimport type { Store } from './store/store.js';\nimport { DEFAULT_BOX_RELAY_PORT } from './types.js';\nimport { buildCpArgv, cpFlags, normalizeCpParams, type CpMethod } from './cp-rpc.js';\nimport type {\n BoxRegistration,\n BoxWorktree,\n BridgeActionResultBody,\n BridgePollResponse,\n BrowserOpenRpcParams,\n CheckpointRpcParams,\n ClearNoticeBody,\n CpRpcParams,\n DownloadKind,\n DownloadRpcParams,\n GitRpcParams,\n GitRpcResult,\n HostAction,\n PostEventBody,\n PostRpcBody,\n PromptAnswerBody,\n RegisterBoxBody,\n RelayEvent,\n SetNoticeBody,\n} from './types.js';\n\nexport type RelayMode = 'host' | 'box';\n\nexport interface RelayServerOptions {\n port: number;\n /** Bind address; defaults to '0.0.0.0' so containers can reach the relay across the local docker network OR the Daytona preview proxy can hit the in-sandbox box-mode relay. */\n host?: string;\n logger?: (line: string) => void;\n /**\n * 'host' (default): host relay process; executes host-only RPCs locally\n * via `spawn` and serves `/admin/*` to the CLI / wrapper.\n * 'box': in-sandbox relay; host-only RPCs enqueue on a `HostActionQueue`\n * for the host poller to drain via `/bridge/*`.\n */\n mode?: RelayMode;\n /**\n * Required when `mode === 'box'`: bearer for the box-only `/bridge/*`\n * routes. Distinct from per-box `BoxRegistration.token` so a compromised\n * in-box agent cannot impersonate the host poller.\n */\n bridgeToken?: string;\n /**\n * Persisted-state backend. Defaults to an in-memory store wrapping the\n * relay's historical in-memory structures (the laptop relay + tests). A\n * hosted control plane injects a Postgres-backed store; a federated laptop\n * relay injects a RemoteStore. See `./store/store.ts`.\n */\n store?: Store;\n /**\n * How host-action approvals are obtained. Defaults to 'block' (the\n * long-lived laptop relay blocks on a human). The stateless hosted plane\n * uses 'poll' via its own handler, not this server. See `./permission.ts`.\n */\n promptMode?: PromptMode;\n /**\n * GitHub App config for `git.lease-token` (the hosted plane mints repo-scoped\n * installation tokens and leases them to boxes). Defaults to\n * {@link loadGitHubAppConfig} (`GITHUB_APP_ID` + `GITHUB_APP_PRIVATE_KEY`).\n * Null/absent → `git.lease-token` returns a clear \"not configured\" error.\n */\n githubApp?: GitHubAppConfig | null;\n /**\n * Custody store (agent creds / project secrets / box SSH keys). Absent → the\n * `/admin/custody/*` routes are not served here. The control box (hetzner\n * profile) wires an {@link FsCustodyStore}. See `./custody/routes.ts`.\n */\n custody?: CustodyStore | null;\n /**\n * Per-request body cap for custody PUTs (`relay.custodyMaxBodyBytes`).\n * Defaults to 32 MiB — big enough for a project's untracked-files seed tar,\n * and scoped to custody so the 1 MiB control-plane cap still governs every\n * other route.\n */\n custodyMaxBodyBytes?: number;\n /**\n * Cap for the streaming blob surface (`relay.custodyMaxBlobBytes`). Defaults\n * to 100 MiB to match `box.cpMaxBytes`, so a `carry:` entry the CLI accepted\n * at resolve time can actually be stored — the two caps disagreeing is what\n * let an approved 25.7 MiB file be promised to the user and then dropped.\n * Enforced mid-stream, so an over-cap body is cut off rather than landed.\n */\n custodyMaxBlobBytes?: number;\n /**\n * Admin bearer that gates `/admin/custody/*` (the ONLY proof accepted — the\n * loopback bypass that covers the other `/admin/*` routes does not apply to\n * custody, since a control box behind Caddy makes every request look\n * loopback). Required for custody to serve; other admin routes are unaffected.\n */\n adminToken?: string;\n /**\n * True on a control box (the hub's password profile). Turns on the\n * `/admin/hostreach/*` surface and makes host actions that need the user's\n * own filesystem — `cp.*` — park for that machine instead of running here.\n *\n * They cannot run here: a control box's record of a box it created points at\n * the create job's temp clone, which the worker deletes, so executing locally\n * spawns the CLI with a cwd that no longer exists. Even when it does exist,\n * it is the wrong machine's files. See `docs/plans/box-cp-host-reach-plan.md`.\n */\n controlPlane?: boolean;\n /**\n * How long a parked host action waits for the user's machine before the\n * control box gives up on it (`relay.hostReachTimeoutMs`). Only meaningful\n * with `controlPlane`.\n */\n hostReachTimeoutMs?: number;\n /**\n * Optional delegate for requests that matched no relay route (e.g. Next's\n * `getRequestHandler()`). Invoked at the top-level 404 fallthrough, so every\n * relay route still matches first and the UI can never shadow `/admin`,\n * `/rpc`, etc. Lets the hub serve Next on the relay's own port.\n */\n uiHandler?: (req: IncomingMessage, res: ServerResponse) => void;\n}\n\nexport interface RelayServerHandle {\n server: Server;\n /** The persisted-state backend the handlers use (memory by default). */\n store: Store;\n registry: BoxRegistry;\n events: EventBuffer;\n statusStore: BoxStatusStore;\n prompts: PendingPrompts;\n subscribers: PromptSubscribers;\n notices: BoxNotices;\n /** Fan-out for the embedded hub UI's SSE route (pending-approval changes). */\n hubNotifier: HubNotifier;\n /** The custody store, when wired (control box). Used by the hub backend's reap. */\n custody?: CustodyStore | null;\n /** Present only in `mode === 'box'`: the parking lot for host-only RPCs. */\n hostActions?: HostActionQueue;\n /**\n * Present only on a control box (`controlPlane`): the parking lot for actions\n * that need the user's own machine, drained by that machine's relay over\n * `/admin/hostreach/*`.\n */\n hostReach?: HostReachQueue;\n url: string;\n /**\n * Wire a \"kick the queue scheduler now\" callback. Called by\n * `POST /admin/queue/enqueue` so a freshly-submitted background job doesn't\n * wait up to one tick for the relay to notice the new manifest.\n * No-op until set; the queue still picks the job up via the periodic tick.\n */\n setQueuePoke: (fn: () => void) => void;\n /**\n * Kick the queue scheduler in-process (same effect as `POST\n * /admin/queue/enqueue`, without a loopback round-trip). Used by the embedded\n * hub after it enqueues a create job via `enqueueQueueJob`. No-op until\n * `setQueuePoke` has wired the scheduler.\n */\n pokeQueue: () => void;\n /**\n * Stop the host-mode `CloudBoxPoller` for one box. The keepalive loop calls\n * this after it idle-pauses a box, because on a backend whose paused\n * sandboxes auto-resume on inbound traffic (e2b) the poller would otherwise\n * wake the box on its next long-poll. A no-op when no poller is running for\n * that box; a later `/admin/register-box` starts a fresh one.\n */\n stopCloudPoller: (boxId: string) => Promise<void>;\n close: () => Promise<void>;\n}\n\n/** Event type whose payload is a durable BoxStatus snapshot (persisted, not ringed). */\nconst BOX_STATUS_EVENT = 'box-status';\n\nconst MAX_BODY_BYTES = 1024 * 1024; // 1 MiB hard cap; relay is for control-plane traffic, not payloads.\n/**\n * Per-request cap for custody PUTs only. Custody carries project seed material\n * (an untracked-files tarball) as base64 JSON, which the 1 MiB control-plane cap\n * is far too small for — but raising {@link MAX_BODY_BYTES} would hand the same\n * budget to `/rpc` and `/events`, which have no business with payloads. Override\n * with `relay.custodyMaxBodyBytes`.\n */\nconst DEFAULT_CUSTODY_MAX_BODY_BYTES = 32 * 1024 * 1024; // 32 MiB\n/** Matches `box.cpMaxBytes` — see the `custodyMaxBlobBytes` option doc. */\nconst DEFAULT_CUSTODY_MAX_BLOB_BYTES = 100 * 1024 * 1024; // 100 MiB\nconst GIT_RPC_TIMEOUT_MS = 120_000; // git push/pull can be slow on big repos.\nconst CHECKPOINT_RPC_TIMEOUT_MS = 600_000; // capturing node_modules/build trees can be slow.\nconst DOWNLOAD_RPC_TIMEOUT_MS = 600_000; // claude/workspace pulls over rsync can take minutes.\nconst CP_RPC_TIMEOUT_MS = 300_000; // single-file/dir cp; tar pipe through docker exec.\nconst SSE_HEARTBEAT_MS = 15_000; // every 15s; wrapper reconnects if it sees no traffic for ~30s.\n/** Default hold for an idle `/admin/hostreach/poll` — under Caddy's 30s idle default. */\nconst DEFAULT_HOSTREACH_WAIT_MS = 25_000;\n/** Ceiling for a client-requested hold, for the same proxy reason. */\nconst MAX_HOSTREACH_WAIT_MS = 60_000;\n\nfunction send(\n res: ServerResponse,\n status: number,\n body: unknown,\n contentType: string = 'application/json',\n): void {\n const text = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);\n res.statusCode = status;\n if (text.length > 0) {\n res.setHeader('Content-Type', contentType);\n res.setHeader('Content-Length', Buffer.byteLength(text).toString());\n res.end(text);\n } else {\n res.end();\n }\n}\n\nasync function readJsonBody<T>(req: IncomingMessage): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let total = 0;\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > MAX_BODY_BYTES) {\n reject(new Error('request body too large'));\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf8');\n if (text.length === 0) {\n resolve({} as T);\n return;\n }\n try {\n resolve(JSON.parse(text) as T);\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n });\n req.on('error', reject);\n });\n}\n\nasync function readRawBody(\n req: IncomingMessage,\n maxBytes: number = MAX_BODY_BYTES,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let total = 0;\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > maxBytes) {\n reject(new Error('request body too large'));\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n req.on('error', reject);\n });\n}\n\nfunction bearerToken(req: IncomingMessage): string {\n const raw = req.headers.authorization;\n if (typeof raw !== 'string') return '';\n const m = /^Bearer\\s+(.+)$/i.exec(raw.trim());\n return m ? m[1]!.trim() : '';\n}\n\nfunction isLoopbackAddress(addr: string | undefined): boolean {\n if (!addr) return false;\n return (\n addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1' || addr.startsWith('127.')\n );\n}\n\n/**\n * Build the relay HTTP server. Routes:\n * POST /events — bearer auth (box token), appends to ring buffer.\n * POST /rpc — bearer auth; dispatches git.push/fetch, cp.*, download.*, checkpoint.create on the host.\n * POST /admin/register-box — loopback only.\n * POST /admin/forget-box — loopback only.\n * POST /admin/stop-poller — loopback only; stops one box's CloudBoxPoller, keeps the registration.\n * GET /admin/box-status — loopback only; query `box`; latest snapshot.\n * GET /admin/events — loopback only; query `box`, `since`.\n * GET /admin/registry — loopback only; list registered boxes (token redacted).\n * GET /admin/prompts — loopback only; query `boxId`; one-shot list of pending host-action approvals.\n * GET /admin/prompts/stream — loopback only; SSE; pushes prompt-ask/prompt-resolved/notice-set/notice-clear/ping events.\n * POST /admin/prompts/answer — loopback only; resolves a pending prompt by id.\n * POST /admin/host-initiated/mint — loopback only; mints a one-time token scoped to (boxId, method).\n * POST /admin/notices/set — loopback only; sets an informational box notice (returns {id}).\n * POST /admin/notices/clear — loopback only; clears a box notice by id.\n * GET /healthz — liveness + capability probe (no auth); reports {pid, cliEntry}.\n */\nexport function createRelayServer(opts: RelayServerOptions): RelayServerHandle {\n const log = opts.logger ?? (() => {});\n const registry = new BoxRegistry();\n const events = new EventBuffer();\n const statusStore = new BoxStatusStore();\n const prompts = new PendingPrompts();\n const subscribers = new PromptSubscribers();\n const notices = new BoxNotices(subscribers);\n // Fan-out for the embedded hub UI: every change to the pending-approval set\n // pushes a refresh to browsers subscribed on the hub's SSE route. No-op when\n // no hub is attached (the CLI relay bin never subscribes).\n const hubNotifier = new HubNotifier();\n prompts.setOnChange(() => hubNotifier.notify());\n // The persisted-state seam. Defaults to a MemoryStore wrapping the concrete\n // instances above, so the laptop relay + tests behave exactly as before; a\n // hosted control plane injects a Postgres-backed store instead. Handlers go\n // through `store.*`; the concrete instances stay exposed on the handle for\n // the autopause / queue loops (bin.ts) and the unit tests that read them.\n // Persisted-state seam. localhost/tests get a MemoryStore wrapping the concrete\n // instances above (byte-identical to the pre-seam relay). A control box injects\n // a durable store (SQLite/Postgres); wrap it so every write also mirrors into\n // those instances — the daemon's loops + the hub backend read them synchronously\n // and would otherwise see an empty registry/statusStore (Backlog: phase-3\n // blocker A). `startRelayServer` hydrates the mirror from the store on boot.\n const store: Store = opts.store\n ? new WriteThroughStore(opts.store, { registry, events, statusStore })\n : new MemoryStore({ registry, events, statusStore });\n // Per-box `box.autoApproveHostActions`: when a box registered with the flag,\n // host-action confirms resolve to 'y' without a prompt, but every bypass\n // lands in the event ring buffer (visible via `/admin/events`) so it's\n // auditable. Reads the concrete registry/events synchronously (not the async\n // store): `askPrompt` broadcasts to SSE subscribers synchronously, so this\n // gate must stay sync. The MemoryStore wraps these same instances, so the\n // sync policy view and the async store view never diverge on the laptop relay.\n prompts.setAutoApprovePolicy({\n shouldAutoApprove: (boxId) => registry.get(boxId)?.autoApproveHostActions === true,\n audit: (boxId, params, reason) => {\n events.append({\n boxId,\n type: 'host-action-auto-approved',\n payload: {\n command: params.context?.command,\n argv: params.context?.argv,\n message: params.message,\n ...(reason ? { reason } : {}),\n },\n });\n log(\n `auto-approved host action for ${boxId}: ${params.context?.command ?? params.message}` +\n (reason ? ` (${reason})` : ''),\n );\n },\n });\n const hostInitiatedTokens = new HostInitiatedTokens();\n let queuePoke: (() => void) | null = null;\n const host = opts.host ?? '0.0.0.0';\n const mode: RelayMode = opts.mode ?? 'host';\n // Box mode parks host-only RPCs until the host poller answers; host mode\n // executes them inline (the historical behavior).\n const hostActions = mode === 'box' ? new HostActionQueue() : null;\n // A control box brokers rather than executes: actions that need the user's own\n // files park here for that machine's relay to drain.\n const hostReach =\n opts.controlPlane === true\n ? new HostReachQueue(\n typeof opts.hostReachTimeoutMs === 'number' && opts.hostReachTimeoutMs > 0\n ? { reachTimeoutMs: opts.hostReachTimeoutMs }\n : {},\n )\n : null;\n // Host-mode handler for refreshed agent credentials (newest-wins backup\n // write + debounced `agentbox credentials propagate` spawn). In box mode the\n // event rides the local ring buffer to the bridge instead — the host's\n // poller hands it to this handler on the other side.\n // `custody` is the control box's store — passing it is what lets an accepted\n // token reach custody, so the next hub create seeds a current credential\n // instead of the last one a PC pushed. Absent on a localhost relay (no store).\n const credentialsFanout =\n mode === 'box' ? null : new CredentialsFanout({ log, custody: opts.custody ?? null });\n if (mode === 'box' && (!opts.bridgeToken || opts.bridgeToken.length === 0)) {\n throw new Error(\"relay mode='box' requires a non-empty bridgeToken\");\n }\n const bridgeToken = opts.bridgeToken ?? '';\n // The laptop relay blocks on a human for approvals (today's behavior). The\n // stateless hosted plane uses 'poll' via its own handler, not this server.\n const promptMode: PromptMode = opts.promptMode ?? 'block';\n const gateDeps: GateDeps = { mode: promptMode, store, prompts, subscribers };\n // GitHub App leaser for `git.lease-token` (hosted plane). Off when no App is\n // configured — the laptop relay never needs it (it pushes host-side / cloud\n // boxes reach it via the poller).\n const githubAppConfig = opts.githubApp === undefined ? loadGitHubAppConfig() : opts.githubApp;\n const leaser = githubAppConfig ? new GitHubAppLeaser(githubAppConfig) : null;\n const custody = opts.custody ?? null;\n const custodyAdminToken = opts.adminToken ?? '';\n const custodyMaxBodyBytes =\n typeof opts.custodyMaxBodyBytes === 'number' && opts.custodyMaxBodyBytes > 0\n ? opts.custodyMaxBodyBytes\n : DEFAULT_CUSTODY_MAX_BODY_BYTES;\n const custodyMaxBlobBytes =\n typeof opts.custodyMaxBlobBytes === 'number' && opts.custodyMaxBlobBytes > 0\n ? opts.custodyMaxBlobBytes\n : DEFAULT_CUSTODY_MAX_BLOB_BYTES;\n const uiHandler = opts.uiHandler;\n\n // Host-mode pollers for cloud-tagged boxes; started on /admin/register-box,\n // stopped on /admin/forget-box. Lazy import to keep host-mode startup free\n // of cloud-poller deps until actually needed.\n type CloudPollersModule = typeof import('./cloud-poller.js');\n let pollers: InstanceType<CloudPollersModule['CloudBoxPollers']> | null = null;\n async function getPollers(): Promise<InstanceType<CloudPollersModule['CloudBoxPollers']>> {\n if (!pollers) {\n const mod: CloudPollersModule = await import('./cloud-poller.js');\n pollers = new mod.CloudBoxPollers();\n }\n return pollers;\n }\n\n const server = createServer((req, res) => {\n handle(req, res).catch((err: unknown) => {\n const msg = err instanceof Error ? err.message : String(err);\n log(`relay: handler error: ${msg}`);\n if (!res.headersSent) send(res, 500, { error: 'internal error' });\n else res.end();\n });\n });\n\n async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'relay'}`);\n const route = `${req.method ?? 'GET'} ${url.pathname}`;\n\n if (route === 'GET /healthz') {\n // `cliEntry` and `pid` let the host-side `ensureRelay` distinguish a\n // *capable* relay from one that's merely alive: a relay spawned without\n // AGENTBOX_CLI_ENTRY silently fails every cp/download/checkpoint host\n // action (exit 64) for its whole lifetime. Reporting it here lets the\n // caller reclaim (kill by `pid`) and respawn instead of reusing it.\n send(res, 200, {\n ok: true,\n boxes: await store.countBoxes(),\n events: await store.countEvents(),\n pid: process.pid,\n // True when a Next UI is delegated here (the embedded hub) vs a bare relay.\n // Lets `agentbox hub` distinguish \"a hub already runs\" from \"a lean relay\n // holds the port\" (reclaim + respawn as the hub).\n ui: Boolean(uiHandler),\n cliEntry: Boolean(process.env.AGENTBOX_CLI_ENTRY),\n // The spawning CLI's version/commit (inherited via env at spawn time).\n // `version` lets host-side ensureRelay reclaim a relay left over from a\n // different agentbox version; `commit` is observability-only.\n version: process.env.AGENTBOX_CLI_VERSION || undefined,\n commit: process.env.AGENTBOX_CLI_COMMIT || undefined,\n // The running hub's profile + whether the resident create worker is on.\n // `agentbox hub expose` flips a localhost hub to the `hetzner` profile;\n // reporting it here lets host-side `ensureHub` reclaim a hub running in\n // the wrong mode (a plain localhost hub while deploy.json says exposed),\n // and `hub status` show what is actually running.\n profile: process.env.AGENTBOX_HUB_PROFILE || undefined,\n worker: process.env.AGENTBOX_HUB_WORKER === 'on' ? true : undefined,\n });\n return;\n }\n\n // Bridge routes are the host poller's view into an in-sandbox box-mode\n // relay. They are bearer-authed with the per-relay bridgeToken and\n // exist only when mode === 'box'. No loopback check: the Daytona\n // preview proxy reaches them from non-loopback IPs.\n if (url.pathname.startsWith('/bridge/')) {\n if (mode !== 'box' || !hostActions) {\n send(res, 404, { error: 'bridge routes available only in mode=box' });\n return;\n }\n if (bearerToken(req) !== bridgeToken) {\n send(res, 401, { error: 'invalid bridge token' });\n return;\n }\n if (route === 'GET /bridge/healthz') {\n send(res, 200, { ok: true, queued: hostActions.size(), events: events.size() });\n return;\n }\n if (route === 'GET /bridge/poll') {\n const since = Number.parseInt(url.searchParams.get('since') ?? '0', 10) || 0;\n const newEvents = await store.listEvents(since);\n const lastId = newEvents.length > 0 ? newEvents[newEvents.length - 1]!.id : since;\n const actions = hostActions.drain();\n // A box-mode relay only ever has one registered box (itself). The\n // status snapshot — if any has been pushed — belongs to that box.\n const only = (await store.listBoxes())[0];\n const status = only ? ((await store.getStatus(only.boxId)) ?? null) : null;\n const reply: BridgePollResponse = {\n actions,\n events: newEvents,\n status,\n cursor: lastId,\n };\n send(res, 200, reply);\n return;\n }\n if (route === 'POST /bridge/action-result') {\n const body = await readJsonBody<BridgeActionResultBody>(req);\n if (\n !body ||\n typeof body.id !== 'string' ||\n body.id.length === 0 ||\n typeof body.exitCode !== 'number'\n ) {\n send(res, 400, { error: 'expected {id, exitCode, stdout, stderr}' });\n return;\n }\n const ok = hostActions.resolve(body.id, {\n exitCode: body.exitCode,\n stdout: typeof body.stdout === 'string' ? body.stdout : '',\n stderr: typeof body.stderr === 'string' ? body.stderr : '',\n });\n if (!ok) {\n send(res, 404, { error: 'no parked action with that id' });\n return;\n }\n send(res, 204, null);\n return;\n }\n send(res, 404, { error: 'not found', route });\n return;\n }\n\n // The blob surface must be dispatched BEFORE the JSON one, because it is the\n // only path that does not buffer the body — handing a 100 MiB carry payload\n // to `readRawBody` below is exactly what this route exists to avoid. The\n // request object IS the stream; nothing has consumed it yet.\n if (isCustodyBlobPath(url.pathname)) {\n const blobRes = await handleCustodyBlobRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n bearer: bearerToken(req),\n body: req.method === 'PUT' ? req : undefined,\n maxBytes: custodyMaxBlobBytes,\n },\n { custody, adminToken: custodyAdminToken, log },\n );\n if (blobRes) {\n if (blobRes.stream) {\n res.writeHead(blobRes.status, {\n 'content-type': 'application/octet-stream',\n ...(blobRes.entry ? { 'content-length': String(blobRes.entry.size) } : {}),\n ...(blobRes.entry ? { 'x-agentbox-sha256': blobRes.entry.sha256 } : {}),\n });\n blobRes.stream.pipe(res);\n blobRes.stream.on('error', () => res.destroy());\n } else {\n send(res, blobRes.status, blobRes.body ?? null);\n }\n return;\n }\n }\n\n // The user's machine draining actions this control box parked for it.\n //\n // Admin-bearer-gated, NOT loopback-gated — the same rule, and the same\n // reason, as custody: on a control box every request arrives through Caddy\n // on the same host, so \"looks loopback\" proves nothing, and a box could\n // otherwise poll this surface to read other boxes' actions or forge their\n // results. Dispatched before the loopback gate below for that reason.\n if (url.pathname.startsWith('/admin/hostreach')) {\n if (!hostReach) {\n send(res, 404, { error: 'host-reach is served only by a control box' });\n return;\n }\n if (custodyAdminToken.length === 0) {\n send(res, 503, { error: 'host-reach not configured: admin token unset' });\n return;\n }\n if (!timingSafeEqualStr(bearerToken(req) ?? '', custodyAdminToken)) {\n send(res, 401, { error: 'invalid admin token' });\n return;\n }\n if (route === 'GET /admin/hostreach/events') {\n // The preferred shape: the machine holds one connection instead of\n // re-asking every 25s, and its presence becomes the connection itself.\n // The poll route below stays as the fallback — a proxy that buffers\n // event streams, or an older control box, must degrade rather than\n // break, so neither side may assume this route exists.\n const pollerId = url.searchParams.get('poller') ?? '';\n if (pollerId.length === 0) {\n send(res, 400, { error: 'missing poller query param' });\n return;\n }\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n // Same reason as the prompt stream: stop a proxy buffering the chunked\n // response into uselessness.\n res.setHeader('X-Accel-Buffering', 'no');\n if (typeof res.flushHeaders === 'function') res.flushHeaders();\n res.write(': connected\\n\\n');\n const unsubscribe = hostReach.subscribe(pollerId, (actions) => {\n try {\n for (const action of actions) {\n res.write(`event: action\\ndata: ${JSON.stringify(action)}\\n\\n`);\n }\n } catch {\n /* dead socket; the close handler unsubscribes */\n }\n });\n const heartbeat = setInterval(() => {\n try {\n res.write(`event: ping\\ndata: {\"ts\":\"${new Date().toISOString()}\"}\\n\\n`);\n // A quiet stream is still a present machine — without this the\n // sweep would decide the owner of an in-flight copy had vanished.\n hostReach.touch(pollerId);\n } catch {\n /* dead socket; the close handler unsubscribes */\n }\n }, SSE_HEARTBEAT_MS);\n if (typeof heartbeat.unref === 'function') heartbeat.unref();\n res.on('close', () => {\n clearInterval(heartbeat);\n unsubscribe();\n log(`host-reach: machine ${pollerId.slice(0, 8)} disconnected`);\n });\n log(`host-reach: machine ${pollerId.slice(0, 8)} streaming`);\n return;\n }\n if (route === 'GET /admin/hostreach/poll') {\n const requested = Number.parseInt(url.searchParams.get('wait') ?? '', 10);\n // Bounded server-side: a client asking to be held for an hour would tie\n // up a connection past every proxy's idle timeout.\n const waitMs = Number.isFinite(requested)\n ? Math.min(Math.max(requested, 0), MAX_HOSTREACH_WAIT_MS)\n : DEFAULT_HOSTREACH_WAIT_MS;\n // The polling process's identity, so a restarted relay is offered the\n // work its predecessor accepted but never finished.\n const pollerId = url.searchParams.get('poller') ?? undefined;\n const actions = await hostReach.poll(waitMs, pollerId);\n send(res, 200, { actions });\n return;\n }\n // The outbox: copies out of a box that were waiting for this machine.\n if (route === 'GET /admin/hostreach/outbox') {\n const items = custody ? await listCpOutbox(custody) : [];\n send(res, 200, { items });\n return;\n }\n if (req.method === 'DELETE' && url.pathname.startsWith('/admin/hostreach/outbox/')) {\n const id = decodeURIComponent(url.pathname.slice('/admin/hostreach/outbox/'.length));\n const items = custody ? await listCpOutbox(custody) : [];\n const hit = items.find((i) => i.meta.id === id);\n if (!hit || !custody) {\n send(res, 404, { error: 'no such parked copy' });\n return;\n }\n await removeCpOutboxItem(custody, hit);\n log(`cp outbox: ${id} landed and cleared`);\n send(res, 204, null);\n return;\n }\n if (route === 'POST /admin/hostreach/decline') {\n const body = await readJsonBody<{ id?: string; poller?: string }>(req);\n if (!body || typeof body.id !== 'string' || body.id.length === 0) {\n send(res, 400, { error: 'expected {id}' });\n return;\n }\n const ok = hostReach.decline(\n body.id,\n typeof body.poller === 'string' ? body.poller : undefined,\n );\n send(\n res,\n ok ? 204 : 404,\n ok ? null : { error: 'no parked action with that id for this machine' },\n );\n return;\n }\n if (route === 'POST /admin/hostreach/result') {\n const body = await readJsonBody<BridgeActionResultBody>(req);\n if (\n !body ||\n typeof body.id !== 'string' ||\n body.id.length === 0 ||\n typeof body.exitCode !== 'number'\n ) {\n send(res, 400, { error: 'expected {id, exitCode, stdout, stderr}' });\n return;\n }\n const ok = hostReach.resolve(\n body.id,\n {\n exitCode: body.exitCode,\n stdout: typeof body.stdout === 'string' ? body.stdout : '',\n stderr: typeof body.stderr === 'string' ? body.stderr : '',\n },\n typeof body.poller === 'string' ? body.poller : undefined,\n );\n if (!ok) {\n // Also the answer for a poller whose copy was re-offered while it was\n // still working: its result is stale, and the current owner's counts.\n send(res, 404, { error: 'no parked action with that id for this machine' });\n return;\n }\n send(res, 204, null);\n return;\n }\n send(res, 404, { error: 'not found', route });\n return;\n }\n\n // Custody (`/admin/custody/*`) is admin-bearer-gated, NOT loopback-gated:\n // on the control box the hub sits behind Caddy on the same host, so every\n // proxied request looks loopback. The shared dispatcher enforces the bearer\n // (and fail-closes with 503 when custody or the admin token is unset), so\n // this must run BEFORE the loopback rejection below.\n if (url.pathname === '/admin/custody' || url.pathname.startsWith('/admin/custody/')) {\n const bodyText =\n req.method === 'PUT' || req.method === 'POST'\n ? await readRawBody(req, custodyMaxBodyBytes)\n : '';\n const custodyRes = await handleCustodyRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n query: url.searchParams,\n bearer: bearerToken(req),\n bodyText,\n },\n { custody, adminToken: custodyAdminToken, log },\n );\n if (custodyRes) {\n send(res, custodyRes.status, custodyRes.body ?? null);\n return;\n }\n }\n\n // Create-queue surface (`/remote/boxes`) — admin-bearer-gated like custody\n // (not loopback: the control box is behind Caddy). The shared dispatcher is\n // the SAME one the Vercel plane's `core/handler.ts` mounts, so the PC can\n // `agentbox create --via-hub` against the control box exactly as against the\n // hosted plane. Runs before the loopback rejection below.\n if (isRemoteBoxesPath(url.pathname)) {\n const bodyText = req.method === 'POST' ? await readRawBody(req) : '';\n const remoteRes = await handleRemoteBoxesRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n bearer: bearerToken(req),\n bodyText,\n query: url.searchParams,\n },\n { store, adminToken: custodyAdminToken, custody, readJobLog: readCreateJobLog, log },\n );\n if (remoteRes) {\n send(res, remoteRes.status, remoteRes.body ?? null);\n return;\n }\n }\n\n // Generic Store RPC (`/admin/store`) — admin-bearer-gated shared dispatcher,\n // the same one `core/handler.ts` mounts, so a PC's RemoteStore reads the\n // control box's registry/status/events over HTTP. Carries its own bearer\n // gate (not loopback: the control box is behind Caddy), so it runs before the\n // loopback rejection below. A laptop relay has no admin token → 503.\n if (isStoreRpcPath(url.pathname)) {\n const bodyText = req.method === 'POST' ? await readRawBody(req) : '';\n const storeRpcRes = await handleStoreRpcRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n bearer: bearerToken(req),\n bodyText,\n },\n { store, adminToken: custodyAdminToken, log },\n );\n if (storeRpcRes) {\n send(res, storeRpcRes.status, storeRpcRes.body ?? null);\n return;\n }\n }\n\n // Admin endpoints are reachable from loopback, or — on a relay with an\n // admin token configured (the control box) — with that bearer. The relay\n // binds to 0.0.0.0 so containers can reach /events and /rpc via\n // host.docker.internal, but admin operations (register-box, forget-box,\n // list events, etc.) are for the host CLI / an authenticated admin and must\n // not be exposed to boxes. A laptop relay sets no admin token, so its gate\n // stays loopback-only. Any other `/remote/*` is a hosted-plane surface not\n // served by this relay.\n if (url.pathname.startsWith('/admin/') || url.pathname.startsWith('/remote/')) {\n if (url.pathname.startsWith('/remote/')) {\n send(res, 404, { error: 'not found', route });\n return;\n }\n const loopback = isLoopbackAddress(req.socket.remoteAddress);\n if (!adminGateAllows(loopback, bearerToken(req), custodyAdminToken)) {\n send(res, 403, { error: 'admin endpoints are loopback-only' });\n return;\n }\n }\n\n if (route === 'POST /events') {\n const reg = await authBox(req, res);\n if (!reg) return;\n const body = await readJsonBody<PostEventBody>(req);\n if (!body || typeof body.type !== 'string' || body.type.length === 0) {\n send(res, 400, { error: 'missing \"type\" string' });\n return;\n }\n // box-status is durable state, not an event: persist the latest snapshot\n // per box and skip the ring buffer (a 15s heartbeat per box would\n // otherwise evict the useful git/service events from the 1000-cap ring).\n if (body.type === BOX_STATUS_EVENT) {\n if (!isValidBoxStatus(body.payload)) {\n send(res, 400, { error: 'invalid box-status payload' });\n return;\n }\n // Normalize at the door, so the stored file, the memory store and the\n // broadcast below all carry the keyed agent map even when the box's\n // baked ctl still posts the old named blocks.\n const snapshot = normalizeBoxStatus(body.payload);\n await store.setStatus(reg.boxId, reg.name, reg.projectIndex, snapshot);\n // Push it to attached wrappers. The durable file only serves a footer on\n // THIS machine; a box owned by a remote hub has no such file on the\n // user's laptop, so the stream is the only way its footer learns the\n // agent activity and the `starting N/M…` service count.\n subscribers.broadcast(reg.boxId, BOX_STATUS_EVENT, snapshot);\n log(`box-status box=${reg.boxId}`);\n send(res, 202, { ok: true });\n return;\n }\n // Refreshed agent credentials: handled out-of-band in host mode — the\n // payload is a secret and must never land in the event ring buffer. In\n // box mode it falls through to the ring so the bridge drains it to the\n // host poller (which routes it to the host relay's handler).\n if (body.type === CREDENTIALS_UPDATED_EVENT && credentialsFanout) {\n const verdict = await credentialsFanout.handle(reg.boxId, body.payload);\n log(\n `credentials-updated box=${reg.boxId} accepted=${String(verdict.accepted)} (${verdict.reason})`,\n );\n send(res, 202, { ok: true, accepted: verdict.accepted });\n return;\n }\n const ev = await store.appendEvent({\n boxId: reg.boxId,\n type: body.type,\n ts: typeof body.ts === 'string' ? body.ts : undefined,\n payload: body.payload,\n });\n log(`event ${String(ev.id)} box=${reg.boxId} type=${body.type}`);\n send(res, 202, { id: ev.id });\n return;\n }\n\n if (route === 'POST /rpc') {\n const reg = await authBox(req, res);\n if (!reg) return;\n const body = await readJsonBody<PostRpcBody>(req);\n if (!body || typeof body.method !== 'string' || body.method.length === 0) {\n send(res, 400, { error: 'missing \"method\" string' });\n return;\n }\n log(`rpc box=${reg.boxId} method=${body.method}`);\n // Box-mode: every host-only RPC (anything except the in-sandbox-local\n // `browser.open` notification) is parked on the HostActionQueue. The\n // host's CloudBoxPoller drains via `/bridge/poll`, executes on the\n // host (with the existing `askPrompt` gate for `git.push`), and POSTs\n // the result back to `/bridge/action-result`, which resolves the\n // awaited Promise here and unblocks the in-box `/rpc` caller.\n if (mode === 'box' && hostActions && body.method !== 'browser.open') {\n const queued = await hostActions.enqueue(reg.boxId, body.method, body.params);\n const status = queued.exitCode === 0 ? 200 : 500;\n send(res, status, queued);\n return;\n }\n // Read-only machine-global metadata: the agent registry ctl reconciles\n // against at daemon start. Dispatched HERE, before worktree resolution,\n // for two reasons: the registry is not project-scoped (a box with no\n // registered worktree must still get it), and it must never be gated\n // behind askPrompt — a prompt would hang every box's startup reconcile.\n // Same posture as `tool.list`, which is also read-only and unprompted.\n if (body.method === 'agents.list') {\n send(res, 200, {\n exitCode: 0,\n stdout: JSON.stringify(buildAgentDescriptors({ boxAgents: registrationAgents(reg) })),\n stderr: '',\n });\n return;\n }\n if (body.method === 'git.push' || body.method === 'git.fetch') {\n // Cloud box reaching this host-mode relay directly over the forwarder\n // (rather than via the poller): run the cloud bundle pull-back executor,\n // which does its own gating and pushes via the host workspace.\n if (reg.kind === 'cloud') {\n const action: HostAction = {\n id: '',\n boxId: reg.boxId,\n method: body.method,\n params: body.params,\n createdAt: new Date().toISOString(),\n };\n const result = await executeCloudAction(action, {\n backendName: reg.backend ?? '',\n boxId: reg.boxId,\n boxName: reg.name,\n prompts,\n subscribers,\n hostInitiatedTokens,\n autoApproveSafeHostActions: reg.autoApproveSafeHostActions,\n controlPlane: opts.controlPlane === true,\n originUrl: reg.originUrl,\n boxAgents: registrationAgents(reg),\n log,\n });\n send(res, result.exitCode === 0 ? 200 : 500, result);\n return;\n }\n // Only `push` mutates the user's remote; fetch is read-only and noisy.\n // Per-box `agentbox/<name>` branches are the box's own scratch branch\n // — pushes to them are the whole point of agentbox, so they bypass\n // the y/N gate. Any other branch still prompts.\n if (body.method === 'git.push') {\n const hostOnlyParams = body.params as GitRpcParams | undefined;\n if (hostOnlyParams?.hostOnly) {\n // Landing the branch in the host's local repo publishes nothing,\n // so the push-confirm gate doesn't apply. Land and return.\n const saveResult = await handleGitSaveToHost(reg, hostOnlyParams);\n send(res, saveResult.exitCode === 0 ? 200 : 500, saveResult);\n return;\n }\n const params = body.params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, params?.path ?? '/workspace');\n // The docker relay always pushes the worktree's host-selected branch\n // (`sanctionedBranch`, falling back to the create-time `branch`) — the\n // in-box agent can't influence which branch is pushed. Key the gate on\n // THAT branch, not the immutable create-time `branch` (which is always\n // `agentbox/*`): after a host `agentbox git checkout main`, the push\n // target is `main`, so it must NOT be treated as a scratch bypass.\n // A scratch target bypasses unconditionally; a non-scratch sanctioned\n // target bypasses only as part of the safe subset (honors\n // `box.autoApproveSafeHostActions`) and leaves an audit trail.\n const dockerPushBranch = worktree?.sanctionedBranch ?? worktree?.branch;\n const isScratch = isScratchBranch(dockerPushBranch);\n const safeApproveOn = reg.autoApproveSafeHostActions !== false;\n // `isSanctionedPushBranch(dockerPushBranch, dockerPushBranch)` is true\n // only for a resolved branch — so a box with no registered worktree\n // (undefined branch) never bypasses and still prompts.\n const isSanctionedNonScratch =\n !isScratch &&\n safeApproveOn &&\n isSanctionedPushBranch(dockerPushBranch, dockerPushBranch);\n const bypassPushGate = isScratch || isSanctionedNonScratch;\n if (isSanctionedNonScratch) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `git push to sanctioned branch ${dockerPushBranch ?? ''} from box ${reg.name}`,\n context: { command: 'git push', cwd: params?.path, argv: params?.args },\n },\n 'safe: sanctioned-branch push',\n );\n }\n // Host-initiated pushes (driven by `agentbox git push <box>`) skip\n // the confirm prompt — but only if the host CLI minted a valid,\n // unexpired, scope-matched, params-hash-bound token via\n // /admin/host-initiated/mint. If a token is *present* but doesn't\n // validate (wrong scope, mutated params, expired, replayed), reject\n // hard: that's an attack signal (the only way to get a token is to\n // mint one host-side, and a legitimate host call always sends what\n // it minted for). Fall through to the prompt only when no token was\n // claimed — that's the normal agent-initiated path.\n const tokenClaimed = typeof params?.hostInitiated === 'string';\n const incomingHash = hashRpcParams(params);\n const hostInitiatedOk =\n !bypassPushGate &&\n tokenClaimed &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, 'git.push', incomingHash);\n if (!bypassPushGate && tokenClaimed && !hostInitiatedOk) {\n send(res, 500, {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n });\n return;\n }\n if (!bypassPushGate && !hostInitiatedOk) {\n const gate = await gateApproval(gateDeps, reg.boxId, 'git.push', body.params, {\n kind: 'confirm',\n message: `Allow git push from box ${reg.name}?`,\n detail: `${resolveRemote(params?.remote)} ${(params?.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: {\n command: 'git push',\n cwd: params?.path,\n argv: params?.args,\n },\n });\n // Poll mode: parked — the box polls /rpc/status/<promptId> for the\n // verdict + result (the push runs there, on approval).\n if (gate.kind === 'pending') {\n send(res, 202, { status: 'pending', promptId: gate.promptId });\n return;\n }\n if (gate.kind === 'deny') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n }\n const result = await handleGitRpc(\n reg,\n body.method,\n body.params as GitRpcParams | undefined,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'git.lease-token') {\n // The hosted-plane equivalent of git.push: instead of the relay pushing,\n // it leases a repo-scoped GitHub-App token and the box pushes directly.\n // Because that token can push ANY branch (the relay doesn't pick the\n // branch here, unlike git.push), the sanctioned-branch auto-approve does\n // NOT apply — only the box's own scratch branch bypasses; others prompt.\n const params = body.params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, params?.path ?? '/workspace');\n const isAgentboxBranch = isScratchBranch(worktree?.branch);\n if (!isAgentboxBranch) {\n const gate = await gateApproval(gateDeps, reg.boxId, 'git.lease-token', body.params, {\n kind: 'confirm',\n message: `Allow box ${reg.name} to lease a push token for ${reg.originUrl ?? 'its repo'}?`,\n detail: `branch ${worktree?.branch ?? '(unregistered)'}`,\n defaultAnswer: 'n',\n context: { command: 'git lease-token', cwd: params?.path },\n });\n if (gate.kind === 'pending') {\n send(res, 202, { status: 'pending', promptId: gate.promptId });\n return;\n }\n if (gate.kind === 'deny') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await leaseTokenResult(leaser, reg);\n send(res, result.exitCode === 0 ? 200 : 500, result);\n return;\n }\n if (\n hostReach &&\n reg.kind === 'cloud' &&\n isHostReachMethod(body.method) &&\n !(await boxWorkspaceExistsHere(reg.boxId))\n ) {\n // A control box has neither the user's files nor a live checkout to\n // resolve them against, so it brokers instead of executing: park the\n // action for the machine that does, and let THAT machine gate it. The\n // gate belongs with the executor — deciding \"contained in the project\"\n // here would judge a path that does not exist on this disk (it is the\n // create job's deleted temp clone), which is how a copy the user never\n // saw got auto-approved as safe.\n //\n // `tool.*` travels for the same reason and lands in the same place: a\n // grant is a per-project file on the machine that made it, and the\n // binary it names is installed THERE. Executing here read grants from\n // that same deleted directory and would have run the control box's\n // binaries under the user's tool name.\n const cachePrefix = cpCachePrefix({\n projectSlug: reg.originUrl\n ? (projectSlugFromOriginUrl(reg.originUrl) ?? undefined)\n : undefined,\n boxId: reg.boxId,\n });\n const outcome = await hostReach.request(reg.boxId, body.method, body.params, {\n cachePrefix,\n });\n if (outcome.kind === 'result') {\n send(res, outcome.result.exitCode === 0 ? 200 : 500, outcome.result);\n return;\n }\n log(`${body.method} for ${reg.boxId}: host unreachable (${outcome.reason})`);\n // Tools have no fallback by design: a cached file is still that file,\n // but \"some binary of the same name on another machine\" is a different\n // program. Say the machine is offline and stop.\n if (body.method.startsWith('tool.')) {\n send(res, 500, {\n exitCode: 69,\n stdout: '',\n stderr: toolUnreachableMessage(reg.name, outcome.reason),\n });\n return;\n }\n // The machine is offline — but a copy it made earlier may be in custody.\n // Only reads can be served that way: an outbound copy has nowhere to go\n // until that machine is back (see the outbox in `cp.toHost` below).\n if (body.method === 'cp.fromHost') {\n const cached = await serveCachedCp({\n params: body.params as CpRpcParams | undefined,\n reg,\n custody,\n cachePrefix,\n prompts,\n subscribers,\n log,\n });\n if (cached) {\n send(res, cached.exitCode === 0 ? 200 : 500, cached);\n return;\n }\n } else {\n // Outbound: nothing to fall back to, but the bytes are still in the\n // box. Take them now and hold them for the machine, rather than\n // letting an agent's output evaporate because a laptop was shut.\n const parked = await parkOutboundCp({\n params: body.params as CpRpcParams | undefined,\n reg,\n custody,\n maxBytes: custodyMaxBlobBytes,\n log,\n });\n if (parked) {\n send(res, parked.exitCode === 0 ? 200 : 500, parked);\n return;\n }\n }\n send(res, 500, {\n exitCode: 69,\n stdout: '',\n stderr: cpUnreachableMessage(body.method as CpMethod, reg.name, outcome.reason, {\n cacheMiss: body.method === 'cp.fromHost',\n }),\n });\n return;\n }\n if (body.method === 'cp.toHost' || body.method === 'cp.fromHost') {\n const params = body.params as CpRpcParams | undefined;\n let norm: { sources: string[]; dest: string };\n try {\n norm = normalizeCpParams(body.method, params);\n } catch (err) {\n send(res, 400, { error: err instanceof Error ? err.message : String(err) });\n return;\n }\n if (\n params!.exclude !== undefined &&\n (!Array.isArray(params!.exclude) || params!.exclude.some((p) => typeof p !== 'string'))\n ) {\n send(res, 400, { error: 'cp.* exclude must be an array of strings' });\n return;\n }\n const direction = body.method === 'cp.toHost' ? 'box -> host' : 'host -> box';\n // Resolve host paths against THIS box's workspace so a relative path\n // doesn't land under the relay daemon's CWD (whichever project started\n // the relay), and so the consent prompt shows the real destination.\n const workspacePath = await boxWorkspacePath(reg.boxId);\n const {\n argv: cpArgs,\n detail,\n contextArgv,\n } = buildCpArgv({\n method: body.method,\n boxName: reg.name,\n sources: norm.sources,\n dest: norm.dest,\n resolveHost: (p) => resolveHostPath(workspacePath, p),\n flags: cpFlags(params!),\n });\n const detailParts = [detail];\n if (params!.exclude && params!.exclude.length > 0) {\n detailParts.push(`exclude: ${params!.exclude.join(', ')}`);\n }\n if (params!.defaultExcludes === false) detailParts.push('(default excludes off)');\n if (params!.yes) detailParts.push('(over size limit — confirmed)');\n // Auto-approve a transfer that stays inside the box's project folder\n // (box->host: check the dest; host->box: check the sources, keeping\n // secret files behind the prompt). Anything else prompts as before.\n const cpHostPaths =\n body.method === 'cp.toHost'\n ? [resolveHostPath(workspacePath, norm.dest)]\n : norm.sources.map((s) => resolveHostPath(workspacePath, s));\n const cpAuto = await canAutoApproveTransfer({\n enabled: reg.autoApproveSafeHostActions !== false,\n workspacePath,\n hostPaths: cpHostPaths,\n checkSecret: body.method === 'cp.fromHost',\n carried: body.method === 'cp.fromHost' ? await boxCarriedHostPaths(reg.boxId) : undefined,\n });\n if (cpAuto) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `cp (${direction}) on ${reg.name}`,\n detail: detailParts.join('\\n'),\n context: { command: body.method, argv: contextArgv },\n },\n body.method === 'cp.toHost'\n ? 'safe: contained copy to host'\n : 'safe: contained copy from host',\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow cp (${direction}) on ${reg.name}?`,\n detail: detailParts.join('\\n'),\n defaultAnswer: 'n',\n context: {\n command: body.method,\n argv: contextArgv,\n },\n });\n if (verdict.answer !== 'y') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await handleCpRpc(cpArgs, workspacePath);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'gh.exec') {\n const result = await handleGhExecRpc(\n reg,\n body.params as GhExecRpcParams | undefined,\n prompts,\n subscribers,\n hostInitiatedTokens,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method.startsWith('tool.')) {\n const result = await handleToolRpc(\n body.method,\n reg,\n body.params as Record<string, unknown> | undefined,\n prompts,\n subscribers,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'git.clone' || body.method === 'gh.repo.clone') {\n // Clone bundle-ship-back machinery is deferred to a follow-up PR\n // The shim + ctl plumbing is in place so the next iteration only has\n // to land the relay-side host clone + bundle + box transfer.\n send(res, 501, {\n exitCode: 64,\n stdout: '',\n stderr: `${body.method}: not yet implemented for this box. Run \\`gh\\` / \\`git\\` on the host directly for now.\\n`,\n });\n return;\n }\n if (\n body.method === 'download.workspace' ||\n body.method === 'download.env' ||\n body.method === 'download.config' ||\n body.method === 'download.claude'\n ) {\n const params = body.params as DownloadRpcParams | undefined;\n const kind = parseDownloadKind(body.method);\n // `download.workspace` lands under the box's project folder (contained by\n // construction), so it auto-approves under the safe flag. The env/config/\n // claude kinds land in ~/.agentbox / ~/.claude (outside the project) and\n // keep prompting.\n const dlWorkspace = await boxWorkspacePath(reg.boxId);\n const dlAuto =\n kind === 'workspace' &&\n (await canAutoApproveTransfer({\n enabled: reg.autoApproveSafeHostActions !== false,\n workspacePath: dlWorkspace,\n hostPaths: dlWorkspace ? [dlWorkspace] : [],\n checkSecret: false,\n }));\n if (dlAuto) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `download (${kind}) from ${reg.name}`,\n detail: params?.hostPath ?? '(default host location)',\n context: { command: body.method, argv: params?.hostPath ? [params.hostPath] : [] },\n },\n 'safe: contained download',\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow download (${kind}) from ${reg.name}?`,\n detail: params?.hostPath ?? '(default host location)',\n defaultAnswer: 'n',\n context: {\n command: body.method,\n argv: params?.hostPath ? [params.hostPath] : [],\n },\n });\n if (verdict.answer !== 'y') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await handleDownloadRpc(reg, kind);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'checkpoint.create') {\n const result = await handleCheckpointRpc(\n reg,\n body.params as CheckpointRpcParams | undefined,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'browser.open') {\n const params = body.params as BrowserOpenRpcParams | undefined;\n const url = typeof params?.url === 'string' ? params.url.trim() : '';\n if (!isOpenableUrl(url)) {\n // The scheme guard keeps a box from handing the host's `open` a\n // file path or app instead of a URL.\n send(res, 400, {\n exitCode: 64,\n stdout: '',\n stderr: 'browser.open: only http/https URLs are allowed\\n',\n });\n return;\n }\n // The box already opened the link in its own browser; this RPC is\n // just a notification. Record the event and answer at once — never\n // block the box on the host user's decision.\n await store.appendEvent({ boxId: reg.boxId, type: 'browser-open', payload: { url } });\n send(res, 200, { exitCode: 0, stdout: '', stderr: '' });\n // Mirror the link to the host browser. Part of the safe host-action\n // subset (`box.autoApproveSafeHostActions`), so it normally just opens\n // — `browserOpenBudget` is what keeps a looping agent from spraying\n // tabs now that no prompt stands in the way. Skipped under\n // AGENTBOX_PROMPT=off so a headless box can't open host tabs at all.\n if (process.env.AGENTBOX_PROMPT !== 'off') {\n if (mode === 'box' && hostActions) {\n // Cloud: the in-sandbox relay has no SSE subscribers (the host\n // wrapper attaches to the host relay, not the in-sandbox one).\n // Queue a `browser.open.mirror` host action — the host poller\n // drains it, applies the same budget + open against host\n // subscribers, and resolves the parked entry. We don't await;\n // the host's verdict isn't reported back to the in-box agent\n // and `HostActionQueue.maxAgeMs` GCs the entry if it lingers.\n void hostActions.enqueue(reg.boxId, 'browser.open.mirror', { url });\n } else {\n // Offer it to whichever surface the human is at (footer, dashboard,\n // tray, hub web); only when nothing is attached AND this relay is\n // the human's own machine does it open here. See ./open-link.ts.\n void offerBrowserOpen(\n {\n prompts,\n subscribers,\n boxId: reg.boxId,\n boxName: reg.name,\n autoApproveSafe: reg.autoApproveSafeHostActions !== false,\n controlPlane: opts.controlPlane === true,\n log,\n },\n url,\n ).catch(() => {\n /* best-effort: the box never observes the outcome */\n });\n }\n }\n return;\n }\n await store.appendEvent({\n boxId: reg.boxId,\n type: 'rpc-unknown',\n payload: { method: body.method },\n });\n send(res, 501, { error: 'rpc method not implemented', method: body.method });\n return;\n }\n\n // Poll-mode verdict + result for a parked approval (see ./permission.ts).\n // The box polls this after a `/rpc` returned `202 {promptId}`:\n // - pending → keep polling\n // - denied/cancelled → exit 10\n // - approved → run the action once, cache the result, return it\n if (req.method === 'GET' && url.pathname.startsWith('/rpc/status/')) {\n const reg = await authBox(req, res);\n if (!reg) return;\n const promptId = decodeURIComponent(url.pathname.slice('/rpc/status/'.length));\n const row = await store.getPrompt(promptId);\n if (!row || row.boxId !== reg.boxId) {\n send(res, 404, { error: 'no such prompt', promptId });\n return;\n }\n if (row.status === 'pending') {\n send(res, 200, { status: 'pending' });\n return;\n }\n if (row.answer !== 'y' || row.cancelled) {\n send(res, 200, {\n status: 'done',\n result: { exitCode: 10, stdout: '', stderr: 'denied by user\\n' },\n });\n return;\n }\n // Approved. Idempotent: a cached result short-circuits re-polls; the box\n // polls sequentially so there is no concurrent first-execute race here.\n const cached = row.result;\n const result = cached ?? (await dispatchApprovedAction(reg, row.method, row.params));\n if (!cached) await store.setPromptResult(promptId, result);\n send(res, 200, { status: 'done', result });\n return;\n }\n\n if (route === 'POST /admin/register-box') {\n const body = await readJsonBody<RegisterBoxBody>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n typeof body.token !== 'string' ||\n typeof body.name !== 'string' ||\n body.boxId.length === 0 ||\n body.token.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, token, name}' });\n return;\n }\n const worktrees = sanitizeWorktrees(body.worktrees);\n // Only accept a finite positive integer; everything else (including the\n // common `undefined` from legacy boxes) drops to `undefined` and the\n // status-store falls back to the `<id>-<mnemonic>` segment shape.\n const projectIndex =\n typeof body.projectIndex === 'number' &&\n Number.isFinite(body.projectIndex) &&\n body.projectIndex > 0\n ? Math.trunc(body.projectIndex)\n : undefined;\n const kind = body.kind === 'cloud' ? 'cloud' : 'docker';\n const reg: BoxRegistration = {\n boxId: body.boxId,\n token: body.token,\n name: body.name,\n kind,\n backend:\n typeof body.backend === 'string' && body.backend.length > 0 ? body.backend : undefined,\n sandboxId:\n typeof body.sandboxId === 'string' && body.sandboxId.length > 0\n ? body.sandboxId\n : undefined,\n registeredAt: new Date().toISOString(),\n containerName:\n typeof body.containerName === 'string' && body.containerName.length > 0\n ? body.containerName\n : undefined,\n createdAt:\n typeof body.createdAt === 'string' && body.createdAt.length > 0\n ? body.createdAt\n : undefined,\n projectIndex,\n worktrees,\n previewUrl:\n typeof body.previewUrl === 'string' && body.previewUrl.length > 0\n ? body.previewUrl\n : undefined,\n previewToken:\n typeof body.previewToken === 'string' && body.previewToken.length > 0\n ? body.previewToken\n : undefined,\n bridgeToken:\n typeof body.bridgeToken === 'string' && body.bridgeToken.length > 0\n ? body.bridgeToken\n : undefined,\n autoApproveHostActions: body.autoApproveHostActions === true,\n // Default on: only an explicit `false` disables the safe subset, so an\n // older wire body without the field stays relaxed.\n autoApproveSafeHostActions: body.autoApproveSafeHostActions !== false,\n originUrl:\n typeof body.originUrl === 'string' && body.originUrl.length > 0\n ? body.originUrl\n : undefined,\n publicHost:\n typeof body.publicHost === 'string' && body.publicHost.length > 0\n ? body.publicHost\n : undefined,\n image: typeof body.image === 'string' && body.image.length > 0 ? body.image : undefined,\n webPort:\n typeof body.webPort === 'number' && Number.isFinite(body.webPort) && body.webPort > 0\n ? Math.trunc(body.webPort)\n : undefined,\n agent: typeof body.agent === 'string' && body.agent.length > 0 ? body.agent : undefined,\n projectSlug:\n typeof body.projectSlug === 'string' && body.projectSlug.length > 0\n ? body.projectSlug\n : undefined,\n };\n await store.registerBox(reg);\n log(\n `registered ${kind} box ${reg.boxId} (${reg.name})` +\n (worktrees && worktrees.length > 0\n ? ` with ${String(worktrees.length)} worktree(s)`\n : ''),\n );\n // Cloud boxes get a host-side poller so the host relay can mirror their\n // status into its BoxStatusStore (and, once the executor is wired,\n // drain queued host-only RPCs and post results back).\n if (kind === 'cloud' && reg.previewUrl && reg.bridgeToken) {\n try {\n const set = await getPollers();\n set.start(reg.boxId, {\n boxId: reg.boxId,\n previewUrl: reg.previewUrl,\n bridgeToken: reg.bridgeToken,\n previewToken: reg.previewToken,\n onEvents: async (evs) => {\n for (const ev of evs) {\n // Credential updates carry a secret blob — route to the\n // fan-out handler, never into the host event ring buffer.\n if (ev.type === CREDENTIALS_UPDATED_EVENT && credentialsFanout) {\n const verdict = await credentialsFanout.handle(reg.boxId, ev.payload);\n log(\n `credentials-updated box=${reg.boxId} accepted=${String(verdict.accepted)} (${verdict.reason})`,\n );\n continue;\n }\n await store.appendEvent({\n boxId: reg.boxId,\n type: ev.type,\n payload: ev.payload,\n ts: ev.ts,\n });\n }\n },\n onStatus: (status) => {\n if (isValidBoxStatus(status)) {\n const snapshot = normalizeBoxStatus(status);\n void store.setStatus(reg.boxId, reg.name, reg.projectIndex, snapshot);\n // Same reason as the direct-POST path above: this is the only\n // status source an attached footer has for a cloud box.\n subscribers.broadcast(reg.boxId, BOX_STATUS_EVENT, snapshot);\n }\n },\n // Drained host-only RPCs (git.push, …) run on the host via the\n // executor and the result is POSTed back to /bridge/action-result.\n // No backend name → no executor; the poller's default respond\n // already returns a \"no executor\" error so the box unblocks.\n onAction: reg.backend\n ? async (action, respond) => {\n try {\n const result = await executeCloudAction(action, {\n backendName: reg.backend!,\n boxId: reg.boxId,\n boxName: reg.name,\n prompts,\n subscribers,\n hostInitiatedTokens,\n autoApproveSafeHostActions: reg.autoApproveSafeHostActions,\n controlPlane: opts.controlPlane === true,\n originUrl: reg.originUrl,\n boxAgents: registrationAgents(reg),\n log,\n });\n await respond(result);\n } catch (err) {\n await respond({\n exitCode: 1,\n stdout: '',\n stderr: `host executor failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n });\n }\n }\n : undefined,\n // Self-heal a dead preview transport (hetzner SSH `-L` after a\n // ControlMaster death). The relay strips the `cloud:` prefix\n // the cloud-provider tags onto BoxRecord.container — what the\n // backend's `get(sandboxId)` expects is the bare sandbox id.\n recoverPreviewUrl: reg.backend\n ? async () => refreshCloudPreviewUrl(reg.backend!, reg.boxId, DEFAULT_BOX_RELAY_PORT)\n : undefined,\n logger: log,\n });\n } catch (err) {\n log(\n `failed to start cloud poller for ${reg.boxId}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/forget-box') {\n const body = await readJsonBody<{ boxId?: string }>(req);\n if (!body || typeof body.boxId !== 'string' || body.boxId.length === 0) {\n send(res, 400, { error: 'expected {boxId}' });\n return;\n }\n const existed = await store.forgetBox(body.boxId);\n await store.deleteStatus(body.boxId);\n if (pollers) await pollers.stop(body.boxId);\n log(`forgot box ${body.boxId} (existed=${String(existed)})`);\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/stop-poller') {\n const body = await readJsonBody<{ boxId?: string }>(req);\n if (!body || typeof body.boxId !== 'string' || body.boxId.length === 0) {\n send(res, 400, { error: 'expected {boxId}' });\n return;\n }\n // Deliberately NOT forget-box: the registration and status survive, so\n // `list`/the hub keep showing the box. This only silences the poller,\n // which has nothing to talk to while the box is paused — and on an\n // auto-resuming backend (e2b) would otherwise wake it right back up.\n if (pollers) await pollers.stop(body.boxId);\n send(res, 204, null);\n return;\n }\n\n if (route === 'GET /admin/box-status') {\n const box = url.searchParams.get('box') ?? '';\n const status = box ? await store.getStatus(box) : undefined;\n if (!status) {\n send(res, 404, { error: 'no status for box', box });\n return;\n }\n send(res, 200, status);\n return;\n }\n\n if (route === 'GET /admin/events') {\n const since = Number.parseInt(url.searchParams.get('since') ?? '0', 10) || 0;\n const box = url.searchParams.get('box') ?? undefined;\n const list = await store.listEvents(since, box ?? undefined);\n send(res, 200, { events: list });\n return;\n }\n\n if (route === 'GET /admin/registry') {\n // Redact tokens; callers on the admin path don't need them and we don't\n // want them showing up in logs if someone curls this.\n const redacted = (await store.listBoxes()).map((r) => ({\n boxId: r.boxId,\n name: r.name,\n registeredAt: r.registeredAt,\n containerName: r.containerName,\n createdAt: r.createdAt,\n projectIndex: r.projectIndex,\n worktrees: r.worktrees ?? [],\n }));\n send(res, 200, { boxes: redacted });\n return;\n }\n\n if (route === 'GET /admin/prompts') {\n // One-shot snapshot of pending host-action approvals for a box. The SSE\n // `/stream` variant is for long-lived wrappers; this is for an\n // orchestrator (or `agentbox agent approvals`) that wants to inspect the\n // backlog, answer via /admin/prompts/answer, and move on without holding\n // a stream open. `boxId=` required, same as /stream.\n const boxId = url.searchParams.get('boxId') ?? '';\n if (boxId.length === 0) {\n send(res, 400, { error: 'missing boxId query param' });\n return;\n }\n // Poll mode parks prompts in the store; block mode keeps them in-process.\n const pending =\n promptMode === 'poll'\n ? (await store.listPendingPrompts(boxId)).map((r) => r.ev)\n : prompts.forBox(boxId);\n send(res, 200, { prompts: pending });\n return;\n }\n\n if (route === 'GET /admin/prompts/stream') {\n // Per-box SSE channel. The wrapper (apps/cli/src/wrapped-pty) subscribes\n // and stays connected; we push prompt-ask events on broadcast and a\n // periodic ping so the wrapper can detect a dead socket without traffic.\n // `boxId=` is required so a host with multiple boxes only sees its own\n // box's prompts (the wrapper attaches per-box anyway).\n const boxId = url.searchParams.get('boxId') ?? '';\n if (boxId.length === 0) {\n send(res, 400, { error: 'missing boxId query param' });\n return;\n }\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n // Helps with proxies (e.g. nginx) that would otherwise buffer the\n // chunked response. The relay binds to loopback so this is belt-and-\n // suspenders, but the cost is one extra header.\n res.setHeader('X-Accel-Buffering', 'no');\n if (typeof res.flushHeaders === 'function') res.flushHeaders();\n res.write(': connected\\n\\n');\n subscribers.add(boxId, res);\n // Flush any prompts that arrived while no wrapper was attached — per\n // the design we block indefinitely on the in-box RPC, so a backlog can\n // build up between detach and reattach.\n for (const ev of prompts.forBox(boxId)) {\n res.write(`event: prompt-ask\\ndata: ${JSON.stringify(ev)}\\n\\n`);\n }\n // Then any active notices, so a wrapper attaching mid-checkpoint still\n // sees the in-progress warning (prompts first — they outrank notices).\n for (const ev of notices.forBox(boxId)) {\n res.write(`event: notice-set\\ndata: ${JSON.stringify(ev)}\\n\\n`);\n }\n const heartbeat = setInterval(() => {\n try {\n res.write(`event: ping\\ndata: {\"ts\":\"${new Date().toISOString()}\"}\\n\\n`);\n } catch {\n /* dead socket; close handler below removes */\n }\n }, SSE_HEARTBEAT_MS);\n if (typeof heartbeat.unref === 'function') heartbeat.unref();\n res.on('close', () => {\n clearInterval(heartbeat);\n subscribers.remove(boxId, res);\n });\n return;\n }\n\n if (route === 'POST /admin/prompts/answer') {\n const body = await readJsonBody<PromptAnswerBody>(req);\n if (!isPromptAnswerBody(body)) {\n send(res, 400, { error: 'expected {id, answer:\"y\"|\"n\", cancelled?}' });\n return;\n }\n // Poll mode: the answer lands on the store row; the box's /rpc/status\n // poll picks it up and runs (or denies) the parked action.\n if (promptMode === 'poll') {\n const row = await store.getPrompt(body.id);\n const hit = await store.answerPrompt(body.id, body.answer, body.cancelled);\n if (!hit) {\n send(res, 404, { error: 'no pending prompt with that id' });\n return;\n }\n if (row) subscribers.broadcast(row.boxId, 'prompt-resolved', { id: body.id });\n send(res, 204, null);\n return;\n }\n // Block mode: resolve the in-process pending Promise (the parked /rpc\n // call unblocks and runs/denies inline). Find the owning box first so we\n // can target the prompt-resolved broadcast (other wrappers clear their\n // stale footer).\n const targetBox = prompts.boxFor(body.id);\n const hit = prompts.resolve(body.id, body.answer, body.cancelled, body.openedByClient);\n if (!hit) {\n // Already answered (idempotent) or never existed.\n send(res, 404, { error: 'no pending prompt with that id' });\n return;\n }\n if (targetBox) {\n subscribers.broadcast(targetBox, 'prompt-resolved', { id: body.id });\n }\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/host-initiated/mint') {\n // Host CLI mints a one-time token before invoking `agentbox-ctl` in a\n // box for a credentialed RPC. The token is scoped to\n // (boxId, method, paramsHash) and consumed on first use.\n // See ./host-initiated.ts for rationale.\n //\n // paramsHash is mandatory in practice — without it a box that\n // harvests the token from agentbox-ctl's /proc/<pid>/cmdline could\n // replay it with mutated args. Accept `null` only for callers that\n // intentionally opt out (none today).\n const body = await readJsonBody<{\n boxId?: string;\n method?: string;\n paramsHash?: string | null;\n ttlMs?: number;\n }>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n body.boxId.length === 0 ||\n typeof body.method !== 'string' ||\n body.method.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, method, paramsHash, ttlMs?}' });\n return;\n }\n // Allow `paramsHash: null` (explicit opt-out) or a hex string.\n let paramsHash: string | null;\n if (body.paramsHash === null || body.paramsHash === undefined) {\n paramsHash = null;\n } else if (typeof body.paramsHash === 'string' && /^[0-9a-f]{64}$/.test(body.paramsHash)) {\n paramsHash = body.paramsHash;\n } else {\n send(res, 400, { error: 'paramsHash must be a 64-hex sha256 string or null' });\n return;\n }\n const ttlMs =\n typeof body.ttlMs === 'number' && Number.isFinite(body.ttlMs) && body.ttlMs > 0\n ? body.ttlMs\n : undefined;\n const token = hostInitiatedTokens.mint(body.boxId, body.method, paramsHash, ttlMs);\n log(\n `host-initiated-mint box=${body.boxId} method=${body.method} paramsBound=${paramsHash !== null}`,\n );\n send(res, 200, { token });\n return;\n }\n\n if (route === 'POST /admin/notices/set') {\n const body = await readJsonBody<SetNoticeBody>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n body.boxId.length === 0 ||\n typeof body.kind !== 'string' ||\n body.kind.length === 0 ||\n typeof body.message !== 'string' ||\n body.message.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, kind, message}' });\n return;\n }\n const ttlMs =\n typeof body.ttlMs === 'number' && Number.isFinite(body.ttlMs) && body.ttlMs > 0\n ? body.ttlMs\n : undefined;\n const id = notices.set(body.boxId, body.kind, body.message, ttlMs);\n log(`notice-set box=${body.boxId} kind=${body.kind} id=${id}`);\n send(res, 200, { id });\n return;\n }\n\n if (route === 'POST /admin/queue/enqueue') {\n // The CLI's `submitQueueJob` writes the manifest first, then POSTs here\n // so the relay's scheduler runs immediately instead of waiting for the\n // next periodic tick. Body is informational — the source of truth is\n // the manifest on disk.\n const body = await readJsonBody<{ id?: string }>(req);\n if (!body || typeof body.id !== 'string' || body.id.length === 0) {\n send(res, 400, { error: 'expected {id}' });\n return;\n }\n log(`queue-enqueue id=${body.id}`);\n queuePoke?.();\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/notices/clear') {\n const body = await readJsonBody<ClearNoticeBody>(req);\n if (!body || typeof body.id !== 'string' || body.id.length === 0) {\n send(res, 400, { error: 'expected {boxId, id}' });\n return;\n }\n notices.clear(body.id);\n log(`notice-clear id=${body.id}`);\n send(res, 204, null);\n return;\n }\n\n if (uiHandler) {\n uiHandler(req, res);\n return;\n }\n send(res, 404, { error: 'not found', route });\n }\n\n /**\n * Run a host action that has already cleared its approval gate (poll mode:\n * the box reached `/rpc/status` after a `y`). No re-gating here. Extended per\n * method as the hosted plane grows.\n */\n async function dispatchApprovedAction(\n reg: BoxRegistration,\n method: string,\n params: unknown,\n ): Promise<GitRpcResult> {\n if (method === 'git.push' || method === 'git.fetch') {\n return handleGitRpc(reg, method, params as GitRpcParams | undefined);\n }\n if (method === 'git.lease-token') {\n return leaseTokenResult(leaser, reg);\n }\n return {\n exitCode: 64,\n stdout: '',\n stderr: `relay: no approved-action executor for ${method}\\n`,\n };\n }\n\n async function authBox(\n req: IncomingMessage,\n res: ServerResponse,\n ): Promise<BoxRegistration | null> {\n const token = bearerToken(req);\n if (token.length === 0) {\n send(res, 401, { error: 'missing bearer token' });\n return null;\n }\n const match = await store.authenticateBox(token);\n if (!match) {\n send(res, 401, { error: 'unknown box token' });\n return null;\n }\n return match;\n }\n\n return {\n server,\n store,\n registry,\n events,\n statusStore,\n prompts,\n subscribers,\n notices,\n hubNotifier,\n custody,\n hostActions: hostActions ?? undefined,\n hostReach: hostReach ?? undefined,\n url: `http://${host}:${String(opts.port)}`,\n setQueuePoke: (fn) => {\n queuePoke = fn;\n },\n pokeQueue: () => {\n queuePoke?.();\n },\n stopCloudPoller: async (boxId) => {\n if (pollers) await pollers.stop(boxId);\n },\n close: async () => {\n if (pollers) await pollers.stopAll();\n // Settles every parked copy as unreachable, so an in-flight `cp` fails\n // fast on hub restart instead of hanging until the box's own timeout.\n hostReach?.stop();\n await new Promise<void>((resolve, reject) => {\n server.close((err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n },\n };\n}\n\nfunction sanitizeWorktrees(input: BoxWorktree[] | undefined): BoxWorktree[] | undefined {\n if (!Array.isArray(input)) return undefined;\n const out: BoxWorktree[] = [];\n for (const w of input) {\n if (\n w &&\n typeof w.containerPath === 'string' &&\n typeof w.hostMainRepo === 'string' &&\n typeof w.branch === 'string'\n ) {\n out.push({\n containerPath: w.containerPath,\n hostMainRepo: w.hostMainRepo,\n branch: w.branch,\n ...(typeof w.sanctionedBranch === 'string' && w.sanctionedBranch.length > 0\n ? { sanctionedBranch: w.sanctionedBranch }\n : {}),\n });\n }\n }\n return out;\n}\n\n/**\n * git.push --host-only: make the box's branch available in the host's *local*\n * repo without pushing to any remote. Docker boxes commit against the\n * bind-mounted `.git/`, so the box's branch ref already lives in the host repo;\n * we just copy it to the requested destination ref via a self-fetch (which\n * enforces fast-forward and works even though the source branch is checked out\n * in the worktree). When the destination equals the source branch this is a\n * no-op success — the branch is already on the host.\n */\nasync function handleGitSaveToHost(\n reg: BoxRegistration,\n params: GitRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n // Land the branch the box is actually on (its host-sanctioned branch, updated\n // by `agentbox git checkout`), matching what `git.push` publishes — not the\n // stale create-time scratch ref.\n const src = worktree.sanctionedBranch ?? worktree.branch;\n const dest = resolveLandDest(src, params?.as);\n if (dest === src) {\n return {\n exitCode: 0,\n stdout: `branch ${dest} already available in ${worktree.hostMainRepo}\\n`,\n stderr: '',\n };\n }\n const refspec = landRefspec(src, dest, params?.force);\n const result = await runHostCommand(['git', '-C', worktree.hostMainRepo, 'fetch', '.', refspec]);\n if (result.exitCode === 0) {\n return {\n exitCode: 0,\n stdout: `branch ${dest} available in ${worktree.hostMainRepo}\\n${result.stdout}`,\n stderr: result.stderr,\n };\n }\n return result;\n}\n\n/**\n * git.push / git.fetch: run `git -C <hostMainRepo> <op> <remote> <branch>\n * [args]` on the host with the user's creds. The in-container worktree's\n * working tree isn't on the host, so we operate on the shared `.git/` from\n * the main repo dir — refs already point at the in-container commits\n * (committed there against the bind-mounted .git).\n *\n * git.pull is intentionally NOT handled here: a pull merges into the\n * working tree, which lives inside the container. The in-box\n * `agentbox-ctl git pull` calls git.fetch via RPC, then runs a local merge.\n */\nasync function handleGitRpc(\n reg: BoxRegistration,\n method: 'git.push' | 'git.fetch',\n params: GitRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n // A worker-created (hub) box registered its `hostMainRepo` as the create-time\n // seed clone (a temp dir deleted after create), so `git -C <that>` would fail\n // cryptically. Reject fail-closed with a clear message instead.\n const unavailable = hostRepoUnavailableReason(worktree, reg.boxId, method);\n if (unavailable) {\n return { exitCode: 64, stdout: '', stderr: unavailable };\n }\n const op = method === 'git.push' ? 'push' : 'fetch';\n const remote = resolveRemote(params?.remote);\n // Operate on the host-sanctioned branch (updated by `agentbox git checkout`),\n // falling back to the create-time `branch` for records without the field.\n // The agent can't influence this — the relay picks the branch — so pushing\n // it is always host-controlled.\n const pushBranch = worktree.sanctionedBranch ?? worktree.branch;\n const argv = ['git', '-C', worktree.hostMainRepo, op, remote, pushBranch];\n argv.push(...sanitizeGitArgs(params?.args));\n const result = await runHostCommand(argv);\n // After a successful push, mirror what `git push -u` would have left behind:\n // make the branch track `origin/<branch>` so the in-box `git status` /\n // Claude Code's PR badge see an upstream. Skip per-box scratch branches\n // (`agentbox/<name>`) — they're local-only by design. Docker shares .git/\n // with the box, so update-ref of the remote-tracking ref already happened\n // during the push; only the upstream config is missing.\n if (method === 'git.push' && result.exitCode === 0 && !isScratchBranch(pushBranch)) {\n await runHostCommand([\n 'git',\n '-C',\n worktree.hostMainRepo,\n 'branch',\n `--set-upstream-to=${upstreamRef(remote, pushBranch)}`,\n pushBranch,\n ]);\n }\n return result;\n}\n\n/**\n * `gh.exec`: run the host's `gh` with the box's argv.\n *\n * One handler for the whole CLI, replacing the old per-subcommand allowlist\n * (`gh.pr.<op>` / `gh.run.<op>` / `gh.api`) that refused anything it had not\n * been taught — which is what made `gh issue` unreachable (issue #304).\n * Policy now lives in three small lists in `gh.ts`: blocked outright,\n * always-confirmed, and everything else allow-once.\n *\n * Runs with `cwd = worktree.hostMainRepo` so `gh` infers the repo from that\n * repo's `git remote -v`. `pr` keeps two pieces of special handling that are\n * about correctness rather than policy: the box's branch is injected into a\n * headless `pr create`, and `pr checkout` stays opt-in because it moves the\n * HOST's working tree.\n */\nasync function handleGhExecRpc(\n reg: BoxRegistration,\n params: GhExecRpcParams | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n hostInitiatedTokens: HostInitiatedTokens,\n): Promise<GitRpcResult> {\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n if (args.length === 0) {\n return { exitCode: 64, stdout: '', stderr: 'gh: no arguments\\n' };\n }\n\n const blocked = refuseBlockedGhCall(args);\n if (blocked) return blocked;\n\n // Read the verb past any leading global flags, so `gh -R o/r pr checkout`\n // is still recognised as a checkout.\n const verb = ghVerbArgv(args);\n const family = verb[0] ?? '';\n const op = verb[1] ?? '';\n if (family === 'pr') {\n const checkoutOptIn = refuseCheckoutByDefault(op);\n if (checkoutOptIn) return checkoutOptIn;\n }\n if (family === 'api') {\n const inputRefusal = refuseGhApiInput(args);\n if (inputRefusal) return inputRefusal;\n }\n\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n // `tools.gh.enabled: false` revokes the built-in grant. Per call, layered,\n // and before any host probe, so a revoked gh never surfaces as a prompt.\n const ghRevoked = await refuseIfGhDisabled(worktree.hostMainRepo);\n if (ghRevoked) return ghRevoked;\n\n const ghTarget = await resolveGhTarget(reg.originUrl);\n if (ghTarget.error) return ghTarget.error;\n\n if (family === 'pr' && op === 'checkout') {\n // Refuse a host checkout onto ANY branch a box currently occupies — its\n // create-time scratch ref AND its host-sanctioned branch — either of\n // which the bind-mounted `.git/HEAD` would corrupt.\n const branches = (reg.worktrees ?? []).flatMap((w) =>\n w.sanctionedBranch && w.sanctionedBranch !== w.branch\n ? [w.branch, w.sanctionedBranch]\n : [w.branch],\n );\n const guard = await checkoutGuards(worktree.hostMainRepo, branches);\n if (guard) return guard;\n }\n\n // Host-initiated calls (from `agentbox git pr <op> <box>`) skip the confirm\n // with a scope-matched, params-hash-bound one-time token. A token that is\n // present but invalid is a hard reject — that is an attack signal, not a\n // retry. Absent token falls through to the normal gate.\n const tokenClaimed = typeof params?.hostInitiated === 'string';\n const hostInitiatedOk =\n tokenClaimed &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, 'gh.exec', hashRpcParams(params));\n if (tokenClaimed && !hostInitiatedOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n\n if (!hostInitiatedOk) {\n const destructive = ghDestructiveTarget(args);\n const label = `gh ${args.slice(0, 2).join(' ')}`.trim();\n const ctx = {\n kind: 'confirm' as const,\n message: destructive\n ? `Allow \\`gh ${args.join(' ')}\\` from box ${reg.name}? This destroys a ${destructive}.`\n : `Allow \\`gh ${args.join(' ')}\\` from box ${reg.name}?`,\n detail: args.join(' ').slice(0, 200),\n context: { command: label, cwd: containerPath, argv: args },\n };\n // Destructive ops confirm even when the box carries the auto-approve\n // flag: the flag says \"don't interrupt me for ordinary work\", not\n // \"delete things without asking\".\n if (destructive || reg.autoApproveSafeHostActions === false) {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n ...ctx,\n defaultAnswer: 'n',\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n } else {\n prompts.noteAutoApprove(reg.boxId, ctx, `allow-once: ${label}`);\n }\n }\n\n // A headless `pr create` must never fall back to the host repo's checked-out\n // branch. Injected AFTER token validation, which hashes the incoming params\n // rather than this rewritten argv.\n let finalArgs = args;\n if (family === 'pr') {\n // Rebuild around the ORIGINAL argv so leading global flags (`-R o/r`)\n // survive, and slice the op's tail off the NORMALIZED argv so the verb is\n // not duplicated.\n const head = args.slice(0, args.length - verb.length);\n const rest = injectPrCreateHead(\n op,\n worktree.sanctionedBranch ?? worktree.branch,\n verb.slice(2),\n );\n if (prCreateNeedsHead(op, rest)) return PR_CREATE_NO_HEAD_REFUSAL;\n finalArgs = [...head, family, op, ...rest];\n }\n const run = ghRunContext(worktree.hostMainRepo, reg.originUrl, finalArgs);\n return runHostGh(run.args, run.cwd, { host: ghTarget.host });\n}\n\n/**\n * `tool.list` / `tool.request` / `tool.run`: the generic host-tool proxy.\n *\n * `tool.run`'s gate order is load-bearing, cheapest-and-most-absolute first:\n * 1. worktree resolve — exit 64, nothing to run in\n * 2. grant lookup — exit 65, re-read every call so an approval is live\n * 3. built-in deny list — exit 65, before any prompt or spawn\n * 4. per-tool deny rules — exit 65, layered on top, never replacing (3)\n * 5. allow rules / gate — silent when explicitly allowed or when the box\n * runs with `box.autoApproveSafeHostActions`\n * (default), else a host prompt; deny → exit 10\n * 6. spawn in hostMainRepo — the host's own credentials, buffered, no TTY\n *\n * Every failure returns the same `{exitCode, stdout, stderr}` envelope as the\n * gh handlers, and `host-actions.ts` runs the identical sequence for cloud\n * boxes, per the \"fix across all providers\" rule.\n */\nasync function handleToolRpc(\n method: string,\n reg: BoxRegistration,\n params: Record<string, unknown> | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n): Promise<GitRpcResult> {\n const containerPath = typeof params?.['path'] === 'string' ? params['path'] : '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const cwd = worktree.hostMainRepo;\n\n if (method === 'tool.list') {\n const grants = await loadGrantedTools(cwd);\n const json = params?.['format'] === 'json';\n return {\n exitCode: 0,\n stdout: json ? renderToolListJson(grants.values()) : renderToolList(grants.values()),\n stderr: '',\n };\n }\n\n const name = typeof params?.['name'] === 'string' ? params['name'].trim() : '';\n if (!name || !isValidToolName(name)) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${method}: missing or invalid tool name\\n`,\n };\n }\n\n if (method === 'tool.request') {\n const reason =\n typeof (params as ToolRequestRpcParams | undefined)?.reason === 'string'\n ? String(params?.['reason']).slice(0, 500)\n : '';\n return handleToolRequest(name, reason, reg, cwd, containerPath, prompts, subscribers);\n }\n\n if (method !== 'tool.run') {\n return { exitCode: 64, stdout: '', stderr: `unknown tool method: ${method}\\n` };\n }\n\n const resolved = await resolveToolGrant(name, cwd);\n if ('refusal' in resolved) return resolved.refusal;\n const grant = resolved.grant;\n\n const args = Array.isArray(params?.['args'])\n ? (params['args'] as unknown[]).filter((a): a is string => typeof a === 'string')\n : [];\n\n const credRefusal = refuseCredentialArgv(name, args, grant.bin);\n if (credRefusal) return credRefusal;\n const denyRefusal = refuseDeniedArgv(grant, args);\n if (denyRefusal) return denyRefusal;\n\n const promptEvent = {\n kind: 'confirm' as const,\n message: `Allow \\`${grant.bin} ${args.join(' ')}\\` on the host from box ${reg.name}?`,\n detail: `runs with the host's own ${grant.bin} credentials in ${cwd}`,\n context: { command: `tool ${name}`, cwd: containerPath, argv: args },\n };\n\n if (argvIsExplicitlyAllowed(grant, args)) {\n prompts.noteAutoApprove(reg.boxId, promptEvent, `allow-rule: tool ${name}`);\n } else if (reg.autoApproveSafeHostActions !== false) {\n // The grant itself was the human decision; the per-call prompt is the\n // opt-in stricter mode. Still audited so every host-tool call is visible\n // in the relay event ring buffer.\n prompts.noteAutoApprove(reg.boxId, promptEvent, `safe: tool ${name}`);\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n ...promptEvent,\n defaultAnswer: 'n',\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n\n return runGrantedTool(grant, args, cwd);\n}\n\n/**\n * A box asking for a host CLI it doesn't have. The host PATH probe runs\n * BEFORE the prompt on purpose: the user explicitly wants a box that guesses\n * wrong (`tool request terrafrom`) to get a direct \"not installed\" answer\n * instead of interrupting them with an approval for a binary that could never\n * run. That does let a box learn whether a given binary exists on the host,\n * which is why requests are gated by `tools.request.enabled` and every one is\n * recorded as a relay event.\n */\nasync function handleToolRequest(\n name: string,\n reason: string,\n reg: BoxRegistration,\n cwd: string,\n containerPath: string,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n): Promise<GitRpcResult> {\n if (!(await toolRequestsEnabled(cwd))) {\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n 'host-tool requests are disabled for this project ' +\n '(`agentbox config set --project tools.request.enabled true` to allow them)\\n',\n };\n }\n const existing = await loadGrantedTools(cwd);\n if (existing.has(name)) {\n return { exitCode: 0, stdout: `${name} is already granted\\n`, stderr: '' };\n }\n if (!(await hostToolInstalled(name))) {\n return {\n exitCode: 127,\n stdout: '',\n stderr: `${name} is not installed on the host — nothing to grant\\n`,\n };\n }\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Box ${reg.name} requests access to the host CLI \\`${name}\\`. Grant it?`,\n detail: reason ? `reason: ${reason}` : 'no reason given',\n defaultAnswer: 'n',\n context: { command: `tool request ${name}`, cwd: containerPath, argv: [name] },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n await writeToolGrant(await resolveProjectToolsFile(cwd), {\n name,\n bin: name,\n source: 'request',\n approvedAt: new Date().toISOString(),\n });\n return {\n exitCode: 0,\n stdout: `${name} granted for this project\\n`,\n stderr: '',\n };\n}\n\n/**\n * Park an outbound copy for a machine that is offline. Returns null when there\n * is nothing to park (no custody, nothing pulled, over the cap), in which case\n * the caller reports the plain unreachable error.\n */\nasync function parkOutboundCp(args: {\n params: CpRpcParams | undefined;\n reg: BoxRegistration;\n custody: CustodyStore | null;\n maxBytes: number;\n log: (line: string) => void;\n}): Promise<GitRpcResult | null> {\n const { params, reg, custody, maxBytes, log } = args;\n if (!custody) return null;\n let norm: { sources: string[]; dest: string };\n try {\n norm = normalizeCpParams('cp.toHost', params);\n } catch {\n return null;\n }\n return parkCpOutbox(norm.sources, norm.dest, {\n custody,\n cliEntry: process.env.AGENTBOX_CLI_ENTRY,\n boxId: reg.boxId,\n boxName: reg.name,\n prefix: cpOutboxPrefix({\n projectSlug: reg.originUrl\n ? (projectSlugFromOriginUrl(reg.originUrl) ?? undefined)\n : undefined,\n boxId: reg.boxId,\n }),\n maxBytes,\n log,\n });\n}\n\n/**\n * Whether this machine still has the box's registered workspace on disk — the\n * test for \"are the files here, or on someone else's machine?\".\n *\n * A control box is not automatically the wrong place to run a copy. `agentbox\n * hub expose` turns the user's own laptop into the control box, and there the\n * workspace is right where the record says: parking a copy for a remote machine\n * that does not exist would break a flow that works today. On a VPS control box\n * the same check fails for both shapes that matter — a box created there records\n * the create job's temp clone, which the worker deletes, and a box created on a\n * PC records a path that never existed on the VPS — so those park.\n *\n * Existence rather than a flag, because that is literally the question: `cp`\n * spawns the CLI with this directory as its cwd, and a missing cwd is what\n * produced `spawn <node> ENOENT` on a live control box.\n */\nasync function boxWorkspaceExistsHere(boxId: string): Promise<boolean> {\n try {\n const path = await boxWorkspacePath(boxId);\n return typeof path === 'string' && path.length > 0 && existsSync(path);\n } catch {\n return false;\n }\n}\n\n/**\n * What a box is told when its `cp` could not reach the machine that holds the\n * files. Distinguishes the two ways that happens, because the fixes differ: a\n * machine that never connected needs starting, one that vanished mid-copy needs\n * the copy retried.\n *\n * Exit 69 (EX_UNAVAILABLE) rather than a generic 1, so an agent can tell \"your\n * side is offline, try later\" apart from \"that path is wrong\".\n */\n/**\n * Methods a control box brokers to the machine that owns the box, rather than\n * running itself: the ones whose meaning is \"do this where the user's project\n * lives\". `cp` needs the files; `tool.*` needs the grants (a per-project file on\n * that machine) and the binaries they name.\n */\nfunction isHostReachMethod(method: string): boolean {\n return method === 'cp.toHost' || method === 'cp.fromHost' || method.startsWith('tool.');\n}\n\n/**\n * What a box is told when a host tool could not reach the machine that granted\n * it. Deliberately has no fallback to offer, unlike a cached copy: running a\n * same-named binary from somewhere else is not a degraded answer, it is a\n * different program.\n */\nfunction toolUnreachableMessage(boxName: string, reason: HostReachUnreachable): string {\n const lead =\n reason === 'went-away'\n ? 'the machine that granted these tools stopped responding'\n : 'the machine that granted these tools is not connected to this hub';\n return [\n `host tools are unavailable: ${lead}.`,\n '',\n 'Grants live with the machine that made them, and so do the binaries they name —',\n 'this hub only brokers the call.',\n 'Start AgentBox there (`agentbox relay start`) and retry.',\n `Its grants are listed by \\`agentbox tools list\\` on that machine (box: ${boxName}).`,\n '',\n ].join('\\n');\n}\n\nfunction cpUnreachableMessage(\n method: CpMethod,\n boxName: string,\n reason: HostReachUnreachable,\n opts: { cacheMiss?: boolean } = {},\n): string {\n const direction = method === 'cp.toHost' ? 'to' : 'from';\n const lead =\n reason === 'went-away'\n ? 'the machine holding these files stopped responding part-way through the copy'\n : 'the machine holding these files is not connected to this hub';\n return [\n `cp ${direction} the host could not run: ${lead}.`,\n // Naming BOTH facts matters: \"offline\" alone reads as \"wait and retry\",\n // when the fix for a cold cache is to pre-load the file instead.\n ...(opts.cacheMiss ? ['This hub has no cached copy of those paths either.'] : []),\n '',\n 'This hub brokers the copy; it does not hold your project files.',\n `Start AgentBox on that machine (\\`agentbox relay start\\`) and retry, or run it there directly:`,\n ` agentbox cp ${boxName}:<src> <dst>`,\n ...(opts.cacheMiss\n ? [\n 'To make a file readable with that machine offline, upload it there once:',\n ' agentbox cp <file> hub:',\n ]\n : []),\n '',\n ].join('\\n');\n}\n\n/**\n * Serve a `cp.fromHost` from custody when the owning machine is offline, behind\n * the same approval a live copy gets — parked on this control box, so it can be\n * answered from the web UI or the tray with the laptop shut.\n *\n * Returns null when there is nothing cached (the caller then reports the\n * two-fact error) or when the user declines.\n */\nasync function serveCachedCp(args: {\n params: CpRpcParams | undefined;\n reg: BoxRegistration;\n custody: CustodyStore | null;\n cachePrefix: string;\n prompts: PendingPrompts;\n subscribers: PromptSubscribers;\n log: (line: string) => void;\n}): Promise<GitRpcResult | null> {\n const { params, reg, custody, cachePrefix, prompts, subscribers, log } = args;\n if (!custody) return null;\n let sources: string[];\n try {\n sources = normalizeCpParams('cp.fromHost', params).sources;\n } catch {\n return null;\n }\n // Keyed by the request as the box spelled it — NOT by a path resolved here.\n // This machine's idea of the box's workspace is the create job's temp clone,\n // so resolving would produce a key the owning machine never writes.\n const lookup = await lookupCpCache(sources, { custody, cachePrefix });\n if (lookup.missing.length > 0) return null;\n\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow ${reg.name} to read a CACHED copy of these files?`,\n detail: [\n 'The machine holding them is offline; this hub has an older copy:',\n describeCpCacheEntries(lookup),\n ].join('\\n'),\n defaultAnswer: 'n',\n // Shows the paths the entries were CAPTURED from, not the box's spelling:\n // the user is approving a copy of files on their own disk.\n context: {\n command: 'cp.fromHost (cached)',\n argv: lookup.entries.map((e) => e.meta.sourcePath),\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n return serveCpFromCache(params, sources, {\n custody,\n cliEntry: process.env.AGENTBOX_CLI_ENTRY,\n boxName: reg.name,\n cachePrefix,\n log,\n });\n}\n\n/**\n * cp.toHost / cp.fromHost: copy a file/dir between box and host. Shells\n * out to the installed agentbox CLI's `cp` subcommand — that command\n * already knows how to handle the docker exec tar pipe + chown + auto-\n * unpause; duplicating that here would drift. `AGENTBOX_CLI_ENTRY` is set\n * by `ensureRelay` when it spawns this process.\n *\n * Caller (the /rpc route) already gated this with askPrompt and rejected\n * non-'y' answers; we never reach this code without consent.\n */\nasync function handleCpRpc(cpArgs: string[], cwd?: string): Promise<GitRpcResult> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run cp host-side',\n };\n }\n // Re-shell the installed `agentbox cp` (it owns the tar pipe, excludes, the\n // size guard, and provider routing). `cpArgs` is the fully-built argv from\n // buildCpArgv (box side prefixed with `<name>:`, host paths absolute); `cwd`\n // (the box workspace) makes the host CLI's project-config lookup box-correct.\n const argv = [process.execPath, entry, ...cpArgs];\n return runHostCommand(argv, CP_RPC_TIMEOUT_MS, cwd);\n}\n\n/**\n * download.{workspace,env,config,claude}: ask the installed agentbox CLI\n * to pull box contents to the host. Same decoupling rationale as cp — the\n * CLI owns rsync exclude lists, gitignore handling, claude registry\n * merging. The relay passes `-y` so the host CLI doesn't try to prompt\n * (we already did, via the host wrapper, before reaching this handler).\n */\nasync function handleDownloadRpc(reg: BoxRegistration, kind: DownloadKind): Promise<GitRpcResult> {\n // params.hostPath is reserved in the wire shape; the v1 relay ignores it\n // and lets the host CLI use its defaults (box.workspacePath or ~/.claude).\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run download host-side',\n };\n }\n const argv = [process.execPath, entry, 'download'];\n // `workspace` is the default download (no subcommand); the other three\n // are subcommands of `download`.\n if (kind !== 'workspace') argv.push(kind);\n argv.push(reg.name, '-y');\n // Run from the box's host workspace so the host CLI's project-config lookup\n // is box-correct (the destination already defaults to box.workspacePath).\n const cwd = await boxWorkspacePath(reg.boxId);\n return runHostCommand(argv, DOWNLOAD_RPC_TIMEOUT_MS, cwd);\n}\n\n/**\n * Capture a checkpoint host-side by shelling out to the installed agentbox\n * CLI (same decoupling philosophy as `handleGitRpc` spawning `git`). The\n * relay only knows the box id; the CLI resolves the BoxRecord (project root,\n * checkpoint config, snapshot storage) from it. `AGENTBOX_CLI_ENTRY` is set\n * by `ensureRelay` when it spawns this process.\n */\nasync function handleCheckpointRpc(\n reg: BoxRegistration,\n params: CheckpointRpcParams | undefined,\n): Promise<GitRpcResult> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run checkpoint host-side',\n };\n }\n const argv = [process.execPath, entry, 'checkpoint', 'create', reg.boxId];\n if (params?.name) argv.push('--name', params.name);\n if (params?.merged === true) argv.push('--merged');\n if (params?.setDefault === true) argv.push('--set-default');\n if (params?.replace === true) argv.push('--replace');\n return runHostCommand(argv, CHECKPOINT_RPC_TIMEOUT_MS);\n}\n\n/**\n * Guard for the `browser.open` RPC: only absolute http/https URLs may be\n * handed to the host's `open`. Rejecting every other scheme (`file:`,\n * `javascript:`, bare paths) keeps an in-box agent from opening host files\n * or apps under the guise of \"opening a link\".\n */\nexport function isOpenableUrl(value: string): boolean {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n return url.protocol === 'http:' || url.protocol === 'https:';\n}\n\nfunction runHostCommand(\n argv: string[],\n timeoutMs: number = GIT_RPC_TIMEOUT_MS,\n cwd?: string,\n): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const [cmd, ...rest] = argv;\n if (!cmd) {\n resolve({ exitCode: 64, stdout: '', stderr: 'empty command' });\n return;\n }\n const child = spawn(cmd, rest, {\n env: process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Default to the relay daemon's CWD when unset (legacy behaviour); callers\n // that know the box pass its workspace so relative host paths + project\n // config resolve against the box, not whatever dir launched the relay.\n ...(cwd ? { cwd } : {}),\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n stderr += String(err.message ?? err);\n finish(127);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\nexport async function startRelayServer(opts: RelayServerOptions): Promise<RelayServerHandle> {\n const handle = createRelayServer(opts);\n // Hydrate the in-memory mirror from a durable store before the caller starts\n // the daemon loops, so a control box's registry/statusStore survive a restart\n // (no-op for the MemoryStore laptop path — it has no `hydrate`).\n if (handle.store instanceof WriteThroughStore) await handle.store.hydrate();\n await new Promise<void>((resolve, reject) => {\n handle.server.once('error', reject);\n handle.server.listen(opts.port, opts.host ?? '0.0.0.0', () => {\n handle.server.removeListener('error', reject);\n resolve();\n });\n });\n return handle;\n}\n\nexport type { BoxRegistration, RelayEvent };\n","/**\n * Host-side executor for actions parked by the in-sandbox `box-mode` relay\n * and drained by the `CloudBoxPoller`. This is where the host actually does\n * the work an in-box `agentbox-ctl git push` needs done — with host SSH\n * creds, in the host repo, without ever sending secrets into the box.\n *\n * v0 implements `git.push` and `git.fetch` via the git-bundle pull-back\n * pattern: the in-sandbox `git bundle create` is fetched into a host tmp\n * file, the host repo `git fetch`es the per-box branch from it (always a\n * fast-forward — the per-box branch only ever moves forward), then runs\n * the real `git push origin` / `git fetch origin`. `cp.*`, `download.*`,\n * `checkpoint.create`, `browser.open` are stubbed with a clear \"not yet\n * supported for cloud boxes\" error so the in-box command unblocks instead\n * of hanging. Filling each in is localized to this file.\n */\n\nimport { execa } from 'execa';\nimport { toHttpsUrl } from './git-pat.js';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n isResolvedBranch,\n isScratchBranch,\n isSanctionedPushBranch,\n landRefspec,\n parseDownloadKind,\n realpathSafe,\n remoteTrackingRef,\n resolveHostPath,\n resolveLandDest,\n resolveRemote,\n sanitizeGitArgs,\n upstreamRef,\n} from '@agentbox/core';\nimport type { CloudBackend, CloudHandle, Provider } from '@agentbox/core';\nimport {\n buildAgentDescriptors,\n findBox,\n isSupportedApiVersion,\n pluginForProvider,\n readState,\n} from '@agentbox/sandbox-core';\nimport {\n checkoutGuards,\n ghDestructiveTarget,\n ghRunContext,\n ghVerbArgv,\n injectPrCreateHead,\n PR_CREATE_NO_HEAD_REFUSAL,\n prCreateNeedsHead,\n refuseBlockedGhCall,\n refuseCheckoutByDefault,\n refuseGhApiInput,\n resolveGhTarget,\n runHostGh,\n type GhExecRpcParams,\n} from './gh.js';\nimport { hashRpcParams, type HostInitiatedTokens } from './host-initiated.js';\nimport { buildCpArgv, cpFlags, normalizeCpParams, type CpMethod } from './cp-rpc.js';\nimport { captureCpCacheEntry, type CpCacheCaptureDeps } from './cp-cache-capture.js';\nimport { askPrompt, type PendingPrompts, type PromptSubscribers } from './prompts.js';\nimport {\n isValidToolName,\n loadGrantedTools,\n resolveProjectToolsFile,\n writeToolGrant,\n} from '@agentbox/config';\nimport {\n argvIsExplicitlyAllowed,\n hostToolInstalled,\n refuseCredentialArgv,\n refuseDeniedArgv,\n refuseIfGhDisabled,\n renderToolList,\n renderToolListJson,\n resolveToolGrant,\n runGrantedTool,\n toolRequestsEnabled,\n} from './host-tools.js';\nimport { canAutoApproveTransfer } from './safe-transfer.js';\nimport { recordAgents } from './registration-to-record.js';\nimport { offerBrowserOpen } from './open-link.js';\nimport type {\n CheckpointRpcParams,\n CpRpcParams,\n DownloadRpcParams,\n GitRpcParams,\n HostAction,\n HostActionResult,\n} from './types.js';\n\nexport interface CloudActionExecutorDeps {\n /** From BoxRegistration.backend (e.g. 'daytona'). */\n backendName: string;\n /** From BoxRegistration.boxId. Used to look up the BoxRecord in ~/.agentbox/state.json. */\n boxId: string;\n /** Friendly box name — used in confirm-prompt messages. Falls back to boxId. */\n boxName?: string;\n /** Host relay's pending-prompts queue, for gating destructive ops like git push. */\n prompts?: PendingPrompts;\n /** Host wrapper SSE subscribers — the prompt UX feeds through them. */\n subscribers?: PromptSubscribers;\n /** Host CLI one-time tokens; presence + scope-match skips the confirm prompt. */\n hostInitiatedTokens?: HostInitiatedTokens;\n /**\n * Mirrors `box.autoApproveSafeHostActions` from the registration (default\n * on). When not `false`, the SAFE subset of host actions auto-resolves; only\n * an explicit `false` restores the always-prompt behavior. Undefined is\n * treated as enabled so callers that don't know the flag stay relaxed.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * True when this relay is a control box rather than the human's own machine.\n * `browser.open` reads it: a link must never be opened on the VPS, only\n * handed to an attached surface. See ./open-link.ts.\n */\n controlPlane?: boolean;\n /**\n * The agents the box was created for (`BoxRegistration.agent` / the\n * BoxRecord's `agents`). Gates which `surface: 'service'` agents' units\n * `agents.list` hands the box; undefined ships every agent's (legacy rows).\n */\n boxAgents?: readonly string[];\n /**\n * The box's REGISTERED origin URL (`BoxRegistration.originUrl`). Two uses:\n * pushing from a scratch repo when this host has no working checkout for the\n * box (the control-box case — the create worker's clone is a temp dir it\n * deletes), and picking which GitHub host the `gh` proxy points at\n * (`resolveGhTarget`, for GitHub Enterprise Server repos).\n *\n * It must come from the registration, never from the box: the box could\n * rewrite its own `origin`, and either pushing to an attacker-chosen URL with\n * the host's credential helper attached or aiming the host's authenticated\n * `gh` at an attacker-chosen instance would hand over the token. Same\n * invariant the lease path states in `lease.ts`.\n */\n originUrl?: string;\n /** Best-effort logger. */\n log?: (line: string) => void;\n}\n\n/**\n * Host-side loader for the built-in cloud backends, injected by whichever\n * bundle owns this relay process.\n *\n * ## Why this is injected rather than imported\n *\n * The relay can't depend on the `@agentbox/sandbox-*` packages: that would\n * close a `sandbox-daytona → sandbox-cloud → sandbox-docker → relay` cycle in\n * the package.json deps. It used to reach them with a computed dynamic import\n * (`'@agentbox/sandbox-' + 'daytona'`) on the theory that esbuild would\n * constant-fold and inline the package. It does not — esbuild never bundles\n * `import(pkg)`, so the specifier stayed a runtime `node_modules` lookup. That\n * works in the pnpm dev tree (workspace symlinks) and fails on every npm\n * install, where the `@agentbox/*` packages are devDependencies bundled into\n * the CLI and therefore absent from `node_modules` entirely.\n *\n * So each bundle that hosts a relay registers a loader built from ITS OWN\n * literal-specifier provider map (the maps are already inlined there):\n * - the CLI's spawned relay bin — `AGENTBOX_CLOUD_BACKENDS` points at\n * `apps/cli/dist/cloud-backends.js`, side-loaded lazily in `bin.ts`.\n * - the hub / control box — `apps/hub/server.ts` registers in-process\n * before starting the daemon.\n *\n * `resolveBackend` returns `null` for anything it doesn't own (plugins,\n * `docker`), so the plugin registry stays the single gated path for external\n * providers.\n */\nexport interface CloudBackendLoader {\n /** Stable marker for logs + the build-time wiring check. */\n id?: string;\n /** Resolve a BUILT-IN backend; `null` means \"not mine — keep looking\". */\n resolveBackend(name: string): Promise<CloudBackend | null>;\n /**\n * Resolve a BUILT-IN provider (docker included — it has no cloud backend but\n * is very much a provider). `null` means \"not mine — keep looking\".\n *\n * Optional: a loader written before the persistent-box reconcile existed omits\n * it, and the relay falls back to its own bare-specifier import.\n */\n resolveProvider?(name: string): Promise<Provider | null>;\n /** The `@agentbox/sandbox-cloud` cp helpers used by the download executor. */\n loadCloudCp(): Promise<CloudCpModule>;\n}\n\nlet cloudBackendLoader: CloudBackendLoader | undefined;\n\n/**\n * Register (or clear, with `undefined`) the host's built-in backend loader.\n * Must run before the relay starts serving — `startCloudKeepaliveLoop` caches a\n * failed resolve per backend name for the process lifetime.\n */\nexport function setCloudBackendLoader(loader: CloudBackendLoader | undefined): void {\n cloudBackendLoader = loader;\n cloudCpModule = undefined;\n}\n\n/** The registered loader, for consumers that resolve more than cloud backends. */\nexport function currentCloudBackendLoader(): CloudBackendLoader | undefined {\n return cloudBackendLoader;\n}\n\n/**\n * Lazy backend resolver, in precedence order:\n * 1. the injected loader (built-ins, from the host bundle),\n * 2. the legacy bare-specifier import — only resolves in the pnpm dev tree or\n * for a standalone embedder that installed the packages itself,\n * 3. the plugin registry (external providers, imported by absolute path),\n * 4. throw.\n *\n * Built-ins are tried before plugins in both 1 and 2 so a plugin can never\n * shadow a shipped provider name.\n */\nexport async function resolveCloudBackend(name: string): Promise<CloudBackend> {\n if (cloudBackendLoader) {\n const injected = await cloudBackendLoader.resolveBackend(name);\n if (injected) return injected;\n }\n // Legacy fallback. The `'@agentbox/sandbox-' + '<name>'` specifiers stay\n // computed so esbuild leaves them alone instead of trying (and failing) to\n // inline a package the relay doesn't depend on. Reached only when no loader\n // was injected — i.e. the dev tree or a standalone embedder.\n if (name === 'daytona') {\n const pkg = '@agentbox/sandbox-' + 'daytona';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { daytonaBackend: CloudBackend }).daytonaBackend,\n );\n }\n if (name === 'hetzner') {\n const pkg = '@agentbox/sandbox-' + 'hetzner';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { hetznerBackend: CloudBackend }).hetznerBackend,\n );\n }\n if (name === 'vercel') {\n const pkg = '@agentbox/sandbox-' + 'vercel';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { vercelBackend: CloudBackend }).vercelBackend,\n );\n }\n if (name === 'e2b') {\n const pkg = '@agentbox/sandbox-' + 'e2b';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { e2bBackend: CloudBackend }).e2bBackend,\n );\n }\n if (name === 'digitalocean') {\n const pkg = '@agentbox/sandbox-' + 'digitalocean';\n return loadCloudBackend(\n pkg,\n async () =>\n ((await import(pkg)) as { digitaloceanBackend: CloudBackend }).digitaloceanBackend,\n );\n }\n if (name === 'remote-docker') {\n const pkg = '@agentbox/sandbox-' + 'remote-docker';\n return loadCloudBackend(\n pkg,\n async () =>\n ((await import(pkg)) as { remoteDockerBackend: CloudBackend }).remoteDockerBackend,\n );\n }\n // External provider plugins: not bundle-inlined, so resolve from the same\n // `~/.agentbox/plugins.json` registry the CLI writes and `import()` the\n // recorded entry with a TRUE variable specifier. The relay runs on the host\n // (same ~/.agentbox), so the registry + the installed package are reachable.\n const plugin = pluginForProvider(name);\n if (plugin) {\n if (!isSupportedApiVersion(plugin.apiVersion)) {\n throw new Error(\n `relay: plugin '${plugin.packageName}' targets provider SDK v${String(plugin.apiVersion)}, which this AgentBox does not support`,\n );\n }\n return loadCloudBackend(plugin.packageName, async () => {\n const mod = (await import(pathToFileURL(plugin.resolvedEntry).href)) as {\n providerModule?: { provider?: { name?: string }; backend?: CloudBackend };\n providerModules?: { provider?: { name?: string }; backend?: CloudBackend }[];\n };\n const all = mod.providerModules ?? (mod.providerModule ? [mod.providerModule] : []);\n // Strict name match — never fall back to all[0] (wrong-backend hazard).\n const pm = all.find((m) => m.provider?.name === name);\n if (!pm?.backend) {\n throw new Error(`plugin '${plugin.packageName}' exposes no cloud backend for '${name}'`);\n }\n return pm.backend;\n });\n }\n throw new Error(`no host executor for cloud backend '${name}'`);\n}\n\n/**\n * True for \"the module isn't installed\" failures. The `code` check is the\n * durable one: Node's ESM resolver says `Cannot find package 'x' imported from\n * y` (ERR_MODULE_NOT_FOUND) while CJS says `Cannot find module` — matching only\n * the CJS wording let the raw ESM error through untranslated.\n */\nexport function isModuleNotFound(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code;\n if (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND') return true;\n const msg = err instanceof Error ? err.message : String(err);\n return /cannot find (module|package)|MODULE_NOT_FOUND/i.test(msg);\n}\n\n/**\n * Run a provider's dynamic import, turning a missing-module failure into the\n * actionable \"no loader was injected\" error (other errors propagate unchanged).\n * Shared by every branch of `resolveCloudBackend`'s legacy fallback.\n */\nasync function loadCloudBackend(\n pkg: string,\n load: () => Promise<CloudBackend>,\n): Promise<CloudBackend> {\n try {\n return await load();\n } catch (err) {\n if (isModuleNotFound(err)) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `relay: cannot load '${pkg}' at runtime — no cloud-backend loader was injected and the package is not installed next to @agentbox/relay (the @madarco/agentbox CLI injects one via AGENTBOX_CLOUD_BACKENDS; the hub registers one in-process). Original: ${msg}`,\n );\n }\n throw err;\n }\n}\n\n/**\n * Re-mint the preview URL for a cloud box's `port` after a transport-level\n * failure (the host CloudBoxPoller saw ECONNREFUSED on the local port).\n * Hetzner reopens its SSH ControlMaster + `-L` forward; Daytona's permanent\n * CloudFront alias doesn't need refresh and this returns null.\n *\n * Takes the agentbox `boxId` (the one the relay knows), resolves it to the\n * backend's sandboxId via `~/.agentbox/state.json` the same way\n * `executeCloudAction` does, then asks the backend to refresh.\n *\n * Best-effort: any error during resolve/refresh returns null and the\n * poller stays on the (broken) URL — the next poll will trip the same\n * recovery hook on the next ECONNREFUSED. Throwing here would crash the\n * poller; we'd rather keep retrying.\n */\nexport async function refreshCloudPreviewUrl(\n backendName: string,\n boxId: string,\n port: number,\n): Promise<string | null> {\n try {\n const backend = await resolveCloudBackend(backendName);\n if (!backend.refreshPreviewUrl) return null;\n const lookup = await lookupCloudBox(boxId);\n const handle: CloudHandle = cloudHandleOf(lookup);\n const url = await backend.refreshPreviewUrl(handle, port);\n return url.url;\n } catch {\n return null;\n }\n}\n\nexport async function executeCloudAction(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const log = deps.log ?? (() => {});\n log(`executing ${action.method} for box ${deps.boxId}`);\n\n // Cloud twin of the host-relay `agents.list` handler. A cloud box's RPCs are\n // parked on the HostActionQueue and drained here, so a method handled only in\n // server.ts works on docker and silently fails on every cloud provider.\n // Read-only and unprompted, like tool.list — and NOT worktree-scoped, since\n // the agent registry is machine-global.\n if (action.method === 'agents.list') {\n return {\n exitCode: 0,\n stdout: JSON.stringify(buildAgentDescriptors({ boxAgents: deps.boxAgents })),\n stderr: '',\n };\n }\n if (action.method === 'git.push' || action.method === 'git.fetch') {\n return runGitRpc(action, deps);\n }\n if (action.method === 'cp.toHost' || action.method === 'cp.fromHost') {\n return runCpRpc(action, deps);\n }\n if (\n action.method === 'download.workspace' ||\n action.method === 'download.env' ||\n action.method === 'download.config' ||\n action.method === 'download.claude'\n ) {\n return runDownloadRpc(action, deps);\n }\n if (action.method === 'checkpoint.create') {\n return runCheckpointRpc(action, deps);\n }\n if (action.method === 'browser.open.mirror') {\n return runBrowserOpenMirror(action, deps);\n }\n if (action.method === 'gh.exec') {\n return runGhExecRpc(action, deps);\n }\n if (action.method.startsWith('tool.')) {\n return runToolRpc(action, deps);\n }\n if (action.method === 'git.clone' || action.method === 'gh.repo.clone') {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${action.method}: not yet implemented for this box. Run \\`gh\\` / \\`git\\` on the host directly for now.\\n`,\n };\n }\n return {\n exitCode: 1,\n stdout: '',\n stderr: `host executor for '${action.method}' is not yet supported for cloud boxes\\n`,\n };\n}\n\n/**\n * Cloud-side confirm gate for a write op. Mirrors the prompt / no-subscriber\n * handling in `runGhPrRpc` (`AGENTBOX_GH_NO_SUB` deny/allow/prompt). Returns a\n * ready-to-send denial `HostActionResult` to abort, or `null` to proceed.\n */\nasync function cloudWriteConfirm(\n deps: CloudActionExecutorDeps,\n command: string,\n cwd: string | undefined,\n args: string[],\n): Promise<HostActionResult | null> {\n if (!deps.prompts || !deps.subscribers) return null;\n const ctx = {\n kind: 'confirm' as const,\n message: `Allow ${command} from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail: args.join(' ').slice(0, 200),\n defaultAnswer: 'n' as const,\n context: { command, cwd, argv: args },\n };\n const hasSubscriber = deps.subscribers.count(deps.boxId) > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.(`${command} auto-approved (no subscribers, AGENTBOX_GH_NO_SUB=allow)`);\n return null;\n }\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx, {\n ttlMs: 5 * 60 * 1000,\n });\n return verdict.answer === 'y' ? null : { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx);\n return verdict.answer === 'y' ? null : { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n}\n\n/**\n * Cloud `gh.exec`. Mirrors `handleGhExecRpc` in server.ts step for step —\n * same blocklist, same destructive-confirm set, same allow-once default — so\n * `gh` behaves identically whichever provider the box runs on. The only\n * difference is the confirm helper: cloud goes through `cloudWriteConfirm`,\n * which carries the no-subscriber fallback every gated cloud action shares.\n */\nasync function runGhExecRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as GhExecRpcParams;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n if (args.length === 0) {\n return { exitCode: 64, stdout: '', stderr: 'gh: no arguments\\n' };\n }\n\n const blocked = refuseBlockedGhCall(args);\n if (blocked) return blocked;\n\n const verb = ghVerbArgv(args);\n const family = verb[0] ?? '';\n const op = verb[1] ?? '';\n if (family === 'pr') {\n const checkoutOptIn = refuseCheckoutByDefault(op);\n if (checkoutOptIn) return checkoutOptIn;\n }\n if (family === 'api') {\n const inputRefusal = refuseGhApiInput(args);\n if (inputRefusal) return inputRefusal;\n }\n\n const ghTarget = await resolveGhTarget(deps.originUrl);\n if (ghTarget.error) return ghTarget.error;\n const lookup = await lookupCloudBox(deps.boxId);\n\n const ghRevoked = await refuseIfGhDisabled(lookup.workspacePath);\n if (ghRevoked) return ghRevoked;\n\n if (family === 'pr' && op === 'checkout') {\n // Same guard the docker path applies: never check the host repo out onto\n // a branch a box occupies, and never over a dirty tree.\n const branches = lookup.sanctionedBranch ? [lookup.sanctionedBranch] : [];\n const guard = await checkoutGuards(lookup.workspacePath, branches);\n if (guard) return guard;\n }\n\n // Host-initiated calls carry a scope- and params-hash-bound one-time token.\n // A present-but-invalid token is a hard reject — an attack signal, not a\n // retry — and this must hold on cloud too, not just docker.\n const tokenClaimed = typeof params.hostInitiated === 'string';\n const hostInitiatedOk =\n tokenClaimed &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n 'gh.exec',\n hashRpcParams(params),\n ) ??\n false);\n if (tokenClaimed && !hostInitiatedOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n\n const destructive = ghDestructiveTarget(args);\n if (!hostInitiatedOk && (destructive || deps.autoApproveSafeHostActions === false)) {\n const label = destructive\n ? `gh ${args.slice(0, 2).join(' ')} (destroys a ${destructive})`\n : `gh ${args.slice(0, 2).join(' ')}`;\n const denied = await cloudWriteConfirm(deps, label.trim(), params.path, [...args]);\n if (denied) return denied;\n }\n\n let finalArgs = args;\n if (family === 'pr') {\n const head = args.slice(0, args.length - verb.length);\n const rest = injectPrCreateHead(op, lookup.sanctionedBranch, verb.slice(2));\n if (prCreateNeedsHead(op, rest)) return PR_CREATE_NO_HEAD_REFUSAL;\n finalArgs = [...head, family, op, ...rest];\n }\n const run = ghRunContext(lookup.workspacePath, deps.originUrl, finalArgs);\n return runHostGh(run.args, run.cwd, { host: ghTarget.host });\n}\n\n/**\n * Cloud `tool.*` executor. Mirrors `handleToolRpc` in server.ts step for\n * step — same grant lookup, same built-in credential deny list, same\n * per-tool rules, same gate — so a host tool behaves identically whichever\n * provider the box runs on. The only difference is the confirm helper:\n * cloud goes through `cloudWriteConfirm`, which carries the no-subscriber\n * fallback every gated cloud action shares.\n */\nasync function runToolRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as Record<string, unknown>;\n const containerPath = typeof params['path'] === 'string' ? params['path'] : '/workspace';\n const lookup = await lookupCloudBox(deps.boxId);\n const cwd = lookup.workspacePath;\n\n if (action.method === 'tool.list') {\n const grants = await loadGrantedTools(cwd);\n const json = params['format'] === 'json';\n return {\n exitCode: 0,\n stdout: json ? renderToolListJson(grants.values()) : renderToolList(grants.values()),\n stderr: '',\n };\n }\n\n const name = typeof params['name'] === 'string' ? params['name'].trim() : '';\n if (!name || !isValidToolName(name)) {\n return { exitCode: 64, stdout: '', stderr: `${action.method}: missing or invalid tool name\\n` };\n }\n\n if (action.method === 'tool.request') {\n if (!(await toolRequestsEnabled(cwd))) {\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n 'host-tool requests are disabled for this project ' +\n '(`agentbox config set --project tools.request.enabled true` to allow them)\\n',\n };\n }\n const existing = await loadGrantedTools(cwd);\n if (existing.has(name)) {\n return { exitCode: 0, stdout: `${name} is already granted\\n`, stderr: '' };\n }\n if (!(await hostToolInstalled(name))) {\n return {\n exitCode: 127,\n stdout: '',\n stderr: `${name} is not installed on the host — nothing to grant\\n`,\n };\n }\n const reason = typeof params['reason'] === 'string' ? params['reason'].slice(0, 500) : '';\n const denied = await cloudWriteConfirm(\n deps,\n `tool request ${name}`,\n containerPath,\n reason ? [name, `reason: ${reason}`] : [name],\n );\n if (denied) return denied;\n await writeToolGrant(await resolveProjectToolsFile(cwd), {\n name,\n bin: name,\n source: 'request',\n approvedAt: new Date().toISOString(),\n });\n return { exitCode: 0, stdout: `${name} granted for this project\\n`, stderr: '' };\n }\n\n if (action.method !== 'tool.run') {\n return { exitCode: 64, stdout: '', stderr: `unknown tool method: ${action.method}\\n` };\n }\n\n const resolved = await resolveToolGrant(name, cwd);\n if ('refusal' in resolved) return resolved.refusal;\n const grant = resolved.grant;\n\n const args = Array.isArray(params['args'])\n ? (params['args'] as unknown[]).filter((a): a is string => typeof a === 'string')\n : [];\n\n const credRefusal = refuseCredentialArgv(name, args, grant.bin);\n if (credRefusal) return credRefusal;\n const denyRefusal = refuseDeniedArgv(grant, args);\n if (denyRefusal) return denyRefusal;\n\n const silent = argvIsExplicitlyAllowed(grant, args) || deps.autoApproveSafeHostActions !== false;\n if (!silent) {\n const denied = await cloudWriteConfirm(deps, `tool ${name}`, containerPath, [...args]);\n if (denied) return denied;\n }\n\n return runGrantedTool(grant, args, cwd);\n}\n\n/**\n * Mirror an in-box `browser.open` notification on the human's machine. Part of\n * the safe host-action subset (`box.autoApproveSafeHostActions`), so no human\n * approves it; `offerBrowserOpen` decides whether it opens here or is handed to\n * an attached surface (footer / dashboard / tray / hub web), and the budget is\n * what keeps a looping agent from spraying tabs.\n *\n * The action runs detached from the box's `/rpc` (the in-box handler responded\n * 200 long before queuing this), so waiting for a surface to claim it ties up\n * no agent. Always resolves exit 0 because the box doesn't observe the result.\n */\nasync function runBrowserOpenMirror(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as { url?: string };\n const url = typeof params.url === 'string' ? params.url.trim() : '';\n if (!url || !/^https?:\\/\\//i.test(url)) {\n return { exitCode: 0, stdout: '', stderr: '' };\n }\n if (!deps.prompts || !deps.subscribers) return { exitCode: 0, stdout: '', stderr: '' };\n if (process.env['AGENTBOX_PROMPT'] === 'off') {\n return { exitCode: 0, stdout: '', stderr: '' };\n }\n try {\n await offerBrowserOpen(\n {\n prompts: deps.prompts,\n subscribers: deps.subscribers,\n boxId: deps.boxId,\n boxName: deps.boxName,\n autoApproveSafe: deps.autoApproveSafeHostActions !== false,\n controlPlane: deps.controlPlane === true,\n log: deps.log,\n },\n url,\n );\n } catch (err) {\n deps.log?.(`browser.open.mirror failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n return { exitCode: 0, stdout: '', stderr: '' };\n}\n\ninterface BoxLookup {\n workspacePath: string;\n cloudSandboxId: string;\n /**\n * Provider-specific sandbox class, when the record carries one. Daytona's\n * exec wrap keys on it: a handle without it is treated as a `linux-vm` and\n * every command gets `sudo -u vscode`, which a `container` sandbox — already\n * running as vscode — refuses (\"user vscode is not allowed to execute … as\n * vscode\"), so `agentbox-ctl git push` failed to even resolve the branch.\n */\n sandboxClass?: string;\n /**\n * Branch the host has sanctioned for this box's pushes (defaults to the\n * create-time `workspaceBranch`). The push gate auto-approves a push only to\n * a scratch branch or this value.\n */\n sanctionedBranch?: string;\n}\n\n/** The backend handle for a looked-up box — id plus the class the exec wrap needs. */\nexport function cloudHandleOf(\n lookup: Pick<BoxLookup, 'cloudSandboxId' | 'sandboxClass'>,\n): CloudHandle {\n return {\n sandboxId: lookup.cloudSandboxId,\n ...(lookup.sandboxClass ? { sandboxClass: lookup.sandboxClass } : {}),\n };\n}\n\nasync function lookupCloudBox(boxId: string): Promise<BoxLookup> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok') {\n throw new Error(`box ${boxId} not in ~/.agentbox/state.json`);\n }\n const sid = hit.box.cloud?.sandboxId;\n if (!sid) {\n throw new Error(`box ${boxId} has no cloud.sandboxId — record is malformed`);\n }\n return {\n workspacePath: hit.box.workspacePath,\n cloudSandboxId: sid,\n ...(hit.box.cloud?.sandboxClass ? { sandboxClass: hit.box.cloud.sandboxClass } : {}),\n sanctionedBranch: hit.box.cloud?.sanctionedBranch ?? hit.box.cloud?.workspaceBranch,\n };\n}\n\n/**\n * Cache every host source a just-completed `cp.fromHost` read, under `prefix`.\n *\n * Lives here because resolving \"what did that copy actually read?\" is this\n * module's job: the box sends paths relative to its own project, and only the\n * machine holding that project can turn them into absolute ones — the same\n * resolution `runCpRpc` just did. Re-deriving it (rather than having the copy\n * report its sources back) keeps one definition of the source set.\n */\nexport async function cacheCpSources(\n action: HostAction,\n prefix: string,\n deps: CpCacheCaptureDeps,\n): Promise<void> {\n try {\n const { sources } = normalizeCpParams('cp.fromHost', action.params as CpRpcParams | undefined);\n const workspacePath = await boxWorkspacePath(action.boxId);\n for (const src of sources) {\n // Tar the resolved file; key it by what the box asked for, which is the\n // only spelling the control box can reproduce when it later looks it up.\n await captureCpCacheEntry(resolveHostPath(workspacePath, src), prefix, deps, src);\n }\n } catch (err) {\n deps.logger?.(\n `cp cache: nothing stored for ${action.boxId}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\n/**\n * What this machine knows about a box it owns a record for. Deliberately not\n * `originUrl`: that lives on the *registration* (never the record) precisely so\n * a box can't nominate its own push target, and no cp path needs it.\n */\nexport interface CloudBoxOwner {\n name: string;\n /** `cloud.backend` — which provider's executor the action needs. */\n backendName: string;\n autoApproveSafeHostActions?: boolean;\n /** The agents the box runs, for the `agents.list` unit gate. */\n agents?: readonly string[];\n}\n\n/**\n * Resolve a box from THIS machine's `~/.agentbox/state.json`, for the host-reach\n * poller: a control box hands over an action by box id, and only the machine\n * that actually has the box's record (and therefore its project checkout) can\n * carry it out.\n *\n * Null rather than throwing when the box is unknown — an un-adopted box is an\n * ordinary state the caller answers with instructions, not a failure.\n */\nexport async function lookupCloudBoxOwner(boxId: string): Promise<CloudBoxOwner | null> {\n try {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok') return null;\n const backendName = hit.box.cloud?.backend ?? hit.box.provider;\n if (!backendName) return null;\n return {\n name: hit.box.name,\n backendName,\n autoApproveSafeHostActions: hit.box.autoApproveSafeHostActions,\n agents: recordAgents(hit.box),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * The box's registered host workspace (the host dir that mirrors `/workspace`),\n * used as the base for resolving relative host paths in `cp`/`download` RPCs.\n * Returns `undefined` when the box isn't in state. Shared by the docker\n * (server.ts) and cloud handlers so a relative host path never silently\n * resolves against the long-lived relay daemon's CWD (which is arbitrary — one\n * relay serves many boxes/projects).\n */\nexport async function boxWorkspacePath(boxId: string): Promise<string | undefined> {\n const state = await readState();\n const hit = findBox(boxId, state);\n return hit.kind === 'ok' ? hit.box.workspacePath : undefined;\n}\n\n/**\n * The realpath'd host source paths this box already approved via its `carry:`\n * block, so the cp auto-approve gate can exempt a secret file that the user\n * already consented to copy in at create time. Best-effort: empty set on any\n * read failure (→ secret files fall back to prompting). Shared by the docker\n * and cloud cp handlers.\n */\nexport async function boxCarriedHostPaths(boxId: string): Promise<Set<string>> {\n const out = new Set<string>();\n try {\n const state = await readState();\n const hit = findBox(boxId, state);\n const entries = hit.kind === 'ok' ? hit.box.carry?.entries : undefined;\n for (const e of entries ?? []) out.add(await realpathSafe(e.src));\n } catch {\n /* best-effort */\n }\n return out;\n}\n\n// resolveHostPath's pure decision moved to `@agentbox/core`'s sync/files.ts.\n// Re-exported here so `server.ts` (and the cp/download call sites below) keep\n// importing it from `./host-actions.js` unchanged.\nexport { resolveHostPath };\n\n/**\n * The `@agentbox/sandbox-cloud` cp helpers the download executor needs. Kept\n * out of the relay bundle for the same dependency-cycle reason as the provider\n * backends — the injected `CloudBackendLoader` supplies them; the computed\n * specifier below is the same dev-tree-only fallback.\n */\nexport interface CloudCpModule {\n pullCloudDirContents(\n backend: CloudBackend,\n handle: CloudHandle,\n boxSrc: string,\n hostDst: string,\n ): Promise<{ finalPath: string }>;\n}\n\nlet cloudCpModule: CloudCpModule | undefined;\nasync function loadCloudCp(): Promise<CloudCpModule> {\n if (cloudCpModule) return cloudCpModule;\n if (cloudBackendLoader) {\n cloudCpModule = await cloudBackendLoader.loadCloudCp();\n return cloudCpModule;\n }\n // Legacy fallback — see resolveCloudBackend.\n const pkg = '@agentbox/sandbox-' + 'cloud';\n try {\n const mod = (await import(pkg)) as CloudCpModule;\n cloudCpModule = mod;\n return mod;\n } catch (err) {\n if (isModuleNotFound(err)) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `relay: cannot load '${pkg}' at runtime — no cloud-backend loader was injected and the package is not installed next to @agentbox/relay (the @madarco/agentbox CLI injects one via AGENTBOX_CLOUD_BACKENDS; the hub registers one in-process). Original: ${msg}`,\n );\n }\n throw err;\n }\n}\n\nasync function runCpRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const method = action.method as CpMethod;\n const params = (action.params ?? {}) as CpRpcParams;\n let norm: { sources: string[]; dest: string };\n try {\n norm = normalizeCpParams(method, params);\n } catch (err) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run cp host-side\\n',\n };\n }\n const direction = method === 'cp.toHost' ? 'box -> host' : 'host -> box';\n // Resolve host paths against THIS box's workspace so a relative path doesn't\n // land under the relay daemon's CWD (which belongs to whichever project\n // started the relay), and so the consent prompt shows the real destination.\n const lookup = await lookupCloudBox(deps.boxId);\n const boxName = deps.boxName ?? deps.boxId;\n const {\n argv: cpArgs,\n detail,\n contextArgv,\n } = buildCpArgv({\n method,\n boxName,\n sources: norm.sources,\n dest: norm.dest,\n resolveHost: (p) => resolveHostPath(lookup.workspacePath, p),\n flags: cpFlags(params),\n });\n // Same askPrompt UX as docker's /rpc handler — keeps the in-box agent from\n // pulling host files / scattering box files without explicit consent. A\n // transfer contained in the box project folder (non-secret for host->box)\n // auto-approves under the safe flag, mirroring the docker handler.\n const cpHostPaths =\n method === 'cp.toHost'\n ? [resolveHostPath(lookup.workspacePath, norm.dest)]\n : norm.sources.map((s) => resolveHostPath(lookup.workspacePath, s));\n const cpAuto = await canAutoApproveTransfer({\n enabled: deps.autoApproveSafeHostActions !== false,\n workspacePath: lookup.workspacePath,\n hostPaths: cpHostPaths,\n checkSecret: method === 'cp.fromHost',\n carried: method === 'cp.fromHost' ? await boxCarriedHostPaths(deps.boxId) : undefined,\n });\n if (cpAuto) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `cp (${direction}) on ${boxName}`,\n detail,\n context: { command: method, argv: contextArgv },\n },\n method === 'cp.toHost' ? 'safe: contained copy to host' : 'safe: contained copy from host',\n );\n } else if (deps.prompts && deps.subscribers) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow cp (${direction}) on ${boxName}?`,\n detail,\n defaultAnswer: 'n',\n context: { command: method, argv: contextArgv },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n // Converge on the docker path: re-shell the installed `agentbox cp`. Its\n // `isCloud` branch routes to the cloud provider's uploadPath/downloadPath, so\n // excludes, the size guard, and provider routing are honored identically to a\n // host-typed `agentbox cp` (the old direct-primitive path silently dropped\n // them). cwd = the box workspace makes project-config lookup box-correct.\n const argv = [process.execPath, entry, ...cpArgs];\n const result = await execa(argv[0]!, argv.slice(1), {\n reject: false,\n cwd: lookup.workspacePath,\n });\n return {\n exitCode: result.exitCode ?? 1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\n/**\n * Capture a checkpoint by shelling out to the installed `agentbox` CLI\n * (same decoupling as the docker handler — the CLI owns checkpoint name\n * allocation, the `--set-default` config write, snapshot store layout, and\n * the cloud-snapshot creation via `provider.checkpoint.create`). The CLI's\n * `checkpoint create` is already provider-aware, so this path works for\n * both backends; we just hand it the box id.\n */\nasync function runCheckpointRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as Partial<CheckpointRpcParams>;\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run checkpoint host-side\\n',\n };\n }\n // Vercel checkpoints stop + reboot the box: `sb.snapshot()` powers off the\n // microVM (resume is lazy on the next SDK call). When an interactive wrapper\n // is attached, warn + require confirmation before we yank the box out from\n // under it. Other backends snapshot without stopping (docker `docker commit`,\n // hetzner no-pause, daytona), so they stay prompt-free. No attached wrapper →\n // proceed (a headless caller already knows the box will reboot).\n if (\n deps.backendName === 'vercel' &&\n deps.autoApproveSafeHostActions === false &&\n deps.prompts &&\n deps.subscribers &&\n deps.subscribers.count(deps.boxId) > 0\n ) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Create checkpoint on ${deps.boxName ?? deps.boxId}? The vercel box will stop and reboot.`,\n detail: params.name ? `checkpoint: ${params.name}` : '(auto-named)',\n defaultAnswer: 'n',\n context: { command: 'checkpoint create', argv: params.name ? [params.name] : [] },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'checkpoint denied by user\\n' };\n }\n } else if (\n deps.backendName === 'vercel' &&\n deps.subscribers &&\n deps.subscribers.count(deps.boxId) > 0\n ) {\n // Checkpoint is a safe subset op (the box's own snapshot); audit the\n // reboot-causing auto-approval so it's still visible in the event feed.\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `checkpoint create on ${deps.boxName ?? deps.boxId} (vercel box will stop and reboot)`,\n detail: params.name ? `checkpoint: ${params.name}` : '(auto-named)',\n context: { command: 'checkpoint create', argv: params.name ? [params.name] : [] },\n },\n 'safe: checkpoint create',\n );\n }\n\n const argv = [process.execPath, entry, 'checkpoint', 'create', deps.boxId];\n if (params.name) argv.push('--name', params.name);\n // --merged is docker-image-layer specific (flatten). For cloud snapshots\n // it's a no-op; pass it through anyway so the CLI's docker branch sees it\n // and the cloud branch ignores it cleanly.\n if (params.merged === true) argv.push('--merged');\n if (params.setDefault === true) argv.push('--set-default');\n if (params.replace === true) argv.push('--replace');\n const result = await execa(argv[0]!, argv.slice(1), { reject: false });\n return {\n exitCode: result.exitCode ?? 1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\nasync function runDownloadRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as Partial<DownloadRpcParams>;\n const kind = parseDownloadKind(action.method);\n // Only `workspace` lands cleanly on cloud today — env/config/claude live in\n // per-agent volumes and aren't routed yet (Phase 6 follow-up; see backlog\n // 2.2). Surface a clear error instead of pretending to succeed.\n if (kind !== 'workspace') {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `download.${kind} is not yet supported for cloud boxes (only download.workspace is)\\n`,\n };\n }\n const lookup = await lookupCloudBox(deps.boxId);\n // params.hostPath is reserved in the wire shape; v1 lands /workspace under\n // box.workspacePath (the host project root), matching docker's default. A\n // relative override resolves against the box workspace, not the relay's CWD.\n const hostDst =\n typeof params.hostPath === 'string' && params.hostPath.length > 0\n ? resolveHostPath(lookup.workspacePath, params.hostPath)\n : lookup.workspacePath;\n // Auto-approve when the destination stays inside the box project folder\n // (the default does); an escaping override still prompts.\n const dlAuto = await canAutoApproveTransfer({\n enabled: deps.autoApproveSafeHostActions !== false,\n workspacePath: lookup.workspacePath,\n hostPaths: [hostDst],\n checkSecret: false,\n });\n if (dlAuto) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `download (${kind}) from ${deps.boxName ?? deps.boxId}`,\n detail: params.hostPath ?? '(default host location)',\n context: { command: action.method, argv: params.hostPath ? [params.hostPath] : [] },\n },\n 'safe: contained download',\n );\n } else if (deps.prompts && deps.subscribers) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow download (${kind}) from ${deps.boxName ?? deps.boxId}?`,\n detail: params.hostPath ?? '(default host location)',\n defaultAnswer: 'n',\n context: {\n command: action.method,\n argv: params.hostPath ? [params.hostPath] : [],\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n const backend = await resolveCloudBackend(deps.backendName);\n const handle: CloudHandle = cloudHandleOf(lookup);\n const cp = await loadCloudCp();\n try {\n const result = await cp.pullCloudDirContents(backend, handle, '/workspace', hostDst);\n return { exitCode: 0, stdout: `${result.finalPath}\\n`, stderr: '' };\n } catch (err) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `download failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n}\n\n/**\n * Git RPC executor for cloud boxes. The push direction:\n *\n * 1. In the sandbox, write a bundle of the per-box branch.\n * 2. Download the bundle to the host.\n * 3. Fetch the bundle ref into the host repo (always a fast-forward).\n * 4. Run the real git push from the host repo.\n *\n * Fetch direction is the mirror: host fetches origin, bundles, uploads,\n * sandbox fetches from the bundle, in-box `agentbox-ctl git pull` then\n * does its local merge as today.\n */\n/**\n * Where the host runs its half of a git RPC, and what it pushes to.\n *\n * On a laptop this is the user's real checkout: `dir` is the working copy and\n * `remote` is whatever `origin` resolves to there. On a **control box** there is\n * no checkout at all — the create worker clones into a temp dir and deletes it\n * in a `finally` — so `dir` is a throwaway repo we initialize per call and\n * `remote` is the registered origin URL.\n *\n * A scratch repo is enough because `git bundle create <file> <branch>` is\n * self-contained: it carries the branch's full history with no prerequisites, so\n * unbundling into an empty repo yields a pushable ref. Nothing needs to persist\n * between pushes, which is why the hub keeps no per-project clones.\n */\nexport interface HostGitRepo {\n dir: string;\n /** Explicit push target — a URL for scratch repos, else the caller's remote name. */\n remote: string;\n scratch: boolean;\n cleanup: () => Promise<void>;\n}\n\n/**\n * The push URL a scratch (checkout-less) host repo should use. SSH/scp remotes\n * are rewritten to plain HTTPS; anything already HTTPS — or any URL shape\n * `toHttpsUrl` can't parse — is passed through untouched, so an unusual remote\n * fails at git with its own message instead of here.\n */\nfunction httpsOriginForScratchPush(origin: string): string {\n if (/^https?:\\/\\//i.test(origin)) return origin;\n try {\n return toHttpsUrl(origin);\n } catch {\n return origin;\n }\n}\n\nexport async function resolveHostGitRepo(\n workspacePath: string,\n deps: CloudActionExecutorDeps,\n remoteName: string,\n): Promise<HostGitRepo> {\n if (workspacePath.length > 0 && existsSync(workspacePath)) {\n return {\n dir: workspacePath,\n remote: remoteName,\n scratch: false,\n cleanup: () => Promise.resolve(),\n };\n }\n // No host checkout. Only the REGISTERED origin can be trusted as a push\n // target — see the `originUrl` doc on CloudActionExecutorDeps.\n const rawOrigin = deps.originUrl?.trim() ?? '';\n if (rawOrigin.length === 0) {\n throw new Error(\n `host-side git is unavailable for box ${deps.boxId}: its host repo (${workspacePath || '<unset>'}) does not exist ` +\n `and the box has no registered origin URL to push to. Adopt the box on a host with a checkout, or re-register it.`,\n );\n }\n // A checkout-less host is a control box, which authenticates git through a\n // credential helper (`hub.gitAuth=gh`) or an App token — never an SSH key. An\n // scp-form `git@github.com:owner/repo` origin therefore dies at host-key\n // verification before auth is ever consulted, so rewrite it to the HTTPS URL\n // the helper covers. Mirrors the create worker's clone (`hub-worker.ts`),\n // which has always done this — without it the clone side works and the push\n // side fails for every SSH-origin project.\n const origin = httpsOriginForScratchPush(rawOrigin);\n const dir = await mkdtemp(join(tmpdir(), 'agentbox-git-scratch-'));\n const init = await execa('git', ['-C', dir, 'init', '--quiet'], { reject: false });\n if ((init.exitCode ?? 1) !== 0) {\n await rm(dir, { recursive: true, force: true });\n throw new Error(`could not initialize a scratch git repo: ${init.stderr ?? ''}`);\n }\n return {\n dir,\n remote: origin,\n scratch: true,\n cleanup: () => rm(dir, { recursive: true, force: true }),\n };\n}\n\nasync function runGitRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as GitRpcParams;\n const lookup = await lookupCloudBox(deps.boxId);\n const backend = await resolveCloudBackend(deps.backendName);\n const handle: CloudHandle = cloudHandleOf(lookup);\n\n // The in-box ctl sends `params.path = process.cwd()`. When the user runs\n // `agentbox-ctl git push` from anywhere outside /workspace (e.g. $HOME),\n // that path won't be a git repo and `git rev-parse` would fail. Fall back\n // to /workspace whenever the supplied path can't resolve a git dir — the\n // per-box branch only ever lives at /workspace anyway.\n let containerPath = params.path ?? '/workspace';\n if (containerPath !== '/workspace') {\n const probe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --git-dir`,\n );\n if (probe.exitCode !== 0) containerPath = '/workspace';\n }\n\n // 1. Resolve the box's current branch (the per-box `agentbox/<name>`).\n const branchProbe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --abbrev-ref HEAD`,\n );\n const branch = (branchProbe.stdout ?? '').trim();\n if (branchProbe.exitCode !== 0 || !isResolvedBranch(branch)) {\n return {\n exitCode: branchProbe.exitCode || 1,\n stdout: '',\n stderr: `failed to resolve branch in sandbox ${containerPath}: ${branchProbe.stderr || branch}`,\n };\n }\n\n // Host-only landing: copy the box's branch into the host's *local* repo\n // (no remote push, nothing published). This is the push flow's bundle\n // pull-back steps without the final `git push` — so it skips the confirm\n // gate below entirely. Destination defaults to the box's branch name.\n if (params.hostOnly) {\n // Unlike push/fetch, this one has nowhere to go without a real checkout —\n // its whole purpose is to leave the branch in the host's repo. A scratch\n // repo we delete would be a no-op dressed up as a success.\n if (lookup.workspacePath.length === 0 || !existsSync(lookup.workspacePath)) {\n return {\n exitCode: 64,\n stdout: '',\n stderr:\n `--host-only is unavailable for box ${deps.boxId}: this host has no working copy of the project ` +\n `(${lookup.workspacePath || '<unset>'} does not exist). Boxes created by a control box have no host ` +\n `checkout — push to the remote instead, or adopt the box on a machine that has one.\\n`,\n };\n }\n const dest = resolveLandDest(branch, params.as);\n const stageSave = await mkdtemp(join(tmpdir(), 'agentbox-git-save-'));\n const hostBundleSave = join(stageSave, 'op.bundle');\n const remoteBundleSave = '/tmp/agentbox-rpc-save.bundle';\n try {\n const make = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} bundle create ${shellQuote(remoteBundleSave)} ${shellQuote(branch)}`,\n );\n if (make.exitCode !== 0) {\n return {\n exitCode: make.exitCode,\n stdout: '',\n stderr: `bundle create failed: ${make.stderr || make.stdout}`,\n };\n }\n await backend.downloadFile(handle, remoteBundleSave, hostBundleSave);\n const refspec = landRefspec(branch, dest, params.force);\n const landed = await execa(\n 'git',\n ['-C', lookup.workspacePath, 'fetch', hostBundleSave, refspec],\n { reject: false },\n );\n if ((landed.exitCode ?? 1) !== 0) {\n return {\n exitCode: landed.exitCode ?? 1,\n stdout: landed.stdout ?? '',\n stderr: `host git fetch from bundle failed: ${landed.stderr ?? ''}`,\n };\n }\n return {\n exitCode: 0,\n stdout: `branch ${dest} available in ${lookup.workspacePath}\\n${landed.stdout ?? ''}`,\n stderr: landed.stderr ?? '',\n };\n } finally {\n await rm(stageSave, { recursive: true, force: true });\n await backend.exec(handle, `rm -f ${shellQuote(remoteBundleSave)}`).catch(() => {\n /* best-effort */\n });\n }\n }\n\n // Gate `git.push` (and only `git.push`) behind the same host-side confirm\n // prompt the Docker provider already uses. The wrapper's SSE subscriber on\n // /admin/prompts/stream surfaces it as a footer y/N; `askPrompt` returns\n // auto-`y` when AGENTBOX_PROMPT=off (matches Docker behavior).\n // The gate is bypassed for pushes to a *sanctioned* branch: the box's own\n // `agentbox/<name>` scratch branch (always its job), or the branch the host\n // last put the box on (`sanctionedBranch`). A scratch push bypasses\n // unconditionally; the sanctioned-but-non-scratch bypass is part of the safe\n // subset, so it honors `box.autoApproveSafeHostActions` and leaves an audit\n // trail. An agent that self-switches HEAD to another branch still prompts.\n const isScratch = isScratchBranch(branch);\n const safeApproveOn = deps.autoApproveSafeHostActions !== false;\n const isSanctionedNonScratch =\n !isScratch && safeApproveOn && isSanctionedPushBranch(branch, lookup.sanctionedBranch);\n const bypassPushGate = isScratch || isSanctionedNonScratch;\n if (action.method === 'git.push' && isSanctionedNonScratch) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `git push to sanctioned branch ${branch} on ${deps.boxName ?? deps.boxId}`,\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n },\n 'safe: sanctioned-branch push',\n );\n }\n // Host-initiated pushes (driven by `agentbox git push <box>`) skip the\n // confirm prompt — but only with a valid scope-matched, params-hash-bound\n // one-time token. If a token is *present* but invalid (mutated args,\n // replayed, expired), reject hard: that's an attack signal. Only fall\n // through to the prompt when no token was claimed.\n const tokenClaimedGit = typeof params.hostInitiated === 'string';\n const incomingHashGit = hashRpcParams(params);\n const hostInitiatedOk =\n !bypassPushGate &&\n tokenClaimedGit &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n 'git.push',\n incomingHashGit,\n ) ??\n false);\n if (action.method === 'git.push' && !bypassPushGate && tokenClaimedGit && !hostInitiatedOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n if (\n action.method === 'git.push' &&\n !bypassPushGate &&\n !hostInitiatedOk &&\n deps.prompts &&\n deps.subscribers\n ) {\n // Cloud-specific fallback: when no SSE subscriber is attached the prompt\n // would block indefinitely (the user has nothing to answer in). Choose\n // up-front whether to auto-deny (default) or auto-approve based on env\n // — same env knob shape as `AGENTBOX_PROMPT`. The decision is bounded\n // by `AGENTBOX_GIT_PUSH_NO_SUB`: 'deny' (default), 'allow', or 'prompt'\n // (block anyway, legacy behavior).\n const hasSubscriber = deps.subscribers.count(deps.boxId) > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GIT_PUSH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GIT_PUSH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.('git.push auto-approved (no subscribers, AGENTBOX_GIT_PUSH_NO_SUB=allow)');\n // Fall through to the actual push.\n } else {\n // 'prompt' or anything else: legacy blocking behavior with a TTL so\n // a never-attaching user doesn't wedge the executor forever.\n const verdict = await askPrompt(\n deps.prompts,\n deps.subscribers,\n deps.boxId,\n {\n kind: 'confirm',\n message: `Allow git push from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail:\n `${resolveRemote(params.remote)} ${branch} ${(params.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n },\n { ttlMs: 5 * 60 * 1000 },\n );\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n } else {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow git push from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail: `${resolveRemote(params.remote)} ${branch} ${(params.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n\n const remoteName = resolveRemote(params.remote);\n let repo: HostGitRepo;\n try {\n repo = await resolveHostGitRepo(lookup.workspacePath, deps, remoteName);\n } catch (err) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n if (repo.scratch) {\n deps.log?.(\n `git.${action.method === 'git.push' ? 'push' : 'fetch'}: no host checkout for box ${deps.boxId}; using a scratch repo against ${repo.remote}`,\n );\n }\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-git-rpc-'));\n const hostBundle = join(stage, 'op.bundle');\n const remoteBundle = '/tmp/agentbox-rpc.bundle';\n try {\n if (action.method === 'git.push') {\n // 2a. Bundle the per-box branch inside the sandbox.\n const make = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} bundle create ${shellQuote(remoteBundle)} ${shellQuote(branch)}`,\n );\n if (make.exitCode !== 0) {\n return {\n exitCode: make.exitCode,\n stdout: '',\n stderr: `bundle create failed: ${make.stderr || make.stdout}`,\n };\n }\n // 2b. Download to host tmp.\n await backend.downloadFile(handle, remoteBundle, hostBundle);\n // 3. Fast-forward the host repo's per-box branch ref to the sandbox tip.\n // In a scratch repo this is what materializes the branch at all.\n const fetch = await execa(\n 'git',\n ['-C', repo.dir, 'fetch', hostBundle, `${branch}:${branch}`],\n { reject: false },\n );\n if (fetch.exitCode !== 0) {\n return {\n exitCode: fetch.exitCode ?? 1,\n stdout: fetch.stdout ?? '',\n stderr: `host git fetch from bundle failed: ${fetch.stderr ?? ''}`,\n };\n }\n // 4. Real push. Args are user-controlled (`agentbox-ctl git push --\n // <args>`); pass them through to git on the host. `repo.remote` is the\n // caller's remote name against a real checkout, or the registered origin\n // URL when we're pushing out of a scratch repo (which has no remotes).\n const remote = repo.remote;\n const argv = ['-C', repo.dir, 'push', remote, branch];\n argv.push(...sanitizeGitArgs(params.args));\n const push = await execa('git', argv, { reject: false });\n let pushStderr = push.stderr ?? '';\n // After a successful push, sync the box's view of origin to match what\n // a normal local `git push -u` would have left behind: write the pushed\n // tip into the box's `refs/remotes/origin/<branch>` and set the branch\n // upstream to track it. Without this, Claude Code's PR badge sees no\n // upstream on the branch and doesn't fetch / display the PR. Per-box\n // scratch branches (`agentbox/<name>`) skip the sync — they're\n // local-only by design.\n if ((push.exitCode ?? 1) === 0 && !isScratchBranch(branch)) {\n try {\n const sha = await execa('git', ['-C', repo.dir, 'rev-parse', branch], { reject: false });\n const shaText = (sha.stdout ?? '').trim();\n if (sha.exitCode === 0 && shaText.length > 0) {\n // These are refs INSIDE the box, so they must use the remote NAME —\n // `repo.remote` may be a bare URL when we pushed from a scratch repo.\n const updateRef = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} update-ref ${remoteTrackingRef(remoteName, branch)} ${shellQuote(shaText)}`,\n );\n if (updateRef.exitCode !== 0) {\n pushStderr += `\\nrelay: post-push in-box update-ref ${remoteTrackingRef(remoteName, branch)} failed: ${updateRef.stderr || updateRef.stdout}`;\n }\n const setUpstream = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} branch --set-upstream-to=${upstreamRef(remoteName, branch)} ${shellQuote(branch)}`,\n );\n if (setUpstream.exitCode !== 0) {\n pushStderr += `\\nrelay: post-push in-box --set-upstream-to=${upstreamRef(remoteName, branch)} failed: ${setUpstream.stderr || setUpstream.stdout}`;\n }\n } else {\n pushStderr += `\\nrelay: post-push rev-parse ${branch} failed on host; skipping in-box origin/upstream sync`;\n }\n } catch (err) {\n pushStderr += `\\nrelay: post-push in-box origin/upstream sync threw: ${err instanceof Error ? err.message : String(err)}`;\n }\n }\n return {\n exitCode: push.exitCode ?? 1,\n stdout: push.stdout ?? '',\n stderr: pushStderr,\n };\n }\n // git.fetch: host fetches origin, bundles, uploads, sandbox fetches.\n // A scratch repo has no configured remote, so fetch the registered URL\n // straight into the remote-tracking namespace the bundle step reads back.\n const fetchArgs = repo.scratch\n ? ['-C', repo.dir, 'fetch', repo.remote, '+refs/heads/*:refs/remotes/origin/*', '--tags']\n : ['-C', repo.dir, 'fetch', repo.remote];\n const hostFetch = await execa('git', fetchArgs, { reject: false });\n if (hostFetch.exitCode !== 0) {\n return {\n exitCode: hostFetch.exitCode ?? 1,\n stdout: hostFetch.stdout ?? '',\n stderr: `host git fetch failed: ${hostFetch.stderr ?? ''}`,\n };\n }\n // Bundle origin's remote-tracking refs so the sandbox sees the updates.\n const bundle = await execa('git', ['-C', repo.dir, 'bundle', 'create', hostBundle, `--all`], {\n reject: false,\n });\n if (bundle.exitCode !== 0) {\n return {\n exitCode: bundle.exitCode ?? 1,\n stdout: '',\n stderr: `host git bundle create failed: ${bundle.stderr ?? ''}`,\n };\n }\n await backend.uploadFile(handle, hostBundle, remoteBundle);\n const sandboxFetch = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} fetch ${shellQuote(remoteBundle)} '+refs/heads/*:refs/remotes/origin/*' --tags`,\n );\n return {\n exitCode: sandboxFetch.exitCode,\n stdout: sandboxFetch.stdout,\n stderr: sandboxFetch.stderr,\n };\n } finally {\n await rm(stage, { recursive: true, force: true });\n await repo.cleanup().catch(() => {\n /* best-effort */\n });\n await backend.exec(handle, `rm -f ${shellQuote(remoteBundle)}`).catch(() => {\n /* best-effort */\n });\n }\n}\n\n/** Local helper — sandbox-cloud's `quoteShellArg` would be a cross-package import. */\nfunction shellQuote(arg: string): string {\n if (arg.length === 0) return \"''\";\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(arg)) return arg;\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n","/**\n * Host-side helpers for the `gh.pr.*` RPCs (PR create / view / list / comment /\n * review / merge / checkout / close / reopen). The relay reuses the host's\n * `gh` install + auth: the in-box agent has no GitHub token, the host does.\n *\n * Same decoupling philosophy as `handleGitRpc`'s direct `git` spawn — we shell\n * out to `gh` with a known `cwd` (the host main repo) so `gh` infers the\n * GitHub repo from `git remote -v` and uses the user's authenticated gh\n * identity. No new credential plumbing inside the box.\n *\n * Lives in its own file so both `server.ts` (docker path) and `host-actions.ts`\n * (cloud path) can share `assertGhReady` + `runHostGh` + the `checkout`\n * guards without creating an import cycle.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { resolveSshConfigTarget } from '@agentbox/sandbox-core';\nimport { ghHostFromRemote, repoSlugFromRemote } from './git-pat.js';\nimport type { GitRpcResult } from './types.js';\n\n/** Whitelisted subset of `gh pr` ops exposed via RPC. Keep in sync with the ctl CLI. */\n/**\n * `gh` policy: a blacklist, not an allowlist.\n *\n * The original model proxied a curated set of subcommands and refused the\n * rest, which meant every new agent workflow (`gh issue`, `gh search`,\n * `gh release`) hit \"not proxied\" and needed a code change to unblock —\n * see issue #304. The surface is now open, with three narrow exceptions:\n *\n * 1. {@link GH_BLOCKED} — refused outright. Credential dumps, and anything\n * that mutates the HOST's auth state. The host owns the credential; a\n * box must not be able to read it or move it.\n * 2. {@link GH_DESTRUCTIVE} — always confirmed with the user, even when\n * the box carries `box.autoApproveSafeHostActions`. Reserved for the\n * irreversible: deleting a repo, a release, a secret. `pr merge` is\n * deliberately NOT here — merging is ordinary agent work and is\n * revertable.\n * 3. everything else — allow-once. The grant is the decision; calls run\n * silently by default, and prompt per-call when the box opts into\n * strict mode (`box.autoApproveSafeHostActions: false`).\n *\n * Patterns match the space-joined argv, case-insensitively.\n */\nexport const GH_BLOCKED: readonly { pattern: RegExp; why: string }[] = [\n {\n pattern: /^auth\\s+(token|refresh)\\b/i,\n why: 'prints or rotates the host credential',\n },\n {\n pattern: /^auth\\s+(login|logout|switch|setup-git)\\b/i,\n why: \"changes the host's GitHub auth state, which the host owns\",\n },\n {\n pattern: /^config\\s+set\\b/i,\n why: \"rewrites the host's gh configuration\",\n },\n {\n // `gh alias set x '!sh -c ...'` defines a shell escape that later runs on\n // the host under the host's credentials.\n pattern: /^alias\\s+(set|delete|import)\\b/i,\n why: 'defines host-side command aliases that later run with host credentials',\n },\n {\n pattern: /^extension\\s+(install|remove|upgrade|exec)\\b/i,\n why: 'installs or runs third-party code on the host',\n },\n {\n pattern: /^(ssh-key|gpg-key)\\s+(add|delete)\\b/i,\n why: \"changes the host account's keys\",\n },\n];\n\nexport const GH_DESTRUCTIVE: readonly { pattern: RegExp; what: string }[] = [\n { pattern: /^repo\\s+(delete|archive|rename|transfer)\\b/i, what: 'repository' },\n { pattern: /^release\\s+delete(-asset)?\\b/i, what: 'release' },\n { pattern: /^secret\\s+(set|delete)\\b/i, what: 'repository secret' },\n { pattern: /^variable\\s+delete\\b/i, what: 'repository variable' },\n { pattern: /^cache\\s+delete\\b/i, what: 'Actions cache' },\n { pattern: /^ruleset\\b.*\\b(delete|edit)\\b/i, what: 'repository ruleset' },\n { pattern: /^org\\s+\\S*\\b(delete|remove)\\b/i, what: 'organization' },\n { pattern: /^gist\\s+delete\\b/i, what: 'gist' },\n { pattern: /^label\\s+delete\\b/i, what: 'label' },\n { pattern: /^project\\s+(delete|item-delete|field-delete)\\b/i, what: 'project' },\n // `gh api -X DELETE` reaches all of the above through the raw API. gh\n // accepts `-X DELETE`, `-X=DELETE`, `-XDELETE` and `--method[= ]DELETE`,\n // so match every spelling — a missed one is a silent hole, not a typo.\n { pattern: /(^|\\s)(-X=?\\s*|--method[=\\s]+)(DELETE|PUT|PATCH)\\b/i, what: 'raw API write' },\n // `gh api graphql -f query='mutation { deleteRepository ... }'` is a POST,\n // so no method flag betrays it. GraphQL is a raw write channel with the same\n // reach as the REST verbs above; agents rarely need it, so confirming every\n // mutation is a cheap way to keep the hole shut.\n // Lookaheads rather than adjacency: the endpoint may be spelled `/graphql`,\n // and cobra accepts flags before it (`gh api --paginate graphql …`), so\n // requiring `api graphql` side by side left the hole open.\n {\n pattern: /^api\\b(?=[\\s\\S]*\\bgraphql\\b)(?=[\\s\\S]*\\bmutation\\b)/i,\n what: 'raw GraphQL mutation',\n },\n];\n\n/**\n * gh accepts a few global flags BEFORE the subcommand (`gh -R o/r issue list`),\n * and every policy pattern here is anchored at the start of argv. Without\n * stripping them, `gh -R o/r auth token` would present as argv starting with\n * `-R` and match nothing — sailing past the blocklist, the destructive\n * confirm, and the `pr checkout` opt-in alike.\n *\n * Returns argv from the first non-flag token onward. Value-taking global flags\n * consume their value; unknown leading flags are dropped conservatively (a\n * dropped flag can only make a pattern MORE likely to match, never less).\n */\nconst GH_GLOBAL_VALUE_FLAGS = new Set(['-R', '--repo', '--hostname']);\n\nexport function ghVerbArgv(args: readonly string[]): string[] {\n let i = 0;\n while (i < args.length) {\n const arg = args[i] ?? '';\n if (!arg.startsWith('-')) break;\n // `--repo=o/r` / `-Ro/r` carry their value inline; the split forms eat the\n // next token.\n if (GH_GLOBAL_VALUE_FLAGS.has(arg)) i += 2;\n else i += 1;\n }\n return args.slice(i);\n}\n\n/** Ready-to-send refusal when the argv is on the hard blocklist. */\nexport function refuseBlockedGhCall(args: readonly string[]): GitRpcResult | null {\n const joined = ghVerbArgv(args).join(' ');\n for (const { pattern, why } of GH_BLOCKED) {\n if (pattern.test(joined)) {\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n `gh ${joined}: refused — ${why}. The host runs gh with its own credentials, ` +\n `so the box never needs them.\\n`,\n };\n }\n }\n return null;\n}\n\n/**\n * The thing this argv would irreversibly change, or null when it is ordinary\n * work. A non-null result always raises a confirm, regardless of the box's\n * auto-approve setting.\n */\nexport function ghDestructiveTarget(args: readonly string[]): string | null {\n const joined = ghVerbArgv(args).join(' ');\n for (const { pattern, what } of GH_DESTRUCTIVE) {\n if (pattern.test(joined)) return what;\n }\n return null;\n}\n\n/**\n * The one thing `gh api` still cannot do through the relay, and it is a\n * transport limit rather than a policy one: `--input` reads a body from stdin\n * or a file, and the host `gh` runs with stdin ignored, so the request would\n * silently send nothing. Point the caller at `-f`/`-F` fields instead.\n *\n * Method and endpoint are no longer gated here — `GH_DESTRUCTIVE` catches the\n * irreversible verbs, and everything else is ordinary allow-once work.\n */\nexport function refuseGhApiInput(args: readonly string[]): GitRpcResult | null {\n for (const arg of args) {\n if (arg === '--input' || arg.startsWith('--input=')) {\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n \"gh api: '--input' (stdin/file body) isn't supported through the relay \" +\n '(the host gh runs with stdin ignored); use -f/-F fields\\n',\n };\n }\n }\n return null;\n}\n\n/**\n * Default `gh pr create`'s `--head` to the box's branch so the PR is for the\n * box's work, not whatever the host main repo happens to have checked out\n * (`gh` infers head from the cwd's HEAD, which is the user's own branch — or\n * an untracked one, which aborts with \"you must first push the current branch\n * to a remote, or use the --head flag\"). Only injected for `create`, only when\n * the caller didn't already pass `--head` (or its `-H` shorthand), and only when we resolved a real\n * branch (not empty / detached `HEAD`). The host CLI's `agentbox git pr create`\n * already injects this; the relay covers the in-box `agentbox-ctl git pr` /\n * `gh pr` path, which forwards args verbatim.\n */\nexport function injectPrCreateHead(\n op: string,\n branch: string | undefined,\n args: string[],\n): string[] {\n if (op !== 'create') return args;\n if (!branch || branch === 'HEAD') return args;\n if (hasHeadArg(args)) return args;\n return ['--head', branch, ...args];\n}\n\nfunction hasHeadArg(args: string[]): boolean {\n // `gh pr create` accepts `--head`, `--head=<b>`, and the `-H` shorthand in\n // its `-H <b>` / `-H<b>` / `-H=<b>` forms. Recognize all so an explicit head\n // neither gets double-injected nor triggers the no-head refusal.\n return args.some((a) => a === '--head' || a.startsWith('--head=') || a.startsWith('-H'));\n}\n\n/**\n * True when the caller passed an explicit `--head`/`-H` on a `gh pr create`.\n * The safe-subset auto-approve only covers a `create` with NO explicit head:\n * the relay then forces `--head` to the box's sanctioned branch, so the PR can\n * only ever target the box's own work. An explicit head (which could name any\n * branch, e.g. `main`) falls back to the confirm prompt.\n */\nexport function prCreateHasExplicitHead(op: string, args: string[]): boolean {\n return op === 'create' && hasHeadArg(args);\n}\n\n/**\n * True when a `gh pr create` would run with no `--head` — i.e. we couldn't\n * resolve the box's branch to inject and the caller didn't pass one. The\n * relay must refuse rather than let `gh` fall back to the host repo's\n * *checked-out* branch, which would open a PR for the wrong branch.\n */\nexport function prCreateNeedsHead(op: string, args: string[]): boolean {\n return op === 'create' && !hasHeadArg(args);\n}\n\n/** Ready-to-send refusal for a `create` that has no resolvable `--head`. */\nexport const PR_CREATE_NO_HEAD_REFUSAL: GitRpcResult = {\n exitCode: 65,\n stdout: '',\n stderr:\n 'gh pr create: refusing to run without --head — could not resolve this ' +\n \"box's branch, and falling back to the host repo's checked-out branch \" +\n 'would open a PR for the wrong branch. Ensure the box branch is pushed, ' +\n 'or pass --head <branch> explicitly.\\n',\n};\n\n/** Wire params for every `gh.pr.<op>` method. Mirrors the new ctl command surface. */\n/** Wire params for `gh.exec` — the whole `gh` CLI behind one method. */\nexport interface GhExecRpcParams {\n /** Container path the ctl ran in; picks the registered worktree. */\n path?: string;\n /** Full gh argv, e.g. `['issue','list','--state','open']`. */\n args?: string[];\n /**\n * One-time token minted by the host CLI before a host-driven\n * `agentbox git pr <op> <box>`. Scope- and params-hash-bound, consumed on\n * match, and skips the confirm. Boxes cannot mint tokens (the mint endpoint\n * is loopback-only); a present-but-invalid token is a hard reject.\n */\n hostInitiated?: string;\n}\n\nconst GH_RPC_TIMEOUT_MS = 120_000;\nconst GH_READY_CACHE_TTL_MS = 60_000;\n\ninterface GhReadyCache {\n /** null on success; a ready-to-send error envelope when gh isn't usable. */\n result: GitRpcResult | null;\n expiresAt: number;\n}\n/** Auth verdicts, keyed by target host (`''` = gh's own default host). */\nconst ghReadyCache = new Map<string, GhReadyCache>();\n/** `gh --version` is host-independent, so it caches on its own. */\nlet ghInstalledCache: GhReadyCache | undefined;\n/** `ssh -G` expansions, keyed by the raw host read off the remote. */\nconst sshHostCache = new Map<string, { host: string | null; expiresAt: number }>();\n\n/** Where this call's `gh` must be pointed, plus the readiness verdict. */\nexport interface GhTarget {\n /** `GH_HOST` for every gh spawn in this call; null leaves gh on its default. */\n host: string | null;\n /** Ready-to-send envelope when gh can't serve this host; null when good to go. */\n error: GitRpcResult | null;\n}\n\n/**\n * Decide which GitHub host a box's `gh` ops belong to, and whether this machine\n * can serve them. The host comes from the box's REGISTERED origin — never from\n * anything the box says (see `CloudActionExecutorDeps.originUrl`): it selects\n * which instance the host's own authenticated `gh` is pointed at.\n *\n * A github.com origin takes exactly the path it always did — same single\n * `gh auth status` probe, no `GH_HOST`, no extra subprocess.\n *\n * For any other host, `gh` needs `GH_HOST` (without it `gh api` talks to\n * api.github.com whatever the remote says) and the readiness probe needs\n * `--hostname` (a bare `gh auth status` exits non-zero when ANY configured host\n * has a stale token, so one dead github.com entry would mask a perfectly good\n * enterprise login). Before trusting the hostname we expand it through\n * `ssh -G`, exactly as git and gh do, so an `~/.ssh/config` alias\n * (`git@github.com-work:owner/repo`, the usual multi-account setup) resolves to\n * the host that actually answers instead of becoming a bogus `GH_HOST`.\n */\nexport async function resolveGhTarget(originUrl: string | undefined): Promise<GhTarget> {\n const derived = ghHostFromRemote(originUrl);\n if (!derived) return { host: null, error: await assertGhReady(null) };\n\n const expanded = derived.aliasable ? await expandSshHost(derived.host) : derived.host;\n // An alias pointing at github.com was never enterprise — take the default path.\n if (expanded === 'github.com') return { host: null, error: await assertGhReady(null) };\n\n const host = expanded ?? derived.host;\n const scoped = await assertGhReady(host);\n if (!scoped) return { host, error: null };\n // gh missing / broken says nothing about the host; reprobing would just repeat it.\n if (scoped.exitCode !== 4) return { host: null, error: scoped };\n if (expanded === null) {\n // ssh couldn't expand the host, so we can't tell an unauthenticated\n // enterprise host from an alias only gh knows how to resolve. Fall back to\n // what this relay did before it knew about GH_HOST rather than break a\n // setup that works today; keep the host-scoped message if gh is unusable\n // either way, since it is the more specific of the two.\n const generic = await assertGhReady(null);\n return { host: null, error: generic ? scoped : null };\n }\n return { host: null, error: scoped };\n}\n\n/**\n * Expand a remote's host through `ssh -G` the way ssh itself would. Returns\n * null when ssh can't answer (not installed, unresolvable) — the caller then\n * treats the hostname as unverified.\n */\nasync function expandSshHost(host: string): Promise<string | null> {\n const now = Date.now();\n const cached = sshHostCache.get(host);\n if (cached && cached.expiresAt > now) return cached.host;\n let resolved: string | null = null;\n try {\n const target = await resolveSshConfigTarget(host);\n const value = target?.host.trim().toLowerCase() ?? '';\n resolved = value.length > 0 ? value : null;\n } catch {\n resolved = null;\n }\n sshHostCache.set(host, { host: resolved, expiresAt: now + GH_READY_CACHE_TTL_MS });\n return resolved;\n}\n\n/**\n * Returns `null` when the host has a usable, authenticated `gh` for `host`\n * (or for gh's default host when `host` is null/omitted). Otherwise returns a\n * ready-to-send `{ exitCode, stdout, stderr }` envelope describing what's\n * missing. Cached per host for ~60s so a burst of PR ops doesn't reprobe gh on\n * every call.\n *\n * - `gh` missing → exit 127 (matches Bash's \"command not found\").\n * - `gh` present but `gh auth status` non-zero → exit 4 (gh's own conventional\n * \"not logged in\" exit code).\n *\n * With no host we don't pass `--hostname` — any authed host is good enough,\n * which is what every github.com box has always relied on.\n */\nexport async function assertGhReady(host?: string | null): Promise<GitRpcResult | null> {\n const key = host ?? '';\n const now = Date.now();\n const cached = ghReadyCache.get(key);\n if (cached && cached.expiresAt > now) return cached.result;\n const result = await probeGh(host ?? null);\n ghReadyCache.set(key, { result, expiresAt: now + GH_READY_CACHE_TTL_MS });\n return result;\n}\n\n/** Test-only: clear the readiness caches between cases. */\nexport function _resetGhReadyCacheForTests(): void {\n ghReadyCache.clear();\n ghInstalledCache = undefined;\n sshHostCache.clear();\n}\n\nasync function probeGh(host: string | null): Promise<GitRpcResult | null> {\n const installed = await probeGhInstalled();\n if (installed) return installed;\n // gh authenticates directly from a token in the environment and ignores any\n // stored `gh auth login`. When a token is supplied that way with no stored\n // login, `gh auth status` would falsely report \"not logged in\" even though\n // every API call succeeds. Treat a present token as authenticated.\n if (firstNonEmptyEnv(ghTokenEnvNames(host))) return null;\n const auth = await runHostGh(\n host ? ['auth', 'status', '--hostname', host] : ['auth', 'status'],\n process.cwd(),\n { timeoutMs: 15_000 },\n );\n if (auth.exitCode !== 0) {\n return {\n exitCode: 4,\n stdout: '',\n stderr: host\n ? `gh not authenticated on host for ${host} (run \\`gh auth login --hostname ${host}\\`)\\n`\n : 'gh not authenticated on host (run `gh auth login`)\\n',\n };\n }\n return null;\n}\n\nasync function probeGhInstalled(): Promise<GitRpcResult | null> {\n const now = Date.now();\n if (ghInstalledCache && ghInstalledCache.expiresAt > now) return ghInstalledCache.result;\n const result = await probeGhVersion();\n ghInstalledCache = { result, expiresAt: now + GH_READY_CACHE_TTL_MS };\n return result;\n}\n\nasync function probeGhVersion(): Promise<GitRpcResult | null> {\n const version = await runHostGh(['--version'], process.cwd(), { timeoutMs: 10_000 });\n if (version.exitCode === 127 || /ENOENT/.test(version.stderr)) {\n return {\n exitCode: 127,\n stdout: '',\n stderr: 'gh not installed on host (https://cli.github.com)\\n',\n };\n }\n if (version.exitCode !== 0) {\n return {\n exitCode: version.exitCode,\n stdout: '',\n stderr: `gh --version failed: ${version.stderr || version.stdout}`.trimEnd() + '\\n',\n };\n }\n return null;\n}\n\n/**\n * The env vars gh reads a token from for `host`. gh uses GH_TOKEN /\n * GITHUB_TOKEN for github.com and for Enterprise Cloud tenancy hosts\n * (`*.ghe.com`), and GH_ENTERPRISE_TOKEN / GITHUB_ENTERPRISE_TOKEN everywhere\n * else — so a GH_TOKEN in the environment says nothing about whether a call to\n * a self-hosted GHES will authenticate.\n */\nfunction ghTokenEnvNames(host: string | null): string[] {\n if (host === null) return ['GH_TOKEN', 'GITHUB_TOKEN'];\n const enterprise = ['GH_ENTERPRISE_TOKEN', 'GITHUB_ENTERPRISE_TOKEN'];\n return host.endsWith('.ghe.com') ? [...enterprise, 'GH_TOKEN', 'GITHUB_TOKEN'] : enterprise;\n}\n\n/** First env var with a real value — `GH_TOKEN=''` means unset, not \"set to empty\". */\nfunction firstNonEmptyEnv(names: readonly string[]): string | null {\n for (const name of names) {\n const value = process.env[name];\n if (typeof value === 'string' && value.length > 0) return value;\n }\n return null;\n}\n\n/**\n * Where to run `gh`, and whether it must be told the repo.\n *\n * `gh` infers the repo from its cwd's git remote, so the host checkout is the\n * natural place to run it. A control box has no checkout: passing that path as\n * `cwd` makes the spawn itself fail with a bare `spawn gh ENOENT` (Node reports\n * a missing cwd exactly like a missing binary), which reads as \"gh isn't\n * installed\" and sent us hunting the wrong problem. Fall back to a directory\n * that exists and name the repo explicitly from the registered origin instead.\n */\nexport function ghRunContext(\n workspacePath: string,\n originUrl: string | undefined,\n args: string[],\n): { cwd: string; args: string[] } {\n if (workspacePath.length > 0 && existsSync(workspacePath)) {\n return { cwd: workspacePath, args };\n }\n const origin = originUrl?.trim() ?? '';\n const alreadyScoped = args.some((a) => a === '--repo' || a === '-R' || a.startsWith('--repo='));\n if (origin.length === 0 || alreadyScoped) return { cwd: tmpdir(), args };\n try {\n return { cwd: tmpdir(), args: ['--repo', repoSlugFromRemote(origin), ...args] };\n } catch {\n return { cwd: tmpdir(), args };\n }\n}\n\nexport interface RunHostGhOptions {\n /** `GH_HOST` for this spawn; null/omitted leaves gh on its default host. */\n host?: string | null;\n timeoutMs?: number;\n}\n\n/**\n * Spawn `gh` on the host with the given argv inside `cwd`. Returns the\n * standard `{ exitCode, stdout, stderr }` envelope. Self-contained\n * (doesn't call into `server.ts`'s `runHostCommand`) so this module has no\n * import dependency on the server module — keeps the relay's two RPC\n * dispatch paths (docker `/rpc` and cloud `executeCloudAction`) from\n * importing each other.\n */\nexport function runHostGh(\n args: string[],\n cwd: string,\n opts: RunHostGhOptions = {},\n): Promise<GitRpcResult> {\n const timeoutMs = opts.timeoutMs ?? GH_RPC_TIMEOUT_MS;\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn('gh', args, {\n cwd,\n // GH_HOST is what points gh at a GitHub Enterprise Server instance; without\n // it gh targets github.com no matter what the repo's remote says.\n env: opts.host ? { ...process.env, GH_HOST: opts.host } : process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: gh command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n // ENOENT (gh missing) lands here too; surface as exit 127 to match shell semantics.\n const code = (err as NodeJS.ErrnoException).code;\n stderr += String(err.message ?? err);\n finish(code === 'ENOENT' ? 127 : 1);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/**\n * Pre-flight for `gh.pr.checkout`. Refuses when:\n * - the host repo has uncommitted changes (clobbers WIP), or\n * - HEAD is currently any registered per-box branch (`agentbox/<name>`) —\n * the box's bind-mounted `.git/HEAD` would silently flip with the host.\n *\n * Returns a ready-to-send error envelope on refusal, or `null` to proceed.\n */\nexport async function checkoutGuards(\n hostMainRepo: string,\n registeredBranches: readonly string[],\n): Promise<GitRpcResult | null> {\n const status = await runGitProbe(['-C', hostMainRepo, 'status', '--porcelain']);\n if (status.exitCode !== 0) {\n return {\n exitCode: status.exitCode,\n stdout: '',\n stderr:\n `gh pr checkout: failed to inspect host repo: ${status.stderr || status.stdout}`.trimEnd() +\n '\\n',\n };\n }\n if (status.stdout.trim().length > 0) {\n return {\n exitCode: 12,\n stdout: '',\n stderr: `gh pr checkout: ${hostMainRepo} has uncommitted changes; refusing to switch branches\\n`,\n };\n }\n const head = await runGitProbe(['-C', hostMainRepo, 'rev-parse', '--abbrev-ref', 'HEAD']);\n if (head.exitCode !== 0) {\n return {\n exitCode: head.exitCode,\n stdout: '',\n stderr:\n `gh pr checkout: failed to resolve HEAD: ${head.stderr || head.stdout}`.trimEnd() + '\\n',\n };\n }\n const currentBranch = head.stdout.trim();\n if (registeredBranches.includes(currentBranch)) {\n return {\n exitCode: 12,\n stdout: '',\n stderr: `gh pr checkout: ${hostMainRepo} is on registered box branch ${currentBranch}; refusing (would corrupt the bind-mounted box HEAD)\\n`,\n };\n }\n return null;\n}\n\nfunction runGitProbe(args: string[]): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn('git', args, { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (c: Buffer) => {\n stdout += c.toString('utf8');\n });\n child.stderr?.on('data', (c: Buffer) => {\n stderr += c.toString('utf8');\n });\n child.on('error', (err) => {\n resolve({ exitCode: 127, stdout, stderr: stderr + String(err.message ?? err) });\n });\n child.on('close', (code) => {\n resolve({ exitCode: code ?? -1, stdout, stderr });\n });\n });\n}\n\n/**\n * `gh pr checkout` stays gated behind an explicit opt-in env even under the\n * open policy, and for a different reason than the rest: it is the one `gh`\n * subcommand that mutates the HOST's working tree rather than something on\n * GitHub. The box's bind-mounted `.git/HEAD` follows the host, so a checkout\n * yanks the branch out from under whatever the user is doing. Returns a\n * ready-to-send envelope when the op should be refused; `null` otherwise.\n */\nexport function refuseCheckoutByDefault(op: string): GitRpcResult | null {\n if (op !== 'checkout') return null;\n if (process.env['AGENTBOX_GH_PR_CHECKOUT'] === 'allow') return null;\n return {\n exitCode: 13,\n stdout: '',\n stderr: 'gh pr checkout: disabled by default; set AGENTBOX_GH_PR_CHECKOUT=allow to enable\\n',\n };\n}\n","/**\n * Host-initiated RPC tokens.\n *\n * `agentbox git <op> <box>` runs on the host but ultimately triggers a\n * credentialed RPC (`git.push`, `gh.pr.<op>`, …) on the host-side relay.\n * Those RPCs normally surface a y/N confirm prompt to the user — the box\n * (and the agent inside it) is untrusted, so every push/PR must be approved.\n *\n * For host-initiated calls, the user has already typed the command on the\n * host, so re-prompting is just friction. But \"host-initiated\" must not be\n * something the box can claim by setting a flag — a malicious agent could\n * trivially abuse that. So instead the host CLI:\n *\n * 1. Computes a `paramsHash` of the exact params it's about to send.\n * 2. Mints a one-time token via the relay's loopback-only admin endpoint\n * `POST /admin/host-initiated/mint`, scoped to `(boxId, method, paramsHash)`.\n * 3. Passes the token to `agentbox-ctl` (via `--host-initiated-token`),\n * which forwards it in `params.hostInitiated` on the RPC.\n * 4. The relay re-hashes the incoming params (excluding `hostInitiated`),\n * compares against the minted hash, and only skips the prompt on a\n * full `(boxId, method, paramsHash)` match. The token is then consumed.\n *\n * Tokens are 32 random bytes (256 bits — collision/guessing safety), expire\n * after ~120s, and are one-shot.\n *\n * Failure-mode policy (enforced at each call site, not here):\n *\n * - `params.hostInitiated` absent → no token claimed; the RPC falls\n * through to the normal askPrompt path (the agent-initiated default).\n * - `params.hostInitiated` present but `consume()` returns false →\n * **reject the RPC outright** (exit code 10). The only way to obtain a\n * token is via the loopback-only mint endpoint; a token that doesn't\n * validate (wrong scope, mutated params, replayed, expired) is an\n * attack signal. Falling through to the prompt would (a) leak that the\n * attacker has a token, (b) bait the user into approving a call they\n * didn't initiate. Hard reject.\n *\n * ## Threat model\n *\n * The mint endpoint is loopback-only, so a box cannot mint its own tokens\n * (boxes see the relay on `host.docker.internal` or via cloud bridges,\n * never 127.0.0.1).\n *\n * The token is delivered to the box via `docker exec --argv agentbox-ctl …\n * --host-initiated-token <tok>`. /proc/<pid>/cmdline is world-readable on\n * Linux, so a malicious in-box process polling /proc COULD harvest the\n * token while agentbox-ctl is running. Without paramsHash binding the\n * attacker could then send their own RPC with the same token but *modified\n * args* (`--force` on push, altered `--title`/`--body` on PR create) and\n * win a race against the legit caller. paramsHash binding closes that gap:\n * the relay rejects any incoming params that don't hash to the minted hash,\n * so harvested tokens are only good for the exact params the host CLI\n * already authorized.\n *\n * Optional `paramsHash === undefined` mode exists for forward compatibility\n * (callers that don't need params binding); the production callers\n * (`agentbox git`) always pass a hash.\n */\n\nimport { createHash, randomBytes } from 'node:crypto';\n\nconst DEFAULT_TTL_MS = 120_000;\n\ninterface TokenRecord {\n boxId: string;\n method: string;\n /**\n * Hex SHA-256 of the canonicalized params the host CLI committed to\n * sending. Verified against the incoming `/rpc` params in `consume()`.\n * `null` means \"no params binding\" — only safe for calls where the\n * params surface is fully host-controlled (none in practice today).\n */\n paramsHash: string | null;\n expiresAt: number;\n}\n\n/**\n * Compute a stable SHA-256 of the JSON params, with keys sorted and the\n * `hostInitiated` field stripped (so the token-bearing call hashes the same\n * as the at-mint-time intended params). Stable hash regardless of key order\n * in the wire payload, regardless of whether `hostInitiated` is set.\n */\nexport function hashRpcParams(params: unknown): string {\n return createHash('sha256').update(canonicalJson(params)).digest('hex');\n}\n\nfunction canonicalJson(v: unknown): string {\n if (v === null) return 'null';\n if (typeof v === 'undefined') return 'null';\n if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'null';\n if (typeof v === 'boolean') return v ? 'true' : 'false';\n if (typeof v === 'string') return JSON.stringify(v);\n if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']';\n if (typeof v === 'object') {\n const entries = Object.entries(v as Record<string, unknown>)\n .filter(([k]) => k !== 'hostInitiated')\n .filter(([, val]) => val !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return (\n '{' + entries.map(([k, val]) => JSON.stringify(k) + ':' + canonicalJson(val)).join(',') + '}'\n );\n }\n return 'null';\n}\n\nexport class HostInitiatedTokens {\n private readonly store = new Map<string, TokenRecord>();\n\n /**\n * Mint a fresh one-time token scoped to (boxId, method, paramsHash).\n * `paramsHash` MUST be supplied for any call surface where the box can\n * influence the eventual RPC params. Pass `null` only when there are no\n * params (no current call sites use this).\n */\n mint(\n boxId: string,\n method: string,\n paramsHash: string | null,\n ttlMs: number = DEFAULT_TTL_MS,\n ): string {\n const token = randomBytes(32).toString('hex');\n this.store.set(token, { boxId, method, paramsHash, expiresAt: Date.now() + ttlMs });\n return token;\n }\n\n /**\n * Returns true exactly once if `token` is a valid, unexpired token for the\n * given `(boxId, method)` AND the supplied `incomingParamsHash` matches\n * the hash bound at mint time. The token is removed on a successful match\n * (one-shot semantics). All failure modes return false — callers fall back\n * to the normal prompt path.\n */\n consume(\n token: string | undefined,\n boxId: string,\n method: string,\n incomingParamsHash: string,\n ): boolean {\n if (!token || typeof token !== 'string') return false;\n const record = this.store.get(token);\n if (!record) return false;\n if (record.expiresAt < Date.now()) {\n this.store.delete(token);\n return false;\n }\n if (record.boxId !== boxId || record.method !== method) return false;\n // paramsHash null = \"no binding\"; otherwise enforce exact match.\n if (record.paramsHash !== null && record.paramsHash !== incomingParamsHash) {\n return false;\n }\n this.store.delete(token);\n return true;\n }\n\n /** Drop expired entries. Cheap; safe to call periodically. */\n gc(): void {\n const now = Date.now();\n for (const [token, record] of this.store) {\n if (record.expiresAt < now) this.store.delete(token);\n }\n }\n\n /** Test-only: number of live tokens. */\n size(): number {\n return this.store.size;\n }\n}\n","/**\n * Shared `cp.toHost` / `cp.fromHost` wire handling for both the docker `/rpc`\n * route (`server.ts`) and the cloud host-action queue (`host-actions.ts`).\n *\n * Both paths converge on the same move: normalize the wire params into\n * sources + destination, then re-shell the installed `agentbox cp` host CLI\n * (which owns the tar pipe, excludes, the size guard, and provider routing).\n * Keeping the argv builder here means the docker and cloud paths can't drift.\n */\n\nimport type { CpRpcParams } from './types.js';\n\nexport type CpMethod = 'cp.toHost' | 'cp.fromHost';\n\n/**\n * Normalize the wire params into `{ sources, dest }`, tolerating the legacy\n * single-source `{ boxPath, hostPath }` shape sent by an older in-box\n * `agentbox-ctl` baked into a box image before multi-source support. Throws a\n * plain `Error` (message is safe to surface) on a malformed payload.\n */\nexport function normalizeCpParams(\n method: CpMethod,\n params: CpRpcParams | undefined,\n): { sources: string[]; dest: string } {\n if (!params) throw new Error('cp.* requires params');\n let sources = params.sources;\n let dest = params.dest;\n // Legacy fallback: derive sources/dest from boxPath/hostPath by direction.\n if (!Array.isArray(sources) || sources.length === 0 || typeof dest !== 'string') {\n if (typeof params.boxPath === 'string' && typeof params.hostPath === 'string') {\n if (method === 'cp.toHost') {\n sources = [params.boxPath];\n dest = params.hostPath;\n } else {\n sources = [params.hostPath];\n dest = params.boxPath;\n }\n }\n }\n if (\n !Array.isArray(sources) ||\n sources.length === 0 ||\n sources.some((s) => typeof s !== 'string')\n ) {\n throw new Error(\n 'cp.* requires a non-empty {sources} string array (or legacy {boxPath, hostPath})',\n );\n }\n if (typeof dest !== 'string') {\n throw new Error('cp.* requires a {dest} string (or legacy {boxPath, hostPath})');\n }\n return { sources, dest };\n}\n\n/** Translate the optional cp flags back into `agentbox cp` argv flags. */\nexport function cpFlags(params: CpRpcParams): string[] {\n const flags: string[] = [];\n for (const pat of params.exclude ?? []) flags.push('--exclude', pat);\n if (params.defaultExcludes === false) flags.push('--no-default-excludes');\n if (params.yes) flags.push('--yes');\n return flags;\n}\n\n/**\n * Build the `agentbox cp <src...> <dst>` argv (leading `cp`, no node/entry) plus\n * a human-facing detail line for the consent prompt. The box side carries the\n * `<boxName>:` prefix; host paths are resolved to absolute via `resolveHost`\n * (against the box workspace) so the prompt shows the real destination and the\n * argv doesn't depend on the re-shelled process's cwd.\n */\nexport function buildCpArgv(opts: {\n method: CpMethod;\n boxName: string;\n sources: string[];\n dest: string;\n resolveHost: (p: string) => string;\n flags: string[];\n}): { argv: string[]; detail: string; contextArgv: string[] } {\n const { method, boxName, sources, dest, resolveHost, flags } = opts;\n if (method === 'cp.toHost') {\n const hostAbs = resolveHost(dest);\n const boxArgs = sources.map((s) => `${boxName}:${s}`);\n return {\n argv: ['cp', ...boxArgs, hostAbs, ...flags],\n detail: `${sources.join(', ')} -> ${hostAbs}`,\n contextArgv: [...sources, hostAbs],\n };\n }\n const hostAbsSrcs = sources.map(resolveHost);\n return {\n argv: ['cp', ...hostAbsSrcs, `${boxName}:${dest}`, ...flags],\n detail: `${hostAbsSrcs.join(', ')} -> ${dest}`,\n contextArgv: [...hostAbsSrcs, dest],\n };\n}\n","/**\n * The PC's half of the cp cache: after it copies a file out to a box, it also\n * files a copy with the control box, so the same request still answers when this\n * machine is asleep.\n *\n * Deliberately a **side effect of a successful copy**, not a step inside it. The\n * copy the user asked for has already happened over the direct path by the time\n * anything here runs; a control box that is full, unreachable or running an\n * older build costs a log line, never the copy. That ordering is the whole\n * design: caching must not be able to break the thing it accelerates.\n */\n\nimport { execFile } from 'node:child_process';\nimport { createReadStream } from 'node:fs';\nimport { mkdtemp, rm, stat } from 'node:fs/promises';\nimport { hostname, tmpdir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { cpCacheMetaPath, cpCacheTarPath, type CpCacheMeta } from './cp-cache.js';\n\nexport interface CpCacheCaptureDeps {\n /** Control box base URL. */\n controlPlaneUrl: string;\n adminToken: string;\n /** Skip anything larger than this (the hub's own blob cap). */\n maxBytes?: number;\n logger?: (line: string) => void;\n}\n\n/** Matches the relay's default `custodyMaxBlobBytes`, and `box.cpMaxBytes`. */\nconst DEFAULT_MAX_CACHE_BYTES = 100 * 1024 * 1024;\nconst TAR_TIMEOUT_MS = 120_000;\nconst UPLOAD_TIMEOUT_MS = 300_000;\n\n/**\n * Tar `absPath` and store it (plus its sidecar) under `prefix` on the control\n * box. Returns true when the entry landed.\n *\n * Never throws.\n */\nexport async function captureCpCacheEntry(\n absPath: string,\n prefix: string,\n deps: CpCacheCaptureDeps,\n /**\n * The path AS REQUESTED, which is what the key is derived from — the resolved\n * `absPath` is only what gets tarred. The two differ on every relative\n * request, and keying on the resolved one is unreadable to the control box\n * (see {@link cpCacheKeyInput}). Defaults to `absPath` for an absolute\n * request, where they are the same string.\n */\n requestPath: string = absPath,\n): Promise<boolean> {\n const log = deps.logger ?? ((): void => {});\n const maxBytes = deps.maxBytes ?? DEFAULT_MAX_CACHE_BYTES;\n let workDir: string | undefined;\n try {\n const info = await stat(absPath);\n const dir = await mkdtemp(join(tmpdir(), 'agentbox-cp-cache-'));\n workDir = dir;\n const tarPath = join(dir, 'entry.tar');\n // -C the parent + a bare name, so the archive holds `q3.csv` rather than\n // `Users/marco/data/q3.csv` and unpacks anywhere.\n await run('tar', ['-cf', tarPath, '-C', dirname(absPath), basename(absPath)], TAR_TIMEOUT_MS);\n const tarInfo = await stat(tarPath);\n if (tarInfo.size > maxBytes) {\n // Silence here would read as \"cached\" and turn into a confusing miss\n // later, when the machine is offline and nobody can investigate.\n log(\n `cp cache: skipping ${absPath} — ${String(tarInfo.size)} bytes exceeds the hub's ${String(maxBytes)}-byte limit`,\n );\n return false;\n }\n const meta: CpCacheMeta = {\n sourcePath: absPath,\n isDir: info.isDirectory(),\n capturedAt: new Date().toISOString(),\n size: tarInfo.size,\n capturedOn: hostname(),\n };\n const base = deps.controlPlaneUrl.replace(/\\/+$/, '');\n await putBlob(\n `${base}/admin/custody-blob/${cpCacheTarPath(prefix, requestPath)}`,\n tarPath,\n deps.adminToken,\n );\n await putJson(\n `${base}/admin/custody/${cpCacheMetaPath(prefix, requestPath)}`,\n { data: Buffer.from(JSON.stringify(meta), 'utf8').toString('base64') },\n deps.adminToken,\n );\n log(`cp cache: stored ${absPath} (${String(tarInfo.size)} bytes) for offline use`);\n return true;\n } catch (err) {\n log(\n `cp cache: could not store ${absPath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n return false;\n } finally {\n if (workDir) await rm(workDir, { recursive: true, force: true }).catch(() => {});\n }\n}\n\nfunction run(bin: string, args: string[], timeout: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n execFile(bin, args, { timeout }, (err) => (err ? reject(err) : resolve()));\n });\n}\n\n/** Stream a file to the custody blob surface. */\nfunction putBlob(url: string, filePath: string, token: string): Promise<void> {\n const target = new URL(url);\n const isHttps = target.protocol === 'https:';\n const transport = isHttps ? httpsRequest : httpRequest;\n return new Promise<void>((resolve, reject) => {\n const req = transport(\n {\n host: target.hostname,\n port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,\n method: 'PUT',\n path: target.pathname,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/octet-stream',\n },\n timeout: UPLOAD_TIMEOUT_MS,\n },\n (res) => {\n res.resume();\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) resolve();\n else reject(new Error(`custody blob PUT → ${String(status)}`));\n },\n );\n req.on('error', reject);\n req.on('timeout', () => {\n req.destroy();\n reject(new Error('custody blob PUT timed out'));\n });\n createReadStream(filePath).pipe(req);\n });\n}\n\nfunction putJson(url: string, body: unknown, token: string): Promise<void> {\n const target = new URL(url);\n const isHttps = target.protocol === 'https:';\n const transport = isHttps ? httpsRequest : httpRequest;\n const payload = JSON.stringify(body);\n return new Promise<void>((resolve, reject) => {\n const req = transport(\n {\n host: target.hostname,\n port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,\n method: 'PUT',\n path: target.pathname,\n headers: {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(payload).toString(),\n },\n timeout: UPLOAD_TIMEOUT_MS,\n },\n (res) => {\n res.resume();\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) resolve();\n else reject(new Error(`custody PUT → ${String(status)}`));\n },\n );\n req.on('error', reject);\n req.on('timeout', () => {\n req.destroy();\n reject(new Error('custody PUT timed out'));\n });\n req.write(payload);\n req.end();\n });\n}\n","/**\n * The custody-backed cache behind `cp fromHost` — what makes a copy from your\n * machine still answer when your machine is asleep.\n *\n * A live copy writes its bytes here on the way past; a copy that finds nobody\n * home reads them back. The same entries are what `agentbox cp <file> hub:`\n * writes, so \"pre-load a file for my boxes\" and \"warm the cache\" are one\n * operation rather than two features.\n *\n * Keyed by the **resolved absolute host path**, hashed: custody path segments\n * are a flat `[A-Za-z0-9._-]` namespace, and a hash is the only way to put\n * `/Users/marco/data/q3.csv` in one. Two boxes of the same project asking for\n * the same file therefore share an entry, which is the point — the cache is per\n * project, not per box.\n *\n * Every entry is a tar, even for a single file: it carries the name and mode\n * with it, so unpacking on the far side needs no second channel to know what it\n * is looking at.\n */\n\nimport { createHash } from 'node:crypto';\n\n/** Sidecar recorded next to each cached tar. */\nexport interface CpCacheMeta {\n /** Absolute host path this entry was captured from. */\n sourcePath: string;\n /** True when the tar holds a directory tree rather than one file. */\n isDir: boolean;\n /** ISO timestamp of the capture. */\n capturedAt: string;\n /** Bytes of the tar. */\n size: number;\n /** Hostname of the machine it came from — an entry outlives the session that wrote it. */\n capturedOn?: string;\n}\n\n/**\n * Custody prefix for a project's cp cache. `originUrl`-derived slug when the\n * box has one; otherwise the box's own id, so a box with no remote still gets a\n * (narrower) cache instead of none.\n */\nexport function cpCachePrefix(opts: { projectSlug?: string; boxId: string }): string {\n const slug = (opts.projectSlug ?? '').trim();\n return slug.length > 0 ? `projects/${slug}/cp` : `boxes/${opts.boxId}/cp`;\n}\n\n/**\n * Normalize a source into the string both sides key on.\n *\n * **Not** the resolved absolute path. That was the mistake a live run caught:\n * the machine that owns the files resolves `./data.csv` against the real\n * project, while the control box resolves it against the create job's temp\n * clone — two different absolute paths for one request, so every write landed\n * under a key the read could never compute, and the cache always missed.\n *\n * What both sides do agree on is the path as the box asked for it. A\n * project-relative request keys as `rel:data.csv`, an absolute one as\n * `abs:/Users/me/data.csv`. That also gives `agentbox cp <file> hub:` a precise\n * meaning: run inside the project, it pre-loads exactly the key a box's own\n * `cp fromHost ./data.csv` looks up.\n */\nexport function cpCacheKeyInput(source: string): string {\n const trimmed = source.trim().replace(/\\/+$/, '');\n if (trimmed.startsWith('/')) return `abs:${trimmed}`;\n // `./x`, `x` and `././x` are one request. `../x` keeps its shape — it escapes\n // the project, and both sides still spell it identically.\n const rel = trimmed.replace(/^(\\.\\/)+/, '').replace(/\\/\\.\\//g, '/');\n return `rel:${rel}`;\n}\n\n/** Hex sha256 of a {@link cpCacheKeyInput} — the cache key's single segment. */\nexport function cpCacheKey(source: string): string {\n return createHash('sha256').update(cpCacheKeyInput(source)).digest('hex').slice(0, 32);\n}\n\n/** Custody path of the tar for `source` under `prefix`. */\nexport function cpCacheTarPath(prefix: string, source: string): string {\n return `${prefix}/${cpCacheKey(source)}.tar`;\n}\n\n/** Custody path of the sidecar metadata for `source` under `prefix`. */\nexport function cpCacheMetaPath(prefix: string, source: string): string {\n return `${prefix}/${cpCacheKey(source)}.json`;\n}\n\n/**\n * Human phrasing of a cached entry's age, for the approval detail and the line\n * the box sees. An agent that reads \"cached\" without \"from when\" has no way to\n * judge whether it is looking at today's data or last month's.\n */\nexport function describeCacheAge(capturedAt: string, now: number = Date.now()): string {\n const then = Date.parse(capturedAt);\n if (!Number.isFinite(then)) return 'captured at an unknown time';\n const seconds = Math.max(0, Math.round((now - then) / 1000));\n if (seconds < 90) return `captured ${String(seconds)}s ago`;\n const minutes = Math.round(seconds / 60);\n if (minutes < 90) return `captured ${String(minutes)}m ago`;\n const hours = Math.round(minutes / 60);\n if (hours < 48) return `captured ${String(hours)}h ago`;\n return `captured ${String(Math.round(hours / 24))}d ago`;\n}\n\n/** Parse a sidecar, or null when it is missing/corrupt (treated as no cache). */\nexport function parseCpCacheMeta(raw: string): CpCacheMeta | null {\n try {\n const parsed = JSON.parse(raw) as Partial<CpCacheMeta>;\n if (typeof parsed.sourcePath !== 'string' || typeof parsed.capturedAt !== 'string') return null;\n return {\n sourcePath: parsed.sourcePath,\n isDir: parsed.isDir === true,\n capturedAt: parsed.capturedAt,\n size: typeof parsed.size === 'number' ? parsed.size : 0,\n ...(typeof parsed.capturedOn === 'string' ? { capturedOn: parsed.capturedOn } : {}),\n };\n } catch {\n return null;\n }\n}\n","/**\n * Host-side machinery for the `tool.*` RPCs — the relay-side spine that lets\n * an in-box agent drive an arbitrary host CLI without ever holding that CLI's\n * credentials.\n *\n * The gate lives here, not in the box. The in-box shim is a three-line\n * forwarder by design (it was never the security boundary — see\n * docs/architecture.md); this file is the only thing that consults the grant\n * list, the built-in credential deny list, the per-tool argv rules and the\n * host approval prompt. One check covers every caller: the shim, a direct\n * `agentbox-ctl tool run`, and the cloud executor.\n *\n * Lives in its own file so both `server.ts` (docker `POST /rpc`) and\n * `host-actions.ts` (cloud path) share it — same cycle-avoidance reasoning\n * as `gh.ts`.\n */\n\nimport { basename } from 'node:path';\nimport { loadEffectiveConfig, loadGrantedTools, type ToolGrant } from '@agentbox/config';\nimport { assertHostBinReady, hostBinExists, runHostBinary } from './host-exec.js';\nimport type { GitRpcResult } from './types.js';\n\n/** Wire params for `tool.run`. */\nexport interface ToolRunRpcParams {\n /** Container path the ctl ran in; picks the registered worktree. */\n path?: string;\n /** Tool name, as granted. */\n name?: string;\n /** Argv forwarded verbatim to the host binary. */\n args?: string[];\n}\n\n/** Wire params for `tool.request`. */\nexport interface ToolRequestRpcParams {\n path?: string;\n name?: string;\n /** Free text the agent supplies, shown to the human in the prompt. */\n reason?: string;\n}\n\n/** Wire params for `tool.list`. */\nexport interface ToolListRpcParams {\n path?: string;\n /**\n * `'json'` returns a machine-readable grant array on stdout instead of the\n * human table. The in-box daemon uses it to keep the per-tool shim symlinks\n * in sync with the grant list — that is what makes an approval take effect\n * without restarting the box.\n */\n format?: 'text' | 'json';\n}\n\n/**\n * Argv shapes that make a host CLI print a credential to stdout. Refused\n * unconditionally — before the per-tool rules, before any prompt, before any\n * spawn — because the box would capture the output. This is the generic\n * replacement for the old linear connector's bespoke `auth token` reject.\n *\n * Matched case-insensitively against the space-joined argv. Deliberately\n * broad: a false positive costs the user one `--allow` pattern, a false\n * negative leaks a host credential into an untrusted box.\n */\nexport const CREDENTIAL_ARGV_PATTERNS: readonly RegExp[] = [\n /\\bauth\\s+(token|print-token|print-access-token|export)\\b/i,\n // `print-`, `get-`, `create-`, `fetch-` all name the same hazard; matching\n // the token noun with any of those verbs is cheaper than chasing each CLI.\n /\\b(print|get|fetch|create|issue)-(access-|identity-|id-|session-|refresh-)?token\\b/i,\n /\\bexport-credentials\\b/i,\n /\\bconfigure\\s+get\\b/i,\n // AWS STS hands out live session credentials; IAM can mint a durable key.\n /\\bsts\\s+(get-session-token|get-federation-token|assume-role\\S*)\\b/i,\n /\\biam\\s+create-access-key\\b/i,\n /\\bsecrets?\\s+(get|reveal|show|print|list)\\b/i,\n /\\bcredentials?\\s+(get|reveal|show|print)\\b/i,\n /\\bget-secret-value\\b/i,\n /\\bkeyring\\s+(get|show)\\b/i,\n /--show-secret\\b/i,\n /\\btoken\\s+--raw\\b/i,\n];\n\n/**\n * Ready-to-send refusal when the call would print a host credential.\n *\n * `bin` matters as much as `name`: a grant can point a bland name at a\n * hazardous binary (`tools add safe --bin keyring`, or a yaml `bin:`), and\n * the process that actually runs is the bin.\n *\n * The two are matched as SEPARATE candidates rather than concatenated into\n * one string, for two reasons a single haystack got wrong:\n * - Only the binary's basename is considered. `--bin` may be an absolute\n * path, and scanning its directory components would let an innocent\n * folder name (`~/tools/get-token-helper/bin/x`) refuse every call to an\n * unrelated tool — with no way to override, since this guard runs ahead\n * of `allow`.\n * - Splicing the bin between the name and the argv breaks patterns that\n * key on `<command> <subcommand>`: `keyring get` would no longer match\n * once a path sat in the middle.\n */\nexport function refuseCredentialArgv(\n name: string,\n args: readonly string[],\n bin?: string,\n): GitRpcResult | null {\n const joined = args.join(' ');\n const candidates = [`${name} ${joined}`];\n const binName = bin ? basename(bin) : undefined;\n if (binName && binName !== name) candidates.push(`${binName} ${joined}`);\n for (const re of CREDENTIAL_ARGV_PATTERNS) {\n if (candidates.some((c) => re.test(c))) {\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n `${name}: refused — '${joined}' prints a host credential, which would land ` +\n `inside the box. The host runs this tool so the box never needs its token.\\n`,\n };\n }\n }\n return null;\n}\n\n/** Per-tool `deny` rules from the grant. Runs after the built-in list. */\nexport function refuseDeniedArgv(grant: ToolGrant, args: readonly string[]): GitRpcResult | null {\n if (!grant.deny || grant.deny.length === 0) return null;\n const joined = args.join(' ');\n for (const pattern of grant.deny) {\n let re: RegExp;\n try {\n re = new RegExp(pattern);\n } catch {\n // A grant file with a bad regex must not silently stop denying.\n return {\n exitCode: 78,\n stdout: '',\n stderr: `${grant.name}: grant has an invalid deny pattern '${pattern}'\\n`,\n };\n }\n if (re.test(joined)) {\n return {\n exitCode: 65,\n stdout: '',\n stderr: `${grant.name}: refused — argv matches this tool's deny rule '${pattern}'\\n`,\n };\n }\n }\n return null;\n}\n\n/**\n * True when the argv matches one of the grant's `allow` patterns, meaning it\n * runs with no prompt regardless of the box's auto-approve setting. An\n * invalid pattern never matches (fail closed → the call just gets prompted).\n */\nexport function argvIsExplicitlyAllowed(grant: ToolGrant, args: readonly string[]): boolean {\n if (!grant.allow || grant.allow.length === 0) return false;\n const joined = args.join(' ');\n return grant.allow.some((pattern) => {\n try {\n return new RegExp(pattern).test(joined);\n } catch {\n return false;\n }\n });\n}\n\n/**\n * Resolve the grant for `name` under `cwd`, or a ready-to-send refusal.\n * Re-reads the grant files on every call so an approval takes effect without\n * bouncing the relay — same live-flip approach the autopause loop uses.\n * Fails closed: an unreadable grant file yields no grants.\n */\nexport async function resolveToolGrant(\n name: string,\n cwd: string,\n loader: (cwd: string) => Promise<Map<string, ToolGrant>> = (c) => loadGrantedTools(c),\n): Promise<{ grant: ToolGrant } | { refusal: GitRpcResult }> {\n let grants: Map<string, ToolGrant>;\n try {\n grants = await loader(cwd);\n } catch {\n grants = new Map();\n }\n const grant = grants.get(name);\n if (!grant) {\n return {\n refusal: {\n exitCode: 65,\n stdout: '',\n stderr:\n `${name} is not a granted host tool for this project. Grant it on the host with ` +\n `\\`agentbox tools add ${name}\\`, or ask from inside the box with ` +\n `\\`agentbox-ctl tool request ${name}\\`.\\n`,\n },\n };\n }\n // `gh` keeps its own relay handler (branch injection, the `gh api` endpoint\n // allowlist). Routing it through the generic path would quietly drop those\n // guards, so refuse rather than silently downgrade.\n if (grant.source === 'builtin') {\n return {\n refusal: {\n exitCode: 65,\n stdout: '',\n stderr: `${name} is handled by its own relay path, not the generic host-tool proxy\\n`,\n },\n };\n }\n return { grant };\n}\n\n/** Whether boxes may raise access requests at all (`tools.request.enabled`). */\nexport async function toolRequestsEnabled(\n cwd: string,\n loader: (cwd: string) => Promise<{\n effective: { tools?: { request?: { enabled?: boolean } } };\n }> = loadEffectiveConfig,\n): Promise<boolean> {\n try {\n const cfg = await loader(cwd);\n return cfg.effective.tools?.request?.enabled !== false;\n } catch {\n // Malformed config fails closed — a box shouldn't get to prompt the user\n // because the host's config didn't parse.\n return false;\n }\n}\n\n/** Whether the built-in `gh` grant is live (`tools.gh.enabled`). */\nexport async function ghToolEnabled(\n cwd: string,\n loader: (cwd: string) => Promise<{\n effective: { tools?: { gh?: { enabled?: boolean } } };\n }> = loadEffectiveConfig,\n): Promise<boolean> {\n try {\n const cfg = await loader(cwd);\n return cfg.effective.tools?.gh?.enabled !== false;\n } catch {\n // Unlike a tool grant, gh fails OPEN on an unreadable config: it is on by\n // default and agent flows (Claude Code's PR badge) depend on it, so a\n // malformed config should not silently break PR operations.\n return true;\n }\n}\n\n/**\n * Ready-to-send refusal when `tools.gh.enabled` is false, else null. The\n * relay-side half of revoking the built-in grant — without this the config\n * key would be documentation with no effect.\n */\nexport async function refuseIfGhDisabled(\n cwd: string,\n loader?: Parameters<typeof ghToolEnabled>[1],\n): Promise<GitRpcResult | null> {\n if (await ghToolEnabled(cwd, loader)) return null;\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n 'gh is disabled for this project — re-enable with ' +\n '`agentbox config set --project tools.gh.enabled true`\\n',\n };\n}\n\n/** Probe the host for a binary the box asked for. */\nexport async function hostToolInstalled(bin: string): Promise<boolean> {\n return hostBinExists(bin);\n}\n\n/** Spawn the granted tool in the worktree's host repo. */\nexport async function runGrantedTool(\n grant: ToolGrant,\n args: readonly string[],\n cwd: string,\n): Promise<GitRpcResult> {\n const ready = await assertHostBinReady(grant.bin);\n if (ready) return ready;\n return runHostBinary(grant.bin, args, cwd, grant.timeoutMs);\n}\n\n/** Machine-readable `tool.list` payload for the in-box daemon. */\nexport function renderToolListJson(grants: Iterable<ToolGrant>): string {\n const rows = [...grants]\n .filter((g) => g.source !== 'builtin')\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((g) => ({ name: g.name, bin: g.bin }));\n return JSON.stringify({ tools: rows }) + '\\n';\n}\n\n/** Rendered `tool.list` payload. One line per granted tool. */\nexport function renderToolList(grants: Iterable<ToolGrant>): string {\n const rows = [...grants].sort((a, b) => a.name.localeCompare(b.name));\n if (rows.length === 0) {\n return 'no host tools granted for this project\\n';\n }\n const width = Math.max(...rows.map((g) => g.name.length));\n return (\n rows\n .map((g) => {\n const notes: string[] = [`host: ${g.bin}`, g.source];\n if (g.allow) notes.push(`${String(g.allow.length)} allow`);\n if (g.deny) notes.push(`${String(g.deny.length)} deny`);\n return `${g.name.padEnd(width)} ${notes.join(' ')}`;\n })\n .join('\\n') + '\\n'\n );\n}\n","/**\n * Generic host-binary spawn + readiness probe, shared by every relay path\n * that runs a host CLI on behalf of a box (`host-tools.ts` today; `gh.ts`\n * keeps its own `runHostGh` because it layers gh-specific target/env\n * resolution on top).\n *\n * Self-contained on purpose — no import dependency on the rest of the relay,\n * so both `server.ts` (docker `POST /rpc`) and `host-actions.ts` (cloud path)\n * can pull it in without a cycle. Same reasoning as `gh.ts`.\n */\n\nimport { spawn } from 'node:child_process';\nimport type { GitRpcResult } from './types.js';\n\nexport const HOST_EXEC_DEFAULT_TIMEOUT_MS = 120_000;\nconst READY_CACHE_TTL_MS = 60_000;\n\n/**\n * Spawn `bin argv` in `cwd` and resolve the standard\n * `{ exitCode, stdout, stderr }` envelope. stdin is ignored (there is no TTY\n * on the other end of an RPC) and output is buffered, so this is for short,\n * non-interactive commands only.\n *\n * Never rejects: a missing binary lands as exit 127, a timeout as exit 124.\n */\nexport function runHostBinary(\n bin: string,\n argv: readonly string[],\n cwd: string,\n timeoutMs: number = HOST_EXEC_DEFAULT_TIMEOUT_MS,\n): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn(bin, [...argv], {\n cwd,\n env: process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: ${bin} command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n // ENOENT (binary missing) lands here too; surface as exit 127.\n const code = (err as NodeJS.ErrnoException).code;\n stderr += String(err.message ?? err);\n finish(code === 'ENOENT' ? 127 : 1);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\ninterface ReadyCacheEntry {\n /** null when the binary resolves; ready-to-send envelope when it doesn't. */\n result: GitRpcResult | null;\n expiresAt: number;\n}\nconst readyCache = new Map<string, ReadyCacheEntry>();\n\n/**\n * Returns `null` when `bin` resolves on the host's PATH, otherwise a\n * ready-to-send exit-127 envelope. Cached ~60s so a burst of tool calls\n * doesn't reprobe every time (same TTL as `assertGhReady`).\n *\n * Deliberately an EXISTENCE check, not a `--version` run. `--version` is a\n * bad proxy for \"is this usable\": plenty of real CLIs don't accept it\n * (`sw_vers`, `tar`, many subcommand-style tools), and treating their usage\n * error as \"not ready\" would block a perfectly good tool. If the binary is\n * broken in some other way, its own error text passes straight through to\n * the agent on the real call, which is more useful than a probe's guess.\n *\n * Auth state is likewise not probed: an unauthed CLI exits non-zero with its\n * own clear message, which the relay passes through verbatim. Auth reporting\n * is `agentbox doctor`'s job, not the hot path.\n */\nexport async function assertHostBinReady(bin: string): Promise<GitRpcResult | null> {\n const now = Date.now();\n const cached = readyCache.get(bin);\n if (cached && cached.expiresAt > now) return cached.result;\n const exists = await hostBinExists(bin);\n const result: GitRpcResult | null = exists\n ? null\n : {\n exitCode: 127,\n stdout: '',\n stderr: `${bin} is not installed on the host\\n`,\n };\n readyCache.set(bin, { result, expiresAt: now + READY_CACHE_TTL_MS });\n return result;\n}\n\n/** Test-only: clear the readiness cache between cases. */\nexport function _resetHostBinReadyCacheForTests(): void {\n readyCache.clear();\n}\n\n/**\n * True when `bin` resolves on the host's PATH. Used by `tool.request` to give\n * the box a direct \"not installed on the host\" answer instead of raising an\n * approval prompt for a binary that could never run.\n */\nexport async function hostBinExists(bin: string): Promise<boolean> {\n const probe = await runHostBinary('command', ['-v', bin], process.cwd(), 5_000);\n if (probe.exitCode === 0) return true;\n // `command` is a shell builtin on some hosts; fall back to `which`.\n const which = await runHostBinary('which', [bin], process.cwd(), 5_000);\n return which.exitCode === 0;\n}\n","/**\n * Shared decision for auto-approving file transfers between a box and the host\n * under `box.autoApproveSafeHostActions`. Used by both the docker (`server.ts`)\n * and cloud (`host-actions.ts`) cp/download handlers so the containment + secret\n * policy can't drift between the two transports.\n *\n * The rule: a transfer auto-approves only when every host-side path it touches\n * resolves *inside the box's project folder* (`workspacePath`), following\n * symlinks. For a host->box copy, a secret-looking source additionally keeps the\n * prompt unless that exact file was already approved via the `carry:` block.\n * Anything else falls back to the interactive confirm — the prompt is never\n * removed, only skipped when provably safe.\n */\n\nimport { isContainedInWorkspace, looksLikeSecret, realpathSafe } from '@agentbox/core';\n\nexport interface TransferApproveInput {\n /** `box.autoApproveSafeHostActions` (false → always prompt). */\n enabled: boolean;\n /** The box's host project folder; relative paths already resolved against it. */\n workspacePath: string | undefined;\n /**\n * Resolved host-side paths the transfer touches: the *destination* for\n * box->host (cp.toHost / download), the *sources* for host->box (cp.fromHost).\n */\n hostPaths: string[];\n /** Apply the secret-file guard (host->box only). */\n checkSecret: boolean;\n /** realpath'd host sources already approved via `carry:` (secret exemption). */\n carried?: Set<string>;\n}\n\n/**\n * True when the transfer may skip the approval prompt. Conservative: any\n * uncontained path, any not-yet-carried secret source, an unknown workspace, or\n * the feature being disabled all return false (→ the caller prompts).\n */\nexport async function canAutoApproveTransfer(input: TransferApproveInput): Promise<boolean> {\n if (!input.enabled) return false;\n if (!input.workspacePath || input.hostPaths.length === 0) return false;\n for (const p of input.hostPaths) {\n if (!(await isContainedInWorkspace(p, input.workspacePath))) return false;\n if (input.checkSecret && looksLikeSecret(p)) {\n const real = await realpathSafe(p);\n if (!input.carried?.has(real)) return false;\n }\n }\n return true;\n}\n","/**\n * Rebuild a drivable `BoxRecord` from a control-box `BoxRegistration`.\n *\n * The single source of truth for \"registration → record\" reconstruction, used by\n * BOTH sides of the control-plane topology:\n * - the PC's `agentbox hub adopt` (materializes the record into the PC's\n * `state.json` so direct PC↔box commands resolve the box), and\n * - the control box's own hub backend (`hydrateRegisteredBox`), which drives a\n * box it knows only from its Store registration — created on a PC / another\n * host — so `/api/v1` lifecycle, git, and REAL destroy work on it, not just a\n * state reap.\n *\n * Everything needed rides on the registration (the adoption material added by the\n * plane-register enrichment): provider, sandbox id, public VM host, image, web\n * port, agent, branch, origin URL, bridge/preview tokens. Host-specific concerns\n * stay with the caller: which LOCAL project the box maps to (PC only — the\n * control box has no local clone), SSH-key material (downloaded from custody over\n * HTTP on the PC, read from the local FS store on the control box), and the token\n * generator used for the relay/bridge fallbacks.\n *\n * Kept pure (no fs, no network) so both callers layer their own IO around it.\n */\nimport type { BoxRecord, GitWorktreeRecord, SshTargetRecord } from '@agentbox/core';\nimport { boxSshDirForProvider } from '@agentbox/sandbox-core';\nimport type { BoxRegistration } from './types.js';\n\n/** Box user on every cloud provider's image (the agent never runs as root). */\nconst BOX_SSH_USER = 'vscode';\n\nexport interface RegistrationToRecordOptions {\n /** The control-plane base URL, persisted on the record's cloud fields. */\n controlPlaneUrl: string;\n /**\n * A local record for the same box, when re-adopting: its id/project linkage\n * and live tokens are preserved so status paths stay stable and a refresh\n * never re-mints tokens already injected in the running box.\n */\n existing?: BoxRecord;\n /**\n * Absolute host path of the LOCAL checkout the box maps to. Set only when a\n * clone is present (the PC path); on the control box there is none, so git\n * worktree bookkeeping is left off (the registration's `hostMainRepo` is the\n * control box's create-time temp clone, deleted after create — carrying it\n * over would point host-side git RPCs at a path that doesn't exist).\n */\n projectRoot?: string;\n /** 1-based per-project box index, when the caller resolved one. */\n projectIndex?: number;\n /** Fallback token generator for the relay/bridge tokens (e.g. `generateRelayToken`). */\n freshToken: () => string;\n}\n\n/**\n * The agents a registration says its box runs, or undefined when it never said.\n * Feeds `agents.list`: a `surface: 'service'` agent's units go only to a box\n * that runs it. Undefined (a row from an older host) keeps the ship-everything\n * answer rather than starving an openclaw box of its daemon.\n */\nexport function registrationAgents(\n reg: Pick<BoxRegistration, 'agent'>,\n): readonly string[] | undefined {\n return reg.agent ? [reg.agent] : undefined;\n}\n\n/** Same answer from a BoxRecord: `agents` as created, else the last agent that ran. */\nexport function recordAgents(\n box: Pick<BoxRecord, 'agents' | 'lastAgent'>,\n): readonly string[] | undefined {\n if (box.agents && box.agents.length > 0) return box.agents;\n return box.lastAgent ? [box.lastAgent] : undefined;\n}\n\n/** Narrow a registration's free-form agent string to the record's union. */\nexport function normalizeRegistrationAgent(agent: string | undefined): BoxRecord['lastAgent'] {\n return agent === 'claude' || agent === 'codex' || agent === 'opencode' ? agent : undefined;\n}\n\n/**\n * The box's SSH target, or undefined when the registration carries no host.\n *\n * `identityFile` is set only when the provider actually mints a per-box key dir:\n * a provider that reports a `publicHost` but no keypair would otherwise get a\n * bogus absolute `\"/id_ed25519\"` written into the record. Omitting it leaves ssh\n * to its normal key resolution.\n */\nexport function buildSshTarget(\n provider: string,\n sandboxId: string,\n publicHost: string | undefined,\n): SshTargetRecord | undefined {\n if (!publicHost) return undefined;\n const dir = boxSshDirForProvider(provider, sandboxId);\n return {\n host: publicHost,\n user: BOX_SSH_USER,\n ...(dir ? { identityFile: `${dir}/id_ed25519` } : {}),\n };\n}\n\n/**\n * Map a `BoxRegistration` (+ caller-supplied host context) to a `BoxRecord`.\n * Pure: it neither reads SSH keys nor writes state — the caller does that around\n * it. Idempotent-friendly: pass `existing` to preserve local identity on refresh.\n */\nexport function registrationToBoxRecord(\n reg: BoxRegistration,\n opts: RegistrationToRecordOptions,\n): BoxRecord {\n const provider = reg.backend ?? 'docker';\n const sandboxId = reg.sandboxId ?? reg.boxId;\n const { existing, projectRoot, projectIndex, controlPlaneUrl, freshToken } = opts;\n\n const branch = reg.worktrees?.[0]?.branch ?? `agentbox/${reg.name}`;\n const sanctionedBranch = reg.worktrees?.[0]?.sanctionedBranch ?? branch;\n\n // Git worktree bookkeeping points at the LOCAL clone (PC only). On the control\n // box `projectRoot` is undefined → no worktrees, which is correct: cloud\n // lifecycle/destroy need none, and host-side git RPCs would have no repo here.\n const gitWorktrees: GitWorktreeRecord[] | undefined = projectRoot\n ? [\n {\n kind: 'root',\n branch,\n sanctionedBranch,\n containerPath: '/workspace',\n hostMainRepo: projectRoot,\n gitWorktreePath: '',\n relPathFromWorkspace: '',\n },\n ]\n : undefined;\n\n return {\n id: existing?.id ?? reg.boxId,\n name: reg.name,\n displayName: existing?.displayName,\n provider,\n container: `cloud:${sandboxId}`,\n image: reg.image ?? existing?.image ?? '',\n workspacePath: projectRoot ?? existing?.workspacePath ?? '/workspace',\n projectRoot,\n projectIndex,\n // Tokens are regenerated only for a fresh adoption; a re-adopt keeps the\n // box's live tokens (already injected in the running box).\n relayToken: existing?.relayToken ?? reg.token ?? freshToken(),\n lastAgent: normalizeRegistrationAgent(reg.agent) ?? existing?.lastAgent,\n gitWorktrees,\n createdAt: reg.createdAt ?? existing?.createdAt ?? new Date().toISOString(),\n ssh: buildSshTarget(provider, sandboxId, reg.publicHost) ?? existing?.ssh,\n cloud: {\n ...existing?.cloud,\n backend: provider,\n sandboxId,\n image: reg.image ?? existing?.cloud?.image,\n webPort: reg.webPort ?? existing?.cloud?.webPort,\n publicHost: reg.publicHost ?? existing?.cloud?.publicHost,\n bridgeToken: reg.bridgeToken ?? existing?.cloud?.bridgeToken ?? freshToken(),\n relayPreviewUrl: reg.previewUrl ?? existing?.cloud?.relayPreviewUrl,\n relayPreviewToken: reg.previewToken ?? existing?.cloud?.relayPreviewToken,\n workspaceBranch: branch,\n sanctionedBranch,\n lastState: existing?.cloud?.lastState ?? 'running',\n topology: 'control-plane',\n controlPlaneUrl,\n // A hub-created box clones in-box from a leased URL — it shares no fork\n // base with a PC, so the session-start live resync must skip it.\n hostSeeded: undefined,\n },\n };\n}\n","/**\n * \"Open this link where the human actually is.\"\n *\n * A box that opens a URL (`agentbox-ctl open`, or anything through the box's\n * `$BROWSER`/`xdg-open` shim — an OAuth flow, `gh`, a dev-server preview) asks\n * the relay to mirror it on the host. Executing that in the relay process is\n * only right when the relay IS the human's machine: on a control box it opens a\n * browser on the VPS and the human sees nothing.\n *\n * So the relay decides *whether* the link may open (safe subset +\n * {@link browserOpenBudget}, server-side so every surface shares one policy) and\n * then hands it to whichever surface is attached, as an `open-link` prompt. The\n * claim is `PendingPrompts.resolve` — first caller wins, losers get 404 — which\n * is why every client claims BEFORE it opens. `openedByClient` on the answer is\n * how the winner tells the relay not to open it a second time.\n *\n * Shared by the docker (`server.ts`) and cloud (`host-actions.ts`) mirror paths\n * for the same reason `safe-transfer.ts` is: the policy must not drift between\n * the two transports.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { openOnHost } from '@agentbox/sandbox-core';\nimport { browserOpenBudget, type BrowserOpenBudget } from './browser-open-budget.js';\nimport type { PendingPrompts, PromptSubscribers } from './prompts.js';\nimport type { PromptAskEvent } from './types.js';\n\n/** How long an unclaimed open-link offer stays in the mailbox. */\nexport const OPEN_LINK_TTL_MS = 90_000;\n\nexport interface OpenLinkDeps {\n prompts: PendingPrompts;\n subscribers: PromptSubscribers;\n boxId: string;\n /** Box name for the card text; falls back to the id. */\n boxName?: string;\n /** `box.autoApproveSafeHostActions !== false` — the safe-subset gate. */\n autoApproveSafe: boolean;\n /**\n * True when this relay is a control box: it is not the human's machine, so it\n * must never open a link itself, however the offer ends.\n */\n controlPlane?: boolean;\n ttlMs?: number;\n /** Test seam; defaults to the process-wide budget both transports share. */\n budget?: BrowserOpenBudget;\n /** Test seam; defaults to a detached spawn of the host's URL handler. */\n openHost?: (url: string) => void;\n log?: (msg: string) => void;\n}\n\n/** What {@link offerBrowserOpen} did, for logs and tests. */\nexport type OpenLinkOutcome =\n /** Duplicate link inside the dedupe window — nothing happened. */\n | 'dropped'\n /** No surface attached and this relay is the human's machine: opened here. */\n | 'opened-locally'\n /** A client claimed it and opened it on its own machine. */\n | 'opened-by-client'\n /** Claimed with a plain `y` (a client that can't open) — opened here. */\n | 'opened-after-answer'\n /** Denied, dismissed, or expired unclaimed. */\n | 'unclaimed';\n\n/**\n * Offer `url` to the box's attached surfaces, and open it here when this relay\n * is the right machine and nobody else will. Resolves once the offer is settled;\n * the docker path fires it without awaiting (the box already got its 200).\n */\nexport async function offerBrowserOpen(deps: OpenLinkDeps, url: string): Promise<OpenLinkOutcome> {\n const budget = deps.budget ?? browserOpenBudget;\n const open = deps.openHost ?? openOnHost;\n const decision = budget.decide(deps.boxId, url, deps.autoApproveSafe);\n if (decision.action === 'drop') return 'dropped';\n // Charge an approved link against the budget HERE, not when it finally\n // opens. The box's `/rpc` is answered before the offer is even made, so a\n // looping agent fires the next `browser.open` while this one is still parked\n // — waiting for the claim to record would let every link in the loop see an\n // empty window, clear the burst limit, and be claimed together. That is the\n // tab-spray the budget exists to stop.\n if (decision.action === 'open') budget.record(deps.boxId, url);\n\n const promptEvent: Omit<PromptAskEvent, 'id'> = {\n kind: 'open-link',\n message: `Open link from box ${deps.boxName ?? deps.boxId}?`,\n detail: url,\n defaultAnswer: 'n',\n url,\n ...(decision.action === 'open' ? { autoOpen: true } : {}),\n context: { command: 'browser.open', argv: [url] },\n };\n\n // Approved, nobody streaming, and this relay is the human's own machine:\n // open it here and now. Skipping the offer keeps the laptop path instant and\n // is exactly what the relay did before surfaces could claim.\n //\n // A link that still needs a human is parked even with no stream attached —\n // the tray and the hub web UI read the approvals mailbox over REST, and\n // neither counts as a subscriber, so dropping it would hide the link from the\n // two surfaces most likely to be there when no terminal is.\n if (\n decision.action === 'open' &&\n !deps.controlPlane &&\n deps.subscribers.count(deps.boxId) === 0\n ) {\n deps.prompts.noteAutoApprove(deps.boxId, promptEvent, decision.reason);\n open(url);\n return 'opened-locally';\n }\n\n // `box.autoApproveHostActions` — the blanket opt-in — used to resolve this\n // confirm through `askPrompt`. Honour it here too (it audits itself), or an\n // unattended box that opted into everything would park an over-budget link\n // and drop it at the TTL instead of opening it.\n if (decision.action !== 'open' && deps.prompts.consumeAutoApprove(deps.boxId, promptEvent)) {\n budget.record(deps.boxId, url);\n if (deps.controlPlane) {\n deps.log?.(`browser.open: auto-approved but nothing here can open it (control box): ${url}`);\n return 'unclaimed';\n }\n open(url);\n return 'opened-locally';\n }\n\n const ev: PromptAskEvent = { id: randomUUID(), ...promptEvent };\n const settled = deps.prompts.add(deps.boxId, ev);\n const timer = setTimeout(() => {\n if (deps.prompts.resolve(ev.id, 'n', true)) {\n deps.subscribers.broadcast(deps.boxId, 'prompt-resolved', { id: ev.id });\n }\n }, deps.ttlMs ?? OPEN_LINK_TTL_MS);\n if (typeof timer.unref === 'function') timer.unref();\n deps.subscribers.broadcast(deps.boxId, 'prompt-ask', ev);\n\n const verdict = await settled;\n clearTimeout(timer);\n if (verdict.answer !== 'y' || verdict.cancelled) return 'unclaimed';\n if (decision.action === 'open') {\n deps.prompts.noteAutoApprove(deps.boxId, promptEvent, decision.reason);\n } else {\n // Only the over-budget path is uncharged at this point: an approved link\n // was recorded before it was offered.\n budget.record(deps.boxId, url);\n }\n if (verdict.openedByClient) return 'opened-by-client';\n // A plain `y`: the answering surface either can't open URLs or predates\n // `open-link` and rendered a confirm. Open it here — unless \"here\" is a\n // control box, where that would just pop a tab nobody can see.\n if (deps.controlPlane) {\n deps.log?.(`browser.open: approved but no client opened it (control box): ${url}`);\n return 'unclaimed';\n }\n open(url);\n return 'opened-after-answer';\n}\n","/**\n * Rate limiter for mirroring an in-box `browser.open` on the host browser.\n *\n * Opening a link on the host is part of the safe host-action subset\n * (`box.autoApproveSafeHostActions`), so it no longer waits for a human. The\n * confirm prompt used to double as the rate limiter — without it a looping\n * agent could spray the host with tabs — so the budget below takes over that\n * job: two opens per 30s and ten per 10 minutes, per box, counting every URL.\n *\n * Shared by the docker (`server.ts`) and cloud (`host-actions.ts`) mirror\n * paths, for the same reason `safe-transfer.ts` is shared: the policy must not\n * drift between the two transports.\n */\n\n/** Burst window: at most 2 host opens per box per 30s. */\nexport const BROWSER_OPEN_BURST = { limit: 2, windowMs: 30_000 } as const;\n/** Sustained window: at most 10 host opens per box per 10 minutes. */\nexport const BROWSER_OPEN_SUSTAINED = { limit: 10, windowMs: 600_000 } as const;\n/** A repeat of the exact same URL inside this window is dropped, not re-opened. */\nexport const BROWSER_OPEN_DEDUPE_MS = 30_000;\n\nexport type BrowserOpenDecision =\n /** Auto-approve: audit it and open on the host, no human involved. */\n | { action: 'open'; reason: string }\n /** Ask the host user, exactly as before the safe-subset change. */\n | { action: 'prompt'; reason: string }\n /** Duplicate link — do nothing at all (no open, no prompt). */\n | { action: 'drop'; reason: string };\n\ninterface OpenRecord {\n url: string;\n at: number;\n}\n\n/**\n * Per-box sliding-window budget. Stateful but pure of I/O; the clock is\n * injectable so the windows are unit-testable without waiting on real time.\n */\nexport class BrowserOpenBudget {\n private readonly opens = new Map<string, OpenRecord[]>();\n\n constructor(private readonly now: () => number = Date.now) {}\n\n /**\n * Decide what to do with a host-mirror request. Reads only — the caller\n * calls {@link record} when a host open actually happens, so a link the user\n * approved at the prompt feeds the same windows as an auto-approved one.\n */\n decide(boxId: string, url: string, autoApproveSafe: boolean): BrowserOpenDecision {\n const recent = this.prune(boxId);\n const now = this.now();\n if (recent.some((r) => r.url === url && now - r.at < BROWSER_OPEN_DEDUPE_MS)) {\n // A retry loop re-opening the identical tab is noise: it must not consume\n // budget, and it must not fall back to a prompt either.\n return { action: 'drop', reason: 'duplicate url' };\n }\n if (!autoApproveSafe) {\n return { action: 'prompt', reason: 'box.autoApproveSafeHostActions is false' };\n }\n const inWindow = (windowMs: number): number =>\n recent.reduce((n, r) => (now - r.at < windowMs ? n + 1 : n), 0);\n if (inWindow(BROWSER_OPEN_BURST.windowMs) >= BROWSER_OPEN_BURST.limit) {\n return { action: 'prompt', reason: 'burst limit' };\n }\n if (inWindow(BROWSER_OPEN_SUSTAINED.windowMs) >= BROWSER_OPEN_SUSTAINED.limit) {\n return { action: 'prompt', reason: 'sustained limit' };\n }\n return { action: 'open', reason: 'safe: browser.open' };\n }\n\n /** Charge one host open against the box's windows. */\n record(boxId: string, url: string): void {\n const recent = this.prune(boxId);\n recent.push({ url, at: this.now() });\n this.opens.set(boxId, recent);\n }\n\n /** Forget a box entirely (destroy / unregister). */\n forget(boxId: string): void {\n this.opens.delete(boxId);\n }\n\n /**\n * Drop stamps older than the widest window, so a box that opened a few links\n * and went away leaves no entry behind.\n */\n private prune(boxId: string): OpenRecord[] {\n const now = this.now();\n const kept = (this.opens.get(boxId) ?? []).filter(\n (r) => now - r.at < BROWSER_OPEN_SUSTAINED.windowMs,\n );\n if (kept.length === 0) this.opens.delete(boxId);\n else this.opens.set(boxId, kept);\n return kept;\n }\n}\n\n/** Process-wide budget: both mirror paths run in the same host relay process. */\nexport const browserOpenBudget = new BrowserOpenBudget();\n","/**\n * `HostActionQueue` — the box-mode relay's parking lot for host-only RPCs.\n * When the in-sandbox `/rpc` route receives `git.push` / `cp.*` / etc., it\n * cannot execute them locally (no host SSH keys, no host filesystem), so it\n * `enqueue`s and `await`s. The host's `CloudBoxPoller` drains via\n * `/bridge/poll`, executes on the host, and `resolve`s here via\n * `/bridge/action-result` — that resolves the awaited Promise and the\n * in-sandbox `/rpc` finally answers the in-box agent.\n *\n * Lifetime: per in-sandbox relay process; in-memory only. Actions outlive\n * individual polls (the queue is the source of truth, not the wire).\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { HostAction, HostActionResult } from './types.js';\n\ninterface Pending {\n action: HostAction;\n resolve: (r: HostActionResult) => void;\n /** True once a `/bridge/poll` has handed this action out. */\n delivered: boolean;\n}\n\n/**\n * Default max age for a parked action before it expires (15 minutes).\n * Picked to be longer than any reasonable interactive prompt + a host\n * restart window, but short enough that a forgotten queue doesn't replay\n * stale `git.push` attempts when the host relay rehydrates. Override per\n * queue instance for tests.\n */\nexport const DEFAULT_HOST_ACTION_MAX_AGE_MS = 15 * 60 * 1000;\n\nexport interface HostActionQueueOptions {\n /** Override the per-action expiry. Default {@link DEFAULT_HOST_ACTION_MAX_AGE_MS}. */\n maxAgeMs?: number;\n /** Clock injector (tests). */\n now?: () => number;\n}\n\nexport class HostActionQueue {\n private readonly map = new Map<string, Pending>();\n private readonly maxAgeMs: number;\n private readonly now: () => number;\n\n constructor(opts: HostActionQueueOptions = {}) {\n this.maxAgeMs = opts.maxAgeMs ?? DEFAULT_HOST_ACTION_MAX_AGE_MS;\n this.now = opts.now ?? ((): number => Date.now());\n }\n\n /**\n * Park a host-only RPC and return a Promise that resolves when the host\n * poller posts the result back. Caller should `await` and forward the\n * result to the in-box client; there's intentionally no client-side\n * timeout (matches the existing in-box `postRpc`'s \"block while a prompt\n * is open\" semantics).\n */\n enqueue(boxId: string, method: string, params: unknown): Promise<HostActionResult> {\n const id = randomUUID();\n const action: HostAction = {\n id,\n boxId,\n method,\n params,\n createdAt: new Date(this.now()).toISOString(),\n };\n return new Promise<HostActionResult>((resolve) => {\n this.map.set(id, { action, resolve, delivered: false });\n });\n }\n\n /**\n * Return every action the host hasn't been handed yet, marking them\n * delivered. The poller is expected to execute them and POST back to\n * `/bridge/action-result`. Re-delivery on poller retry isn't needed —\n * the queue holds the Promise until `resolve` is called.\n *\n * Actions older than `maxAgeMs` expire here: their `resolve` is called\n * with an `exitCode: 124, stderr: 'expired'` result so the in-box RPC\n * unblocks, and they don't appear in the drained list. Keeps a host\n * relay restart from replaying a long-forgotten `git.push`.\n */\n drain(): HostAction[] {\n const now = this.now();\n const out: HostAction[] = [];\n for (const [id, p] of this.map) {\n const createdAt = Date.parse(p.action.createdAt);\n if (Number.isFinite(createdAt) && now - createdAt > this.maxAgeMs) {\n this.map.delete(id);\n p.resolve({\n exitCode: 124,\n stdout: '',\n stderr: `host action '${p.action.method}' expired before the host could execute it\\n`,\n });\n continue;\n }\n if (!p.delivered) {\n out.push(p.action);\n p.delivered = true;\n }\n }\n return out;\n }\n\n /**\n * Settle a parked action with the host's result. Idempotent: a duplicate\n * resolve on the same id is a no-op. Returns whether the id matched.\n */\n resolve(id: string, result: HostActionResult): boolean {\n const p = this.map.get(id);\n if (!p) return false;\n this.map.delete(id);\n p.resolve(result);\n return true;\n }\n\n size(): number {\n return this.map.size;\n }\n\n /** Test/diagnostic: get the action with this id (returns undefined when settled). */\n peek(id: string): HostAction | undefined {\n return this.map.get(id)?.action;\n }\n}\n","/**\n * `HostReachQueue` — the control box's parking lot for host actions that can\n * only be executed on the user's own machine.\n *\n * The mirror image of {@link HostActionQueue}. There, an in-sandbox relay parks\n * an RPC and the *host* polls in to drain it. Here, a control box parks an RPC\n * and the *PC* polls in — over `/admin/hostreach/*`, authenticated with the\n * admin token — executes it against the real project files, and posts the result\n * back.\n *\n * Why a second queue instead of reusing the first: this one has to answer a\n * question the box-mode queue never faces — **is the other machine there at\n * all?** A cloud box asking for a file from a laptop that is closed must get a\n * useful answer in seconds, not block on a 15-minute expiry. So reachability is\n * modelled explicitly:\n *\n * - Nobody has polled within `reachTimeoutMs` and none arrives within\n * `graceMs` → `unreachable: 'never-connected'`. The caller decides what that\n * means (serve a cached copy, or fail with an actionable message).\n * - A poller took the action and then stopped polling for `reachTimeoutMs` →\n * `unreachable: 'went-away'`. The PC long-polls continuously while it lives,\n * so silence is the only honest signal that it died mid-copy.\n * - A poller took it and is still polling → wait indefinitely. The copy is\n * sitting behind a human approval on that machine, and cutting it off after\n * an arbitrary timeout would be worse than waiting (matches the no-TTL\n * semantics of every other parked approval).\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { HostAction, HostActionResult } from './types.js';\n\n/** Why a request could not be handed to a machine. Both are recoverable. */\nexport type HostReachUnreachable = 'never-connected' | 'went-away';\n\nexport type HostReachOutcome =\n | { kind: 'result'; result: HostActionResult }\n | { kind: 'unreachable'; reason: HostReachUnreachable };\n\n/**\n * Default reachability window. A poller re-polls every long-poll cycle (~25s),\n * so 60s tolerates one missed cycle plus a slow network before declaring the\n * machine gone.\n */\nexport const DEFAULT_HOST_REACH_TIMEOUT_MS = 60_000;\n\nexport interface HostReachQueueOptions {\n /** Silence longer than this means \"that machine is gone\". */\n reachTimeoutMs?: number;\n /**\n * How long a fresh request waits for a first poll before giving up. Defaults\n * to `reachTimeoutMs`. Only applies while the action is undelivered — once a\n * machine takes it, the wait is unbounded.\n */\n graceMs?: number;\n /** Clock injector (tests). */\n now?: () => number;\n /** Sweep interval for the went-away check. Tests pass a small value. */\n sweepIntervalMs?: number;\n}\n\ninterface Pending {\n action: HostAction;\n settle: (outcome: HostReachOutcome) => void;\n /** True once a poll handed this action out. */\n delivered: boolean;\n /**\n * Which poller took it. A restarted relay is a NEW process with a new id, and\n * the work its predecessor accepted but never finished must be re-offered to\n * it — otherwise the box waits forever on a result nobody is going to post,\n * invisible to the went-away sweep because the replacement poller keeps this\n * machine \"reachable\". Seen live: a `relay restart` mid-copy hung the box.\n */\n deliveredTo?: string;\n /** Pollers that refused this action; never offered to them again. */\n declinedBy?: Set<string>;\n /** Grace timer, cleared on delivery and re-armed on a decline. */\n timer?: ReturnType<typeof setTimeout>;\n}\n\ninterface Waiter {\n resolve: (actions: HostAction[]) => void;\n timer: ReturnType<typeof setTimeout>;\n /** Identity of the polling process, for the orphan re-offer above. */\n pollerId?: string;\n}\n\n/** A machine holding an open stream. Unlike a waiter, delivery does not consume it. */\ninterface Subscriber {\n pollerId: string;\n deliver: (actions: HostAction[]) => void;\n}\n\nexport class HostReachQueue {\n private readonly map = new Map<string, Pending>();\n private readonly waiters = new Set<Waiter>();\n private readonly subscribers = new Set<Subscriber>();\n private readonly reachTimeoutMs: number;\n private readonly graceMs: number;\n private readonly now: () => number;\n private readonly sweepIntervalMs: number;\n private lastPollAtMs: number | null = null;\n /** pollerId → last poll time, so \"did the owner of this copy go away?\" is answerable. */\n private readonly pollerSeen = new Map<string, number>();\n private sweepTimer: ReturnType<typeof setInterval> | null = null;\n\n constructor(opts: HostReachQueueOptions = {}) {\n this.reachTimeoutMs = opts.reachTimeoutMs ?? DEFAULT_HOST_REACH_TIMEOUT_MS;\n this.graceMs = opts.graceMs ?? this.reachTimeoutMs;\n this.now = opts.now ?? ((): number => Date.now());\n this.sweepIntervalMs = opts.sweepIntervalMs ?? 5_000;\n }\n\n /** Whether a machine has polled recently enough to be considered present. */\n reachable(): boolean {\n if (this.lastPollAtMs === null) return false;\n return this.now() - this.lastPollAtMs <= this.reachTimeoutMs;\n }\n\n /** Epoch ms of the last poll, or null when no machine has ever connected. */\n lastPollAt(): number | null {\n return this.lastPollAtMs;\n }\n\n /**\n * Park an action for the user's machine and wait for its result.\n *\n * Resolves with `unreachable` rather than rejecting: \"no machine there\" is a\n * normal, expected state (a closed laptop), not an error condition.\n */\n request(\n boxId: string,\n method: string,\n params: unknown,\n opts: { cachePrefix?: string } = {},\n ): Promise<HostReachOutcome> {\n const id = randomUUID();\n const action: HostAction = {\n id,\n boxId,\n method,\n params,\n createdAt: new Date(this.now()).toISOString(),\n ...(opts.cachePrefix ? { cachePrefix: opts.cachePrefix } : {}),\n };\n return new Promise<HostReachOutcome>((resolve) => {\n const pending: Pending = { action, settle: resolve, delivered: false };\n pending.timer = setTimeout(() => {\n // Still undelivered after the grace window: nobody is listening.\n if (this.map.get(id) === pending && !pending.delivered) {\n this.map.delete(id);\n resolve({ kind: 'unreachable', reason: 'never-connected' });\n }\n }, this.graceMs);\n // Node keeps the process alive for pending timers; a parked copy must not\n // be what holds a relay open on shutdown.\n pending.timer.unref?.();\n this.map.set(id, pending);\n this.ensureSweep();\n this.handOff();\n });\n }\n\n /**\n * Long-poll entry point: resolve with every undelivered action, waiting up to\n * `timeoutMs` for one to appear. An empty array means \"nothing for you right\n * now\" — the poller simply polls again.\n *\n * Calling this marks the machine present, whether or not anything is queued:\n * an idle poll is exactly how a laptop says \"I'm here\".\n */\n poll(timeoutMs: number, pollerId?: string): Promise<HostAction[]> {\n this.lastPollAtMs = this.now();\n if (pollerId !== undefined) this.pollerSeen.set(pollerId, this.lastPollAtMs);\n const ready = this.takeUndelivered(pollerId);\n if (ready.length > 0) return Promise.resolve(ready);\n return new Promise<HostAction[]>((resolve) => {\n const waiter: Waiter = {\n resolve,\n pollerId,\n timer: setTimeout(() => {\n this.waiters.delete(waiter);\n resolve([]);\n }, timeoutMs),\n };\n // NOT unref'd, unlike the grace/sweep timers: this one is the deadline of\n // an in-flight HTTP request, and an unref'd timer does not fire on an\n // otherwise-idle loop — the long poll would then never answer.\n this.waiters.add(waiter);\n });\n }\n\n /**\n * Register a machine that stays connected (the SSE stream) instead of asking\n * again after every batch.\n *\n * A subscriber is modelled as a **waiter that is never consumed**: the same\n * eligibility, ownership, decline and orphan rules apply, because they are the\n * same code path. That is deliberate — those rules took four review rounds to\n * get right, and a second delivery mechanism with its own copy of them would\n * be the obvious place for the fifth bug to live.\n *\n * Returns an unsubscribe. Call {@link touch} while the connection is alive so\n * presence does not lapse on a quiet stream.\n */\n subscribe(pollerId: string, deliver: (actions: HostAction[]) => void): () => void {\n this.touch(pollerId);\n const subscriber: Subscriber = { pollerId, deliver };\n this.subscribers.add(subscriber);\n // Whatever is already queued and eligible goes out now: a machine that\n // reconnects mid-copy should not wait for the next action to arrive.\n const ready = this.takeUndelivered(pollerId);\n if (ready.length > 0) deliver(ready);\n return () => {\n this.subscribers.delete(subscriber);\n };\n }\n\n /**\n * Mark a machine present without handing it anything — what an SSE heartbeat\n * means. Presence is what decides whether a copy waits for that machine or\n * falls back, so a live-but-quiet stream must keep it fresh.\n */\n touch(pollerId: string): void {\n const now = this.now();\n this.lastPollAtMs = now;\n this.pollerSeen.set(pollerId, now);\n }\n\n /**\n * Settle a parked action with the machine's result. Returns whether it matched.\n *\n * `pollerId`, when given, must be the poller the action was handed to: after a\n * re-offer the previous owner may still be running, and letting its late\n * result land would settle the box's request with the answer of a machine that\n * no longer owns the copy.\n */\n resolve(id: string, result: HostActionResult, pollerId?: string): boolean {\n const pending = this.map.get(id);\n if (!pending) return false;\n if (\n pollerId !== undefined &&\n pending.deliveredTo !== undefined &&\n pending.deliveredTo !== pollerId\n ) {\n return false;\n }\n this.map.delete(id);\n if (pending.timer) clearTimeout(pending.timer);\n pending.settle({ kind: 'result', result });\n return true;\n }\n\n /**\n * Hand an action back unexecuted, because the machine that took it does not\n * own that box.\n *\n * Settling it instead would be wrong with more than one machine on a hub: the\n * first poller to see fresh work is not necessarily the one holding the files,\n * and its \"I don't know that box\" would answer a question meant for someone\n * else. Declining returns the action to the pool, and the grace/heartbeat\n * timers still bound the case where *nobody* claims it.\n */\n decline(id: string, pollerId?: string): boolean {\n const pending = this.map.get(id);\n if (!pending) return false;\n if (\n pollerId !== undefined &&\n pending.deliveredTo !== undefined &&\n pending.deliveredTo !== pollerId\n ) {\n return false;\n }\n pending.delivered = false;\n pending.deliveredTo = undefined;\n // Never offer it back to the machine that just refused it: it would take,\n // decline, take again — a tight loop that also starves the fallback, since\n // the went-away sweep only looks at delivered work.\n if (pollerId !== undefined) (pending.declinedBy ??= new Set()).add(pollerId);\n // Delivery cleared the grace timer, so without re-arming it a declined\n // action could sit undelivered forever and the box would wait on a copy no\n // machine is ever going to make. Re-armed, an unclaimed decline falls\n // through to the cache / outbox / error like any other unreachable copy.\n if (pending.timer) clearTimeout(pending.timer);\n pending.timer = setTimeout(() => {\n if (this.map.get(id) === pending && !pending.delivered) {\n this.map.delete(id);\n pending.settle({ kind: 'unreachable', reason: 'never-connected' });\n }\n }, this.graceMs);\n pending.timer.unref?.();\n // Another machine may already be waiting for work.\n this.handOff();\n return true;\n }\n\n size(): number {\n return this.map.size;\n }\n\n /** Test/diagnostic: the parked action with this id (undefined once settled). */\n peek(id: string): HostAction | undefined {\n return this.map.get(id)?.action;\n }\n\n /** Release timers + fail every parked action, so a relay can shut down cleanly. */\n stop(): void {\n if (this.sweepTimer) {\n clearInterval(this.sweepTimer);\n this.sweepTimer = null;\n }\n for (const waiter of this.waiters) {\n clearTimeout(waiter.timer);\n waiter.resolve([]);\n }\n this.waiters.clear();\n this.subscribers.clear();\n for (const [id, pending] of this.map) {\n this.map.delete(id);\n if (pending.timer) clearTimeout(pending.timer);\n pending.settle({ kind: 'unreachable', reason: 'went-away' });\n }\n }\n\n /** Hand any undelivered actions to a waiting poller. */\n private handOff(): void {\n // Streams first: a subscriber is already connected, so handing work there\n // costs nothing and leaves the one-shot waiters for machines that are\n // between polls.\n for (const sub of [...this.subscribers]) {\n const ready = this.takeUndelivered(sub.pollerId);\n if (ready.length === 0) continue;\n this.pollerSeen.set(sub.pollerId, this.now());\n sub.deliver(ready);\n return;\n }\n // Every waiter gets a look: the first one may be the machine that just\n // declined this action, and stopping there would leave work parked while\n // another machine sits idle on an open poll.\n for (const waiter of [...this.waiters]) {\n const ready = this.takeUndelivered(waiter.pollerId);\n if (ready.length === 0) continue;\n if (waiter.pollerId !== undefined) this.pollerSeen.set(waiter.pollerId, this.now());\n this.waiters.delete(waiter);\n clearTimeout(waiter.timer);\n waiter.resolve(ready);\n return;\n }\n }\n\n /**\n * Hand one specific action to any waiting poller eligible for it (i.e. one\n * that has not refused it). Returns whether it found a taker.\n */\n private offerToWaiter(pending: Pending): boolean {\n for (const sub of [...this.subscribers]) {\n if (pending.declinedBy?.has(sub.pollerId)) continue;\n pending.delivered = true;\n pending.deliveredTo = sub.pollerId;\n this.pollerSeen.set(sub.pollerId, this.now());\n if (pending.timer) {\n clearTimeout(pending.timer);\n pending.timer = undefined;\n }\n sub.deliver([pending.action, ...this.takeUndelivered(sub.pollerId)]);\n return true;\n }\n for (const waiter of [...this.waiters]) {\n const pid = waiter.pollerId;\n if (pid !== undefined && pending.declinedBy?.has(pid)) continue;\n pending.delivered = true;\n pending.deliveredTo = pid;\n // Handing work to a waiter IS contact with that machine: without this the\n // next sweep judges it by a stale heartbeat and takes back the copy it was\n // just given.\n if (pid !== undefined) this.pollerSeen.set(pid, this.now());\n if (pending.timer) {\n clearTimeout(pending.timer);\n pending.timer = undefined;\n }\n this.waiters.delete(waiter);\n clearTimeout(waiter.timer);\n // Anything else that poller may take rides along, so it is not left\n // waiting a full cycle for work already queued.\n waiter.resolve([pending.action, ...this.takeUndelivered(pid)]);\n return true;\n }\n return false;\n }\n\n private takeUndelivered(pollerId?: string): HostAction[] {\n const out: HostAction[] = [];\n const now = this.now();\n for (const pending of this.map.values()) {\n // Re-offer work whose owner has gone quiet — but only then. Handing an\n // in-flight copy to whichever poller asks next lets a second machine (or\n // an old process still finishing) claim it, answer \"I don't know that box\"\n // (exit 69), and settle the request; the real machine's success then\n // arrives with nowhere to go. So an owner that is still polling keeps its\n // work, however long the user takes to answer its confirm.\n const owner = pending.deliveredTo;\n const ownerSeenAt = owner === undefined ? undefined : this.pollerSeen.get(owner);\n const ownerGone =\n owner !== undefined &&\n owner !== pollerId &&\n (ownerSeenAt === undefined || now - ownerSeenAt > this.reachTimeoutMs);\n const orphaned = pending.delivered && pollerId !== undefined && ownerGone;\n if (pending.delivered && !orphaned) continue;\n // A machine that already refused this action does not get asked twice.\n if (pollerId !== undefined && pending.declinedBy?.has(pollerId)) continue;\n pending.delivered = true;\n pending.deliveredTo = pollerId;\n // Delivery ends the grace window: from here the wait is unbounded, and\n // only the went-away sweep can cut it short.\n if (pending.timer) {\n clearTimeout(pending.timer);\n pending.timer = undefined;\n }\n out.push(pending.action);\n }\n return out;\n }\n\n private ensureSweep(): void {\n if (this.sweepTimer) return;\n this.sweepTimer = setInterval(() => this.sweep(), this.sweepIntervalMs);\n this.sweepTimer.unref?.();\n }\n\n /**\n * Fail delivered-but-unanswered actions once the machine that took them has\n * stopped polling. Without this a laptop that sleeps mid-copy leaves the box\n * blocked forever on an RPC nobody will ever answer.\n */\n private sweep(): void {\n if (this.map.size === 0) {\n if (this.sweepTimer) {\n clearInterval(this.sweepTimer);\n this.sweepTimer = null;\n }\n return;\n }\n const now = this.now();\n for (const [id, pending] of this.map) {\n if (!pending.delivered) continue;\n // Ask whether THIS action's owner is still alive, not whether anyone is.\n // A global \"someone polled recently\" check hangs the box whenever another\n // machine keeps polling: the owner is gone, the survivor already declined\n // the work (or does not hold the box), and nothing settles it.\n const owner = pending.deliveredTo;\n const seenAt = owner === undefined ? this.lastPollAtMs : (this.pollerSeen.get(owner) ?? null);\n if (seenAt !== null && now - seenAt <= this.reachTimeoutMs) continue;\n // Offer THIS action before declaring it lost. A relay that restarted\n // mid-copy is sitting in its long poll right now, and `takeUndelivered`\n // only runs when a poll *arrives* — so without an offer the box fails over\n // to the cache while the machine that owns the files waits, connected, for\n // work to appear. Targeted rather than a generic hand-off, because that\n // stops at the first waiter to receive *anything*: with two orphans in\n // flight it can hand a waiter the other one and leave this one looking\n // unclaimed while an eligible machine is still listening.\n pending.delivered = false;\n pending.deliveredTo = undefined;\n if (this.offerToWaiter(pending)) continue;\n this.map.delete(id);\n pending.settle({ kind: 'unreachable', reason: 'went-away' });\n }\n }\n}\n","/**\n * The control box's half of the cp cache: answering `cp fromHost` from stored\n * bytes when the machine that owns the files is not connected.\n *\n * Two rules shape this, both about not lying to an agent:\n *\n * 1. **All or nothing.** A multi-source copy that finds three of four entries\n * fails rather than delivering a partial set, because the box has no way to\n * tell which of its files is missing and would proceed as if it had them all.\n * 2. **Always say it is cached, and from when.** The result stdout carries the\n * age of every entry. An agent reading a config file has to be able to tell\n * \"this is live\" from \"this is what your laptop looked like on Tuesday\".\n */\n\nimport { execFile } from 'node:child_process';\nimport { createWriteStream, existsSync } from 'node:fs';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, join } from 'node:path';\nimport { pipeline } from 'node:stream/promises';\nimport type { CustodyStore } from './custody/store.js';\nimport {\n cpCacheMetaPath,\n cpCacheTarPath,\n describeCacheAge,\n parseCpCacheMeta,\n type CpCacheMeta,\n} from './cp-cache.js';\nimport { normalizeCpParams } from './cp-rpc.js';\nimport type { CpRpcParams, HostActionResult } from './types.js';\n\nconst UNTAR_TIMEOUT_MS = 120_000;\nconst CP_TIMEOUT_MS = 300_000;\n\nexport interface CpCacheServeDeps {\n custody: CustodyStore | null | undefined;\n /** `AGENTBOX_CLI_ENTRY` — the CLI this hub shells for the box-side copy. */\n cliEntry: string | undefined;\n boxName: string;\n cachePrefix: string;\n log?: (line: string) => void;\n}\n\n/**\n * What the cache can offer for a request, without moving any bytes: used to\n * decide whether to bother asking the user to approve a cached copy.\n */\nexport interface CpCacheLookup {\n /** Resolved absolute host path → its stored metadata. */\n entries: { sourcePath: string; meta: CpCacheMeta }[];\n /** Sources with no cached entry. Non-empty ⇒ the cache cannot serve this. */\n missing: string[];\n}\n\n/** Which of `sources` (already resolved to absolute host paths) the cache holds. */\nexport async function lookupCpCache(\n sources: string[],\n deps: Pick<CpCacheServeDeps, 'custody' | 'cachePrefix'>,\n): Promise<CpCacheLookup> {\n const entries: { sourcePath: string; meta: CpCacheMeta }[] = [];\n const missing: string[] = [];\n if (!deps.custody) return { entries, missing: [...sources] };\n for (const sourcePath of sources) {\n const metaRaw = await deps.custody.get(cpCacheMetaPath(deps.cachePrefix, sourcePath));\n const meta = metaRaw ? parseCpCacheMeta(metaRaw.data.toString('utf8')) : null;\n const tar = await deps.custody.stat(cpCacheTarPath(deps.cachePrefix, sourcePath));\n if (!meta || !tar) missing.push(sourcePath);\n else entries.push({ sourcePath, meta });\n }\n return { entries, missing };\n}\n\n/** One line per entry, so the age is visible in both the approval and the box. */\nexport function describeCpCacheEntries(lookup: CpCacheLookup, now: number = Date.now()): string {\n return lookup.entries\n .map(\n // The path it was captured FROM on the owning machine, not the box's\n // spelling of it: the person approving is being asked about their own disk.\n (e) => ` ${e.meta.sourcePath} (${describeCacheAge(e.meta.capturedAt, now)})`,\n )\n .join('\\n');\n}\n\n/**\n * Unpack the cached entries and deliver them into the box, by shelling the same\n * `agentbox cp` a live copy would use — only the source moves. cwd is the temp\n * dir we just created, which is also why this path cannot reproduce the missing-\n * cwd crash that made cp fail on a control box in the first place.\n */\nexport async function serveCpFromCache(\n params: CpRpcParams | undefined,\n resolved: string[],\n deps: CpCacheServeDeps,\n): Promise<HostActionResult> {\n const log = deps.log ?? ((): void => {});\n if (!deps.cliEntry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot deliver the cached copy\\n',\n };\n }\n const { dest } = normalizeCpParams('cp.fromHost', params);\n const lookup = await lookupCpCache(resolved, deps);\n if (lookup.missing.length > 0 || !deps.custody) {\n return { exitCode: 69, stdout: '', stderr: '' };\n }\n let workDir: string | undefined;\n try {\n const dir = await mkdtemp(join(tmpdir(), 'agentbox-cp-serve-'));\n workDir = dir;\n const names: string[] = [];\n for (const entry of lookup.entries) {\n const found = await deps.custody.getStream(\n cpCacheTarPath(deps.cachePrefix, entry.sourcePath),\n );\n if (!found) return { exitCode: 69, stdout: '', stderr: '' };\n const tarPath = join(dir, `${names.length.toString()}.tar`);\n await pipeline(found.data, createWriteStream(tarPath));\n await run('tar', ['-xf', tarPath, '-C', dir], UNTAR_TIMEOUT_MS);\n await rm(tarPath, { force: true });\n names.push(basename(entry.sourcePath));\n }\n const staged = names.map((n) => join(dir, n));\n // The staged files must exist before we hand them to the CLI. A silent\n // mismatch here (a tar member named differently from the key's basename)\n // would otherwise reach `agentbox cp` as a missing source — and a missing\n // source is exactly the kind of thing a CLI can report in a way this code\n // reads as success.\n const absent = staged.filter((p) => !existsSync(p));\n if (absent.length > 0) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `the hub's cached copy is unusable: ${absent.join(', ')} missing after unpacking\\n`,\n };\n }\n const argv = [deps.cliEntry, 'cp', ...staged, `${deps.boxName}:${dest}`, '--yes'];\n const out = await runCapture(process.execPath, argv, dir, CP_TIMEOUT_MS);\n if (out.exitCode !== 0) return out;\n // Exit 0 is not proof of delivery. `agentbox cp` announces `copied to\n // <box>:<path>` when it actually moves bytes; without that line the copy did\n // not happen, and reporting success would hand the box a file that is not\n // there — the worst failure mode this whole path has.\n if (!/copied to /.test(out.stdout)) {\n log(\n `cp cache: the copy into ${deps.boxName} reported success but said nothing was copied ` +\n `(stdout: ${JSON.stringify(out.stdout.slice(0, 300))}, stderr: ${JSON.stringify(out.stderr.slice(0, 300))})`,\n );\n return {\n exitCode: 1,\n stdout: '',\n stderr:\n `the hub had a cached copy but could not deliver it into this box.\\n` +\n `${out.stderr.trim()}\\n`,\n };\n }\n const age = describeCpCacheEntries(lookup);\n log(`cp cache: served ${String(lookup.entries.length)} entr(y|ies) for ${deps.boxName}`);\n return {\n exitCode: 0,\n // The provenance goes in stdout, where the agent that asked will read it —\n // a cached file that looks live is worse than no file.\n stdout:\n `${out.stdout.trimEnd()}\\n` +\n `NOTE: served from the hub's cache — the machine holding these files is offline.\\n${age}\\n`,\n stderr: out.stderr,\n };\n } catch (err) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `serving the cached copy failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n } finally {\n if (workDir) await rm(workDir, { recursive: true, force: true }).catch(() => {});\n }\n}\n\nfunction run(bin: string, args: string[], timeout: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n execFile(bin, args, { timeout }, (err) => (err ? reject(err) : resolve()));\n });\n}\n\nfunction runCapture(\n bin: string,\n args: string[],\n cwd: string,\n timeout: number,\n): Promise<HostActionResult> {\n return new Promise<HostActionResult>((resolve) => {\n execFile(bin, args, { cwd, timeout }, (err, stdout, stderr) => {\n const code =\n err && typeof (err as { code?: unknown }).code === 'number'\n ? (err as unknown as { code: number }).code\n : err\n ? 1\n : 0;\n resolve({ exitCode: code, stdout: stdout || '', stderr: stderr || '' });\n });\n });\n}\n","/**\n * The outbox: where a box's `cp toHost` waits when the machine it is addressed\n * to is offline.\n *\n * The read direction has a cache to fall back on; the write direction has\n * nowhere to fall back to — the destination is a disk that is not currently\n * reachable. Failing outright would mean an agent's build artifact, diff or log\n * is simply lost because a laptop was shut. So the control box pulls the bytes\n * out of the box while it still can, parks them in custody with their intended\n * destination, and the machine lands them (behind the usual approval) the next\n * time it connects.\n *\n * The box is told plainly that this happened, with a non-zero exit: the copy it\n * asked for has NOT landed yet, and reporting success would be a lie an agent\n * would build on.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { execFile } from 'node:child_process';\nimport { createReadStream, createWriteStream, existsSync } from 'node:fs';\nimport { mkdtemp, readdir, rename, rm, stat } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { pipeline } from 'node:stream/promises';\nimport type { CustodyStore } from './custody/store.js';\nimport type { HostActionResult } from './types.js';\n\n/** Sidecar for one parked outbound copy. */\nexport interface CpOutboxMeta {\n id: string;\n boxId: string;\n boxName: string;\n /** Destination exactly as the box asked for it — resolved on the target machine. */\n dest: string;\n /** Box-side sources, for the approval message. */\n sources: string[];\n createdAt: string;\n size: number;\n}\n\n/** A parked item as the draining machine sees it. */\nexport interface CpOutboxItem {\n meta: CpOutboxMeta;\n /** Custody path of the tar. */\n tarPath: string;\n /** Custody path of the sidecar. */\n metaPath: string;\n}\n\nconst PULL_TIMEOUT_MS = 300_000;\nconst TAR_TIMEOUT_MS = 120_000;\n\n/** Custody prefix for a project's outbox. Mirrors {@link cpCachePrefix}'s shape. */\nexport function cpOutboxPrefix(opts: { projectSlug?: string; boxId: string }): string {\n const slug = (opts.projectSlug ?? '').trim();\n return slug.length > 0 ? `projects/${slug}/cp-out` : `boxes/${opts.boxId}/cp-out`;\n}\n\n/** True for a custody path that is an outbox sidecar (the listing's filter). */\nexport function isCpOutboxMetaPath(path: string): boolean {\n return /\\/cp-out\\/[A-Za-z0-9-]+\\.json$/.test(path);\n}\n\n/** Every parked item currently in custody, newest first. */\nexport async function listCpOutbox(custody: CustodyStore): Promise<CpOutboxItem[]> {\n const out: CpOutboxItem[] = [];\n for (const entry of await custody.list()) {\n if (!isCpOutboxMetaPath(entry.path)) continue;\n const found = await custody.get(entry.path);\n if (!found) continue;\n try {\n const meta = JSON.parse(found.data.toString('utf8')) as CpOutboxMeta;\n if (!meta || typeof meta.id !== 'string' || typeof meta.dest !== 'string') continue;\n out.push({\n meta,\n metaPath: entry.path,\n tarPath: entry.path.replace(/\\.json$/, '.tar'),\n });\n } catch {\n /* a corrupt sidecar is not an item; the sweep below will not touch it */\n }\n }\n return out.sort((a, b) => (a.meta.createdAt < b.meta.createdAt ? 1 : -1));\n}\n\n/** Drop one parked item (both halves). Safe to call twice. */\nexport async function removeCpOutboxItem(custody: CustodyStore, item: CpOutboxItem): Promise<void> {\n await custody.delete(item.tarPath).catch(() => false);\n await custody.delete(item.metaPath).catch(() => false);\n}\n\nexport interface ParkCpOutboxDeps {\n custody: CustodyStore | null | undefined;\n cliEntry: string | undefined;\n boxId: string;\n boxName: string;\n prefix: string;\n maxBytes: number;\n log?: (line: string) => void;\n}\n\n/**\n * Pull `sources` out of the box and park them for the offline machine.\n *\n * Returns the result the box gets. Any failure here degrades to a plain\n * \"machine offline\" answer from the caller — the bytes were never on the target\n * disk, so nothing is lost by not parking them.\n */\nexport async function parkCpOutbox(\n sources: string[],\n dest: string,\n deps: ParkCpOutboxDeps,\n): Promise<HostActionResult | null> {\n const log = deps.log ?? ((): void => {});\n if (!deps.custody || !deps.cliEntry) return null;\n let workDir: string | undefined;\n try {\n const dir = await mkdtemp(join(tmpdir(), 'agentbox-cp-outbox-'));\n workDir = dir;\n const stage = join(dir, 'payload');\n await run('mkdir', ['-p', stage], TAR_TIMEOUT_MS);\n // Pull with the same CLI a live copy uses; cwd is this fresh dir, so the\n // deleted-workspace crash that started all of this cannot recur here.\n for (const src of sources) {\n await runNode(\n [deps.cliEntry, 'cp', `${deps.boxName}:${src}`, stage, '--yes'],\n dir,\n PULL_TIMEOUT_MS,\n );\n }\n const names = await readdir(stage);\n if (names.length === 0) return null;\n const tarPath = join(dir, 'outbox.tar');\n await run('tar', ['-cf', tarPath, '-C', stage, ...names], TAR_TIMEOUT_MS);\n const info = await stat(tarPath);\n if (info.size > deps.maxBytes) {\n log(`cp outbox: ${String(info.size)} bytes exceeds the ${String(deps.maxBytes)}-byte limit`);\n return null;\n }\n const id = randomUUID();\n const meta: CpOutboxMeta = {\n id,\n boxId: deps.boxId,\n boxName: deps.boxName,\n dest,\n sources,\n createdAt: new Date().toISOString(),\n size: info.size,\n };\n await deps.custody.putStream(`${deps.prefix}/${id}.tar`, createReadStream(tarPath), {\n maxBytes: deps.maxBytes,\n });\n await deps.custody.put(`${deps.prefix}/${id}.json`, Buffer.from(JSON.stringify(meta), 'utf8'));\n log(`cp outbox: parked ${String(names.length)} path(s) from ${deps.boxName} for ${dest}`);\n return {\n // 75 = EX_TEMPFAIL: accepted, not yet delivered. A zero here would tell an\n // agent the file is on the user's disk when it is still in transit.\n exitCode: 75,\n stdout: '',\n stderr:\n `the machine these files are addressed to is offline, so they are parked on the hub.\\n` +\n `It will land them at ${dest} — behind the usual approval — the next time it connects.\\n`,\n };\n } catch (err) {\n log(`cp outbox: could not park: ${err instanceof Error ? err.message : String(err)}`);\n return null;\n } finally {\n if (workDir) await rm(workDir, { recursive: true, force: true }).catch(() => {});\n }\n}\n\n/**\n * Land one parked item at `destAbs`, following the same rules a live `cp` does:\n *\n * - a destination that exists as a directory, or was written with a trailing\n * slash, receives the tar's members under their own names;\n * - otherwise the destination NAMES the file, so a single member is renamed onto\n * it (`cp toHost /workspace/report.md ./out/summary.md` must produce\n * `summary.md`, not `report.md`).\n *\n * The naive \"strip to the parent directory\" version silently did the first thing\n * in both cases, so a renaming copy landed under the wrong name and a copy into\n * `./out` (no slash) landed one level too high.\n */\nexport async function landCpOutboxTar(\n tarFile: string,\n destAbs: string,\n opts: { destEndsWithSlash: boolean },\n): Promise<void> {\n const asDirectory =\n opts.destEndsWithSlash || (existsSync(destAbs) && (await stat(destAbs)).isDirectory());\n if (asDirectory) {\n await run('mkdir', ['-p', destAbs], TAR_TIMEOUT_MS);\n await run('tar', ['-xf', tarFile, '-C', destAbs], TAR_TIMEOUT_MS);\n return;\n }\n // Unpack aside so the member's own name never appears at the destination —\n // but stage inside the destination's OWN directory, not the system tmpdir.\n // `/tmp` is routinely a different filesystem, where `rename` fails with EXDEV;\n // deleting the destination first and then discovering that would destroy the\n // file the copy was meant to update. Same-filesystem staging makes the final\n // step an atomic replace that either happens or leaves everything as it was.\n await run('mkdir', ['-p', dirname(destAbs)], TAR_TIMEOUT_MS);\n const staging = await mkdtemp(join(dirname(destAbs), '.agentbox-cp-'));\n try {\n await run('tar', ['-xf', tarFile, '-C', staging], TAR_TIMEOUT_MS);\n const members = await readdir(staging);\n if (members.length === 1) {\n // rename() replaces an existing FILE atomically, so nothing is removed\n // first. A directory in the way cannot be replaced that way and is the\n // only case that needs clearing.\n if (existsSync(destAbs) && (await stat(destAbs)).isDirectory()) {\n await rm(destAbs, { recursive: true, force: true });\n }\n await rename(join(staging, members[0]!), destAbs);\n return;\n }\n // Several members cannot share one filename; the destination is the\n // directory they belong in, which is also what `cp a b dir/` means.\n await run('mkdir', ['-p', destAbs], TAR_TIMEOUT_MS);\n for (const m of members) {\n const target = join(destAbs, m);\n if (existsSync(target) && (await stat(target)).isDirectory()) {\n await rm(target, { recursive: true, force: true });\n }\n await rename(join(staging, m), target);\n }\n } finally {\n await rm(staging, { recursive: true, force: true }).catch(() => {});\n }\n}\n\n/** Write a readable to a temp file and return its path (caller removes the dir). */\nexport async function stageOutboxTar(\n data: NodeJS.ReadableStream,\n): Promise<{ dir: string; tarPath: string }> {\n const dir = await mkdtemp(join(tmpdir(), 'agentbox-cp-land-'));\n const tarPath = join(dir, 'payload.tar');\n await pipeline(data, createWriteStream(tarPath));\n return { dir, tarPath };\n}\n\nfunction run(bin: string, args: string[], timeout: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n execFile(bin, args, { timeout }, (err) => (err ? reject(err) : resolve()));\n });\n}\n\nfunction runNode(argv: string[], cwd: string, timeout: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n execFile(process.execPath, argv, { cwd, timeout }, (err) => (err ? reject(err) : resolve()));\n });\n}\n","/**\n * A minimal in-process fan-out for the embedded hub UI. The hub's SSE route\n * (`/api/events`) subscribes; the relay calls `notify()` whenever the pending\n * approvals set changes (via `PendingPrompts.setOnChange`), so connected\n * browsers refresh without polling. No `EventEmitter` dependency — the surface\n * is just subscribe/notify.\n */\nexport class HubNotifier {\n private readonly listeners = new Set<() => void>();\n\n /** Register a listener; returns an unsubscribe fn. */\n subscribe(fn: () => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /** Fire every listener. A throwing listener never blocks the others. */\n notify(): void {\n for (const fn of this.listeners) {\n try {\n fn();\n } catch {\n /* a dead listener must not break the fan-out */\n }\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { PromptSubscribers } from './prompts.js';\nimport type { BoxNoticeEvent, NoticeKind } from './types.js';\n\n/**\n * Default lifespan of a notice when its owner never clears it explicitly.\n * Longer than the relay's checkpoint RPC timeout (600s) so a notice still\n * self-expires even if the host CLI is SIGKILLed before its `finally` runs.\n */\nconst DEFAULT_NOTICE_TTL_MS = 660_000;\n\ninterface NoticeEntry {\n ev: BoxNoticeEvent;\n boxId: string;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * In-memory per-box informational notices, broadcast over the same SSE\n * channel as confirmation prompts. Unlike {@link import('./prompts.js').PendingPrompts}\n * these are fire-and-forget: there is no awaited promise and no answer. A\n * notice marks a box as transiently busy (a checkpoint freezes it via\n * `docker commit`); the host wrapper renders a spinner so the user can\n * tell the box from stuck.\n *\n * Deliberately NOT gated by `AGENTBOX_PROMPT=off` (which `askPrompt`\n * honours): a notice is informational, not a consent gate, so suppressing\n * it would only hide useful feedback.\n */\nexport class BoxNotices {\n /** keyed by notice id. */\n private readonly entries = new Map<string, NoticeEntry>();\n\n constructor(private readonly subscribers: PromptSubscribers) {}\n\n /**\n * Register a notice for `boxId` and broadcast `notice-set`. At most one\n * notice per (box, kind) is kept — a fresh `set` for the same kind\n * replaces the previous one (and cancels its TTL timer so a stale timer\n * can't later fire a `notice-clear` racing the replacement). Returns the\n * generated notice id.\n */\n set(boxId: string, kind: NoticeKind, message: string, ttlMs?: number): string {\n for (const [id, entry] of this.entries) {\n if (entry.boxId === boxId && entry.ev.kind === kind) {\n clearTimeout(entry.timer);\n this.entries.delete(id);\n }\n }\n const ev: BoxNoticeEvent = { id: randomUUID(), kind, message };\n const ttl = typeof ttlMs === 'number' && ttlMs > 0 ? ttlMs : DEFAULT_NOTICE_TTL_MS;\n const timer = setTimeout(() => {\n // Safety net: a notice whose owner died without clearing it self-expires.\n if (this.entries.delete(ev.id)) {\n this.subscribers.broadcast(boxId, 'notice-clear', { id: ev.id });\n }\n }, ttl);\n if (typeof timer.unref === 'function') timer.unref();\n this.entries.set(ev.id, { ev, boxId, timer });\n this.subscribers.broadcast(boxId, 'notice-set', ev);\n return ev.id;\n }\n\n /**\n * Clear a notice by id. Idempotent: returns false when no such notice\n * exists (already cleared / expired). Broadcasts `notice-clear` on a hit.\n */\n clear(id: string): boolean {\n const entry = this.entries.get(id);\n if (!entry) return false;\n clearTimeout(entry.timer);\n this.entries.delete(id);\n this.subscribers.broadcast(entry.boxId, 'notice-clear', { id });\n return true;\n }\n\n /** Snapshot of active notices for a box; replayed to a new SSE subscriber. */\n forBox(boxId: string): BoxNoticeEvent[] {\n const out: BoxNoticeEvent[] = [];\n for (const entry of this.entries.values()) {\n if (entry.boxId === boxId) out.push(entry.ev);\n }\n return out;\n }\n\n size(): number {\n return this.entries.size;\n }\n}\n","import { timingSafeEqual } from 'node:crypto';\n\n/** Constant-time string compare (length leak only, like the HTTP handlers accept). */\nexport function timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\n/**\n * Whether an `/admin/*` request may proceed on the full relay/hub.\n *\n * Loopback callers are the host CLI/tray — always allowed (unchanged laptop\n * behavior). A non-loopback caller is allowed only when it presents the\n * configured admin bearer: the control box is network-reachable behind Caddy,\n * and its own resident worker + the PC (phase 4) reach `/admin/*` through the\n * public URL. Fail-closed: with no admin token configured the gate stays\n * loopback-only, so a laptop relay (which never sets one) exposes nothing new.\n */\nexport function adminGateAllows(\n isLoopback: boolean,\n bearer: string | undefined,\n adminToken: string,\n): boolean {\n if (isLoopback) return true;\n if (adminToken.length === 0) return false;\n return Boolean(bearer) && timingSafeEqualStr(bearer ?? '', adminToken);\n}\n","/**\n * Byte-offset tail of a create job's progress log\n * (`~/.agentbox/logs/queue-<jobId>.log`, written by the hub worker's job logger).\n *\n * This is what lets a PC watching a hub-routed create see the same lines a local\n * create prints: the `/remote/boxes/:id/logs` route hands this back, and the\n * CLI's poll loop drains it between status checks. Deliberately fs-only — the\n * `/remote/boxes` dispatcher stays framework-agnostic and injects this, so the\n * serverless plane (which has no such file) simply doesn't wire it.\n */\n\nimport { open, stat } from 'node:fs/promises';\nimport { queueLogPath } from './queue.js';\nimport { isSafeJobId } from './remote-boxes.js';\n\n/** Per-response ceiling. A busy job just gets drained over several polls. */\nconst MAX_BYTES_PER_READ = 64 * 1024;\n\nexport interface JobLogTail {\n /** Whole lines appended since the requested offset. */\n lines: string[];\n /** Byte offset to pass to the next call — never mid-line. */\n offset: number;\n}\n\n/**\n * Read whole lines appended to job `id`'s log after `offset`.\n *\n * A missing file is normal, not an error: the job can be claimed a tick before\n * the worker writes its first line, and a job that never ran has no log at all.\n * The id is re-checked here so this is safe to call from anywhere, not only\n * from behind the route's own {@link isSafeJobId} gate.\n * The returned offset only ever advances past complete lines, so a read that\n * lands mid-line re-reads that line's bytes next time rather than emitting a\n * truncated line or dropping it.\n */\nexport async function readCreateJobLog(id: string, offset: number): Promise<JobLogTail> {\n const from = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;\n if (!isSafeJobId(id)) return { lines: [], offset: from };\n const path = queueLogPath(id);\n\n let size: number;\n try {\n size = (await stat(path)).size;\n } catch {\n return { lines: [], offset: from };\n }\n // A truncated/rotated file (size < offset) restarts the tail from the top\n // rather than reading past EOF forever.\n const start = size < from ? 0 : from;\n if (size <= start) return { lines: [], offset: start };\n\n const len = Math.min(size - start, MAX_BYTES_PER_READ);\n const buf = Buffer.alloc(len);\n const fh = await open(path, 'r');\n try {\n await fh.read(buf, 0, len, start);\n } finally {\n await fh.close();\n }\n\n const chunk = buf.toString('utf8');\n const lastNewline = chunk.lastIndexOf('\\n');\n if (lastNewline < 0) {\n // No complete line in this window. Only possible for a single line longer\n // than the cap — hand it over and move on, or the tail would wedge here.\n return len >= MAX_BYTES_PER_READ\n ? { lines: [chunk], offset: start + len }\n : { lines: [], offset: start };\n }\n const complete = chunk.slice(0, lastNewline);\n const consumed = Buffer.byteLength(complete, 'utf8') + 1;\n return {\n lines: complete.split('\\n').filter((l) => l.length > 0),\n offset: start + consumed,\n };\n}\n","/**\n * Host-side handler for the ctl credential watcher's `credentials-updated`\n * events (see `packages/ctl/src/credentials-watcher.ts`). Claude's OAuth\n * refresh rotates the refresh token, so the moment one box refreshes, every\n * other copy (host backup, other boxes) is dead — this accepts the freshest\n * blob into `~/.agentbox/<agent>-credentials.json` (newest-wins) and fans it\n * out to all other boxes by spawning the host CLI\n * (`agentbox credentials propagate`), the same decoupling as the relay's\n * checkpoint/cp handlers.\n *\n * The payload carries a secret: callers must never append these events to the\n * event ring buffer (mirrors how `box-status` skips the ring).\n *\n * Concurrency: per-agent debounce (bursts collapse to one fan-out) + a\n * per-agent promise chain (fan-outs never overlap; a fresh accept during an\n * in-flight run schedules one more). The spawned CLI always reads the\n * *current* backup, so collapsed runs lose nothing.\n */\n\nimport { execa } from 'execa';\nimport {\n parseCredentialsUpdate,\n readCredentialBackup,\n resolveAgentSpec,\n shouldAcceptCredentialUpdate,\n writeCredentialBackup,\n type CredentialAgentKind,\n} from '@agentbox/sandbox-core';\n\n/** Mirrors `CREDENTIALS_UPDATED_EVENT` in @agentbox/ctl (like `box-status`). */\nexport const CREDENTIALS_UPDATED_EVENT = 'credentials-updated';\n\nexport interface CredentialsFanoutDeps {\n log: (msg: string) => void;\n /** Debounce before spawning the propagate CLI. Default 3000ms. */\n debounceMs?: number;\n /** Override the fan-out spawn (tests). Default: spawn the host CLI. */\n runPropagate?: (agent: CredentialAgentKind, sourceBoxId: string) => Promise<void>;\n /** Override the per-agent backup path (tests; default: the registry's). */\n backupPathFor?: (agent: CredentialAgentKind) => string;\n /**\n * The control box's custody store, when this relay owns one. Present ⇒ an\n * accepted credential is mirrored into `agents/<id>/…` so the next hub create\n * seeds from a current copy rather than the last one a PC pushed.\n */\n custody?: CredentialCustodyWriter | null;\n}\n\n/** The single write this needs from a custody store (structural: no import cycle). */\nexport interface CredentialCustodyWriter {\n put(path: string, data: Buffer): Promise<unknown>;\n}\n\nexport interface CredentialsHandleResult {\n accepted: boolean;\n reason: string;\n}\n\nexport class CredentialsFanout {\n private readonly log: (msg: string) => void;\n private readonly debounceMs: number;\n private readonly runPropagate: (agent: CredentialAgentKind, sourceBoxId: string) => Promise<void>;\n private readonly backupPathFor?: (agent: CredentialAgentKind) => string;\n private readonly custody: CredentialCustodyWriter | null;\n private readonly pending = new Map<CredentialAgentKind, NodeJS.Timeout>();\n private readonly chains = new Map<CredentialAgentKind, Promise<void>>();\n\n constructor(deps: CredentialsFanoutDeps) {\n this.log = deps.log;\n this.debounceMs = deps.debounceMs ?? 3_000;\n this.runPropagate = deps.runPropagate ?? defaultRunPropagate;\n this.backupPathFor = deps.backupPathFor;\n this.custody = deps.custody ?? null;\n }\n\n /**\n * Validate, newest-wins-gate, persist the host backup, and schedule the\n * fan-out. Fast (no box I/O); the propagate CLI does the slow work detached.\n */\n async handle(sourceBoxId: string, payload: unknown): Promise<CredentialsHandleResult> {\n const update = parseCredentialsUpdate(payload);\n if (!update) return { accepted: false, reason: 'invalid payload' };\n const backupPath = this.backupPathFor?.(update.agent);\n const existing = await readCredentialBackup(update.agent, { backupPath });\n const verdict = shouldAcceptCredentialUpdate(update.agent, update.content, existing);\n if (!verdict.accept) {\n return { accepted: false, reason: verdict.reason };\n }\n await writeCredentialBackup(update.agent, update.content, { backupPath });\n await this.recordInCustody(update.agent, update.content);\n this.log(\n `credentials: accepted ${update.agent} update from box ${sourceBoxId} (${verdict.reason}); fan-out in ${String(this.debounceMs)}ms`,\n );\n this.schedule(update.agent, sourceBoxId);\n return { accepted: true, reason: verdict.reason };\n }\n\n /**\n * Mirror the accepted blob into custody, on a control box.\n *\n * Without this the freshest token lives ONLY in the host backup, and the next\n * hub create re-seeds that backup from custody — a copy that is only as new as\n * the last PC push. Since a refresh rotates the token, every box built after\n * that came up with a dead credential. Writing here is what makes custody\n * self-healing: the boxes refreshing their own tokens keep it current with no\n * PC involvement.\n *\n * Best-effort by design — a custody failure must not cost us the fan-out,\n * which is the part that fixes the boxes that are already running.\n */\n private async recordInCustody(agent: CredentialAgentKind, content: string): Promise<void> {\n if (!this.custody) return;\n try {\n const spec = resolveAgentSpec(agent);\n // An agent that declares no credential has nothing to mirror. Unreachable\n // via `handle` (`parseCredentialsUpdate` rejects such an agent), but this\n // is the write to custody -- the copy every later create seeds from -- so\n // it checks rather than trusting its caller.\n if (!spec.credential) return;\n await this.custody.put(\n `agents/${agent}/${spec.credential.boxRelPath}`,\n Buffer.from(content, 'utf8'),\n );\n } catch (err) {\n this.log(\n `credentials: could not record ${agent} in custody: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n private schedule(agent: CredentialAgentKind, sourceBoxId: string): void {\n const existing = this.pending.get(agent);\n if (existing) clearTimeout(existing);\n const timer = setTimeout(() => {\n this.pending.delete(agent);\n const prev = this.chains.get(agent) ?? Promise.resolve();\n const next = prev\n .then(() => this.runPropagate(agent, sourceBoxId))\n .catch((err: unknown) => {\n this.log(\n `credentials: ${agent} fan-out failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n this.chains.set(agent, next);\n }, this.debounceMs);\n timer.unref();\n this.pending.set(agent, timer);\n }\n\n /** Pending debounce timers + in-flight chain, for tests/shutdown. */\n async flush(): Promise<void> {\n for (const [agent, timer] of this.pending) {\n clearTimeout(timer);\n this.pending.delete(agent);\n void agent;\n }\n await Promise.all([...this.chains.values()]);\n }\n}\n\n/**\n * Spawn `agentbox credentials propagate` via the CLI entry the daemon was\n * started with — the CLI owns provider resolution and per-box transports\n * (same pattern as the checkpoint/cp host actions).\n */\nasync function defaultRunPropagate(agent: CredentialAgentKind, sourceBoxId: string): Promise<void> {\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n throw new Error('AGENTBOX_CLI_ENTRY not set; cannot run credential propagate host-side');\n }\n const result = await execa(\n process.execPath,\n [entry, 'credentials', 'propagate', '--agent', agent, '--source-box', sourceBoxId],\n { reject: false, timeout: 300_000 },\n );\n if (result.exitCode !== 0) {\n throw new Error(\n `credentials propagate exited ${String(result.exitCode)}: ${String(result.stderr).slice(-300)}`,\n );\n }\n}\n","import { spawn } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type UserConfig,\n} from '@agentbox/config';\nimport { readState } from '@agentbox/sandbox-core';\nimport { readActiveAgent, type WorkingAgentState } from './queue.js';\nimport type { BoxRegistry, EventBuffer } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\nexport interface AutopauseConfig {\n enabled: boolean;\n maxRunningBoxes: number;\n idleMinutes: number;\n}\n\nexport type ContainerState = 'running' | 'paused' | 'stopped' | 'missing';\n/**\n * The pause decision's coarse view of an agent, flattened from the full\n * activity union. Not claude's: `readPauseState` folds whichever agent is live\n * in the box, so a box where codex is working is never paused because claude\n * happens to be idle.\n */\nexport type CoarseAgentState = 'working' | 'idle' | 'waiting' | 'unknown';\n\n/** One box's runtime facts the pure selector reasons about. No I/O, no clock. */\nexport interface BoxScanEntry {\n boxId: string;\n containerName: string;\n /** docker inspect status === 'running'. */\n running: boolean;\n /** Latest reported activity of whichever agent is live, or null when no snapshot exists. */\n agentState: CoarseAgentState | null;\n /** ms the box has been idle (now - the agent entry's updatedAt) when idle; else null. */\n idleMs: number | null;\n /** Box creation time as epoch ms; 0 when unknown/unparseable. */\n createdAt: number;\n /**\n * `BoxRecord.persistent` — an always-on box. Never a pause candidate, and not\n * counted against `maxRunningBoxes`: counting it would make the loop pause\n * expendable boxes to free a slot for a box it can never pause.\n */\n persistent?: boolean;\n}\n\n/**\n * Pure selection: given each running box's idle facts and the config, return\n * the boxIds to pause, in pause order. Pauses only enough to bring the running\n * count back to `maxRunningBoxes`, picking provably-idle boxes longest-idle\n * first (tie-break: oldest box, then boxId for determinism).\n */\nexport function selectBoxesToPause(entries: BoxScanEntry[], cfg: AutopauseConfig): string[] {\n if (!cfg.enabled) return [];\n const runningCount = entries.reduce((n, e) => (e.running && !e.persistent ? n + 1 : n), 0);\n const excess = runningCount - cfg.maxRunningBoxes;\n if (excess <= 0) return [];\n\n const idleThresholdMs = cfg.idleMinutes * 60_000;\n const candidates = entries.filter(\n (e) =>\n e.running &&\n !e.persistent &&\n e.agentState === 'idle' &&\n e.idleMs != null &&\n e.idleMs >= idleThresholdMs,\n );\n candidates.sort(\n (a, b) =>\n (b.idleMs as number) - (a.idleMs as number) ||\n a.createdAt - b.createdAt ||\n (a.boxId < b.boxId ? -1 : a.boxId > b.boxId ? 1 : 0),\n );\n return candidates.slice(0, excess).map((e) => e.boxId);\n}\n\n/**\n * Global+built-in autopause config. The relay is host-wide (not project\n * scoped), so it deliberately ignores the project/workspace layers that\n * `loadEffectiveConfig` would apply. Re-read every tick so\n * `agentbox config set --global autopause.*` takes effect without a relay\n * restart. A missing or malformed global file falls back to built-in defaults.\n */\nexport async function loadAutopauseConfig(): Promise<AutopauseConfig> {\n const d = BUILT_IN_DEFAULTS.autopause;\n let global: Partial<UserConfig> = {};\n try {\n global = parseUserConfig(await readFile(GLOBAL_CONFIG_FILE, 'utf8'), GLOBAL_CONFIG_FILE);\n } catch {\n // ENOENT (no global config yet) or a parse error -> built-in defaults.\n }\n const a = global.autopause ?? {};\n return {\n enabled: a.enabled ?? d.enabled,\n maxRunningBoxes: a.maxRunningBoxes ?? d.maxRunningBoxes,\n idleMinutes: a.idleMinutes ?? d.idleMinutes,\n };\n}\n\nexport interface AutopauseLoopDeps {\n registry: BoxRegistry;\n statusStore: BoxStatusStore;\n events: EventBuffer;\n log: (line: string) => void;\n /** Injectable for tests; defaults to the global-config loader. */\n loadConfig?: () => Promise<AutopauseConfig>;\n /** Injectable for tests; defaults to `docker inspect`. */\n inspectStatus?: (containerName: string) => Promise<ContainerState>;\n /** Injectable for tests; defaults to `docker pause`. */\n pause?: (containerName: string) => Promise<void>;\n intervalMs?: number;\n}\n\nexport interface AutopauseLoopHandle {\n /** Stop scheduling and await any in-flight tick. */\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000;\n\nexport function startAutopauseLoop(deps: AutopauseLoopDeps): AutopauseLoopHandle {\n const loadConfig = deps.loadConfig ?? loadAutopauseConfig;\n const inspectStatus = deps.inspectStatus ?? inspectContainerState;\n const pause = deps.pause ?? pauseContainer;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { registry, statusStore, events, log } = deps;\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function tick(): Promise<void> {\n // A slow tick (many `docker inspect`s) must not overlap the next interval.\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n if (!cfg.enabled) return;\n\n // The registry is the relay's in-memory view and carries no `persistent`\n // flag; the box RECORD is where create persisted it (see BoxRecord).\n // One read per tick, not per box.\n const persistentIds = await readPersistentBoxIds();\n\n const entries: BoxScanEntry[] = [];\n for (const reg of registry.list()) {\n if (!reg.containerName) continue; // pre-feature box; can't pause it\n const state = await inspectStatus(reg.containerName);\n const active = readPauseState(statusStore.get(reg.boxId));\n const idleMs =\n active.state === 'idle' && active.updatedAt ? msSince(active.updatedAt) : null;\n entries.push({\n boxId: reg.boxId,\n containerName: reg.containerName,\n running: state === 'running',\n agentState: active.state,\n idleMs,\n createdAt: reg.createdAt ? toEpoch(reg.createdAt) : 0,\n persistent: persistentIds.has(reg.boxId),\n });\n }\n\n const toPause = selectBoxesToPause(entries, cfg);\n if (toPause.length === 0) return;\n\n const byId = new Map(entries.map((e) => [e.boxId, e]));\n const runningBefore = entries.reduce((n, e) => (e.running && !e.persistent ? n + 1 : n), 0);\n for (const boxId of toPause) {\n const e = byId.get(boxId);\n if (!e) continue;\n try {\n await pause(e.containerName);\n const mins = e.idleMs != null ? Math.round(e.idleMs / 60_000) : null;\n events.append({\n boxId,\n type: 'autopause',\n payload: {\n containerName: e.containerName,\n action: 'paused',\n idleMs: e.idleMs,\n runningBefore,\n max: cfg.maxRunningBoxes,\n },\n });\n log(\n `autopause: paused box ${boxId} (${e.containerName})` +\n (mins != null ? ` after ~${String(mins)}m idle` : '') +\n `; running ${String(runningBefore)} -> target ${String(cfg.maxRunningBoxes)}`,\n );\n } catch (err) {\n // docker failure is non-fatal: log, record, keep going.\n const msg = err instanceof Error ? err.message : String(err);\n log(`autopause: docker pause ${e.containerName} failed: ${msg}`);\n events.append({\n boxId,\n type: 'autopause',\n payload: { containerName: e.containerName, action: 'pause-failed', error: msg },\n });\n }\n }\n } catch (err) {\n // The loop must never crash the relay or stop scheduling.\n const msg = err instanceof Error ? err.message : String(err);\n log(`autopause: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n // The HTTP server keeps the process alive; the timer shouldn't on its own.\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n\ninterface AgentSnap {\n state: CoarseAgentState | null;\n updatedAt: string | null;\n}\n\n/**\n * Coarse activity state for the pause decision, across ALL agents\n * (claude/codex/opencode) — not just claude. Reuses the queue loop's\n * multi-agent reader so a box where codex/opencode is working isn't paused\n * because claude happens to be idle or absent. Any active state (working,\n * compacting, waiting, end-plan, question, error) maps to a non-`idle` value,\n * so only a box whose live agent has settled to `idle` becomes a candidate.\n */\nfunction readPauseState(snap: Record<string, unknown> | undefined): AgentSnap {\n const active = readActiveAgent(snap);\n return { state: coarsePauseState(active.state), updatedAt: active.updatedAt };\n}\n\nfunction coarsePauseState(s: WorkingAgentState | null): CoarseAgentState | null {\n switch (s) {\n case 'idle':\n return 'idle';\n case 'waiting':\n return 'waiting';\n case 'working':\n case 'compacting':\n return 'working';\n case null:\n return null;\n // end-plan / question / error / unknown: a live session expecting attention\n // — never auto-pause it (maps to a non-idle, non-candidate state).\n default:\n return 'unknown';\n }\n}\n\n/**\n * Ids of every box whose record says `persistent`. Read per tick (not cached)\n * so flipping a box's record — or creating a persistent box — takes effect\n * without a relay restart. A missing/corrupt state file yields an empty set:\n * the loop then behaves exactly as it did before this feature.\n */\nexport async function readPersistentBoxIds(): Promise<Set<string>> {\n try {\n const { boxes } = await readState();\n return new Set(boxes.filter((b) => b.persistent === true).map((b) => b.id));\n } catch {\n return new Set();\n }\n}\n\nfunction msSince(iso: string): number | null {\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : Date.now() - t;\n}\n\nfunction toEpoch(iso: string): number {\n const t = Date.parse(iso);\n return Number.isNaN(t) ? 0 : t;\n}\n\nconst INSPECT_TIMEOUT_MS = 15_000;\nconst PAUSE_TIMEOUT_MS = 30_000;\n\ninterface DockerResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runDocker(args: string[], timeoutMs: number): Promise<DockerResult> {\n return new Promise<DockerResult>((resolve) => {\n const child = spawn('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: docker ${args.join(' ')} timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (c: Buffer) => {\n stdout += c.toString('utf8');\n });\n child.stderr?.on('data', (c: Buffer) => {\n stderr += c.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n stderr += String(err.message ?? err);\n finish(127);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/** Mirrors `inspectContainerStatus` in @agentbox/sandbox-docker (no dep on it — cycle). */\nasync function inspectContainerState(name: string): Promise<ContainerState> {\n const r = await runDocker(['inspect', '--format', '{{.State.Status}}', name], INSPECT_TIMEOUT_MS);\n if (r.exitCode !== 0) return 'missing';\n switch (r.stdout.trim()) {\n case 'running':\n return 'running';\n case 'paused':\n return 'paused';\n case 'created':\n case 'exited':\n case 'dead':\n case 'restarting':\n case 'removing':\n return 'stopped';\n default:\n return 'missing';\n }\n}\n\nasync function pauseContainer(name: string): Promise<void> {\n const r = await runDocker(['pause', name], PAUSE_TIMEOUT_MS);\n if (r.exitCode !== 0) {\n throw new Error(r.stderr.trim() || `docker pause ${name} exited ${String(r.exitCode)}`);\n }\n}\n","/**\n * `startCloudKeepaliveLoop` — host-resident loop that renews a cloud box's\n * session-timeout while its in-box agent is active, so a long-running\n * Claude/Codex session isn't killed when the create-time timeout elapses.\n *\n * Sibling to `startAutopauseLoop` (and modeled on it): a host-wide sweep on a\n * timer that reads each box's live agent state from the `BoxStatusStore` and\n * acts. Where autopause *pauses* idle docker boxes, this *keeps alive* active\n * cloud boxes by pushing their death-time out. The window REUSES the autopause\n * idle threshold (`autopause.idleMinutes`) — per the design, there is no\n * separate keepalive knob.\n *\n * - active agent -> hold the death-time a full window ahead of NOW.\n * - idle agent -> let it lapse a window after it went idle, then stop.\n *\n * \"Let it lapse\" only works when the provider's timeout is an absolute deadline\n * (vercel). Daytona's is an INACTIVITY window that any request resets, and e2b's\n * paused sandboxes auto-resume on any inbound request — and this host polls\n * every cloud box's preview URL continuously, so on both the clock never runs\n * out and an idle box would bill forever. For those backends\n * (`CloudBackend.timeoutModel === 'inactivity'`) the loop performs the stop\n * itself: it pauses the box AND stops that box's poller, without which the very\n * next long-poll would revive what we just paused.\n *\n * The additive-vs-absolute SDK split (vercel `extendTimeout` adds to the\n * current deadline and can't read remaining; e2b `setTimeout` sets TTL from\n * now) is resolved by tracking each box's intended deadline in memory and\n * handing the backend BOTH the absolute target and our tracked current\n * deadline. See `CloudBackend.renewTimeout`. The tracked deadline is seeded\n * from the deadline the provider last actually applied\n * (`cloud.sessionDeadlineEpochMs`, re-written on every start/resume), falling\n * back to `createdAt + cloud.sessionTimeoutMs` for pre-feature records.\n *\n * Plan caps (vercel Hobby ~45m, Pro+ ~5h; e2b 1h Hobby, 24h Pro) bound how far\n * a box can be extended — a renew past the cap throws and is swallowed here,\n * after which the box is briefly backed off (so we don't hammer the API / log)\n * and lapses normally. On e2b that lapse is a PAUSE, not a kill\n * (`lifecycle.onTimeout`), so hitting the cap costs a stall rather than the box.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type UserConfig,\n} from '@agentbox/config';\nimport type { CloudBackend } from '@agentbox/core';\nimport { findBox, readState, recordBox } from '@agentbox/sandbox-core';\nimport { loadAutopauseConfig, readPersistentBoxIds, type AutopauseConfig } from './autopause.js';\nimport { resolveCloudBackend } from './host-actions.js';\nimport { readActiveAgent, type WorkingAgentState } from './queue.js';\nimport type { BoxRegistry } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\n/** Coarse activity for the renewal decision. `active` = keep the box alive. */\nexport type KeepaliveAgentState = 'active' | 'idle' | null;\n\n/** One box's facts the pure selector reasons about. No I/O, no clock. */\nexport interface KeepaliveScanEntry {\n boxId: string;\n /** Cloud backend name, e.g. 'vercel'. */\n backend: string;\n /** Coarse activity across claude/codex/opencode, or null when no snapshot. */\n agentState: KeepaliveAgentState;\n /** epoch ms of the active agent's `updatedAt`, or null when no snapshot. */\n lastActivityMs: number | null;\n /**\n * `BoxRecord.persistent` — an always-on box: renewed on every tick regardless\n * of agent state, and never idle-paused. A persistent box typically has NO\n * reporting agent (a plain service box reports `agentState: null`), which\n * every heuristic below would otherwise read as abandoned.\n */\n persistent?: boolean;\n}\n\nexport interface RenewDecision {\n boxId: string;\n backend: string;\n /** Absolute death-time we want this box held at. */\n targetDeadlineEpochMs: number;\n}\n\n/**\n * Pure selection: given each cloud box's activity facts, the window, and the\n * clock, return the boxes to renew with their target death-time.\n *\n * - active agent -> keep alive a full window from NOW (`now + windowMs`).\n * - idle, < window since it went idle -> lapse `window` after it went idle\n * (`lastActivityMs + windowMs`, where `lastActivityMs` is the fresh\n * working->idle transition time).\n * - idle >= window, no agent state, or a wedged agent (error/unknown) -> skip.\n *\n * The active case anchors on `now`, NOT on `lastActivityMs`, and does NOT\n * require `lastActivityMs`: the in-box status reporter bumps `updatedAt` on\n * state changes (per-tool-call), not during a long single `working` op (a\n * 30-min test run), so a stale/absent `updatedAt` must not freeze the target\n * below the tracked deadline — that would kill the box mid-work, the exact\n * failure this feature prevents. The idle case stays `now`-independent so an\n * idle box still lapses.\n */\nexport function selectBoxesToRenew(\n entries: KeepaliveScanEntry[],\n windowMs: number,\n now: number,\n): RenewDecision[] {\n const out: RenewDecision[] = [];\n for (const e of entries) {\n // Always-on, and usually with no agent to report activity: renew\n // unconditionally.\n if (e.persistent) {\n out.push({ boxId: e.boxId, backend: e.backend, targetDeadlineEpochMs: now + windowMs });\n continue;\n }\n if (e.agentState == null) continue;\n let target: number | null = null;\n if (e.agentState === 'active') {\n target = now + windowMs;\n } else if (\n e.agentState === 'idle' &&\n e.lastActivityMs != null &&\n now - e.lastActivityMs < windowMs\n ) {\n target = e.lastActivityMs + windowMs;\n }\n if (target != null) {\n out.push({ boxId: e.boxId, backend: e.backend, targetDeadlineEpochMs: target });\n }\n }\n return out;\n}\n\n/**\n * Would an `inactivity`-model backend have stopped this box by now, had our own\n * polling not kept resetting its idle clock (see `CloudBackend.timeoutModel`)?\n * If so the host pauses it, standing in for the provider's dead timer.\n *\n * `idleWindowMs` is the BOX'S OWN idle timeout — the one it was created with\n * (`cloud.sessionTimeoutMs`, i.e. `box.daytonaTimeoutMs`, 25 min by default) —\n * NOT the keepalive/autopause renewal window (5 min). We are emulating the\n * provider's timer, so we must honour the interval the user configured for it;\n * using the renewal window would pause boxes five times sooner than\n * `box.daytonaTimeoutMs` advertises. A window of `0` means the user disabled\n * the idle timeout, and the caller skips the box entirely.\n *\n * Only a box with a definite `idle` agent is a candidate. A box with no agent\n * state at all (`null` — a plain `agentbox shell` box, or one whose reporter\n * hasn't spoken yet) is left alone: we have no evidence it's unused, and an\n * attached human is exactly the case we must not pull the floor out from under.\n * An `active` agent (incl. waiting/question) is never a candidate.\n */\nexport function shouldIdlePause(e: KeepaliveScanEntry, idleWindowMs: number, now: number): boolean {\n // An always-on box's agent (when it has one) settling to `idle` is its\n // resting state, not evidence the box is unused.\n if (e.persistent) return false;\n if (e.agentState !== 'idle' || e.lastActivityMs == null) return false;\n return now - e.lastActivityMs >= idleWindowMs;\n}\n\n/**\n * Collapse the multi-agent `WorkingAgentState` into the coarse keepalive state.\n * Mirrors autopause's `coarsePauseState`, but here any live session expecting\n * attention (waiting/question/end-plan) counts as `active` so we never let it\n * be killed mid-interaction; only a settled `idle` is the lapse candidate.\n * error/unknown/null → null (don't keep a wedged or unknown box alive forever).\n */\nfunction coarseKeepaliveState(s: WorkingAgentState | null): KeepaliveAgentState {\n switch (s) {\n case 'working':\n case 'compacting':\n case 'waiting':\n case 'question':\n case 'end-plan':\n return 'active';\n case 'idle':\n return 'idle';\n default:\n return null;\n }\n}\n\n/** What the box-record lookup yields for seeding + the renew call. */\nexport interface CloudBoxLookup {\n sandboxId: string;\n /** Box creation time as epoch ms, or null when unparseable. */\n createdAtMs: number | null;\n /** Recorded effective create timeout (ms), or null when not recorded. */\n createTimeoutMs: number | null;\n /**\n * Absolute death-time last applied to the sandbox, or null when not recorded.\n * Preferred over `createdAt + createTimeoutMs` for seeding: the provider\n * re-applies the session window on every start/resume, so the create-derived\n * value is stale for any box that has been paused and woken.\n */\n sessionDeadlineEpochMs?: number | null;\n /**\n * Provider-specific sandbox class, when the record carries one. Daytona needs\n * it to pause: a `linux-vm` freezes, a `container` archives, and each call is\n * rejected for the other class. Without it the backend has to guess.\n */\n sandboxClass?: string;\n}\n\nexport interface CloudKeepaliveLoopDeps {\n registry: BoxRegistry;\n statusStore: BoxStatusStore;\n log: (line: string) => void;\n /** Injectable for tests; defaults to the global autopause config loader. */\n loadConfig?: () => Promise<AutopauseConfig>;\n /** Injectable for tests; defaults to `resolveCloudBackend`. */\n resolveBackend?: (name: string) => Promise<CloudBackend>;\n /** Injectable for tests; defaults to the state.json box lookup. */\n lookupBox?: (boxId: string) => Promise<CloudBoxLookup | null>;\n /** Injectable for tests; defaults to writing `cloud.lastState: 'paused'`. */\n persistPaused?: (boxId: string) => Promise<void>;\n /**\n * Stop the box's `CloudBoxPoller` after an idle pause. Load-bearing on a\n * backend whose paused sandboxes auto-resume on inbound traffic (e2b): the\n * poller long-polls the preview URL forever, so without this it revives the\n * box we just paused on its very next request. Defaults to a no-op (tests,\n * and relays that never started a poller).\n */\n stopPoller?: (boxId: string) => Promise<void>;\n /** Injectable for tests; fallback create timeout when a record lacks one. */\n fallbackCreateTimeoutMs?: (backend: string) => Promise<number>;\n /** Injectable for tests; defaults to `Date.now`. */\n now?: () => number;\n intervalMs?: number;\n}\n\nexport interface CloudKeepaliveLoopHandle {\n /** Stop scheduling and await any in-flight tick. */\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000;\n/** After a failed renew, skip the box for this long (avoid cap hammering / log spam). */\nconst FAILURE_BACKOFF_MS = 5 * 60_000;\n\nexport function startCloudKeepaliveLoop(deps: CloudKeepaliveLoopDeps): CloudKeepaliveLoopHandle {\n const loadConfig = deps.loadConfig ?? loadAutopauseConfig;\n const resolveBackend = deps.resolveBackend ?? resolveCloudBackend;\n const lookupBox = deps.lookupBox ?? defaultLookupBox;\n const persistPaused = deps.persistPaused ?? defaultPersistPaused;\n const stopPoller = deps.stopPoller ?? (async () => {});\n const fallbackCreateTimeoutMs = deps.fallbackCreateTimeoutMs ?? defaultFallbackCreateTimeoutMs;\n const nowFn = deps.now ?? Date.now;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { registry, statusStore, log } = deps;\n\n // Per-box intended death-time we've pushed the session to. Seeded lazily from\n // the recorded `createdAt + create-timeout`; in-memory only — a relay restart\n // re-seeds (at worst one corrective over-extend, bounded by the plan cap).\n const tracked = new Map<string, number>();\n // Per-box \"don't attempt before\" time, set after a failed renew.\n const backoffUntil = new Map<string, number>();\n // Boxes we idle-paused, keyed by the `lastActivityMs` they had when we did.\n // A paused box keeps reporting that same idle snapshot, so without this it\n // would re-qualify for pausing on every tick.\n const idlePaused = new Map<string, number | null>();\n // Resolved backends cached across ticks (one dynamic import per provider).\n const backendCache = new Map<string, CloudBackend | null>();\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function resolveCached(name: string): Promise<CloudBackend | null> {\n if (backendCache.has(name)) return backendCache.get(name) ?? null;\n let backend: CloudBackend | null = null;\n try {\n backend = await resolveBackend(name);\n } catch {\n backend = null; // no executor for this backend — skip its boxes\n }\n backendCache.set(name, backend);\n return backend;\n }\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n if (!cfg.enabled) return;\n const windowMs = cfg.idleMinutes * 60_000;\n const now = nowFn();\n\n // Persistent flags live on the box RECORDS, not on the relay's in-memory\n // registrations. One read per tick.\n const persistentIds = await readPersistentBoxIds();\n\n const live = new Set<string>();\n const entries: KeepaliveScanEntry[] = [];\n for (const reg of registry.list()) {\n if (reg.kind !== 'cloud' || !reg.backend) continue;\n const backend = await resolveCached(reg.backend);\n if (!backend || typeof backend.renewTimeout !== 'function') continue;\n live.add(reg.boxId);\n const active = readActiveAgent(statusStore.get(reg.boxId));\n entries.push({\n boxId: reg.boxId,\n backend: reg.backend,\n agentState: coarseKeepaliveState(active.state),\n lastActivityMs: active.updatedAt ? toEpoch(active.updatedAt) : null,\n persistent: persistentIds.has(reg.boxId),\n });\n }\n\n // Drop per-box state for boxes that are gone (destroyed / forgotten).\n for (const id of [...tracked.keys()]) if (!live.has(id)) tracked.delete(id);\n for (const id of [...backoffUntil.keys()]) if (!live.has(id)) backoffUntil.delete(id);\n for (const id of [...idlePaused.keys()]) if (!live.has(id)) idlePaused.delete(id);\n\n const decisions = selectBoxesToRenew(entries, windowMs, now);\n for (const d of decisions) {\n const until = backoffUntil.get(d.boxId);\n if (until != null && now < until) continue; // recently failed — wait\n\n const lookup = await lookupBox(d.boxId);\n if (!lookup) continue;\n\n // Seed the tracked deadline. Prefer the deadline the provider actually\n // applied (re-written on every start/resume) — deriving it from\n // `createdAt + createTimeoutMs` is wrong for any box that has been\n // paused and woken, and after a relay restart mid-session it points\n // into the past. Fall back to the create-derived value for pre-feature\n // records, and to a provider default when even the timeout is absent.\n let current = tracked.get(d.boxId);\n if (current == null) {\n if (lookup.sessionDeadlineEpochMs != null) {\n current = lookup.sessionDeadlineEpochMs;\n } else {\n const createMs = lookup.createdAtMs ?? now;\n const createTimeoutMs =\n lookup.createTimeoutMs ?? (await fallbackCreateTimeoutMs(d.backend));\n current = createMs + createTimeoutMs;\n }\n tracked.set(d.boxId, current);\n }\n // Only renew when the target meaningfully exceeds the tracked deadline,\n // so we don't churn the SDK for sub-tick gains or extend a box still\n // riding its create timeout.\n if (d.targetDeadlineEpochMs <= current + intervalMs) continue;\n\n try {\n const backend = await resolveCached(d.backend);\n if (!backend?.renewTimeout) continue;\n await backend.renewTimeout(\n { sandboxId: lookup.sandboxId },\n d.targetDeadlineEpochMs,\n current,\n );\n // Only advance the tracked deadline on SUCCESS — a failed extend did\n // not actually move the real deadline, so we must not record it.\n tracked.set(d.boxId, d.targetDeadlineEpochMs);\n backoffUntil.delete(d.boxId);\n log(\n `cloud-keepalive: renewed box ${d.boxId} (${d.backend}) ` +\n `+${String(Math.round((d.targetDeadlineEpochMs - now) / 60_000))}m`,\n );\n } catch (err) {\n // Plan-cap rejection or a transient SDK error. Leave `tracked`\n // unchanged (so we retry once the backoff lapses) and back the box\n // off briefly to avoid hammering the cap / spamming the log.\n backoffUntil.set(d.boxId, now + FAILURE_BACKOFF_MS);\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: renew box ${d.boxId} (${d.backend}) failed: ${msg}`);\n }\n }\n\n // Stop the idle boxes an `inactivity`-model backend can't stop by itself,\n // because our own preview polling keeps resetting its clock.\n for (const e of entries) {\n const boxId = e.boxId;\n if (e.agentState !== 'idle') continue; // cheap reject before any I/O\n const backend = await resolveCached(e.backend);\n if (backend?.timeoutModel !== 'inactivity') continue; // absolute TTL: it lapses on its own\n if (typeof backend.pause !== 'function') continue;\n\n // Don't re-pause a box we already paused: it stays `idle` with the same\n // `updatedAt` while paused, so it would otherwise re-qualify every tick.\n // Any fresh agent activity (a resume that does real work) moves\n // `lastActivityMs` and re-arms it.\n if (idlePaused.get(boxId) === e.lastActivityMs) continue;\n const until = backoffUntil.get(boxId);\n if (until != null && now < until) continue;\n\n const lookup = await lookupBox(boxId);\n if (!lookup) continue;\n // The box's OWN idle timeout (box.daytonaTimeoutMs), not the renewal\n // window — we're standing in for the provider's timer, so we wait as\n // long as the user told the provider to wait. `0` disables it.\n const idleWindowMs = lookup.createTimeoutMs ?? (await fallbackCreateTimeoutMs(e.backend));\n if (idleWindowMs <= 0) continue;\n if (!shouldIdlePause(e, idleWindowMs, now)) continue;\n // Stop polling BEFORE pausing. On a backend with auto-resume (e2b) a\n // long-poll landing after the pause wakes the box straight back up, and\n // `CloudBoxPoller.stop()` aborts the in-flight request — measured at 26s\n // if we instead wait it out. A later wake re-registers the box\n // (`/admin/register-box`), which starts a fresh poller, so this needs no\n // restart path here. Best-effort: a poller that's already gone is fine.\n await stopPoller(boxId).catch(() => {});\n try {\n // Pass the recorded class: daytona freezes a linux-vm but archives a\n // container, and each call is rejected for the other class.\n await backend.pause({\n sandboxId: lookup.sandboxId,\n ...(lookup.sandboxClass ? { sandboxClass: lookup.sandboxClass } : {}),\n });\n idlePaused.set(boxId, e.lastActivityMs);\n backoffUntil.delete(boxId);\n // The tracked deadline belongs to a session that no longer exists;\n // drop it so the next wake re-seeds from the record.\n tracked.delete(boxId);\n // Best-effort, and deliberately after the pause is already a fact: a\n // failed record write must not look like a failed pause and re-arm.\n await persistPaused(boxId).catch(() => {});\n const mins =\n e.lastActivityMs != null ? Math.round((now - e.lastActivityMs) / 60_000) : null;\n log(\n `cloud-keepalive: paused idle box ${boxId} (${e.backend})` +\n (mins != null ? ` after ~${String(mins)}m idle` : '') +\n ` — ${e.backend}'s own idle timer never fires while we poll it`,\n );\n } catch (err) {\n // Already stopped, mid-transition, or a transient SDK error. Back off\n // rather than retry every tick; `probeState` stays authoritative.\n backoffUntil.set(boxId, now + FAILURE_BACKOFF_MS);\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: pause idle box ${boxId} (${e.backend}) failed: ${msg}`);\n }\n }\n } catch (err) {\n // The loop must never crash the relay or stop scheduling.\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n\nfunction toEpoch(iso: string | undefined): number | null {\n if (!iso) return null;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : t;\n}\n\n/** Resolve a box's cloud sandboxId + create facts from `~/.agentbox/state.json`. */\nasync function defaultLookupBox(boxId: string): Promise<CloudBoxLookup | null> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok') return null;\n const sandboxId = hit.box.cloud?.sandboxId;\n if (!sandboxId) return null;\n const sandboxClass = hit.box.cloud?.sandboxClass;\n return {\n sandboxId,\n createdAtMs: toEpoch(hit.box.createdAt),\n createTimeoutMs: hit.box.cloud?.sessionTimeoutMs ?? null,\n sessionDeadlineEpochMs: hit.box.cloud?.sessionDeadlineEpochMs ?? null,\n ...(sandboxClass ? { sandboxClass } : {}),\n };\n}\n\n/**\n * Mark an auto-paused box `paused` on its record. `agentbox list` / `top` / the\n * hub read `cloud.lastState` rather than probing the SDK on every render, so\n * without this the box we just paused keeps showing as `running` until someone\n * runs a live probe. Mirrors cloud-provider's `persistLastState` (which covers\n * the CLI-driven `pause`/`stop`); best-effort, since the pause itself already\n * happened and a state-write failure must not turn into a retry loop.\n */\nasync function defaultPersistPaused(boxId: string): Promise<void> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok' || !hit.box.cloud) return;\n await recordBox({ ...hit.box, cloud: { ...hit.box.cloud, lastState: 'paused' } });\n}\n\n/**\n * Fallback create timeout for a box record that predates `sessionTimeoutMs`.\n * Vercel reads the global `box.vercelTimeoutMs`; other backends use the shared\n * 45-min default (matches the backends' `DEFAULT_TIMEOUT_MS`). A close estimate\n * is enough — the renew gate tolerates seed drift and self-corrects.\n */\nasync function defaultFallbackCreateTimeoutMs(backend: string): Promise<number> {\n const generic = 45 * 60_000;\n if (backend !== 'vercel') return generic;\n const fallback = BUILT_IN_DEFAULTS.box.vercelTimeoutMs;\n try {\n const global: Partial<UserConfig> = parseUserConfig(\n await readFile(GLOBAL_CONFIG_FILE, 'utf8'),\n GLOBAL_CONFIG_FILE,\n );\n const v = global.box?.vercelTimeoutMs;\n return typeof v === 'number' && v > 0 ? v : fallback;\n } catch {\n return fallback;\n }\n}\n","/**\n * `startPersistentBoxLoop` — brings PERSISTENT boxes back up.\n *\n * A persistent box (`BoxRecord.persistent`, from `box.persistent` /\n * `--persistent`) is always-on: autopause never pauses it and the cloud\n * keepalive never lets it lapse. Neither covers the host going away — a reboot,\n * a docker daemon restart, or a laptop that slept through a cloud provider's own\n * stop leaves the box down with nothing to notice.\n *\n * So: on daemon start, and on a slow tick after that, every persistent box whose\n * `provider.probeState` is not `running` is brought back through the provider's\n * `reconnect` (`start` for a provider with no cheaper path).\n *\n * Not a docker `--restart` policy, which would be free: docker's own restart\n * brings the CONTAINER back and nothing else. `/workspace` is a bind of a git\n * worktree re-established by `startBox`'s `bindWorktrees`, which also launches\n * the ctl supervisor and dockerd and re-resolves the published host ports. A\n * docker-restarted container has an empty `/workspace`, no supervisor and a\n * stale port in its record.\n *\n * Failures are logged and retried on the next tick; the loop never throws and\n * never blocks the relay.\n */\n\nimport { pathToFileURL } from 'node:url';\nimport type { BoxRecord, BoxRuntimeState, Provider } from '@agentbox/core';\nimport { isSupportedApiVersion, pluginForProvider, readState } from '@agentbox/sandbox-core';\nimport { currentCloudBackendLoader } from './host-actions.js';\n\n/** One persistent box's facts the pure selector reasons about. No I/O. */\nexport interface PersistentBoxEntry {\n boxId: string;\n name: string;\n provider: string;\n /** Live state from `provider.probeState`. */\n state: BoxRuntimeState;\n}\n\n/**\n * Pure selection: which persistent boxes need bringing back.\n *\n * `running` is already where we want it. `missing` means the underlying\n * container or sandbox is GONE — starting it is not possible and pretending\n * otherwise would just log a failure every tick; that box needs a human\n * (recreate, or drop the record). `stopped` and `paused` are recoverable.\n */\nexport function selectPersistentBoxesToStart(entries: PersistentBoxEntry[]): PersistentBoxEntry[] {\n return entries.filter((e) => e.state === 'stopped' || e.state === 'paused');\n}\n\nexport interface PersistentBoxLoopDeps {\n log: (line: string) => void;\n /** Injectable for tests; defaults to the persistent boxes in `state.json`. */\n listPersistentBoxes?: () => Promise<BoxRecord[]>;\n /** Injectable for tests; defaults to the loader/bare-specifier resolution below. */\n resolveProvider?: (name: string) => Promise<Provider | null>;\n intervalMs?: number;\n /** Run the first reconcile immediately (default true — this IS the boot reconcile). */\n runOnStart?: boolean;\n}\n\nexport interface PersistentBoxLoopHandle {\n /** Stop scheduling and await any in-flight tick. */\n stop: () => Promise<void>;\n /** Awaitable handle on the boot reconcile; tests use it, the daemon doesn't. */\n readonly firstTick: Promise<void>;\n}\n\n/**\n * Slow on purpose. Nothing here is latency-sensitive — the boot reconcile\n * (which runs immediately) covers the case that actually matters, and the tick\n * is only a safety net for a box that goes down later. Each tick costs one\n * provider probe per persistent box, and a cloud probe is an SDK round-trip.\n */\nconst DEFAULT_INTERVAL_MS = 5 * 60_000;\n\nexport function startPersistentBoxLoop(deps: PersistentBoxLoopDeps): PersistentBoxLoopHandle {\n const listPersistentBoxes = deps.listPersistentBoxes ?? defaultListPersistentBoxes;\n const resolveProvider = deps.resolveProvider ?? defaultResolveProvider;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { log } = deps;\n\n // Providers resolved once per process (one dynamic import each).\n const providerCache = new Map<string, Provider | null>();\n // Boxes we already reported as unrecoverable (missing/destroyed) or whose\n // provider we could not resolve — logged once, not every tick.\n const reported = new Set<string>();\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function resolveCached(name: string): Promise<Provider | null> {\n if (providerCache.has(name)) return providerCache.get(name) ?? null;\n let provider: Provider | null = null;\n try {\n provider = await resolveProvider(name);\n } catch (err) {\n provider = null;\n log(\n `persistent: cannot resolve provider '${name}': ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n providerCache.set(name, provider);\n return provider;\n }\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const boxes = await listPersistentBoxes();\n if (boxes.length === 0) return;\n\n const entries: { entry: PersistentBoxEntry; box: BoxRecord; provider: Provider }[] = [];\n for (const box of boxes) {\n const name = box.provider ?? 'docker';\n const provider = await resolveCached(name);\n if (!provider) {\n if (!reported.has(box.id)) {\n reported.add(box.id);\n log(`persistent: no provider '${name}' available for box ${box.name}; skipping`);\n }\n continue;\n }\n let state: PersistentBoxEntry['state'];\n try {\n state = await provider.probeState(box);\n } catch (err) {\n log(\n `persistent: probe of box ${box.name} (${name}) failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n continue;\n }\n if (state === 'missing') {\n if (!reported.has(box.id)) {\n reported.add(box.id);\n log(\n `persistent: box ${box.name} (${name}) is missing — its sandbox is gone, so it cannot be restarted (recreate it, or \\`agentbox destroy ${box.name} --force\\`)`,\n );\n }\n continue;\n }\n entries.push({\n entry: { boxId: box.id, name: box.name, provider: name, state },\n box,\n provider,\n });\n }\n\n const wanted = new Set(\n selectPersistentBoxesToStart(entries.map((e) => e.entry)).map((e) => e.boxId),\n );\n for (const { entry, box, provider } of entries) {\n if (!wanted.has(entry.boxId)) continue;\n try {\n log(`persistent: box ${entry.name} is ${entry.state}; bringing it back up`);\n // `reconnect` is the right verb: it unpauses a paused box and runs the\n // full start path (worktree binds, ctl/dockerd relaunch, port\n // re-resolution) for a stopped one. Providers all implement it.\n await provider.reconnect(box);\n reported.delete(entry.boxId);\n log(`persistent: box ${entry.name} is running again`);\n } catch (err) {\n log(\n `persistent: restarting box ${entry.name} failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n } catch (err) {\n // The loop must never crash the relay or stop scheduling.\n log(`persistent: tick error: ${err instanceof Error ? err.message : String(err)}`);\n } finally {\n ticking = false;\n }\n }\n\n const firstTick = deps.runOnStart === false ? Promise.resolve() : tick();\n inFlight = firstTick;\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return {\n firstTick,\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n\n/** Every box in `state.json` whose record says `persistent`. */\nasync function defaultListPersistentBoxes(): Promise<BoxRecord[]> {\n try {\n const { boxes } = await readState();\n return boxes.filter((b) => b.persistent === true);\n } catch {\n return [];\n }\n}\n\n/**\n * Resolve a provider the same way `resolveCloudBackend` resolves a backend:\n * the injected host loader first (the CLI's `dist/cloud-backends.js`, the hub's\n * in-process map), then a bare-specifier import that only resolves in the dev\n * tree, then the plugin registry. Returns null rather than throwing — a box on a\n * provider this relay cannot load is skipped, not fatal.\n */\nasync function defaultResolveProvider(name: string): Promise<Provider | null> {\n const loader = currentCloudBackendLoader();\n if (loader?.resolveProvider) {\n const injected = await loader.resolveProvider(name);\n if (injected) return injected;\n }\n // Legacy fallback: computed specifier so esbuild leaves it alone (the relay\n // bundle carries no provider packages).\n const builtIn = [\n 'docker',\n 'daytona',\n 'hetzner',\n 'vercel',\n 'e2b',\n 'digitalocean',\n 'remote-docker',\n ];\n if (builtIn.includes(name)) {\n const pkg = '@agentbox/sandbox-' + name;\n try {\n const mod = (await import(pkg)) as { providerModule?: { provider?: Provider } };\n return mod.providerModule?.provider ?? null;\n } catch {\n return null;\n }\n }\n const plugin = pluginForProvider(name);\n if (!plugin || !isSupportedApiVersion(plugin.apiVersion)) return null;\n try {\n const mod = (await import(pathToFileURL(plugin.resolvedEntry).href)) as {\n providerModule?: { provider?: Provider };\n providerModules?: { provider?: Provider }[];\n };\n const all = mod.providerModules ?? (mod.providerModule ? [mod.providerModule] : []);\n // Strict name match — never fall back to all[0] (wrong-provider hazard).\n return all.find((m) => m.provider?.name === name)?.provider ?? null;\n } catch {\n return null;\n }\n}\n","import type { Store } from './store/store.js';\n\n/**\n * Periodic housekeeping for a resident control box: sweep answered prompts and\n * finished create jobs so the durable tables don't grow without bound. Events\n * are already ring-trimmed on append; prompts + jobs are not.\n *\n * A no-op unless the store implements the prune methods (durable stores only —\n * the laptop's MemoryStore is process-lifetime, nothing to sweep). Modeled on\n * the other daemon loops (timer, `unref`, never crashes the process).\n */\n\n/** Rows are kept this long after they finish before a sweep removes them. */\nconst DEFAULT_RETENTION_MS = 24 * 60 * 60_000;\nconst DEFAULT_INTERVAL_MS = 60 * 60_000;\n\nexport interface RetentionLoopDeps {\n store: Store;\n log: (line: string) => void;\n /** How long a finished row survives before it's swept. Default 24h. */\n retentionMs?: number;\n /** Sweep cadence. Default hourly. */\n intervalMs?: number;\n /** Injectable for tests; defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface RetentionLoopHandle {\n stop: () => Promise<void>;\n}\n\nexport function startRetentionLoop(deps: RetentionLoopDeps): RetentionLoopHandle {\n const { store, log } = deps;\n const retentionMs = deps.retentionMs ?? DEFAULT_RETENTION_MS;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const nowFn = deps.now ?? Date.now;\n\n // Nothing to sweep on a store without the prune methods (localhost/tests).\n if (!store.prunePrompts && !store.pruneCreateJobs) {\n return { stop: () => Promise.resolve() };\n }\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const before = new Date(nowFn() - retentionMs).toISOString();\n const prompts = (await store.prunePrompts?.(before)) ?? 0;\n const jobs = (await store.pruneCreateJobs?.(before)) ?? 0;\n if (prompts > 0 || jobs > 0) {\n log(`retention: pruned ${String(prompts)} prompt(s), ${String(jobs)} create job(s)`);\n }\n } catch (err) {\n log(`retention: tick error: ${err instanceof Error ? err.message : String(err)}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n","/**\n * `HostReachPoller` — the PC-resident loop that drains host actions parked on a\n * control box (`/admin/hostreach/*`) and executes them against the real project\n * files on this machine.\n *\n * The counterpart to {@link CloudBoxPoller}: execute, post the result back, back\n * off on failure. The difference is direction — that one reaches *into* a box,\n * this one reaches *out* to the control box, because a laptop behind NAT can't\n * be dialled.\n *\n * Two transports, same work: an SSE stream when the network allows one, and the\n * long poll when it doesn't. The stream is preferred because a machine then\n * holds one connection and its presence IS that connection; the poll survives\n * proxies that buffer event streams and control boxes too old to serve the\n * route. Neither can be detected without trying, so the loop tries the stream,\n * falls back on the first hard evidence against it, and retries it later.\n *\n * Running this is what makes `cp` between a hub box and your machine mean your\n * machine. Without it the control box has no way to touch the user's files\n * (see `docs/plans/box-cp-host-reach-plan.md`), and every idle poll doubles as\n * the \"I'm still here\" heartbeat the control box uses to decide whether to wait\n * for a live copy or fall back to the custody cache.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { SseFrameReader } from './sse-read.js';\nimport type { HostAction, HostActionResult } from './types.js';\n\nexport interface HostReachPollerDeps {\n /** Control box base URL (`relay.controlPlaneUrl`). */\n controlPlaneUrl: string;\n /** Admin bearer — the only credential `/admin/hostreach/*` accepts remotely. */\n adminToken: string;\n /**\n * Execute one drained action on this machine. MUST resolve with a result even\n * on failure (a rejection is caught and turned into a non-zero result), or the\n * box on the other end waits forever.\n */\n execute: (action: HostAction) => Promise<HostActionResult | 'not-mine'>;\n /**\n * Land any copies that were parked for this machine while it was offline.\n * Started (never awaited) on first contact and re-checked periodically; it\n * opens a confirm per item, so it must not gate the poll loop.\n */\n drainOutbox?: () => Promise<void>;\n logger?: (line: string) => void;\n}\n\n/**\n * How long the server holds an idle poll open. Kept under the 30s most reverse\n * proxies use as their default idle timeout (the control box runs behind Caddy),\n * so a quiet loop looks like a slow response rather than a hung connection.\n */\nconst POLL_WAIT_MS = 25_000;\n/** Client-side ceiling: the server answers at POLL_WAIT_MS, so this only catches a wedged connection. */\nconst REQUEST_TIMEOUT_MS = 40_000;\nconst RESULT_TIMEOUT_MS = 30_000;\nconst BACKOFF_BASE_MS = 2_000;\nconst BACKOFF_MAX_MS = 60_000;\n/** How often a long-lived poller re-checks the outbox after its first look. */\nconst OUTBOX_RECHECK_MS = 5 * 60_000;\n/** After the stream proves unusable, how long to stay on the poll before retrying it. */\nconst SSE_RETRY_MS = 5 * 60_000;\n/** A stream that sends nothing at all in this window is being buffered somewhere. */\nconst SSE_HANDSHAKE_MS = 10_000;\n\ninterface JsonResponse {\n status: number;\n text: string;\n}\n\nexport class HostReachPoller {\n private stopped = false;\n private loopPromise: Promise<void> | null = null;\n private backoffMs = 0;\n /** Suppresses repeat log lines while a control box stays unreachable. */\n private loggedFailure = false;\n /**\n * Identity of THIS process. Sent with every poll so the control box can tell a\n * restarted relay from the one that took an action and never came back — and\n * re-offer that orphaned work instead of leaving the box waiting forever.\n */\n private readonly pollerId = randomUUID();\n /** Set while a drain is in flight, so only one runs at a time. */\n private drainingOutbox = false;\n /** Epoch ms of the last drain, for the periodic re-check. */\n private lastDrainAtMs = 0;\n /** Serializes execution beside the poll loop (see {@link enqueue}). */\n private workQueue: Promise<void> = Promise.resolve();\n /** Epoch ms before which the stream is not retried (0 = try it now). */\n private sseBlockedUntilMs = 0;\n /** Logged once per transition so the log answers \"which mode am I in?\". */\n private mode: 'stream' | 'poll' | null = null;\n /**\n * The in-flight event stream, so {@link stop} can cut it.\n *\n * An open stream never ends on its own: without this, stopping the relay\n * waits for the control box to drop the connection, which it has no reason to\n * do — `agentbox relay stop` would hang.\n */\n private activeStream: { destroy: () => void } | null = null;\n\n constructor(private readonly deps: HostReachPollerDeps) {}\n\n start(): void {\n if (this.loopPromise) return;\n this.loopPromise = this.run().catch((err: unknown) => {\n this.log(`host-reach poller crashed: ${err instanceof Error ? err.message : String(err)}`);\n });\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n this.activeStream?.destroy();\n if (this.loopPromise) await this.loopPromise;\n // Let an in-flight copy finish rather than abandoning a box mid-transfer.\n await this.workQueue.catch(() => {});\n }\n\n private async run(): Promise<void> {\n const base = this.deps.controlPlaneUrl.replace(/\\/+$/, '');\n this.log(`host-reach: connecting to ${base} for host actions`);\n while (!this.stopped) {\n // Stream when we can, poll when we can't. The stream is preferred (one\n // connection, presence is the connection); the poll is what keeps this\n // working through a proxy that buffers event streams, or against a\n // control box too old to serve the route — neither of which we can detect\n // any way other than trying.\n if (this.streamingAllowed()) {\n const outcome = await this.stream(base);\n if (this.stopped) break;\n if (outcome === 'fatal') return;\n if (outcome === 'unsupported' || outcome === 'unusable') {\n this.sseBlockedUntilMs = Date.now() + SSE_RETRY_MS;\n this.log(\n outcome === 'unsupported'\n ? 'host-reach: control box has no event stream; falling back to long polling'\n : 'host-reach: event stream did not come through (a proxy may be buffering it); falling back to long polling',\n );\n }\n // A stream that WAS established and then dropped is an ordinary\n // reconnect: loop straight back and try to stream again.\n continue;\n }\n try {\n const res = await this.get(\n `${base}/admin/hostreach/poll?wait=${String(POLL_WAIT_MS)}&poller=${this.pollerId}`,\n );\n if (res.status === 404) {\n // An older control box has no host-reach surface. Nothing this loop\n // can do until it is updated; say so once and stop pestering it.\n this.log(\n 'host-reach: this control box does not serve /admin/hostreach (update it) — poller stopping',\n );\n return;\n }\n if (res.status === 401 || res.status === 403) {\n this.log(\n 'host-reach: control box rejected the admin token — poller stopping (re-run `agentbox hub setup`)',\n );\n return;\n }\n if (res.status < 200 || res.status >= 300) {\n throw new Error(`poll → ${String(res.status)}: ${res.text.slice(0, 200)}`);\n }\n this.backoffMs = 0;\n if (this.loggedFailure) {\n this.log('host-reach: control box reachable again');\n this.loggedFailure = false;\n }\n if (this.mode !== 'poll') {\n this.mode = 'poll';\n this.log('host-reach: long polling for host actions');\n }\n this.maybeDrainOutbox();\n const parsed = JSON.parse(res.text.length > 0 ? res.text : '{}') as {\n actions?: HostAction[];\n };\n const actions = Array.isArray(parsed.actions) ? parsed.actions : [];\n for (const action of actions) this.enqueue(base, action);\n } catch (err) {\n if (this.stopped) break;\n if (!this.loggedFailure) {\n this.log(\n `host-reach: control box unreachable (${err instanceof Error ? err.message : String(err)}); retrying`,\n );\n this.loggedFailure = true;\n }\n this.backoffMs = Math.min(\n this.backoffMs === 0 ? BACKOFF_BASE_MS : this.backoffMs * 2,\n BACKOFF_MAX_MS,\n );\n await delay(this.backoffMs);\n }\n }\n }\n\n /** Whether to attempt the stream, or stay on the poll after it proved unusable. */\n private streamingAllowed(): boolean {\n return Date.now() >= this.sseBlockedUntilMs;\n }\n\n /**\n * Hold one event stream until it drops.\n *\n * Returns why it ended, which is what decides the next move:\n * - `unsupported` — the route 404s (an older control box). Poll.\n * - `unusable` — connected but nothing arrived, not even the preamble, within\n * {@link SSE_HANDSHAKE_MS}. Something between here and there is buffering\n * the response; polling still works through it. Poll.\n * - `dropped` — it worked and then ended (idle timeout, network blip, hub\n * restart). Reconnect; this is the normal case.\n * - `fatal` — the token was rejected. Neither transport will help.\n */\n private stream(base: string): Promise<'unsupported' | 'unusable' | 'dropped' | 'fatal'> {\n const url = new URL(`${base}/admin/hostreach/events?poller=${this.pollerId}`);\n const isHttps = url.protocol === 'https:';\n const transport = isHttps ? httpsRequest : httpRequest;\n return new Promise((resolve) => {\n let settled = false;\n const finish = (outcome: 'unsupported' | 'unusable' | 'dropped' | 'fatal'): void => {\n if (settled) return;\n settled = true;\n clearTimeout(handshake);\n this.activeStream = null;\n req.destroy();\n resolve(outcome);\n };\n // Nothing at all — not even the `: connected` preamble — means the\n // response is being held somewhere. A stream that is merely quiet still\n // gets its heartbeat well inside this window.\n const handshake = setTimeout(() => finish('unusable'), SSE_HANDSHAKE_MS);\n handshake.unref?.();\n\n const req = transport(\n {\n host: url.hostname,\n port: url.port.length > 0 ? Number.parseInt(url.port, 10) : isHttps ? 443 : 80,\n method: 'GET',\n path: `${url.pathname}${url.search}`,\n headers: {\n Authorization: `Bearer ${this.deps.adminToken}`,\n Accept: 'text/event-stream',\n },\n },\n (res) => {\n const status = res.statusCode ?? 0;\n if (status === 404) {\n res.resume();\n finish('unsupported');\n return;\n }\n if (status === 401 || status === 403) {\n res.resume();\n this.log(\n 'host-reach: control box rejected the admin token — stopping (re-run `agentbox hub setup`)',\n );\n finish('fatal');\n return;\n }\n if (status < 200 || status >= 300) {\n res.resume();\n finish('unusable');\n return;\n }\n // A proxy that rewrote the response to something buffered is not a\n // stream, whatever the status says.\n if (!(res.headers['content-type'] ?? '').includes('text/event-stream')) {\n res.resume();\n finish('unusable');\n return;\n }\n const reader = new SseFrameReader();\n res.setEncoding('utf8');\n res.on('data', (chunk: string) => {\n // Any byte proves the response is flowing, including the preamble\n // and heartbeats.\n clearTimeout(handshake);\n if (this.mode !== 'stream') {\n this.mode = 'stream';\n this.log('host-reach: streaming host actions (event stream)');\n }\n this.backoffMs = 0;\n this.loggedFailure = false;\n this.maybeDrainOutbox();\n for (const frame of reader.push(chunk)) {\n if (frame.event !== 'action') continue;\n try {\n this.enqueue(base, JSON.parse(frame.data) as HostAction);\n } catch {\n /* a frame we can't parse is not worth dropping the stream for */\n }\n }\n });\n res.on('end', () => finish('dropped'));\n res.on('error', () => finish('dropped'));\n },\n );\n req.on('error', () => finish('unusable'));\n this.activeStream = req;\n req.end();\n });\n }\n\n /**\n * Kick off an outbox drain, **without** waiting for it.\n *\n * Deliberately not awaited inside the poll loop: a drain opens a confirm per\n * parked copy and blocks until the user answers, so awaiting it here stops\n * this machine polling — the control box then declares it gone and live\n * copies start failing over to the cache while the user is sitting right\n * there. Found exactly that way in a live run.\n *\n * Re-checked periodically rather than once per process: a copy can be parked\n * while this machine is up (a network blip on the control box's side is\n * enough), and a machine that stays online for days would otherwise never\n * look again.\n */\n private maybeDrainOutbox(): void {\n if (!this.deps.drainOutbox || this.drainingOutbox) return;\n if (this.lastDrainAtMs > 0 && Date.now() - this.lastDrainAtMs < OUTBOX_RECHECK_MS) return;\n this.drainingOutbox = true;\n this.lastDrainAtMs = Date.now();\n void this.deps\n .drainOutbox()\n .catch((err: unknown) => {\n this.log(\n `host-reach: could not land parked copies: ${err instanceof Error ? err.message : String(err)}`,\n );\n })\n .finally(() => {\n this.drainingOutbox = false;\n });\n }\n\n /**\n * Queue an action for execution **off** the poll loop.\n *\n * Executing inline stops this machine polling for as long as the copy takes —\n * and a copy takes as long as the user takes to answer its confirm. The\n * control box reads that silence as \"the machine went away\", tells the box so,\n * and then has nowhere to put the result that eventually arrives. The poll\n * loop's only job is the heartbeat; work happens beside it.\n *\n * Still strictly sequential: each action can open a confirm, and two prompts\n * competing for one terminal is not a UX.\n */\n private enqueue(base: string, action: HostAction): void {\n this.workQueue = this.workQueue\n .then(() => (this.stopped ? undefined : this.handle(base, action)))\n .catch((err: unknown) => {\n this.log(\n `host-reach: ${action.method} failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n }\n\n private async handle(base: string, action: HostAction): Promise<void> {\n this.log(`host-reach: executing ${action.method} for box ${action.boxId}`);\n let result: HostActionResult | 'not-mine';\n try {\n result = await this.deps.execute(action);\n } catch (err) {\n result = {\n exitCode: 1,\n stdout: '',\n stderr: `${action.method} failed on this machine: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n try {\n if (result === 'not-mine') {\n // Hand it back rather than answering for a box this machine has never\n // seen: on a hub with two machines the other one may own it.\n await this.post(`${base}/admin/hostreach/decline`, {\n id: action.id,\n poller: this.pollerId,\n });\n return;\n }\n await this.post(`${base}/admin/hostreach/result`, {\n id: action.id,\n poller: this.pollerId,\n ...result,\n });\n } catch (err) {\n // The box is still blocked on this action; the control box will time it\n // out as 'went-away' once we stop polling, so it can't hang forever.\n this.log(\n `host-reach: could not post the result for ${action.id}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n private get(url: string): Promise<JsonResponse> {\n return this.send(url, 'GET', undefined, REQUEST_TIMEOUT_MS);\n }\n\n private post(url: string, body: unknown): Promise<JsonResponse> {\n return this.send(url, 'POST', JSON.stringify(body), RESULT_TIMEOUT_MS);\n }\n\n private send(\n rawUrl: string,\n method: string,\n payload: string | undefined,\n timeoutMs: number,\n ): Promise<JsonResponse> {\n const url = new URL(rawUrl);\n const isHttps = url.protocol === 'https:';\n const transport = isHttps ? httpsRequest : httpRequest;\n const port = url.port.length > 0 ? Number.parseInt(url.port, 10) : isHttps ? 443 : 80;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.deps.adminToken}`,\n };\n if (payload !== undefined) {\n headers['Content-Type'] = 'application/json';\n headers['Content-Length'] = Buffer.byteLength(payload).toString();\n }\n return new Promise<JsonResponse>((resolve, reject) => {\n const req = transport(\n {\n host: url.hostname,\n port,\n method,\n path: `${url.pathname}${url.search}`,\n headers,\n timeout: timeoutMs,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer) => chunks.push(chunk));\n res.on('end', () =>\n resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString('utf8') }),\n );\n res.on('error', reject);\n },\n );\n req.on('error', reject);\n req.on('timeout', () => {\n req.destroy();\n reject(new Error(`${method} ${url.pathname} timed out`));\n });\n if (payload !== undefined) req.write(payload);\n req.end();\n });\n }\n\n private log(line: string): void {\n this.deps.logger?.(line);\n }\n}\n","/**\n * Minimal SSE frame reader.\n *\n * Node has no `EventSource`, so a consumer has to buffer to the `\\n\\n` message\n * boundary and split `event:` / `data:` lines itself. The CLI's prompt stream\n * (`apps/cli/src/wrapped-pty/prompt-client.ts`) already does exactly this — but\n * `@agentbox/relay` cannot import from `apps/cli`, and the relay is a dependency\n * of the CLI rather than the other way round, so the shared copy belongs here.\n * That client can adopt it; until it does, the duplication is deliberate and\n * named rather than silent.\n */\n\nexport interface SseFrame {\n /** `event:` name, or 'message' when the frame omits one (the SSE default). */\n event: string;\n /** Concatenated `data:` lines, newline-joined as the spec requires. */\n data: string;\n}\n\n/**\n * Feed raw stream chunks in, get whole frames out.\n *\n * Stateful across chunks: a server may split a frame at any byte, and the\n * comment lines servers use as keep-alives (`: connected`) are dropped.\n */\nexport class SseFrameReader {\n private buffer = '';\n\n /** Frames completed by this chunk, in order. */\n push(chunk: string): SseFrame[] {\n this.buffer += chunk;\n const out: SseFrame[] = [];\n let idx = this.buffer.indexOf('\\n\\n');\n while (idx !== -1) {\n const raw = this.buffer.slice(0, idx);\n this.buffer = this.buffer.slice(idx + 2);\n const frame = parseFrame(raw);\n if (frame) out.push(frame);\n idx = this.buffer.indexOf('\\n\\n');\n }\n return out;\n }\n\n /** Drop any partial frame — call on reconnect so a torn frame can't merge. */\n reset(): void {\n this.buffer = '';\n }\n}\n\nfunction parseFrame(raw: string): SseFrame | null {\n let event = 'message';\n const data: string[] = [];\n for (const line of raw.split('\\n')) {\n // A line starting with ':' is a comment: keep-alives and the connect\n // preamble arrive that way and carry no event.\n if (line.startsWith(':')) continue;\n if (line.startsWith('event:')) event = line.slice(6).trim();\n else if (line.startsWith('data:')) data.push(line.slice(5).trimStart());\n }\n if (data.length === 0) return null;\n return { event, data: data.join('\\n') };\n}\n","/**\n * Landing copies that were parked while this machine was offline.\n *\n * Runs on the user's machine when its relay first reaches the control box.\n * Every item still goes through a confirm: the copy is being applied to this\n * disk *now*, whatever a box asked for hours ago, and \"I approved it earlier\"\n * is not something the user ever actually did — a parked copy was never\n * approved by anyone, only accepted for transport.\n */\n\nimport { rm } from 'node:fs/promises';\nimport { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { askPrompt, type PendingPrompts, type PromptSubscribers } from './prompts.js';\nimport { boxWorkspacePath, lookupCloudBoxOwner } from './host-actions.js';\nimport { landCpOutboxTar, stageOutboxTar, type CpOutboxItem } from './cp-outbox.js';\nimport { describeCacheAge } from './cp-cache.js';\nimport { resolveHostPath } from '@agentbox/core';\n\nexport interface CpOutboxDrainDeps {\n controlPlaneUrl: string;\n adminToken: string;\n prompts: PendingPrompts;\n subscribers: PromptSubscribers;\n log: (line: string) => void;\n}\n\nconst REQUEST_TIMEOUT_MS = 300_000;\n\n/** Fetch, confirm and land every parked copy this machine can account for. */\nexport async function drainCpOutbox(deps: CpOutboxDrainDeps): Promise<void> {\n const base = deps.controlPlaneUrl.replace(/\\/+$/, '');\n const listed = await getJson(`${base}/admin/hostreach/outbox`, deps.adminToken);\n const items = Array.isArray((listed as { items?: CpOutboxItem[] }).items)\n ? (listed as { items: CpOutboxItem[] }).items\n : [];\n if (items.length === 0) return;\n deps.log(`host-reach: ${String(items.length)} parked cop(y|ies) waiting for this machine`);\n\n for (const item of items) {\n // Only land for boxes this machine actually knows: another machine's parked\n // copy must stay parked for it, not be intercepted here.\n const owner = await lookupCloudBoxOwner(item.meta.boxId);\n if (!owner) continue;\n const workspacePath = await boxWorkspacePath(item.meta.boxId);\n const destAbs = resolveHostPath(workspacePath, item.meta.dest);\n const verdict = await askPrompt(deps.prompts, deps.subscribers, item.meta.boxId, {\n kind: 'confirm',\n message: `Land a copy ${owner.name} sent while this machine was offline?`,\n detail: [\n `${item.meta.sources.join(', ')} -> ${destAbs}`,\n `${describeCacheAge(item.meta.createdAt)}, ${String(item.meta.size)} bytes`,\n ].join('\\n'),\n defaultAnswer: 'n',\n context: { command: 'cp.toHost (parked)', argv: [...item.meta.sources, destAbs] },\n });\n if (verdict.answer !== 'y') {\n deps.log(`host-reach: declined the parked copy from ${owner.name}; leaving it on the hub`);\n continue;\n }\n let stagedDir: string | undefined;\n try {\n const stream = await getStream(`${base}/admin/custody-blob/${item.tarPath}`, deps.adminToken);\n const staged = await stageOutboxTar(stream);\n stagedDir = staged.dir;\n // Destination semantics live in landCpOutboxTar, which follows `cp`: a\n // trailing slash or an existing directory receives the members, anything\n // else NAMES the file and a single member is renamed onto it.\n await landCpOutboxTar(staged.tarPath, destAbs, {\n destEndsWithSlash: /[/\\\\]$/.test(item.meta.dest),\n });\n await del(`${base}/admin/hostreach/outbox/${item.meta.id}`, deps.adminToken);\n deps.log(`host-reach: landed a parked copy from ${owner.name} at ${destAbs}`);\n } catch (err) {\n // Left on the hub deliberately: a failure here must not consume the only\n // copy of an agent's output.\n deps.log(\n `host-reach: could not land the parked copy from ${owner.name} (left on the hub): ${err instanceof Error ? err.message : String(err)}`,\n );\n } finally {\n if (stagedDir) await rm(stagedDir, { recursive: true, force: true }).catch(() => {});\n }\n }\n}\n\nfunction getJson(url: string, token: string): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const target = new URL(url);\n const isHttps = target.protocol === 'https:';\n const req = (isHttps ? httpsRequest : httpRequest)(\n {\n host: target.hostname,\n port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,\n method: 'GET',\n path: target.pathname,\n headers: { Authorization: `Bearer ${token}` },\n timeout: REQUEST_TIMEOUT_MS,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf8');\n const status = res.statusCode ?? 0;\n if (status < 200 || status >= 300) {\n reject(new Error(`${target.pathname} → ${String(status)}`));\n return;\n }\n try {\n resolve(text.length > 0 ? JSON.parse(text) : {});\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n });\n },\n );\n req.on('error', reject);\n req.on('timeout', () => {\n req.destroy();\n reject(new Error(`${target.pathname} timed out`));\n });\n req.end();\n });\n}\n\nfunction getStream(url: string, token: string): Promise<NodeJS.ReadableStream> {\n return new Promise((resolve, reject) => {\n const target = new URL(url);\n const isHttps = target.protocol === 'https:';\n const req = (isHttps ? httpsRequest : httpRequest)(\n {\n host: target.hostname,\n port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,\n method: 'GET',\n path: target.pathname,\n headers: { Authorization: `Bearer ${token}` },\n timeout: REQUEST_TIMEOUT_MS,\n },\n (res) => {\n const status = res.statusCode ?? 0;\n if (status < 200 || status >= 300) {\n res.resume();\n reject(new Error(`custody blob GET → ${String(status)}`));\n return;\n }\n resolve(res);\n },\n );\n req.on('error', reject);\n req.on('timeout', () => {\n req.destroy();\n reject(new Error('custody blob GET timed out'));\n });\n req.end();\n });\n}\n\nfunction del(url: string, token: string): Promise<void> {\n return new Promise((resolve, reject) => {\n const target = new URL(url);\n const isHttps = target.protocol === 'https:';\n const req = (isHttps ? httpsRequest : httpRequest)(\n {\n host: target.hostname,\n port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,\n method: 'DELETE',\n path: target.pathname,\n headers: { Authorization: `Bearer ${token}` },\n timeout: REQUEST_TIMEOUT_MS,\n },\n (res) => {\n res.resume();\n const status = res.statusCode ?? 0;\n if (status >= 200 && status < 300) resolve();\n else reject(new Error(`outbox DELETE → ${String(status)}`));\n },\n );\n req.on('error', reject);\n req.on('timeout', () => {\n req.destroy();\n reject(new Error('outbox DELETE timed out'));\n });\n req.end();\n });\n}\n","import { startRelayServer, type RelayServerHandle, type RelayServerOptions } from './server.js';\nimport { startAutopauseLoop } from './autopause.js';\nimport { startCloudKeepaliveLoop } from './cloud-keepalive.js';\nimport { startPersistentBoxLoop } from './persistent-boxes.js';\nimport { startQueueLoop } from './queue.js';\nimport { startRetentionLoop } from './retention.js';\nimport { HostReachPoller } from './host-reach-poller.js';\nimport { drainCpOutbox } from './cp-outbox-drain.js';\nimport { cacheCpSources, executeCloudAction, lookupCloudBoxOwner } from './host-actions.js';\nimport type { HostAction, HostActionResult } from './types.js';\n\n// Re-exported here (not just from index.ts) so the two processes that own a\n// relay — the CLI's `agentbox-relay serve` bin and the hub server — can register\n// their built-in cloud backends from the same module they already import\n// `startRelayDaemon` from, without pulling the full package barrel.\nexport {\n setCloudBackendLoader,\n type CloudBackendLoader,\n type CloudCpModule,\n} from './host-actions.js';\n\nexport interface RelayDaemonOptions extends RelayServerOptions {\n /**\n * Control box this machine works with (`relay.controlPlaneUrl`). Set → the\n * daemon runs a {@link HostReachPoller} against it. Falls back to\n * `AGENTBOX_CONTROL_PLANE_URL`, which is how the CLI's `spawnRelay` passes it.\n */\n controlPlaneUrl?: string;\n /**\n * Bearer for that control box's `/admin/hostreach/*`. Falls back to\n * `AGENTBOX_RELAY_ADMIN_TOKEN`. Absent → no poller (logged, never silent).\n */\n hostReachAdminToken?: string;\n}\n\nexport interface RelayDaemonHandle {\n /** The underlying relay server (url, store, close, …). */\n handle: RelayServerHandle;\n /** Stop the background loops, then close the server. */\n stop: () => Promise<void>;\n}\n\n/**\n * Boot the relay HTTP server plus its background loops (autopause / cloud\n * keepalive / queue) — the daemon that `agentbox-relay serve` runs. Extracted\n * so the hub server can import it, prepare Next, and pass Next's request\n * handler in as `opts.uiHandler` to serve the UI on the relay's own port.\n *\n * Process-owner concerns (the \"listening\" log line, SIGTERM/SIGINT handling)\n * stay with the caller so the same daemon works under both the relay bin and\n * the hub server.\n */\nexport async function startRelayDaemon(opts: RelayDaemonOptions): Promise<RelayDaemonHandle> {\n const handle = await startRelayServer(opts);\n const log = opts.logger ?? (() => {});\n // With a control box configured, this relay is also the user's side of the\n // host-reach channel: it drains the `cp` actions the control box parked for\n // this machine and runs them against the real project files here.\n const controlPlaneUrl = (opts.controlPlaneUrl ?? process.env.AGENTBOX_CONTROL_PLANE_URL ?? '')\n .trim()\n .replace(/\\/+$/, '');\n const hostReachToken = (\n opts.hostReachAdminToken ??\n process.env.AGENTBOX_RELAY_ADMIN_TOKEN ??\n ''\n ).trim();\n // Never on the control box itself: it is the one parking the actions, and a\n // poller there would race the PC for work it cannot do.\n const hostReachPoller =\n controlPlaneUrl.length > 0 && hostReachToken.length > 0 && opts.controlPlane !== true\n ? new HostReachPoller({\n controlPlaneUrl,\n adminToken: hostReachToken,\n logger: log,\n execute: (action) =>\n executeHostReachAction(action, {\n prompts: handle.prompts,\n subscribers: handle.subscribers,\n log,\n cache: { controlPlaneUrl, adminToken: hostReachToken },\n }),\n drainOutbox: () =>\n drainCpOutbox({\n controlPlaneUrl,\n adminToken: hostReachToken,\n prompts: handle.prompts,\n subscribers: handle.subscribers,\n log,\n }),\n })\n : null;\n hostReachPoller?.start();\n if (controlPlaneUrl.length > 0 && hostReachToken.length === 0 && opts.controlPlane !== true) {\n // Silence here would look exactly like \"cp is broken again\": the box's copy\n // falls back to the hub's cache (or fails) with nothing on this side saying why.\n log(\n 'host-reach: a control box is configured but no admin token is available; ' +\n 'cp between a hub box and this machine will not reach it (re-run `agentbox hub setup`)',\n );\n }\n const autopause = startAutopauseLoop({\n registry: handle.registry,\n statusStore: handle.statusStore,\n events: handle.events,\n log,\n });\n const cloudKeepalive = startCloudKeepaliveLoop({\n registry: handle.registry,\n statusStore: handle.statusStore,\n log,\n // An idle pause must also silence that box's poller, or an auto-resuming\n // backend (e2b) revives the box on the poller's next long-poll.\n stopPoller: (boxId) => handle.stopCloudPoller(boxId),\n });\n // Boot reconcile for always-on boxes: a host reboot (or a provider-side stop)\n // leaves a persistent box down with nothing else to notice. Runs once\n // immediately, then on a slow tick.\n const persistentBoxes = startPersistentBoxLoop({ log });\n const queue = startQueueLoop({\n log,\n registry: handle.registry,\n statusStore: handle.statusStore,\n // Refresh the embedded hub UI whenever a background job flips state\n // (queued → running → done/failed), so a create job's box shows up and\n // then transitions creating → running without waiting for the 15s SSE ping.\n onStatusChange: () => handle.hubNotifier.notify(),\n });\n // Sweep answered prompts + finished create jobs on a resident control box\n // (durable store). A no-op when the store lacks the prune methods (localhost).\n const retention = startRetentionLoop({ store: handle.store, log });\n // `poke` isn't on the declared QueueLoopHandle (only `stop` is); same cast bin.ts used.\n handle.setQueuePoke(() => {\n (queue as { poke?: () => void }).poke?.();\n });\n\n return {\n handle,\n stop: async () => {\n await Promise.allSettled([\n autopause.stop(),\n cloudKeepalive.stop(),\n persistentBoxes.stop(),\n queue.stop(),\n retention.stop(),\n hostReachPoller?.stop() ?? Promise.resolve(),\n ]);\n await handle.close();\n },\n };\n}\n\n/**\n * Run one host-reach action on this machine, with this relay's own prompt\n * surfaces — so the confirm lands in the attach footer / local hub / tray of the\n * person whose files are about to move, and containment is judged against the\n * real project path rather than the control box's idea of one.\n *\n * Resolving the box locally is also the authorization step: this machine only\n * acts for boxes it already knows. An unknown box is DECLINED rather than\n * answered — see the note below.\n */\nasync function executeHostReachAction(\n action: HostAction,\n deps: {\n prompts: RelayServerHandle['prompts'];\n subscribers: RelayServerHandle['subscribers'];\n log: (line: string) => void;\n cache: { controlPlaneUrl: string; adminToken: string };\n },\n): Promise<HostActionResult | 'not-mine'> {\n const owner = await lookupCloudBoxOwner(action.boxId);\n // Not an answer, a refusal: another machine on this hub may hold the box, and\n // answering \"unknown box\" here would settle its user's copy. The hub returns\n // the action to the pool; if nobody claims it, its own timers report that.\n if (!owner) {\n deps.log(`host-reach: declining ${action.method} — box ${action.boxId} is not known here`);\n return 'not-mine';\n }\n const result = await executeCloudAction(action, {\n backendName: owner.backendName,\n boxId: action.boxId,\n boxName: owner.name,\n prompts: deps.prompts,\n subscribers: deps.subscribers,\n autoApproveSafeHostActions: owner.autoApproveSafeHostActions,\n boxAgents: owner.agents,\n log: deps.log,\n });\n // File a copy with the control box so this same request answers when this\n // machine is offline. Strictly after the real copy succeeded, and awaited only\n // so the log lands in order — a failure here cannot change `result`.\n if (result.exitCode === 0 && action.method === 'cp.fromHost' && action.cachePrefix) {\n await cacheCpSources(action, action.cachePrefix, {\n controlPlaneUrl: deps.cache.controlPlaneUrl,\n adminToken: deps.cache.adminToken,\n logger: deps.log,\n });\n }\n return result;\n}\n","import type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { PromptRow, Store } from './store.js';\nimport type { StoreRpcResponse } from './store-rpc.js';\n\n/**\n * A {@link Store} backed by a remote hosted control plane over HTTP. A federated\n * laptop relay uses this so its registry / prompts / events / status live\n * centrally (one cross-machine view) while it still executes host-local actions\n * locally. Each method is one admin-bearer `POST /admin/store {method, args}`.\n *\n * `fetch` (Node 20+) is used directly; inject one for tests.\n */\nexport interface RemoteStoreOptions {\n /** Base URL of the hosted control plane (e.g. https://plane.example.com). */\n baseUrl: string;\n /** Admin bearer for `/admin/store`. */\n adminToken: string;\n fetchImpl?: typeof fetch;\n}\n\nexport class RemoteStore implements Store {\n private readonly url: string;\n private readonly token: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(opts: RemoteStoreOptions) {\n this.url = `${opts.baseUrl.replace(/\\/$/, '')}/admin/store`;\n this.token = opts.adminToken;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n private async call<R>(method: string, args: unknown[]): Promise<R> {\n const res = await this.fetchImpl(this.url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.token}`,\n },\n body: JSON.stringify({ method, args }),\n });\n if (!res.ok) {\n throw new Error(`remote store ${method} → ${String(res.status)}`);\n }\n const body = (await res.json()) as StoreRpcResponse;\n return body.result as R;\n }\n\n registerBox(reg: BoxRegistration): Promise<void> {\n return this.call('registerBox', [reg]);\n }\n getBox(boxId: string): Promise<BoxRegistration | undefined> {\n return this.call<BoxRegistration | null>('getBox', [boxId]).then((r) => r ?? undefined);\n }\n authenticateBox(token: string): Promise<BoxRegistration | null> {\n return this.call('authenticateBox', [token]);\n }\n listBoxes(): Promise<BoxRegistration[]> {\n return this.call('listBoxes', []);\n }\n forgetBox(boxId: string): Promise<boolean> {\n return this.call('forgetBox', [boxId]);\n }\n countBoxes(): Promise<number> {\n return this.call('countBoxes', []);\n }\n\n appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n return this.call('appendEvent', [input]);\n }\n listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n return this.call('listEvents', [since, boxId]);\n }\n countEvents(): Promise<number> {\n return this.call('countEvents', []);\n }\n\n setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n return this.call('setStatus', [boxId, name, projectIndex, status]);\n }\n getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n return this.call<BoxStatusSnapshot | null>('getStatus', [boxId]).then((r) => r ?? undefined);\n }\n deleteStatus(boxId: string): Promise<void> {\n return this.call('deleteStatus', [boxId]);\n }\n listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n return this.call('listStatuses', []);\n }\n\n createPrompt(row: PromptRow): Promise<void> {\n return this.call('createPrompt', [row]);\n }\n getPrompt(promptId: string): Promise<PromptRow | null> {\n return this.call('getPrompt', [promptId]);\n }\n answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n return this.call('answerPrompt', [promptId, answer, cancelled]);\n }\n listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n return this.call('listPendingPrompts', [boxId]);\n }\n setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n return this.call('setPromptResult', [promptId, result]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEAA,SAAS,OAAO,QAAQ,IAAI,iBAAiB;AAC7C,SAAS,eAAe;AACxB,SAAS,YAAY;AEFrB,SAAS,kBAAkB;ACA3B,SAAS,cAAAA,mBAAkB;ACA3B,SAAS,kBAAkB;AIe3B,SAAS,uBAAuB;ACDhC,SAAS,kBAAkB;ACE3B,SAAS,mBAAAC,wBAAuB;ACJhC,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,MAAAC,WAAU;AACnB,SAAS,eAAe;AACxB,SAAS,mBAAAF,wBAAuB;AEfhC,SAAS,kBAAkB;ACA3B,SAAS,aAAa;AACtB,SAAS,mBAAmB;AAC5B,SAAS,SAAAG,QAAO,SAAS,UAAU,UAAAC,SAAQ,QA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uC;AACvF,WAAO,KAAK,KAAK,gBAAgB,CAAC,UAAU,QAAQ,SAAS,CAAC;EAChE;EACA,mBAAmB,OAAqC;AACtD,WAAO,KAAK,KAAK,sBAAsB,CAAC,KAAK,CAAC;EAChD;EACA,gBAAgB,UAAkB,QAAqC;AACrE,WAAO,KAAK,KAAK,mBAAmB,CAAC,UAAU,MAAM,CAAC;EACxD;AACF;","names":["randomUUID","timingSafeEqual","randomUUID","rm","mkdir","rename","writeFile","existsSync","join","randomUUID","err","text","timingSafeEqualStr","timingSafeEqual","parseJson","readState","boxSshDirForProvider","rm","join","STATE_DIR","mkdir","writeFile","rename","normalizeAgentStatus","existsSync","timingSafeEqual","dirname","join","mkdir","readFile","readdir","rename","rm","writeFile","dirname","join","createHash","randomBytes","err","timingSafeEqualStr","timingSafeEqual","parseJson","text","integer","pg","DEFAULT_EVENT_CAP","join","require","ok","dirname","eq","asc","lte","gt","and","inArray","desc","or","lt","isNotNull","STATE_DIR","mkdir","randomBytes","writeFile","rename","rm","createHash","readFile","readdir","spawn","existsSync","mkdtemp","rm","tmpdir","join","spawn","existsSync","createHash","randomBytes","createReadStream","rm","stat","tmpdir","dirname","join","basename","spawn","randomUUID","randomUUID","execFile","createWriteStream","existsSync","mkdtemp","rm","tmpdir","basename","join","pipeline","createReadStream","readdir","rename","stat","dirname","timingSafeEqual","stat","execa","spawn","readFile","readFile","pathToFileURL","randomUUID","httpRequest","httpsRequest","delay","rm","existsSync","spawn","err","createHash","randomBytes","stat","join","tmpdir","dirname","rm","createReadStream","basename","open","randomUUID","verdict","run","loadGrantedTools","realpathSafe","mkdtemp","fetch","pipeline","createWriteStream","execFile","TAR_TIMEOUT_MS","readdir","rename","timingSafeEqualStr","timingSafeEqual","execa","text","ok","buildAgentDescriptors","result","isScratchBranch","isSanctionedPushBranch","resolveRemote","parseDownloadKind","url","hit","resolveLandDest","landRefspec","sanitizeGitArgs","upstreamRef","isValidToolName","writeToolGrant","resolveProjectToolsFile","readFile","DEFAULT_INTERVAL_MS","msSince","readState","toEpoch","findBox","BUILT_IN_DEFAULTS","parseUserConfig","GLOBAL_CONFIG_FILE","pluginForProvider","isSupportedApiVersion","pathToFileURL","delay","httpsRequest","httpRequest","REQUEST_TIMEOUT_MS","resolveHostPath"]}