@madarco/agentbox 0.28.1 → 0.29.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 (452) hide show
  1. package/CHANGELOG.md +146 -0
  2. package/dist/_cloud-attach-EUO2OL7W.js +30 -0
  3. package/dist/chunk-2JHPGPLE.js +71 -0
  4. package/dist/chunk-2JHPGPLE.js.map +1 -0
  5. package/dist/{chunk-JQLOGVZK.js → chunk-4KYP775X.js} +85 -21
  6. package/dist/chunk-4KYP775X.js.map +1 -0
  7. package/dist/{chunk-V5NWSLWD.js → chunk-4NUETVTR.js} +14 -14
  8. package/dist/{chunk-OXKW4GWD.js → chunk-53OTEDBS.js} +4 -70
  9. package/dist/chunk-53OTEDBS.js.map +1 -0
  10. package/dist/{chunk-FGQFVUMH.js → chunk-6YSYQZRH.js} +3 -3
  11. package/dist/{chunk-KFLGXE3R.js → chunk-73D2HKA3.js} +138 -24
  12. package/dist/chunk-73D2HKA3.js.map +1 -0
  13. package/dist/{chunk-HYXCH4GA.js → chunk-7LC5IG5K.js} +7 -7
  14. package/dist/{chunk-NHVGKFVY.js → chunk-7LNXTPEE.js} +340 -22
  15. package/dist/chunk-7LNXTPEE.js.map +1 -0
  16. package/dist/{chunk-74VIUGY6.js → chunk-A2TATHHJ.js} +6 -9
  17. package/dist/chunk-A2TATHHJ.js.map +1 -0
  18. package/dist/{chunk-YI4GHC2E.js → chunk-AC3HU25W.js} +12 -15
  19. package/dist/chunk-AC3HU25W.js.map +1 -0
  20. package/dist/{chunk-7ABO7OIF.js → chunk-AUHYXXCA.js} +4 -4
  21. package/dist/{chunk-FPMRFMVK.js → chunk-B4YFG5TB.js} +9 -9
  22. package/dist/{chunk-OUF3YTQO.js → chunk-BIKWXLX7.js} +14 -17
  23. package/dist/chunk-BIKWXLX7.js.map +1 -0
  24. package/dist/{chunk-CKD3PRON.js → chunk-CZPVVFCF.js} +12 -9
  25. package/dist/{chunk-CKD3PRON.js.map → chunk-CZPVVFCF.js.map} +1 -1
  26. package/dist/chunk-F4PPZ4SI.js +17 -0
  27. package/dist/chunk-F4PPZ4SI.js.map +1 -0
  28. package/dist/{chunk-BWM56FKY.js → chunk-FEFLAITR.js} +11 -11
  29. package/dist/{chunk-EVT2SNF2.js → chunk-FELVUIIM.js} +3 -3
  30. package/dist/{chunk-46NNZMZT.js → chunk-I2DEYQLZ.js} +372 -72
  31. package/dist/chunk-I2DEYQLZ.js.map +1 -0
  32. package/dist/{chunk-OUWVN2F2.js → chunk-I7BSBUPC.js} +16 -13
  33. package/dist/chunk-I7BSBUPC.js.map +1 -0
  34. package/dist/{chunk-G3H2L3O2.js → chunk-MNDKP4VS.js} +23 -3
  35. package/dist/chunk-MNDKP4VS.js.map +1 -0
  36. package/dist/{chunk-BUMKBUXS.js → chunk-PAWAGULH.js} +3 -3
  37. package/dist/{chunk-4PR3KJ5X.js → chunk-PFEBKXFD.js} +20 -20
  38. package/dist/{chunk-JDSYMTMS.js → chunk-QDU7YDME.js} +130 -66
  39. package/dist/chunk-QDU7YDME.js.map +1 -0
  40. package/dist/{chunk-JNC7MCWJ.js → chunk-S32GHLVU.js} +10 -10
  41. package/dist/chunk-S32GHLVU.js.map +1 -0
  42. package/dist/{chunk-WB6S4W7O.js → chunk-THKVKVRF.js} +2413 -1012
  43. package/dist/chunk-THKVKVRF.js.map +1 -0
  44. package/dist/{chunk-7RSE7ESY.js → chunk-UEEW5TW7.js} +27 -18
  45. package/dist/chunk-UEEW5TW7.js.map +1 -0
  46. package/dist/{chunk-B4DAH2F2.js → chunk-UTOC2NHC.js} +3 -3
  47. package/dist/{chunk-NHTRTST5.js → chunk-WDBDFLH3.js} +38 -15
  48. package/dist/chunk-WDBDFLH3.js.map +1 -0
  49. package/dist/{chunk-PSA6GADQ.js → chunk-WHFCJBMO.js} +14 -1
  50. package/dist/chunk-WHFCJBMO.js.map +1 -0
  51. package/dist/{chunk-KJ5TCYNI.js → chunk-WJUKN4L4.js} +7 -6
  52. package/dist/chunk-WJUKN4L4.js.map +1 -0
  53. package/dist/{chunk-GFOWBXV7.js → chunk-XENTK32L.js} +463 -253
  54. package/dist/chunk-XENTK32L.js.map +1 -0
  55. package/dist/cloud-backends.js +5 -5
  56. package/dist/{cloud-poller-SUNA6ZQC-7M5LJHHE.js → cloud-poller-QJRZXB4W-LJ2BRB3L.js} +2 -2
  57. package/dist/{control-plane-5R7PYRQ6.js → control-plane-YQFX2ILX.js} +19 -18
  58. package/dist/cp-hub-upload-RMJ3XJ65.js +81 -0
  59. package/dist/cp-hub-upload-RMJ3XJ65.js.map +1 -0
  60. package/dist/{custody-client-PNCC2HBJ.js → custody-client-L4FEFW4C.js} +5 -4
  61. package/dist/{deploy-hetzner-SSGSXAKA.js → deploy-hetzner-EECQ4JCM.js} +10 -10
  62. package/dist/{dist-RN6JOAG4.js → dist-3BKIPZR3.js} +81 -45
  63. package/dist/{dist-K5M4HKG7.js → dist-C5B6NGBO.js} +21 -9
  64. package/dist/{dist-6PYXFREL.js → dist-E5EXDZG4.js} +61 -16
  65. package/dist/dist-E5EXDZG4.js.map +1 -0
  66. package/dist/{dist-XATN4ZIR.js → dist-FBM2WS5S.js} +22 -4
  67. package/dist/{dist-XQLKK7H3.js → dist-NFF2KEMB.js} +54 -28
  68. package/dist/dist-NFF2KEMB.js.map +1 -0
  69. package/dist/{dist-5OR4QTQW.js → dist-NTUHJOK3.js} +9 -9
  70. package/dist/{dist-ZNQZHTUN.js → dist-PTYASENV.js} +35 -6
  71. package/dist/{dist-POILUDVJ.js → dist-Q4UDCSZQ.js} +9 -9
  72. package/dist/{dist-M4O5MU5K.js → dist-TXFTYNNE.js} +8 -8
  73. package/dist/{dist-EPFS5PRI.js → dist-XUOHE22G.js} +10 -10
  74. package/dist/{dist-SN2TCRZ5.js → dist-Z2TPC3EN.js} +9 -9
  75. package/dist/host-reach-drainer-N4JSFUBY.js +9 -0
  76. package/dist/hub-3HPYOV5O.js +37 -0
  77. package/dist/{hub-adopt-I44VGSBL.js → hub-adopt-NCCCMMXL.js} +8 -8
  78. package/dist/{hub-api-client-WJPBXZAZ.js → hub-api-client-5U6WOTZ3.js} +2 -2
  79. package/dist/{hub-docker-target-REEEWUG2.js → hub-docker-target-ZKAWXVPH.js} +16 -16
  80. package/dist/index.js +1321 -882
  81. package/dist/index.js.map +1 -1
  82. package/dist/prepare-KIVDQRMN.js +41 -0
  83. package/dist/prepared-custody-EFSOOAIQ.js +36 -0
  84. package/dist/{prepared-state-PV3GUBHO-MF56HWMZ.js → prepared-state-LNQ7DYSU-2YFSDOCV.js} +4 -3
  85. package/dist/{publish-credentials-BPHUO5VL.js → publish-credentials-F2A5OVCO.js} +11 -11
  86. package/dist/registry-O3X2CDDU.js +18 -0
  87. package/dist/relay-3T57T4RI.js +20 -0
  88. package/dist/relay-3T57T4RI.js.map +1 -0
  89. package/dist/{remote-docker-share-RX5ARK45.js → remote-docker-share-QDCBM5UM.js} +11 -11
  90. package/dist/remote-docker-share-QDCBM5UM.js.map +1 -0
  91. package/dist/tool-grant-push-6ISDIJKH.js +90 -0
  92. package/dist/tool-grant-push-6ISDIJKH.js.map +1 -0
  93. package/package.json +1 -2
  94. package/runtime/_shared/agentbox-tool-shim +21 -0
  95. package/runtime/_shared/ctl.cjs +6760 -5299
  96. package/runtime/_shared/gh-shim +103 -228
  97. package/runtime/digitalocean/agentbox-tool-shim +21 -0
  98. package/runtime/digitalocean/ctl.cjs +6760 -5299
  99. package/runtime/digitalocean/gh-shim +103 -228
  100. package/runtime/digitalocean/scripts/install-box.sh +9 -15
  101. package/runtime/docker/Dockerfile.box +8 -18
  102. package/runtime/docker/packages/ctl/dist/bin.cjs +6760 -5299
  103. package/runtime/docker/packages/sandbox-docker/scripts/agentbox-tool-shim +21 -0
  104. package/runtime/docker/packages/sandbox-docker/scripts/gh-shim +103 -228
  105. package/runtime/e2b/agentbox-tool-shim +21 -0
  106. package/runtime/e2b/ctl.cjs +6760 -5299
  107. package/runtime/e2b/gh-shim +103 -228
  108. package/runtime/e2b/scripts/build-template.sh +5 -9
  109. package/runtime/hetzner/agentbox-tool-shim +21 -0
  110. package/runtime/hetzner/ctl.cjs +6760 -5299
  111. package/runtime/hetzner/gh-shim +103 -228
  112. package/runtime/hetzner/scripts/install-box.sh +9 -15
  113. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  114. package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +2 -0
  115. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  116. package/runtime/hub/apps/hub/.next/routes-manifest.json +16 -0
  117. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +5 -5
  118. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -1
  119. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
  120. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
  121. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js +2 -2
  122. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
  123. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +2 -2
  124. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
  125. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/agent/route.js +2 -2
  126. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/agent/route.js.nft.json +1 -1
  127. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js +2 -2
  128. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
  129. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js +2 -2
  130. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js.nft.json +1 -1
  131. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +2 -2
  132. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
  133. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js +2 -2
  134. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
  135. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/logs/route.js +1 -1
  136. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/logs/route.js.nft.json +1 -1
  137. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
  138. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
  139. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
  140. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
  141. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js +2 -2
  142. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
  143. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
  144. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
  145. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js +2 -2
  146. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
  147. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route/app-paths-manifest.json +3 -0
  148. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route/build-manifest.json +9 -0
  149. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route/server-reference-manifest.json +4 -0
  150. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js +8 -0
  151. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js.map +5 -0
  152. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js.nft.json +1 -0
  153. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route_client-reference-manifest.js +3 -0
  154. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +2 -2
  155. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
  156. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/checkpoints/route.js +2 -2
  157. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/checkpoints/route.js.nft.json +1 -1
  158. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/[...path]/route.js +1 -1
  159. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/[...path]/route.js.nft.json +1 -1
  160. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/blob/[...path]/route.js +2 -2
  161. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/blob/[...path]/route.js.nft.json +1 -1
  162. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js +2 -2
  163. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.nft.json +1 -1
  164. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +2 -2
  165. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
  166. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +2 -2
  167. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
  168. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
  169. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
  170. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
  171. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
  172. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js +2 -2
  173. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
  174. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js +2 -2
  175. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
  176. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/route.js +2 -2
  177. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/route.js.nft.json +1 -1
  178. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js +2 -2
  179. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
  180. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js +2 -2
  181. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
  182. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js +2 -2
  183. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
  184. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/seed/route.js +2 -2
  185. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/seed/route.js.nft.json +1 -1
  186. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
  187. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
  188. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
  189. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
  190. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
  191. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
  192. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js +2 -2
  193. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
  194. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js +2 -2
  195. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js.nft.json +1 -1
  196. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/system/route.js +2 -2
  197. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/system/route.js.nft.json +1 -1
  198. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js +1 -1
  199. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  200. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js +1 -1
  201. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
  202. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
  203. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route/app-paths-manifest.json +3 -0
  204. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route/build-manifest.json +9 -0
  205. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route/server-reference-manifest.json +4 -0
  206. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js +8 -0
  207. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js.map +5 -0
  208. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js.nft.json +1 -0
  209. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route_client-reference-manifest.js +3 -0
  210. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page.js +1 -1
  211. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page.js.nft.json +1 -1
  212. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js +1 -1
  213. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  214. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js +1 -1
  215. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
  216. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js +1 -1
  217. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  218. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  219. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page.js +1 -1
  220. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page.js.nft.json +1 -1
  221. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +4 -4
  222. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
  223. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  224. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  225. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  226. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  227. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  228. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  229. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  230. package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +2 -0
  231. package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_boxes_[id]_vnc_route_actions_1cy1392.js +3 -0
  232. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_vnc_route_actions_10y_e83.js +3 -0
  233. package/runtime/hub/apps/hub/.next/server/chunks/{[externals]__1nj4awx._.js → [externals]__02a249v._.js} +2 -2
  234. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00f9v4p._.js +1 -1
  235. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01nppdu._.js +1 -1
  236. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02f8rwr._.js +1 -1
  237. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__068_052._.js +1 -1
  238. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__06ma5m4._.js +3 -0
  239. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07kp2fu._.js +1 -1
  240. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1yi-2wa._.js → [root-of-the-server]__08u01ud._.js} +3 -3
  241. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__098bkh3._.js +3 -0
  242. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1hxo1tv._.js → [root-of-the-server]__09hbkgm._.js} +2 -2
  243. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09tmbom._.js +3 -0
  244. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_3m9sf._.js +1 -1
  245. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0aotdzg._.js +3 -0
  246. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0bn6-pu._.js +1 -1
  247. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cpt9f9._.js +1 -1
  248. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +15 -15
  249. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dom248._.js +1 -1
  250. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f0bb7o._.js +1 -1
  251. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0gb04bp._.js +1 -1
  252. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0glplq7._.js +1 -1
  253. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0xrdbh9._.js → [root-of-the-server]__0gxfyol._.js} +2 -2
  254. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0hsb2ak._.js +1 -1
  255. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0joqm8t._.js +1 -1
  256. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jp-895._.js +1 -1
  257. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1leda2s._.js → [root-of-the-server]__0jpqg_t._.js} +2 -2
  258. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__17bhgkz._.js → [root-of-the-server]__0lgnu00._.js} +2 -2
  259. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lsv9-6._.js +1 -1
  260. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0pzgufc._.js +1 -1
  261. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qfv7z6._.js +1 -1
  262. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qlr61y._.js +1 -1
  263. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0s8srqi._.js +1 -1
  264. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0urn9j5._.js +1 -1
  265. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vb8mk2._.js +4 -0
  266. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__17w5eaa._.js → [root-of-the-server]__0x27ifo._.js} +2 -2
  267. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0y7rvy1._.js +1 -1
  268. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0zsgjre._.js +1 -1
  269. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-bqa8a._.js +1 -1
  270. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11uspjg._.js +1 -1
  271. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0zvr6ul._.js → [root-of-the-server]__15tgdh6._.js} +2 -2
  272. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1ek7nxv._.js → [root-of-the-server]__16bz_kz._.js} +2 -2
  273. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1w7jw4q._.js → [root-of-the-server]__18tehjj._.js} +2 -2
  274. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1ds8g0e._.js → [root-of-the-server]__1_hzv4s._.js} +2 -2
  275. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0cgpsh8._.js → [root-of-the-server]__1b5f5h4._.js} +2 -2
  276. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__10-aihp._.js → [root-of-the-server]__1dv80yf._.js} +2 -2
  277. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1eanlxn._.js +1 -1
  278. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__16lcb2d._.js → [root-of-the-server]__1fc-nvn._.js} +2 -2
  279. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4iahl._.js +1 -1
  280. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0f-c-eh._.js → [root-of-the-server]__1j0vnh3._.js} +2 -2
  281. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1lgrtx6._.js +1 -1
  282. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1unqgd7._.js → [root-of-the-server]__1lz7931._.js} +2 -2
  283. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1oclxlx._.js → [root-of-the-server]__1n3u6-5._.js} +2 -2
  284. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qky5cd._.js +1 -1
  285. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1r2quye._.js +3 -0
  286. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rb_nc5._.js +1 -1
  287. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0cv16py._.js → [root-of-the-server]__1spr8ss._.js} +2 -2
  288. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1t_juqb._.js +1 -1
  289. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0t8kwy3._.js → [root-of-the-server]__1tct9rj._.js} +3 -3
  290. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0gfa1jg._.js → [root-of-the-server]__1tjtt06._.js} +2 -2
  291. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__09cigc7._.js → [root-of-the-server]__1whjno0._.js} +2 -2
  292. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wn4-iv._.js +3 -0
  293. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1x6zxrf._.js +1 -1
  294. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0tyixgg._.js → [root-of-the-server]__1xfxc6i._.js} +2 -2
  295. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1m1_gm_._.js → [root-of-the-server]__1xqcvi4._.js} +2 -2
  296. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__207d30i._.js +1 -1
  297. package/runtime/hub/apps/hub/.next/server/chunks/_07icdxf._.js +1 -1
  298. package/runtime/hub/apps/hub/.next/server/chunks/_0907rw0._.js +1 -1
  299. package/runtime/hub/apps/hub/.next/server/chunks/_0adm87k._.js +1 -1
  300. package/runtime/hub/apps/hub/.next/server/chunks/_0g01mkg._.js +1 -1
  301. package/runtime/hub/apps/hub/.next/server/chunks/_0l_klgd._.js +1 -1
  302. package/runtime/hub/apps/hub/.next/server/chunks/_0lfm81x._.js +1 -1
  303. package/runtime/hub/apps/hub/.next/server/chunks/_0tbg83f._.js +1 -1
  304. package/runtime/hub/apps/hub/.next/server/chunks/_0tms_au._.js +1 -1
  305. package/runtime/hub/apps/hub/.next/server/chunks/_0zhli27._.js +1 -1
  306. package/runtime/hub/apps/hub/.next/server/chunks/_10yfoq5._.js +1 -1
  307. package/runtime/hub/apps/hub/.next/server/chunks/_12uhpbp._.js +1 -1
  308. package/runtime/hub/apps/hub/.next/server/chunks/_17a9v8y._.js +2 -2
  309. package/runtime/hub/apps/hub/.next/server/chunks/_1c7x9ee._.js +1 -1
  310. package/runtime/hub/apps/hub/.next/server/chunks/_1n-c443._.js +1 -1
  311. package/runtime/hub/apps/hub/.next/server/chunks/_1y80vfg._.js +1 -1
  312. package/runtime/hub/apps/hub/.next/server/chunks/_214_q-1._.js +1 -1
  313. package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_openapi_ts_1yokmzt._.js +1 -1
  314. package/runtime/hub/apps/hub/.next/server/chunks/{packages_relay_dist_0eg7ay1._.js → packages_relay_dist_0p8dnf4._.js} +4 -4
  315. package/runtime/hub/apps/hub/.next/server/chunks/ssr/{[root-of-the-server]__1plrs94._.js → [root-of-the-server]__0-c5j6l._.js} +2 -2
  316. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0r2xlss._.js +1 -1
  317. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_19vy9ni._.js +2 -2
  318. package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_[id]_page_tsx_1-j_972._.js +1 -1
  319. package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_settings_page_tsx_0hv6n82._.js +1 -1
  320. package/runtime/hub/apps/hub/.next/server/chunks/ssr/{packages_relay_dist_1z9j3g0._.js → packages_relay_dist_0sap-2l._.js} +4 -4
  321. package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +3 -1
  322. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  323. package/runtime/hub/apps/hub/.next/server/middleware.js +1 -1
  324. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  325. package/runtime/hub/apps/hub/.next/static/chunks/{328ny-3zs_h7m.js → 0jefm3re1-2jv.js} +1 -1
  326. package/runtime/hub/apps/hub/.next/static/chunks/{30h8mz040b5-l.js → 3u4odx1_-dy6b.js} +1 -1
  327. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/vnc/route.ts +45 -0
  328. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/openapi.ts +45 -1
  329. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/validate.ts +14 -3
  330. package/runtime/hub/apps/hub/app/(dashboard)/boxes/[id]/vnc/route.ts +58 -0
  331. package/runtime/hub/apps/hub/app/(dashboard)/boxes/components/access.tsx +26 -9
  332. package/runtime/hub/apps/hub/app/(dashboard)/settings/components/provider-actions.tsx +34 -26
  333. package/runtime/hub/apps/hub/{auth-JMVHQKWY.js → auth-V7KPRWPS.js} +2 -2
  334. package/runtime/hub/apps/hub/{auth-config-5IFRWOK4.js → auth-config-B3Y3BT2I.js} +2 -2
  335. package/runtime/hub/apps/hub/{chunk-QU3FFGJY.js → chunk-2WB3A5IN.js} +11 -14
  336. package/runtime/hub/apps/hub/{chunk-LPYK2354.js → chunk-5ABFGGPT.js} +339 -21
  337. package/runtime/hub/apps/hub/{chunk-VKOCY6SX.js → chunk-BI4MPGQT.js} +49 -14
  338. package/runtime/hub/apps/hub/{chunk-UMPTTQBE.js → chunk-G6FJR7TN.js} +461 -251
  339. package/runtime/hub/apps/hub/{chunk-KTVETF3F.js → chunk-QGAP34GN.js} +11 -8
  340. package/runtime/hub/apps/hub/{chunk-5TM7XXLT.js → chunk-QWSP6WJ2.js} +2833 -1277
  341. package/runtime/hub/apps/hub/{chunk-EZUK53CC.js → chunk-RPPOFMPA.js} +85 -21
  342. package/runtime/hub/apps/hub/{chunk-3LAHFDJF.js → chunk-VWQNSZGI.js} +22 -2
  343. package/runtime/hub/apps/hub/{chunk-D33EV4YZ.js → chunk-ZP4RYI4U.js} +1 -1
  344. package/runtime/hub/apps/hub/{cloud-poller-SUNA6ZQC-VSKVMYHL.js → cloud-poller-QJRZXB4W-G7ECKNKQ.js} +1 -1
  345. package/runtime/hub/apps/hub/{dist-JVEDVVVG.js → dist-4F6XEJHK.js} +7 -7
  346. package/runtime/hub/apps/hub/{dist-2YP57GMB.js → dist-A3JOKKYG.js} +13 -13
  347. package/runtime/hub/apps/hub/{dist-D265LCAN.js → dist-CGH7PEMZ.js} +21 -3
  348. package/runtime/hub/apps/hub/{dist-SYWTB6RD.js → dist-F547YSBE.js} +15 -18
  349. package/runtime/hub/apps/hub/{dist-YK5FFPXZ.js → dist-FEHV4PC7.js} +62 -20
  350. package/runtime/hub/apps/hub/{dist-NKCXH5DW.js → dist-P7NT6VLK.js} +6 -6
  351. package/runtime/hub/apps/hub/{dist-E2FTSTCY.js → dist-W2YXTEQN.js} +34 -5
  352. package/runtime/hub/apps/hub/{dist-ELZHBQEM.js → dist-W5SGEJLA.js} +11 -11
  353. package/runtime/hub/apps/hub/{dist-N3E5YAYY.js → dist-YB3Y2XDK.js} +53 -26
  354. package/runtime/hub/apps/hub/{dist-5HTJSOHS.js → dist-ZTJMZLED.js} +19 -7
  355. package/runtime/hub/apps/hub/docker-compose.yml +1 -0
  356. package/runtime/hub/apps/hub/{hub-token-MDOBY7MZ.js → hub-token-DDJ5Z6RS.js} +2 -2
  357. package/runtime/hub/apps/hub/{hub-worker-UFFLF37F.js → hub-worker-I5QBLSRU.js} +16 -16
  358. package/runtime/hub/apps/hub/lib/boxes/backend-types.ts +11 -0
  359. package/runtime/hub/apps/hub/lib/boxes/types.ts +43 -0
  360. package/runtime/hub/apps/hub/lib/boxes/vnc-link.ts +51 -0
  361. package/runtime/hub/apps/hub/lib/hub-backend.ts +127 -54
  362. package/runtime/hub/apps/hub/lib/hub-worker.ts +4 -4
  363. package/runtime/hub/apps/hub/lib/provider-importers.ts +66 -1
  364. package/runtime/hub/apps/hub/{prepared-state-PV3GUBHO-PPRQDYFR.js → prepared-state-LNQ7DYSU-4I7FNNNS.js} +3 -2
  365. package/runtime/hub/apps/hub/server.js +130 -72
  366. package/runtime/hub/apps/hub/server.ts +18 -0
  367. package/runtime/hub/apps/hub/test/vnc-link.test.ts +61 -0
  368. package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
  369. package/runtime/hub-deploy/docker-compose.yml +1 -0
  370. package/runtime/relay/bin.cjs +16626 -14688
  371. package/runtime/vercel/agentbox-tool-shim +21 -0
  372. package/runtime/vercel/ctl.cjs +6760 -5299
  373. package/runtime/vercel/gh-shim +103 -228
  374. package/runtime/vercel/scripts/provision.sh +5 -9
  375. package/share/host-skills/agentbox-info/SKILL.md +24 -14
  376. package/dist/_cloud-attach-Y5HIQ373.js +0 -28
  377. package/dist/chunk-46NNZMZT.js.map +0 -1
  378. package/dist/chunk-74VIUGY6.js.map +0 -1
  379. package/dist/chunk-7RSE7ESY.js.map +0 -1
  380. package/dist/chunk-G3H2L3O2.js.map +0 -1
  381. package/dist/chunk-GFOWBXV7.js.map +0 -1
  382. package/dist/chunk-JDSYMTMS.js.map +0 -1
  383. package/dist/chunk-JNC7MCWJ.js.map +0 -1
  384. package/dist/chunk-JQLOGVZK.js.map +0 -1
  385. package/dist/chunk-KFLGXE3R.js.map +0 -1
  386. package/dist/chunk-KJ5TCYNI.js.map +0 -1
  387. package/dist/chunk-NHTRTST5.js.map +0 -1
  388. package/dist/chunk-NHVGKFVY.js.map +0 -1
  389. package/dist/chunk-OUF3YTQO.js.map +0 -1
  390. package/dist/chunk-OUWVN2F2.js.map +0 -1
  391. package/dist/chunk-OXKW4GWD.js.map +0 -1
  392. package/dist/chunk-PSA6GADQ.js.map +0 -1
  393. package/dist/chunk-WB6S4W7O.js.map +0 -1
  394. package/dist/chunk-YI4GHC2E.js.map +0 -1
  395. package/dist/dist-6PYXFREL.js.map +0 -1
  396. package/dist/dist-XQLKK7H3.js.map +0 -1
  397. package/dist/hub-MJ7O4WXW.js +0 -36
  398. package/dist/prepare-V4U5HVJU.js +0 -40
  399. package/dist/prepared-custody-QIXW7MJM.js +0 -35
  400. package/dist/relay-DRDELF6B.js +0 -20
  401. package/runtime/_shared/linear-shim +0 -181
  402. package/runtime/_shared/ntn-shim +0 -95
  403. package/runtime/digitalocean/linear-shim +0 -181
  404. package/runtime/digitalocean/ntn-shim +0 -95
  405. package/runtime/docker/packages/sandbox-docker/scripts/linear-shim +0 -181
  406. package/runtime/docker/packages/sandbox-docker/scripts/ntn-shim +0 -95
  407. package/runtime/e2b/linear-shim +0 -181
  408. package/runtime/e2b/ntn-shim +0 -95
  409. package/runtime/hetzner/linear-shim +0 -181
  410. package/runtime/hetzner/ntn-shim +0 -95
  411. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__039tc0m._.js +0 -3
  412. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c_3x8u._.js +0 -3
  413. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ty7ew1._.js +0 -3
  414. package/runtime/vercel/linear-shim +0 -181
  415. package/runtime/vercel/ntn-shim +0 -95
  416. /package/dist/{_cloud-attach-Y5HIQ373.js.map → _cloud-attach-EUO2OL7W.js.map} +0 -0
  417. /package/dist/{chunk-V5NWSLWD.js.map → chunk-4NUETVTR.js.map} +0 -0
  418. /package/dist/{chunk-FGQFVUMH.js.map → chunk-6YSYQZRH.js.map} +0 -0
  419. /package/dist/{chunk-HYXCH4GA.js.map → chunk-7LC5IG5K.js.map} +0 -0
  420. /package/dist/{chunk-7ABO7OIF.js.map → chunk-AUHYXXCA.js.map} +0 -0
  421. /package/dist/{chunk-FPMRFMVK.js.map → chunk-B4YFG5TB.js.map} +0 -0
  422. /package/dist/{chunk-BWM56FKY.js.map → chunk-FEFLAITR.js.map} +0 -0
  423. /package/dist/{chunk-EVT2SNF2.js.map → chunk-FELVUIIM.js.map} +0 -0
  424. /package/dist/{chunk-BUMKBUXS.js.map → chunk-PAWAGULH.js.map} +0 -0
  425. /package/dist/{chunk-4PR3KJ5X.js.map → chunk-PFEBKXFD.js.map} +0 -0
  426. /package/dist/{chunk-B4DAH2F2.js.map → chunk-UTOC2NHC.js.map} +0 -0
  427. /package/dist/{cloud-poller-SUNA6ZQC-7M5LJHHE.js.map → cloud-poller-QJRZXB4W-LJ2BRB3L.js.map} +0 -0
  428. /package/dist/{control-plane-5R7PYRQ6.js.map → control-plane-YQFX2ILX.js.map} +0 -0
  429. /package/dist/{custody-client-PNCC2HBJ.js.map → custody-client-L4FEFW4C.js.map} +0 -0
  430. /package/dist/{deploy-hetzner-SSGSXAKA.js.map → deploy-hetzner-EECQ4JCM.js.map} +0 -0
  431. /package/dist/{dist-5OR4QTQW.js.map → dist-3BKIPZR3.js.map} +0 -0
  432. /package/dist/{dist-EPFS5PRI.js.map → dist-C5B6NGBO.js.map} +0 -0
  433. /package/dist/{dist-K5M4HKG7.js.map → dist-FBM2WS5S.js.map} +0 -0
  434. /package/dist/{dist-M4O5MU5K.js.map → dist-NTUHJOK3.js.map} +0 -0
  435. /package/dist/{dist-POILUDVJ.js.map → dist-PTYASENV.js.map} +0 -0
  436. /package/dist/{dist-RN6JOAG4.js.map → dist-Q4UDCSZQ.js.map} +0 -0
  437. /package/dist/{dist-SN2TCRZ5.js.map → dist-TXFTYNNE.js.map} +0 -0
  438. /package/dist/{dist-XATN4ZIR.js.map → dist-XUOHE22G.js.map} +0 -0
  439. /package/dist/{dist-ZNQZHTUN.js.map → dist-Z2TPC3EN.js.map} +0 -0
  440. /package/dist/{hub-MJ7O4WXW.js.map → host-reach-drainer-N4JSFUBY.js.map} +0 -0
  441. /package/dist/{hub-adopt-I44VGSBL.js.map → hub-3HPYOV5O.js.map} +0 -0
  442. /package/dist/{hub-api-client-WJPBXZAZ.js.map → hub-adopt-NCCCMMXL.js.map} +0 -0
  443. /package/dist/{prepare-V4U5HVJU.js.map → hub-api-client-5U6WOTZ3.js.map} +0 -0
  444. /package/dist/{hub-docker-target-REEEWUG2.js.map → hub-docker-target-ZKAWXVPH.js.map} +0 -0
  445. /package/dist/{prepared-custody-QIXW7MJM.js.map → prepare-KIVDQRMN.js.map} +0 -0
  446. /package/dist/{prepared-state-PV3GUBHO-MF56HWMZ.js.map → prepared-custody-EFSOOAIQ.js.map} +0 -0
  447. /package/dist/{relay-DRDELF6B.js.map → prepared-state-LNQ7DYSU-2YFSDOCV.js.map} +0 -0
  448. /package/dist/{publish-credentials-BPHUO5VL.js.map → publish-credentials-F2A5OVCO.js.map} +0 -0
  449. /package/dist/{remote-docker-share-RX5ARK45.js.map → registry-O3X2CDDU.js.map} +0 -0
  450. /package/runtime/hub/apps/hub/.next/static/{z7_2bKU93xE7GwllL1Duv → nDHi_1342DzyGDC14ocQo}/_buildManifest.js +0 -0
  451. /package/runtime/hub/apps/hub/.next/static/{z7_2bKU93xE7GwllL1Duv → nDHi_1342DzyGDC14ocQo}/_clientMiddlewareManifest.js +0 -0
  452. /package/runtime/hub/apps/hub/.next/static/{z7_2bKU93xE7GwllL1Duv → nDHi_1342DzyGDC14ocQo}/_ssgManifest.js +0 -0
@@ -1,11 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- BUILT_IN_DEFAULTS,
4
- GLOBAL_CONFIG_FILE,
5
- STATE_DIR,
6
- loadEffectiveConfig,
7
- parseUserConfig
8
- } from "./chunk-NHVGKFVY.js";
9
2
  import {
10
3
  STATE_DIR as STATE_DIR2,
11
4
  STATE_FILE,
@@ -22,6 +15,7 @@ import {
22
15
  parseCredentialsUpdate,
23
16
  parseDownloadKind,
24
17
  pluginForProvider,
18
+ projectSlugFromOriginUrl,
25
19
  readCredentialBackup,
26
20
  readState,
27
21
  realpathSafe,
@@ -31,11 +25,23 @@ import {
31
25
  resolveHostPath,
32
26
  resolveLandDest,
33
27
  resolveRemote,
28
+ resolveSshConfigTarget,
34
29
  sanitizeGitArgs,
35
30
  shouldAcceptCredentialUpdate,
36
31
  upstreamRef,
37
32
  writeCredentialBackup
38
- } from "./chunk-GFOWBXV7.js";
33
+ } from "./chunk-XENTK32L.js";
34
+ import {
35
+ BUILT_IN_DEFAULTS,
36
+ GLOBAL_CONFIG_FILE,
37
+ STATE_DIR,
38
+ isValidToolName,
39
+ loadEffectiveConfig,
40
+ loadGrantedTools,
41
+ parseUserConfig,
42
+ resolveProjectToolsFile,
43
+ writeToolGrant
44
+ } from "./chunk-7LNXTPEE.js";
39
45
  import {
40
46
  index,
41
47
  integer as integer2,
@@ -62,7 +68,7 @@ import {
62
68
  timestamp
63
69
  } from "./chunk-6V366IZC.js";
64
70
 
65
- // ../../packages/relay/dist/chunk-M7AXMLQF.js
71
+ // ../../packages/relay/dist/chunk-BZAALYSV.js
66
72
  import { mkdir, rename, rm, writeFile } from "fs/promises";
67
73
  import { homedir } from "os";
68
74
  import { join } from "path";
@@ -583,20 +589,23 @@ function hostRepoUnavailableReason(worktree, boxId, op) {
583
589
  function parseGitRemote(origin) {
584
590
  const trimmed = origin.trim();
585
591
  if (trimmed.length === 0) throw new Error("empty git remote URL");
586
- const urlForm = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(trimmed);
592
+ const urlForm = /^([a-z][a-z0-9+.-]*):\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(trimmed);
587
593
  const scpForm = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(trimmed);
588
594
  let host;
589
595
  let path;
596
+ let scheme;
590
597
  if (urlForm) {
591
- host = urlForm[1];
592
- path = urlForm[2];
598
+ scheme = urlForm[1].toLowerCase();
599
+ host = urlForm[2];
600
+ path = urlForm[3];
593
601
  } else if (scpForm && !/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) {
602
+ scheme = null;
594
603
  host = scpForm[1];
595
604
  path = scpForm[2];
596
605
  } else {
597
606
  throw new Error(`unrecognized git remote URL: ${origin}`);
598
607
  }
599
- return { host, path: path.replace(/^\/+/, "") };
608
+ return { host, path: path.replace(/^\/+/, ""), scheme };
600
609
  }
601
610
  function toAuthedHttpsUrl(origin, token) {
602
611
  const { host, path } = parseGitRemote(origin);
@@ -611,6 +620,19 @@ function repoSlugFromRemote(origin) {
611
620
  const repo = path.replace(/\.git$/, "");
612
621
  return host.toLowerCase() === "github.com" ? repo : `${host}/${repo}`;
613
622
  }
623
+ function ghHostFromRemote(origin) {
624
+ const trimmed = origin?.trim() ?? "";
625
+ if (trimmed.length === 0) return null;
626
+ let parsed;
627
+ try {
628
+ parsed = parseGitRemote(trimmed);
629
+ } catch {
630
+ return null;
631
+ }
632
+ const host = parsed.host.toLowerCase();
633
+ if (host === "github.com") return null;
634
+ return { host, aliasable: parsed.scheme !== "https" && parsed.scheme !== "http" };
635
+ }
614
636
  async function leaseTokenResult(leaser, reg) {
615
637
  if (!leaser) {
616
638
  return {
@@ -1024,7 +1046,10 @@ async function handleRemoteBoxesRequest(req, deps) {
1024
1046
  }
1025
1047
  const body = parseJson2(req.bodyText);
1026
1048
  if (!body || typeof body.repoUrl !== "string" || typeof body.provider !== "string") {
1027
- return { status: 400, body: { error: "expected {repoUrl, provider, branch?, name?, agent?, prompt?}" } };
1049
+ return {
1050
+ status: 400,
1051
+ body: { error: "expected {repoUrl, provider, branch?, name?, agent?, prompt?}" }
1052
+ };
1028
1053
  }
1029
1054
  const allowed = deps.createProviders;
1030
1055
  if (allowed && allowed.length > 0 && !allowed.includes(body.provider)) {
@@ -1108,7 +1133,7 @@ async function handleRemoteBoxesRequest(req, deps) {
1108
1133
  async function reapLocalBoxState(boxId, sandboxId, log) {
1109
1134
  let removed = false;
1110
1135
  try {
1111
- const { mutateState, readState: readState2, boxSshDirForProvider: boxSshDirForProvider2 } = await import("./dist-ZNQZHTUN.js");
1136
+ const { mutateState, readState: readState2, boxSshDirForProvider: boxSshDirForProvider2 } = await import("./dist-PTYASENV.js");
1112
1137
  const state = await readState2();
1113
1138
  const record = state.boxes.find((b) => b.id === boxId);
1114
1139
  if (record) {
@@ -1333,19 +1358,23 @@ var GitHubAppLeaser = class {
1333
1358
  }
1334
1359
  const id = await this.installationId(owner, repo);
1335
1360
  const jwt = appJwt(this.cfg, this.now());
1336
- const res = await this.fetchImpl(`${this.apiBase}/app/installations/${String(id)}/access_tokens`, {
1337
- method: "POST",
1338
- headers: { ...this.headers(jwt), "Content-Type": "application/json" },
1339
- body: JSON.stringify({
1340
- repositories: [repo],
1341
- permissions: { contents: "write", pull_requests: "write" }
1342
- })
1343
- });
1361
+ const res = await this.fetchImpl(
1362
+ `${this.apiBase}/app/installations/${String(id)}/access_tokens`,
1363
+ {
1364
+ method: "POST",
1365
+ headers: { ...this.headers(jwt), "Content-Type": "application/json" },
1366
+ body: JSON.stringify({
1367
+ repositories: [repo],
1368
+ permissions: { contents: "write", pull_requests: "write" }
1369
+ })
1370
+ }
1371
+ );
1344
1372
  if (!res.ok) {
1345
1373
  throw new Error(`failed to mint installation token for ${key} (\u2192 ${String(res.status)})`);
1346
1374
  }
1347
1375
  const body = await res.json();
1348
- if (!body.token || !body.expires_at) throw new Error("access_tokens response missing token/expires_at");
1376
+ if (!body.token || !body.expires_at)
1377
+ throw new Error("access_tokens response missing token/expires_at");
1349
1378
  this.cache.set(key, {
1350
1379
  token: body.token,
1351
1380
  expiresAt: body.expires_at,
@@ -1976,7 +2005,7 @@ async function waitForFile(path, timeoutMs = 1e3) {
1976
2005
  return existsSync2(path);
1977
2006
  }
1978
2007
 
1979
- // ../../packages/relay/dist/chunk-DPQ524VB.js
2008
+ // ../../packages/relay/dist/chunk-FFZRXAUM.js
1980
2009
  import { timingSafeEqual as timingSafeEqual4 } from "crypto";
1981
2010
  import { mkdirSync } from "fs";
1982
2011
  import { createRequire } from "module";
@@ -3306,399 +3335,157 @@ var FsCustodyStore = class {
3306
3335
  }
3307
3336
  };
3308
3337
 
3309
- // ../../packages/relay/dist/chunk-DDOSDQJA.js
3338
+ // ../../packages/relay/dist/chunk-YPFYI4NP.js
3310
3339
  import { spawn as spawn3 } from "child_process";
3340
+ import { existsSync as existsSync5 } from "fs";
3311
3341
  import { createServer } from "http";
3312
3342
  import { execa } from "execa";
3313
3343
  import { existsSync as existsSync22 } from "fs";
3314
- import { mkdtemp, rm as rm4 } from "fs/promises";
3315
- import { tmpdir as tmpdir2 } from "os";
3316
- import { join as join4 } from "path";
3344
+ import { mkdtemp as mkdtemp2, rm as rm22 } from "fs/promises";
3345
+ import { tmpdir as tmpdir3 } from "os";
3346
+ import { join as join23 } from "path";
3317
3347
  import { pathToFileURL } from "url";
3318
3348
  import { spawn as spawn2 } from "child_process";
3319
3349
  import { existsSync as existsSync3 } from "fs";
3320
3350
  import { tmpdir } from "os";
3321
3351
  import { createHash as createHash3, randomBytes as randomBytes3 } from "crypto";
3352
+ import { execFile } from "child_process";
3353
+ import { createReadStream as createReadStream2 } from "fs";
3354
+ import { mkdtemp, rm as rm4, stat as stat2 } from "fs/promises";
3355
+ import { hostname, tmpdir as tmpdir2 } from "os";
3356
+ import { basename, dirname as dirname3, join as join4 } from "path";
3357
+ import { request as httpRequest } from "http";
3358
+ import { request as httpsRequest } from "https";
3359
+ import { createHash as createHash22 } from "crypto";
3360
+ import { basename as basename2 } from "path";
3322
3361
  import { spawn as spawn22 } from "child_process";
3323
-
3324
- // ../../packages/integrations/dist/index.js
3325
- var linearConnector = {
3326
- service: "linear",
3327
- hostBin: "linear",
3328
- detect: {
3329
- versionArgs: ["--version"],
3330
- authArgs: ["auth", "whoami"],
3331
- installHint: "install @schpet/linear-cli: npm i -g @schpet/linear-cli",
3332
- loginHint: "linear auth login"
3362
+ import { randomUUID as randomUUID4 } from "crypto";
3363
+ import { randomUUID as randomUUID22 } from "crypto";
3364
+ import { execFile as execFile2 } from "child_process";
3365
+ import { createWriteStream as createWriteStream2, existsSync as existsSync32 } from "fs";
3366
+ import { mkdtemp as mkdtemp3, rm as rm32 } from "fs/promises";
3367
+ import { tmpdir as tmpdir4 } from "os";
3368
+ import { basename as basename3, join as join32 } from "path";
3369
+ import { pipeline as pipeline2 } from "stream/promises";
3370
+ import { randomUUID as randomUUID32 } from "crypto";
3371
+ import { execFile as execFile3 } from "child_process";
3372
+ import { createReadStream as createReadStream22, createWriteStream as createWriteStream22, existsSync as existsSync4 } from "fs";
3373
+ import { mkdtemp as mkdtemp4, readdir as readdir3, rename as rename4, rm as rm42, stat as stat22 } from "fs/promises";
3374
+ import { tmpdir as tmpdir5 } from "os";
3375
+ import { dirname as dirname23, join as join42 } from "path";
3376
+ import { pipeline as pipeline22 } from "stream/promises";
3377
+ import { randomUUID as randomUUID42 } from "crypto";
3378
+ import { timingSafeEqual as timingSafeEqual5 } from "crypto";
3379
+ import { open, stat as stat3 } from "fs/promises";
3380
+ import { execa as execa2 } from "execa";
3381
+ import { spawn as spawn4 } from "child_process";
3382
+ import { readFile as readFile3 } from "fs/promises";
3383
+ import { readFile as readFile22 } from "fs/promises";
3384
+ import { randomUUID as randomUUID5 } from "crypto";
3385
+ import { request as httpRequest2 } from "http";
3386
+ import { request as httpsRequest2 } from "https";
3387
+ import { setTimeout as delay2 } from "timers/promises";
3388
+ import { rm as rm5 } from "fs/promises";
3389
+ import { request as httpRequest3 } from "http";
3390
+ import { request as httpsRequest3 } from "https";
3391
+ var GH_BLOCKED = [
3392
+ {
3393
+ pattern: /^auth\s+(token|refresh)\b/i,
3394
+ why: "prints or rotates the host credential"
3333
3395
  },
3334
- ops: {
3335
- whoami: {
3336
- write: false,
3337
- buildArgv: (args) => ["auth", "whoami", ...args]
3338
- },
3339
- "issue.list": {
3340
- write: false,
3341
- buildArgv: (args) => ["issue", "list", ...args]
3342
- },
3343
- "issue.mine": {
3344
- // The v2-native read for "issues assigned to me" — the README directs
3345
- // users here in place of the older `issue list --me`. Listed as a
3346
- // separate op so the shim doesn't reject the canonical form.
3347
- write: false,
3348
- buildArgv: (args) => ["issue", "mine", ...args]
3349
- },
3350
- "issue.view": {
3351
- write: false,
3352
- buildArgv: (args) => ["issue", "view", ...args]
3353
- },
3354
- "issue.query": {
3355
- write: false,
3356
- buildArgv: (args) => ["issue", "query", ...args]
3357
- },
3358
- "team.list": {
3359
- write: false,
3360
- buildArgv: (args) => ["team", "list", ...args]
3361
- },
3362
- api: {
3363
- write: false,
3364
- buildArgv: (args) => ["api", ...args],
3365
- refuseCall: refuseGraphqlNonQuery
3366
- },
3367
- "issue.create": {
3368
- write: true,
3369
- buildArgv: (args) => ["issue", "create", ...args]
3370
- },
3371
- "issue.update": {
3372
- write: true,
3373
- buildArgv: (args) => ["issue", "update", ...args]
3374
- },
3375
- "issue.comment": {
3376
- // Maps to `linear issue comment add` — `@schpet/linear-cli` v2 uses
3377
- // `add` (not `create`); `add`'s sibling subcommands are `list`,
3378
- // `update`, `delete`.
3379
- write: true,
3380
- buildArgv: (args) => ["issue", "comment", "add", ...args]
3381
- }
3396
+ {
3397
+ pattern: /^auth\s+(login|logout|switch|setup-git)\b/i,
3398
+ why: "changes the host's GitHub auth state, which the host owns"
3399
+ },
3400
+ {
3401
+ pattern: /^config\s+set\b/i,
3402
+ why: "rewrites the host's gh configuration"
3403
+ },
3404
+ {
3405
+ // `gh alias set x '!sh -c ...'` defines a shell escape that later runs on
3406
+ // the host under the host's credentials.
3407
+ pattern: /^alias\s+(set|delete|import)\b/i,
3408
+ why: "defines host-side command aliases that later run with host credentials"
3409
+ },
3410
+ {
3411
+ pattern: /^extension\s+(install|remove|upgrade|exec)\b/i,
3412
+ why: "installs or runs third-party code on the host"
3413
+ },
3414
+ {
3415
+ pattern: /^(ssh-key|gpg-key)\s+(add|delete)\b/i,
3416
+ why: "changes the host account's keys"
3382
3417
  }
3383
- };
3384
- function refuseGraphqlNonQuery(args) {
3385
- const refuse = (reason) => ({
3386
- exitCode: 65,
3387
- stderr: `linear api: ${reason}
3388
- `
3389
- });
3390
- for (let i = 0; i < args.length; i++) {
3391
- const arg = args[i] ?? "";
3392
- if (arg === "--input" || arg.startsWith("--input=")) {
3393
- return refuse("'--input' (stdin/file body) isn't supported through the relay");
3394
- }
3395
- if (arg === "--variable") {
3396
- const next = args[i + 1] ?? "";
3397
- if (variableValueIsFileLoad(next)) {
3398
- return refuse(
3399
- "'--variable key=@<path>' (host-file load) isn't supported through the relay"
3400
- );
3401
- }
3402
- if (!next.startsWith("--")) i++;
3403
- continue;
3404
- }
3405
- if (arg.startsWith("--variable=")) {
3406
- if (variableValueIsFileLoad(arg.slice("--variable=".length))) {
3407
- return refuse(
3408
- "'--variable=key=@<path>' (host-file load) isn't supported through the relay"
3409
- );
3410
- }
3411
- continue;
3412
- }
3413
- if (arg === "--variables-json") {
3414
- const next = args[i + 1] ?? "";
3415
- if (!next.startsWith("--")) i++;
3416
- continue;
3417
- }
3418
- if (arg.startsWith("--variables-json=")) {
3419
- continue;
3420
- }
3421
- if (arg.startsWith("--")) continue;
3422
- const op = firstGraphqlOperationKeyword(arg);
3423
- if (op === "mutation" || op === "subscription") {
3424
- return refuse(
3425
- `only GraphQL queries are proxied (use issue.create / issue.update / issue.comment for writes); detected operation '${op}'`
3426
- );
3427
- }
3428
- if (op === "unparseable") {
3429
- return refuse(
3430
- `couldn't classify positional argv ${JSON.stringify(arg)} as a GraphQL operation (expected 'query', 'mutation', 'subscription', or '{')`
3431
- );
3432
- }
3418
+ ];
3419
+ var GH_DESTRUCTIVE = [
3420
+ { pattern: /^repo\s+(delete|archive|rename|transfer)\b/i, what: "repository" },
3421
+ { pattern: /^release\s+delete(-asset)?\b/i, what: "release" },
3422
+ { pattern: /^secret\s+(set|delete)\b/i, what: "repository secret" },
3423
+ { pattern: /^variable\s+delete\b/i, what: "repository variable" },
3424
+ { pattern: /^cache\s+delete\b/i, what: "Actions cache" },
3425
+ { pattern: /^ruleset\b.*\b(delete|edit)\b/i, what: "repository ruleset" },
3426
+ { pattern: /^org\s+\S*\b(delete|remove)\b/i, what: "organization" },
3427
+ { pattern: /^gist\s+delete\b/i, what: "gist" },
3428
+ { pattern: /^label\s+delete\b/i, what: "label" },
3429
+ { pattern: /^project\s+(delete|item-delete|field-delete)\b/i, what: "project" },
3430
+ // `gh api -X DELETE` reaches all of the above through the raw API. gh
3431
+ // accepts `-X DELETE`, `-X=DELETE`, `-XDELETE` and `--method[= ]DELETE`,
3432
+ // so match every spelling — a missed one is a silent hole, not a typo.
3433
+ { pattern: /(^|\s)(-X=?\s*|--method[=\s]+)(DELETE|PUT|PATCH)\b/i, what: "raw API write" },
3434
+ // `gh api graphql -f query='mutation { deleteRepository ... }'` is a POST,
3435
+ // so no method flag betrays it. GraphQL is a raw write channel with the same
3436
+ // reach as the REST verbs above; agents rarely need it, so confirming every
3437
+ // mutation is a cheap way to keep the hole shut.
3438
+ // Lookaheads rather than adjacency: the endpoint may be spelled `/graphql`,
3439
+ // and cobra accepts flags before it (`gh api --paginate graphql …`), so
3440
+ // requiring `api graphql` side by side left the hole open.
3441
+ {
3442
+ pattern: /^api\b(?=[\s\S]*\bgraphql\b)(?=[\s\S]*\bmutation\b)/i,
3443
+ what: "raw GraphQL mutation"
3433
3444
  }
3434
- return null;
3435
- }
3436
- function variableValueIsFileLoad(value) {
3437
- if (value.startsWith("@")) return true;
3438
- return value.includes("=@");
3439
- }
3440
- function firstGraphqlOperationKeyword(source) {
3445
+ ];
3446
+ var GH_GLOBAL_VALUE_FLAGS = /* @__PURE__ */ new Set(["-R", "--repo", "--hostname"]);
3447
+ function ghVerbArgv(args) {
3441
3448
  let i = 0;
3442
- const n = source.length;
3443
- while (i < n) {
3444
- const c = source[i];
3445
- if (/\s/.test(c) || c === "," || c === "\uFEFF") {
3446
- i++;
3447
- continue;
3448
- }
3449
- if (c === "#") {
3450
- while (i < n && source[i] !== "\n") i++;
3451
- continue;
3452
- }
3453
- break;
3454
- }
3455
- if (i >= n) return null;
3456
- if (source[i] === "{") return "anonymous";
3457
- let j = i;
3458
- while (j < n) {
3459
- const c = source[j];
3460
- if (c >= "a" && c <= "z" || c >= "A" && c <= "Z") {
3461
- j++;
3462
- } else {
3463
- break;
3464
- }
3449
+ while (i < args.length) {
3450
+ const arg = args[i] ?? "";
3451
+ if (!arg.startsWith("-")) break;
3452
+ if (GH_GLOBAL_VALUE_FLAGS.has(arg)) i += 2;
3453
+ else i += 1;
3465
3454
  }
3466
- if (j === i) return "unparseable";
3467
- return source.slice(i, j).toLowerCase();
3455
+ return args.slice(i);
3468
3456
  }
3469
- var notionConnector = {
3470
- service: "notion",
3471
- hostBin: "ntn",
3472
- detect: {
3473
- versionArgs: ["--version"],
3474
- authArgs: ["api", "v1/users/me"],
3475
- installHint: "install ntn: https://developers.notion.com/reference/notion-cli",
3476
- loginHint: "ntn login"
3477
- },
3478
- ops: {
3479
- whoami: {
3480
- write: false,
3481
- buildArgv: (args) => ["whoami", ...args]
3482
- },
3483
- api: {
3484
- write: false,
3485
- buildArgv: (args) => ["api", ...args],
3486
- refuseCall: refuseUnsafeApiCall
3487
- },
3488
- "page.create": {
3489
- write: true,
3490
- buildArgv: (args) => ["pages", "create", ...args]
3491
- },
3492
- "page.update": {
3493
- write: true,
3494
- buildArgv: (args) => ["pages", "update", ...args]
3495
- }
3496
- }
3497
- };
3498
- var READ_POST_ENDPOINTS = [
3499
- /^\/?v1\/search$/,
3500
- /^\/?v1\/databases\/[^/?]+\/query$/,
3501
- /^\/?v1\/data_sources\/[^/?]+\/query$/
3502
- ];
3503
- var SAFE_API_BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
3504
- "--spec",
3505
- "--docs",
3506
- "-h",
3507
- "--help",
3508
- "-v",
3509
- "--verbose",
3510
- "-V",
3511
- "--version"
3512
- ]);
3513
- function refuseUnsafeApiCall(args) {
3514
- const refuse = (reason) => ({
3515
- exitCode: 65,
3516
- stderr: `notion api: ${reason}
3457
+ function refuseBlockedGhCall(args) {
3458
+ const joined = ghVerbArgv(args).join(" ");
3459
+ for (const { pattern, why } of GH_BLOCKED) {
3460
+ if (pattern.test(joined)) {
3461
+ return {
3462
+ exitCode: 65,
3463
+ stdout: "",
3464
+ stderr: `gh ${joined}: refused \u2014 ${why}. The host runs gh with its own credentials, so the box never needs them.
3517
3465
  `
3518
- });
3519
- let explicitMethod = null;
3520
- let hasBody = false;
3521
- let endpoint = null;
3522
- for (let i = 0; i < args.length; i++) {
3523
- const arg = args[i] ?? "";
3524
- if (arg === "-X" || arg === "--method") {
3525
- explicitMethod = args[i + 1] ?? "";
3526
- i++;
3527
- continue;
3528
- }
3529
- if (arg.startsWith("--method=")) {
3530
- explicitMethod = arg.slice("--method=".length);
3531
- continue;
3532
- }
3533
- if (arg.startsWith("-X") && arg.length > 2) {
3534
- explicitMethod = arg.slice(2).replace(/^=/, "");
3535
- continue;
3536
- }
3537
- if (arg === "-d" || arg === "--data") {
3538
- hasBody = true;
3539
- i++;
3540
- continue;
3541
- }
3542
- if (arg.startsWith("--data=") || arg.startsWith("-d") && arg.length > 2) {
3543
- hasBody = true;
3544
- continue;
3545
- }
3546
- if (arg === "--file" || arg.startsWith("--file=")) {
3547
- return refuse("'--file' (host-file upload) isn't supported through the relay");
3548
- }
3549
- if (arg === "--input" || arg.startsWith("--input=")) {
3550
- return refuse("'--input' (stdin/file body) isn't supported through the relay; use -d <JSON>");
3551
- }
3552
- if (arg === "--notion-version") {
3553
- i++;
3554
- continue;
3555
- }
3556
- if (arg.startsWith("--notion-version=")) continue;
3557
- if (arg.startsWith("-")) {
3558
- if (SAFE_API_BOOLEAN_FLAGS.has(arg)) continue;
3559
- return refuse(
3560
- `unsupported option '${arg}' (read-only api accepts a path, inline inputs, -d <JSON>, -X GET/POST, --notion-version, --spec, --docs)`
3561
- );
3562
- }
3563
- if (endpoint === null) {
3564
- endpoint = arg;
3565
- continue;
3466
+ };
3566
3467
  }
3567
- if (isBodyAssignment(arg)) hasBody = true;
3568
- }
3569
- const method = (explicitMethod && explicitMethod.length > 0 ? explicitMethod : hasBody ? "POST" : "GET").toUpperCase();
3570
- if (method === "GET") return null;
3571
- if (method !== "POST") {
3572
- return refuse(
3573
- `only GET and read-only POST are proxied (use page.create / page.update for writes); detected method '${method}'`
3574
- );
3575
3468
  }
3576
- if (endpoint === null) {
3577
- return refuse("could not determine the API endpoint for a non-GET call");
3578
- }
3579
- if (endpoint.split("/").some((seg) => seg === "." || seg === "..")) {
3580
- return refuse(`path traversal segments ('.' / '..') are not allowed in '${endpoint}'`);
3581
- }
3582
- if (READ_POST_ENDPOINTS.some((re) => re.test(endpoint))) return null;
3583
- return refuse(
3584
- `POST is only proxied for read endpoints (v1/search, v1/databases/{id}/query, v1/data_sources/{id}/query); '${endpoint}' is not one (use page.create / page.update for writes)`
3585
- );
3586
- }
3587
- function isBodyAssignment(token) {
3588
- if (token.includes(":=")) return true;
3589
- if (token.includes("==")) return false;
3590
- return token.includes("=");
3469
+ return null;
3591
3470
  }
3592
- var ALL_CONNECTORS = [notionConnector, linearConnector];
3593
- function getConnector(service) {
3594
- for (const c of ALL_CONNECTORS) {
3595
- if (c.service === service) return c;
3471
+ function ghDestructiveTarget(args) {
3472
+ const joined = ghVerbArgv(args).join(" ");
3473
+ for (const { pattern, what } of GH_DESTRUCTIVE) {
3474
+ if (pattern.test(joined)) return what;
3596
3475
  }
3597
3476
  return null;
3598
3477
  }
3599
-
3600
- // ../../packages/relay/dist/chunk-DDOSDQJA.js
3601
- import { randomUUID as randomUUID4 } from "crypto";
3602
- import { randomUUID as randomUUID22 } from "crypto";
3603
- import { timingSafeEqual as timingSafeEqual5 } from "crypto";
3604
- import { open, stat as stat2 } from "fs/promises";
3605
- import { execa as execa2 } from "execa";
3606
- import { spawn as spawn4 } from "child_process";
3607
- import { readFile as readFile3 } from "fs/promises";
3608
- import { readFile as readFile22 } from "fs/promises";
3609
- var GH_PR_OPS = [
3610
- "create",
3611
- "view",
3612
- "list",
3613
- "diff",
3614
- "checks",
3615
- "comment",
3616
- "review",
3617
- "merge",
3618
- "checkout",
3619
- "close",
3620
- "reopen"
3621
- ];
3622
- function isGhPrOp(value) {
3623
- return GH_PR_OPS.includes(value);
3624
- }
3625
- var GH_PR_READ_ONLY_OPS = /* @__PURE__ */ new Set(["view", "list", "diff", "checks"]);
3626
- var GH_PR_SAFE_AUTO_APPROVE_OPS = /* @__PURE__ */ new Set(["create", "comment"]);
3627
- var GH_RUN_OPS = ["list", "view", "rerun"];
3628
- function isGhRunOp(value) {
3629
- return GH_RUN_OPS.includes(value);
3630
- }
3631
- var GH_RUN_READ_ONLY_OPS = /* @__PURE__ */ new Set(["list", "view"]);
3632
- var PR_REVIEW_COMMENT = /^repos\/[^/]+\/[^/]+\/pulls\/\d+\/comments(\?.*)?$/;
3633
- var PR_REVIEW_COMMENT_REPLY = /^repos\/[^/]+\/[^/]+\/pulls\/\d+\/comments\/\d+\/replies(\?.*)?$/;
3634
- var GH_API_WRITE_ALLOWED_ENDPOINTS = [
3635
- PR_REVIEW_COMMENT,
3636
- PR_REVIEW_COMMENT_REPLY
3637
- ];
3638
- var GH_API_ALLOWED_ENDPOINTS = [...GH_API_WRITE_ALLOWED_ENDPOINTS];
3639
- function isAllowedGhApiEndpoint(endpoint) {
3640
- return GH_API_ALLOWED_ENDPOINTS.some((re) => re.test(normalizeGhApiEndpoint(endpoint)));
3641
- }
3642
- function isWriteAllowedGhApiEndpoint(endpoint) {
3643
- return GH_API_WRITE_ALLOWED_ENDPOINTS.some((re) => re.test(normalizeGhApiEndpoint(endpoint)));
3644
- }
3645
- function normalizeGhApiEndpoint(endpoint) {
3646
- return endpoint.replace(/^\/+/, "");
3647
- }
3648
- var GH_API_ENDPOINT_REFUSAL = {
3649
- exitCode: 65,
3650
- stdout: "",
3651
- stderr: "gh api: endpoint not allowlisted. Proxied: GET on repos/:owner/:repo/pulls/:number/comments (and /:id/replies); POST to those endpoints to add a review comment.\n"
3652
- };
3653
- function refuseGhApiCall(endpoint, args) {
3654
- const refuse = (reason) => ({
3655
- exitCode: 65,
3656
- stdout: "",
3657
- stderr: `gh api: ${reason}
3658
- `
3659
- });
3660
- let explicitMethod = null;
3661
- let hasFieldFlag = false;
3662
- for (let i = 0; i < args.length; i++) {
3663
- const arg = args[i] ?? "";
3664
- if (arg === "-X" || arg === "--method") {
3665
- explicitMethod = args[i + 1] ?? "";
3666
- i++;
3667
- continue;
3668
- }
3669
- if (arg.startsWith("--method=")) {
3670
- explicitMethod = arg.slice("--method=".length);
3671
- continue;
3672
- }
3673
- if (arg.startsWith("-X") && arg.length > 2) {
3674
- explicitMethod = arg.slice(2).replace(/^=/, "");
3675
- continue;
3676
- }
3478
+ function refuseGhApiInput(args) {
3479
+ for (const arg of args) {
3677
3480
  if (arg === "--input" || arg.startsWith("--input=")) {
3678
- return refuse(
3679
- "'--input' (stdin/file body) isn't supported through the relay; use -f/-F fields"
3680
- );
3681
- }
3682
- if (arg === "-f" || arg === "-F" || arg === "--field" || arg === "--raw-field") {
3683
- hasFieldFlag = true;
3684
- i++;
3685
- continue;
3686
- }
3687
- if (arg.startsWith("-f") || arg.startsWith("-F") || arg.startsWith("--field=") || arg.startsWith("--raw-field=")) {
3688
- hasFieldFlag = true;
3481
+ return {
3482
+ exitCode: 65,
3483
+ stdout: "",
3484
+ stderr: "gh api: '--input' (stdin/file body) isn't supported through the relay (the host gh runs with stdin ignored); use -f/-F fields\n"
3485
+ };
3689
3486
  }
3690
3487
  }
3691
- const method = (explicitMethod ?? (hasFieldFlag ? "POST" : "GET")).toUpperCase();
3692
- if (method === "GET") return null;
3693
- if (method === "POST") {
3694
- if (isWriteAllowedGhApiEndpoint(endpoint)) return null;
3695
- return refuse(
3696
- `POST is only proxied to PR review-comment endpoints (repos/:o/:r/pulls/:n/comments[/:id/replies]), not '${endpoint}'`
3697
- );
3698
- }
3699
- return refuse(
3700
- `method '${method}' is not proxied \u2014 only GET, and POST to comment endpoints, are allowed`
3701
- );
3488
+ return null;
3702
3489
  }
3703
3490
  function injectPrCreateHead(op, branch, args) {
3704
3491
  if (op !== "create") return args;
@@ -3722,18 +3509,81 @@ var PR_CREATE_NO_HEAD_REFUSAL = {
3722
3509
  };
3723
3510
  var GH_RPC_TIMEOUT_MS = 12e4;
3724
3511
  var GH_READY_CACHE_TTL_MS = 6e4;
3725
- var ghReadyCache;
3726
- async function assertGhReady() {
3512
+ var ghReadyCache = /* @__PURE__ */ new Map();
3513
+ var ghInstalledCache;
3514
+ var sshHostCache = /* @__PURE__ */ new Map();
3515
+ async function resolveGhTarget(originUrl) {
3516
+ const derived = ghHostFromRemote(originUrl);
3517
+ if (!derived) return { host: null, error: await assertGhReady(null) };
3518
+ const expanded = derived.aliasable ? await expandSshHost(derived.host) : derived.host;
3519
+ if (expanded === "github.com") return { host: null, error: await assertGhReady(null) };
3520
+ const host = expanded ?? derived.host;
3521
+ const scoped = await assertGhReady(host);
3522
+ if (!scoped) return { host, error: null };
3523
+ if (scoped.exitCode !== 4) return { host: null, error: scoped };
3524
+ if (expanded === null) {
3525
+ const generic = await assertGhReady(null);
3526
+ return { host: null, error: generic ? scoped : null };
3527
+ }
3528
+ return { host: null, error: scoped };
3529
+ }
3530
+ async function expandSshHost(host) {
3531
+ const now = Date.now();
3532
+ const cached = sshHostCache.get(host);
3533
+ if (cached && cached.expiresAt > now) return cached.host;
3534
+ let resolved = null;
3535
+ try {
3536
+ const target = await resolveSshConfigTarget(host);
3537
+ const value = target?.host.trim().toLowerCase() ?? "";
3538
+ resolved = value.length > 0 ? value : null;
3539
+ } catch {
3540
+ resolved = null;
3541
+ }
3542
+ sshHostCache.set(host, { host: resolved, expiresAt: now + GH_READY_CACHE_TTL_MS });
3543
+ return resolved;
3544
+ }
3545
+ async function assertGhReady(host) {
3546
+ const key = host ?? "";
3727
3547
  const now = Date.now();
3728
- if (ghReadyCache && ghReadyCache.expiresAt > now) {
3729
- return ghReadyCache.result;
3548
+ const cached = ghReadyCache.get(key);
3549
+ if (cached && cached.expiresAt > now) return cached.result;
3550
+ const result = await probeGh(host ?? null);
3551
+ ghReadyCache.set(key, { result, expiresAt: now + GH_READY_CACHE_TTL_MS });
3552
+ return result;
3553
+ }
3554
+ function _resetGhReadyCacheForTests() {
3555
+ ghReadyCache.clear();
3556
+ ghInstalledCache = void 0;
3557
+ sshHostCache.clear();
3558
+ }
3559
+ async function probeGh(host) {
3560
+ const installed = await probeGhInstalled();
3561
+ if (installed) return installed;
3562
+ if (firstNonEmptyEnv(ghTokenEnvNames(host))) return null;
3563
+ const auth = await runHostGh(
3564
+ host ? ["auth", "status", "--hostname", host] : ["auth", "status"],
3565
+ process.cwd(),
3566
+ { timeoutMs: 15e3 }
3567
+ );
3568
+ if (auth.exitCode !== 0) {
3569
+ return {
3570
+ exitCode: 4,
3571
+ stdout: "",
3572
+ stderr: host ? `gh not authenticated on host for ${host} (run \`gh auth login --hostname ${host}\`)
3573
+ ` : "gh not authenticated on host (run `gh auth login`)\n"
3574
+ };
3730
3575
  }
3731
- const result = await probeGh();
3732
- ghReadyCache = { result, expiresAt: now + GH_READY_CACHE_TTL_MS };
3576
+ return null;
3577
+ }
3578
+ async function probeGhInstalled() {
3579
+ const now = Date.now();
3580
+ if (ghInstalledCache && ghInstalledCache.expiresAt > now) return ghInstalledCache.result;
3581
+ const result = await probeGhVersion();
3582
+ ghInstalledCache = { result, expiresAt: now + GH_READY_CACHE_TTL_MS };
3733
3583
  return result;
3734
3584
  }
3735
- async function probeGh() {
3736
- const version = await runHostGh(["--version"], process.cwd(), 1e4);
3585
+ async function probeGhVersion() {
3586
+ const version = await runHostGh(["--version"], process.cwd(), { timeoutMs: 1e4 });
3737
3587
  if (version.exitCode === 127 || /ENOENT/.test(version.stderr)) {
3738
3588
  return {
3739
3589
  exitCode: 127,
@@ -3748,16 +3598,17 @@ async function probeGh() {
3748
3598
  stderr: `gh --version failed: ${version.stderr || version.stdout}`.trimEnd() + "\n"
3749
3599
  };
3750
3600
  }
3751
- if ((process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? "").length > 0) {
3752
- return null;
3753
- }
3754
- const auth = await runHostGh(["auth", "status"], process.cwd(), 15e3);
3755
- if (auth.exitCode !== 0) {
3756
- return {
3757
- exitCode: 4,
3758
- stdout: "",
3759
- stderr: "gh not authenticated on host (run `gh auth login`)\n"
3760
- };
3601
+ return null;
3602
+ }
3603
+ function ghTokenEnvNames(host) {
3604
+ if (host === null) return ["GH_TOKEN", "GITHUB_TOKEN"];
3605
+ const enterprise = ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"];
3606
+ return host.endsWith(".ghe.com") ? [...enterprise, "GH_TOKEN", "GITHUB_TOKEN"] : enterprise;
3607
+ }
3608
+ function firstNonEmptyEnv(names) {
3609
+ for (const name of names) {
3610
+ const value = process.env[name];
3611
+ if (typeof value === "string" && value.length > 0) return value;
3761
3612
  }
3762
3613
  return null;
3763
3614
  }
@@ -3774,11 +3625,14 @@ function ghRunContext(workspacePath, originUrl, args) {
3774
3625
  return { cwd: tmpdir(), args };
3775
3626
  }
3776
3627
  }
3777
- function runHostGh(args, cwd, timeoutMs = GH_RPC_TIMEOUT_MS) {
3628
+ function runHostGh(args, cwd, opts = {}) {
3629
+ const timeoutMs = opts.timeoutMs ?? GH_RPC_TIMEOUT_MS;
3778
3630
  return new Promise((resolve) => {
3779
3631
  const child = spawn2("gh", args, {
3780
3632
  cwd,
3781
- env: process.env,
3633
+ // GH_HOST is what points gh at a GitHub Enterprise Server instance; without
3634
+ // it gh targets github.com no matter what the repo's remote says.
3635
+ env: opts.host ? { ...process.env, GH_HOST: opts.host } : process.env,
3782
3636
  stdio: ["ignore", "pipe", "pipe"]
3783
3637
  });
3784
3638
  let stdout = "";
@@ -3869,16 +3723,6 @@ function runGitProbe(args) {
3869
3723
  });
3870
3724
  });
3871
3725
  }
3872
- function refuseMergeBypass(op) {
3873
- if (op !== "merge") return null;
3874
- if (process.env["AGENTBOX_PROMPT"] !== "off") return null;
3875
- if (process.env["AGENTBOX_GH_FORCE"] === "1") return null;
3876
- return {
3877
- exitCode: 10,
3878
- stdout: "",
3879
- stderr: "gh pr merge: AGENTBOX_PROMPT=off bypass requires AGENTBOX_GH_FORCE=1 (merge is irreversible)\n"
3880
- };
3881
- }
3882
3726
  function refuseCheckoutByDefault(op) {
3883
3727
  if (op !== "checkout") return null;
3884
3728
  if (process.env["AGENTBOX_GH_PR_CHECKOUT"] === "allow") return null;
@@ -3968,7 +3812,9 @@ function normalizeCpParams(method, params) {
3968
3812
  }
3969
3813
  }
3970
3814
  if (!Array.isArray(sources) || sources.length === 0 || sources.some((s) => typeof s !== "string")) {
3971
- throw new Error("cp.* requires a non-empty {sources} string array (or legacy {boxPath, hostPath})");
3815
+ throw new Error(
3816
+ "cp.* requires a non-empty {sources} string array (or legacy {boxPath, hostPath})"
3817
+ );
3972
3818
  }
3973
3819
  if (typeof dest !== "string") {
3974
3820
  throw new Error("cp.* requires a {dest} string (or legacy {boxPath, hostPath})");
@@ -4000,104 +3846,195 @@ function buildCpArgv(opts) {
4000
3846
  contextArgv: [...hostAbsSrcs, dest]
4001
3847
  };
4002
3848
  }
4003
- var INTEGRATION_RPC_TIMEOUT_MS = 12e4;
4004
- var INTEGRATION_READY_CACHE_TTL_MS = 6e4;
4005
- var INTEGRATION_METHOD_RE = /^integration\.([a-z][a-z0-9]*)\.([a-z][a-z0-9.]*)$/;
4006
- function parseIntegrationMethod(method) {
4007
- const m = INTEGRATION_METHOD_RE.exec(method);
4008
- if (!m) return null;
4009
- const service = m[1];
4010
- const op = m[2];
4011
- if (op.endsWith(".") || op.includes("..")) return null;
4012
- return { service, op };
4013
- }
4014
- var integrationReadyCache = /* @__PURE__ */ new Map();
4015
- async function assertIntegrationReady(connector) {
4016
- const now = Date.now();
4017
- const cached = integrationReadyCache.get(connector.hostBin);
4018
- if (cached && cached.expiresAt > now) return cached.result;
4019
- const result = await probeIntegration(connector);
4020
- integrationReadyCache.set(connector.hostBin, {
4021
- result,
4022
- expiresAt: now + INTEGRATION_READY_CACHE_TTL_MS
4023
- });
4024
- return result;
4025
- }
4026
- function _resetIntegrationReadyCacheForTests() {
4027
- integrationReadyCache.clear();
4028
- }
4029
- async function probeIntegration(connector) {
4030
- const version = await runHostBinary(
4031
- connector,
4032
- [...connector.detect.versionArgs],
4033
- process.cwd(),
4034
- 1e4
4035
- );
4036
- if (version.exitCode === 127 || /ENOENT/.test(version.stderr)) {
4037
- return {
4038
- exitCode: 127,
4039
- stdout: "",
4040
- stderr: `${connector.hostBin} not installed on host (install the ${connector.service} CLI on the host)
4041
- `
4042
- };
4043
- }
4044
- if (version.exitCode !== 0) {
3849
+ function cpCachePrefix(opts) {
3850
+ const slug = (opts.projectSlug ?? "").trim();
3851
+ return slug.length > 0 ? `projects/${slug}/cp` : `boxes/${opts.boxId}/cp`;
3852
+ }
3853
+ function cpCacheKeyInput(source) {
3854
+ const trimmed = source.trim().replace(/\/+$/, "");
3855
+ if (trimmed.startsWith("/")) return `abs:${trimmed}`;
3856
+ const rel = trimmed.replace(/^(\.\/)+/, "").replace(/\/\.\//g, "/");
3857
+ return `rel:${rel}`;
3858
+ }
3859
+ function cpCacheKey(source) {
3860
+ return createHash22("sha256").update(cpCacheKeyInput(source)).digest("hex").slice(0, 32);
3861
+ }
3862
+ function cpCacheTarPath(prefix, source) {
3863
+ return `${prefix}/${cpCacheKey(source)}.tar`;
3864
+ }
3865
+ function cpCacheMetaPath(prefix, source) {
3866
+ return `${prefix}/${cpCacheKey(source)}.json`;
3867
+ }
3868
+ function describeCacheAge(capturedAt, now = Date.now()) {
3869
+ const then = Date.parse(capturedAt);
3870
+ if (!Number.isFinite(then)) return "captured at an unknown time";
3871
+ const seconds = Math.max(0, Math.round((now - then) / 1e3));
3872
+ if (seconds < 90) return `captured ${String(seconds)}s ago`;
3873
+ const minutes = Math.round(seconds / 60);
3874
+ if (minutes < 90) return `captured ${String(minutes)}m ago`;
3875
+ const hours = Math.round(minutes / 60);
3876
+ if (hours < 48) return `captured ${String(hours)}h ago`;
3877
+ return `captured ${String(Math.round(hours / 24))}d ago`;
3878
+ }
3879
+ function parseCpCacheMeta(raw) {
3880
+ try {
3881
+ const parsed = JSON.parse(raw);
3882
+ if (typeof parsed.sourcePath !== "string" || typeof parsed.capturedAt !== "string") return null;
4045
3883
  return {
4046
- exitCode: version.exitCode,
4047
- stdout: "",
4048
- stderr: `${connector.hostBin} ${connector.detect.versionArgs.join(" ")} failed: ` + (version.stderr || version.stdout).trimEnd() + "\n"
3884
+ sourcePath: parsed.sourcePath,
3885
+ isDir: parsed.isDir === true,
3886
+ capturedAt: parsed.capturedAt,
3887
+ size: typeof parsed.size === "number" ? parsed.size : 0,
3888
+ ...typeof parsed.capturedOn === "string" ? { capturedOn: parsed.capturedOn } : {}
4049
3889
  };
3890
+ } catch {
3891
+ return null;
4050
3892
  }
4051
- return null;
4052
3893
  }
4053
- function runHostIntegration(connector, op, args, cwd, timeoutMs = INTEGRATION_RPC_TIMEOUT_MS) {
4054
- const argv = op.buildArgv ? op.buildArgv(args) : [...args];
4055
- return runHostBinary(connector, argv, cwd, timeoutMs);
4056
- }
4057
- function mergeConnectorEnv(connector) {
4058
- if (!connector.env) return process.env;
4059
- const allowedPrefix = `${connector.service.toUpperCase()}_`;
4060
- const env = { ...process.env };
4061
- for (const [key, value] of Object.entries(connector.env)) {
4062
- if (!key.startsWith(allowedPrefix)) {
4063
- throw new Error(
4064
- `integration ${connector.service}: env key '${key}' not in '${allowedPrefix}*' namespace; descriptor cannot set it`
3894
+ var DEFAULT_MAX_CACHE_BYTES = 100 * 1024 * 1024;
3895
+ var TAR_TIMEOUT_MS = 12e4;
3896
+ var UPLOAD_TIMEOUT_MS = 3e5;
3897
+ async function captureCpCacheEntry(absPath, prefix, deps, requestPath = absPath) {
3898
+ const log = deps.logger ?? (() => {
3899
+ });
3900
+ const maxBytes = deps.maxBytes ?? DEFAULT_MAX_CACHE_BYTES;
3901
+ let workDir;
3902
+ try {
3903
+ const info = await stat2(absPath);
3904
+ const dir = await mkdtemp(join4(tmpdir2(), "agentbox-cp-cache-"));
3905
+ workDir = dir;
3906
+ const tarPath = join4(dir, "entry.tar");
3907
+ await run("tar", ["-cf", tarPath, "-C", dirname3(absPath), basename(absPath)], TAR_TIMEOUT_MS);
3908
+ const tarInfo = await stat2(tarPath);
3909
+ if (tarInfo.size > maxBytes) {
3910
+ log(
3911
+ `cp cache: skipping ${absPath} \u2014 ${String(tarInfo.size)} bytes exceeds the hub's ${String(maxBytes)}-byte limit`
4065
3912
  );
3913
+ return false;
4066
3914
  }
4067
- env[key] = value;
4068
- }
4069
- return env;
4070
- }
4071
- function runHostBinary(connector, argv, cwd, timeoutMs) {
4072
- let env;
4073
- try {
4074
- env = mergeConnectorEnv(connector);
3915
+ const meta = {
3916
+ sourcePath: absPath,
3917
+ isDir: info.isDirectory(),
3918
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
3919
+ size: tarInfo.size,
3920
+ capturedOn: hostname()
3921
+ };
3922
+ const base = deps.controlPlaneUrl.replace(/\/+$/, "");
3923
+ await putBlob(
3924
+ `${base}/admin/custody-blob/${cpCacheTarPath(prefix, requestPath)}`,
3925
+ tarPath,
3926
+ deps.adminToken
3927
+ );
3928
+ await putJson(
3929
+ `${base}/admin/custody/${cpCacheMetaPath(prefix, requestPath)}`,
3930
+ { data: Buffer.from(JSON.stringify(meta), "utf8").toString("base64") },
3931
+ deps.adminToken
3932
+ );
3933
+ log(`cp cache: stored ${absPath} (${String(tarInfo.size)} bytes) for offline use`);
3934
+ return true;
4075
3935
  } catch (err2) {
4076
- return Promise.resolve({
4077
- exitCode: 78,
4078
- stdout: "",
4079
- stderr: `${connector.hostBin}: ${err2 instanceof Error ? err2.message : String(err2)}
4080
- `
3936
+ log(
3937
+ `cp cache: could not store ${absPath}: ${err2 instanceof Error ? err2.message : String(err2)}`
3938
+ );
3939
+ return false;
3940
+ } finally {
3941
+ if (workDir) await rm4(workDir, { recursive: true, force: true }).catch(() => {
4081
3942
  });
4082
3943
  }
4083
- return new Promise((resolve) => {
4084
- const child = spawn22(connector.hostBin, [...argv], {
4085
- cwd,
4086
- env,
4087
- stdio: ["ignore", "pipe", "pipe"]
4088
- });
4089
- let stdout = "";
4090
- let stderr = "";
4091
- let settled = false;
4092
- const finish = (exitCode) => {
4093
- if (settled) return;
4094
- settled = true;
4095
- resolve({ exitCode, stdout, stderr });
4096
- };
4097
- const timer = setTimeout(() => {
3944
+ }
3945
+ function run(bin, args, timeout) {
3946
+ return new Promise((resolve, reject) => {
3947
+ execFile(bin, args, { timeout }, (err2) => err2 ? reject(err2) : resolve());
3948
+ });
3949
+ }
3950
+ function putBlob(url, filePath, token) {
3951
+ const target = new URL(url);
3952
+ const isHttps = target.protocol === "https:";
3953
+ const transport = isHttps ? httpsRequest : httpRequest;
3954
+ return new Promise((resolve, reject) => {
3955
+ const req = transport(
3956
+ {
3957
+ host: target.hostname,
3958
+ port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,
3959
+ method: "PUT",
3960
+ path: target.pathname,
3961
+ headers: {
3962
+ Authorization: `Bearer ${token}`,
3963
+ "Content-Type": "application/octet-stream"
3964
+ },
3965
+ timeout: UPLOAD_TIMEOUT_MS
3966
+ },
3967
+ (res) => {
3968
+ res.resume();
3969
+ const status = res.statusCode ?? 0;
3970
+ if (status >= 200 && status < 300) resolve();
3971
+ else reject(new Error(`custody blob PUT \u2192 ${String(status)}`));
3972
+ }
3973
+ );
3974
+ req.on("error", reject);
3975
+ req.on("timeout", () => {
3976
+ req.destroy();
3977
+ reject(new Error("custody blob PUT timed out"));
3978
+ });
3979
+ createReadStream2(filePath).pipe(req);
3980
+ });
3981
+ }
3982
+ function putJson(url, body, token) {
3983
+ const target = new URL(url);
3984
+ const isHttps = target.protocol === "https:";
3985
+ const transport = isHttps ? httpsRequest : httpRequest;
3986
+ const payload = JSON.stringify(body);
3987
+ return new Promise((resolve, reject) => {
3988
+ const req = transport(
3989
+ {
3990
+ host: target.hostname,
3991
+ port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,
3992
+ method: "PUT",
3993
+ path: target.pathname,
3994
+ headers: {
3995
+ Authorization: `Bearer ${token}`,
3996
+ "Content-Type": "application/json",
3997
+ "Content-Length": Buffer.byteLength(payload).toString()
3998
+ },
3999
+ timeout: UPLOAD_TIMEOUT_MS
4000
+ },
4001
+ (res) => {
4002
+ res.resume();
4003
+ const status = res.statusCode ?? 0;
4004
+ if (status >= 200 && status < 300) resolve();
4005
+ else reject(new Error(`custody PUT \u2192 ${String(status)}`));
4006
+ }
4007
+ );
4008
+ req.on("error", reject);
4009
+ req.on("timeout", () => {
4010
+ req.destroy();
4011
+ reject(new Error("custody PUT timed out"));
4012
+ });
4013
+ req.write(payload);
4014
+ req.end();
4015
+ });
4016
+ }
4017
+ var HOST_EXEC_DEFAULT_TIMEOUT_MS = 12e4;
4018
+ var READY_CACHE_TTL_MS = 6e4;
4019
+ function runHostBinary(bin, argv, cwd, timeoutMs = HOST_EXEC_DEFAULT_TIMEOUT_MS) {
4020
+ return new Promise((resolve) => {
4021
+ const child = spawn22(bin, [...argv], {
4022
+ cwd,
4023
+ env: process.env,
4024
+ stdio: ["ignore", "pipe", "pipe"]
4025
+ });
4026
+ let stdout = "";
4027
+ let stderr = "";
4028
+ let settled = false;
4029
+ const finish = (exitCode) => {
4030
+ if (settled) return;
4031
+ settled = true;
4032
+ resolve({ exitCode, stdout, stderr });
4033
+ };
4034
+ const timer = setTimeout(() => {
4098
4035
  child.kill("SIGTERM");
4099
4036
  stderr += `
4100
- relay: ${connector.hostBin} command timed out after ${String(timeoutMs)}ms
4037
+ relay: ${bin} command timed out after ${String(timeoutMs)}ms
4101
4038
  `;
4102
4039
  finish(124);
4103
4040
  }, timeoutMs);
@@ -4119,34 +4056,180 @@ relay: ${connector.hostBin} command timed out after ${String(timeoutMs)}ms
4119
4056
  });
4120
4057
  });
4121
4058
  }
4122
- function makeIntegrationOpRefusal(service, op, hostBin, knownOps) {
4123
- return {
4124
- exitCode: 65,
4059
+ var readyCache = /* @__PURE__ */ new Map();
4060
+ async function assertHostBinReady(bin) {
4061
+ const now = Date.now();
4062
+ const cached = readyCache.get(bin);
4063
+ if (cached && cached.expiresAt > now) return cached.result;
4064
+ const exists = await hostBinExists(bin);
4065
+ const result = exists ? null : {
4066
+ exitCode: 127,
4125
4067
  stdout: "",
4126
- stderr: `integration ${service}: op '${op}' not on allowlist for ${hostBin}. Available: ${knownOps.join(", ")}
4068
+ stderr: `${bin} is not installed on the host
4127
4069
  `
4128
4070
  };
4071
+ readyCache.set(bin, { result, expiresAt: now + READY_CACHE_TTL_MS });
4072
+ return result;
4073
+ }
4074
+ function _resetHostBinReadyCacheForTests() {
4075
+ readyCache.clear();
4076
+ }
4077
+ async function hostBinExists(bin) {
4078
+ const probe = await runHostBinary("command", ["-v", bin], process.cwd(), 5e3);
4079
+ if (probe.exitCode === 0) return true;
4080
+ const which = await runHostBinary("which", [bin], process.cwd(), 5e3);
4081
+ return which.exitCode === 0;
4082
+ }
4083
+ var CREDENTIAL_ARGV_PATTERNS = [
4084
+ /\bauth\s+(token|print-token|print-access-token|export)\b/i,
4085
+ // `print-`, `get-`, `create-`, `fetch-` all name the same hazard; matching
4086
+ // the token noun with any of those verbs is cheaper than chasing each CLI.
4087
+ /\b(print|get|fetch|create|issue)-(access-|identity-|id-|session-|refresh-)?token\b/i,
4088
+ /\bexport-credentials\b/i,
4089
+ /\bconfigure\s+get\b/i,
4090
+ // AWS STS hands out live session credentials; IAM can mint a durable key.
4091
+ /\bsts\s+(get-session-token|get-federation-token|assume-role\S*)\b/i,
4092
+ /\biam\s+create-access-key\b/i,
4093
+ /\bsecrets?\s+(get|reveal|show|print|list)\b/i,
4094
+ /\bcredentials?\s+(get|reveal|show|print)\b/i,
4095
+ /\bget-secret-value\b/i,
4096
+ /\bkeyring\s+(get|show)\b/i,
4097
+ /--show-secret\b/i,
4098
+ /\btoken\s+--raw\b/i
4099
+ ];
4100
+ function refuseCredentialArgv(name, args, bin) {
4101
+ const joined = args.join(" ");
4102
+ const candidates = [`${name} ${joined}`];
4103
+ const binName = bin ? basename2(bin) : void 0;
4104
+ if (binName && binName !== name) candidates.push(`${binName} ${joined}`);
4105
+ for (const re of CREDENTIAL_ARGV_PATTERNS) {
4106
+ if (candidates.some((c) => re.test(c))) {
4107
+ return {
4108
+ exitCode: 65,
4109
+ stdout: "",
4110
+ stderr: `${name}: refused \u2014 '${joined}' prints a host credential, which would land inside the box. The host runs this tool so the box never needs its token.
4111
+ `
4112
+ };
4113
+ }
4114
+ }
4115
+ return null;
4116
+ }
4117
+ function refuseDeniedArgv(grant, args) {
4118
+ if (!grant.deny || grant.deny.length === 0) return null;
4119
+ const joined = args.join(" ");
4120
+ for (const pattern of grant.deny) {
4121
+ let re;
4122
+ try {
4123
+ re = new RegExp(pattern);
4124
+ } catch {
4125
+ return {
4126
+ exitCode: 78,
4127
+ stdout: "",
4128
+ stderr: `${grant.name}: grant has an invalid deny pattern '${pattern}'
4129
+ `
4130
+ };
4131
+ }
4132
+ if (re.test(joined)) {
4133
+ return {
4134
+ exitCode: 65,
4135
+ stdout: "",
4136
+ stderr: `${grant.name}: refused \u2014 argv matches this tool's deny rule '${pattern}'
4137
+ `
4138
+ };
4139
+ }
4140
+ }
4141
+ return null;
4142
+ }
4143
+ function argvIsExplicitlyAllowed(grant, args) {
4144
+ if (!grant.allow || grant.allow.length === 0) return false;
4145
+ const joined = args.join(" ");
4146
+ return grant.allow.some((pattern) => {
4147
+ try {
4148
+ return new RegExp(pattern).test(joined);
4149
+ } catch {
4150
+ return false;
4151
+ }
4152
+ });
4153
+ }
4154
+ async function resolveToolGrant(name, cwd, loader = (c) => loadGrantedTools(c)) {
4155
+ let grants;
4156
+ try {
4157
+ grants = await loader(cwd);
4158
+ } catch {
4159
+ grants = /* @__PURE__ */ new Map();
4160
+ }
4161
+ const grant = grants.get(name);
4162
+ if (!grant) {
4163
+ return {
4164
+ refusal: {
4165
+ exitCode: 65,
4166
+ stdout: "",
4167
+ stderr: `${name} is not a granted host tool for this project. Grant it on the host with \`agentbox tools add ${name}\`, or ask from inside the box with \`agentbox-ctl tool request ${name}\`.
4168
+ `
4169
+ }
4170
+ };
4171
+ }
4172
+ if (grant.source === "builtin") {
4173
+ return {
4174
+ refusal: {
4175
+ exitCode: 65,
4176
+ stdout: "",
4177
+ stderr: `${name} is handled by its own relay path, not the generic host-tool proxy
4178
+ `
4179
+ }
4180
+ };
4181
+ }
4182
+ return { grant };
4129
4183
  }
4130
- function refuseIntegrationCall(op, args) {
4131
- const refusal = op.refuseCall?.(args);
4132
- if (!refusal) return null;
4133
- return { exitCode: refusal.exitCode, stdout: "", stderr: refusal.stderr };
4184
+ async function toolRequestsEnabled(cwd, loader = loadEffectiveConfig) {
4185
+ try {
4186
+ const cfg = await loader(cwd);
4187
+ return cfg.effective.tools?.request?.enabled !== false;
4188
+ } catch {
4189
+ return false;
4190
+ }
4134
4191
  }
4135
- async function refuseIfIntegrationDisabled(service, cwd, loader = loadEffectiveConfig) {
4136
- let enabled = false;
4192
+ async function ghToolEnabled(cwd, loader = loadEffectiveConfig) {
4137
4193
  try {
4138
4194
  const cfg = await loader(cwd);
4139
- enabled = cfg.effective.integrations?.[service]?.enabled === true;
4195
+ return cfg.effective.tools?.gh?.enabled !== false;
4140
4196
  } catch {
4197
+ return true;
4141
4198
  }
4142
- if (enabled) return null;
4199
+ }
4200
+ async function refuseIfGhDisabled(cwd, loader) {
4201
+ if (await ghToolEnabled(cwd, loader)) return null;
4143
4202
  return {
4144
4203
  exitCode: 65,
4145
4204
  stdout: "",
4146
- stderr: `${service} integration is disabled \u2014 enable with \`agentbox config set --project integrations.${service}.enabled true\`
4147
- `
4205
+ stderr: "gh is disabled for this project \u2014 re-enable with `agentbox config set --project tools.gh.enabled true`\n"
4148
4206
  };
4149
4207
  }
4208
+ async function hostToolInstalled(bin) {
4209
+ return hostBinExists(bin);
4210
+ }
4211
+ async function runGrantedTool(grant, args, cwd) {
4212
+ const ready = await assertHostBinReady(grant.bin);
4213
+ if (ready) return ready;
4214
+ return runHostBinary(grant.bin, args, cwd, grant.timeoutMs);
4215
+ }
4216
+ function renderToolListJson(grants) {
4217
+ const rows = [...grants].filter((g) => g.source !== "builtin").sort((a, b) => a.name.localeCompare(b.name)).map((g) => ({ name: g.name, bin: g.bin }));
4218
+ return JSON.stringify({ tools: rows }) + "\n";
4219
+ }
4220
+ function renderToolList(grants) {
4221
+ const rows = [...grants].sort((a, b) => a.name.localeCompare(b.name));
4222
+ if (rows.length === 0) {
4223
+ return "no host tools granted for this project\n";
4224
+ }
4225
+ const width = Math.max(...rows.map((g) => g.name.length));
4226
+ return rows.map((g) => {
4227
+ const notes = [`host: ${g.bin}`, g.source];
4228
+ if (g.allow) notes.push(`${String(g.allow.length)} allow`);
4229
+ if (g.deny) notes.push(`${String(g.deny.length)} deny`);
4230
+ return `${g.name.padEnd(width)} ${notes.join(" ")}`;
4231
+ }).join("\n") + "\n";
4232
+ }
4150
4233
  async function canAutoApproveTransfer(input) {
4151
4234
  if (!input.enabled) return false;
4152
4235
  if (!input.workspacePath || input.hostPaths.length === 0) return false;
@@ -4280,17 +4363,11 @@ async function executeCloudAction(action, deps) {
4280
4363
  if (action.method === "browser.open.mirror") {
4281
4364
  return runBrowserOpenMirror(action, deps);
4282
4365
  }
4283
- if (action.method.startsWith("gh.pr.")) {
4284
- return runGhPrRpc(action, deps);
4285
- }
4286
- if (action.method.startsWith("gh.run.")) {
4287
- return runGhRunRpc(action, deps);
4366
+ if (action.method === "gh.exec") {
4367
+ return runGhExecRpc(action, deps);
4288
4368
  }
4289
- if (action.method === "gh.api") {
4290
- return runGhApiRpc(action, deps);
4291
- }
4292
- if (action.method.startsWith("integration.")) {
4293
- return runIntegrationRpc(action, deps);
4369
+ if (action.method.startsWith("tool.")) {
4370
+ return runToolRpc(action, deps);
4294
4371
  }
4295
4372
  if (action.method === "git.clone" || action.method === "gh.repo.clone") {
4296
4373
  return {
@@ -4307,114 +4384,6 @@ async function executeCloudAction(action, deps) {
4307
4384
  `
4308
4385
  };
4309
4386
  }
4310
- async function runGhPrRpc(action, deps) {
4311
- const op = action.method.slice("gh.pr.".length);
4312
- if (!isGhPrOp(op)) {
4313
- return {
4314
- exitCode: 64,
4315
- stdout: "",
4316
- stderr: `unknown gh.pr.* op: ${op}
4317
- `
4318
- };
4319
- }
4320
- const mergeBypass = refuseMergeBypass(op);
4321
- if (mergeBypass) return mergeBypass;
4322
- const checkoutOptIn = refuseCheckoutByDefault(op);
4323
- if (checkoutOptIn) return checkoutOptIn;
4324
- const params = action.params ?? {};
4325
- const args = Array.isArray(params.args) ? params.args.filter((a) => typeof a === "string") : [];
4326
- const ghReady = await assertGhReady();
4327
- if (ghReady) return ghReady;
4328
- const lookup = await lookupCloudBox(deps.boxId);
4329
- if (op === "checkout") {
4330
- const guard = await checkoutGuards(lookup.workspacePath, []);
4331
- if (guard) return guard;
4332
- }
4333
- const tokenClaimedGhCloud = typeof params.hostInitiated === "string";
4334
- const incomingHashGhCloud = hashRpcParams(params);
4335
- const hostInitiatedGhOk = !GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGhCloud && (deps.hostInitiatedTokens?.consume(
4336
- params.hostInitiated,
4337
- deps.boxId,
4338
- `gh.pr.${op}`,
4339
- incomingHashGhCloud
4340
- ) ?? false);
4341
- if (!GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGhCloud && !hostInitiatedGhOk) {
4342
- return {
4343
- exitCode: 10,
4344
- stdout: "",
4345
- stderr: "host-initiated token rejected: invalid, expired, or bound to different params\n"
4346
- };
4347
- }
4348
- const ghSafeAuto = GH_PR_SAFE_AUTO_APPROVE_OPS.has(op) && deps.autoApproveSafeHostActions !== false && !prCreateHasExplicitHead(op, args);
4349
- if (ghSafeAuto && !hostInitiatedGhOk) {
4350
- deps.prompts?.noteAutoApprove(
4351
- deps.boxId,
4352
- {
4353
- kind: "confirm",
4354
- message: `gh pr ${op} from cloud box ${deps.boxName ?? deps.boxId}`,
4355
- detail: args.join(" ").slice(0, 200),
4356
- context: { command: `gh pr ${op}`, cwd: params.path, argv: args }
4357
- },
4358
- `safe: gh pr ${op}`
4359
- );
4360
- }
4361
- if (!GH_PR_READ_ONLY_OPS.has(op) && !ghSafeAuto && !hostInitiatedGhOk && deps.prompts && deps.subscribers) {
4362
- const detail = args.join(" ").slice(0, 200);
4363
- const ctx = {
4364
- kind: "confirm",
4365
- message: `Allow gh pr ${op} from cloud box ${deps.boxName ?? deps.boxId}?`,
4366
- detail,
4367
- defaultAnswer: "n",
4368
- context: {
4369
- command: `gh pr ${op}`,
4370
- cwd: params.path,
4371
- argv: args
4372
- }
4373
- };
4374
- const hasSubscriber = deps.subscribers.count(deps.boxId) > 0;
4375
- if (!hasSubscriber && process.env["AGENTBOX_PROMPT"] !== "off") {
4376
- const noSubMode = (process.env["AGENTBOX_GH_NO_SUB"] ?? "deny").toLowerCase();
4377
- if (noSubMode === "deny") {
4378
- return {
4379
- exitCode: 10,
4380
- stdout: "",
4381
- stderr: "denied automatically \u2014 no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GH_NO_SUB=allow.\n"
4382
- };
4383
- }
4384
- if (noSubMode === "allow") {
4385
- deps.log?.(`gh.pr.${op} auto-approved (no subscribers, AGENTBOX_GH_NO_SUB=allow)`);
4386
- } else {
4387
- const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx, {
4388
- ttlMs: 5 * 60 * 1e3
4389
- });
4390
- if (verdict.answer !== "y") {
4391
- return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
4392
- }
4393
- }
4394
- } else {
4395
- const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx);
4396
- if (verdict.answer !== "y") {
4397
- return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
4398
- }
4399
- }
4400
- }
4401
- let finalArgs = args;
4402
- const containerPath = params.path ?? "/workspace";
4403
- const needsHeadProbe = op === "create" && !args.some((a) => a === "--head" || a.startsWith("--head="));
4404
- if (needsHeadProbe) {
4405
- const backend = await resolveCloudBackend(deps.backendName);
4406
- const handle = { sandboxId: lookup.cloudSandboxId };
4407
- const branchProbe = await backend.exec(
4408
- handle,
4409
- `git -C ${shellQuote(containerPath)} rev-parse --abbrev-ref HEAD`
4410
- );
4411
- const branch = branchProbe.exitCode === 0 ? (branchProbe.stdout ?? "").trim() : "";
4412
- finalArgs = injectPrCreateHead(op, lookup.sanctionedBranch ?? branch, finalArgs);
4413
- }
4414
- if (prCreateNeedsHead(op, finalArgs)) return PR_CREATE_NO_HEAD_REFUSAL;
4415
- const prRun = ghRunContext(lookup.workspacePath, deps.originUrl, finalArgs);
4416
- return runHostGh(["pr", op, ...prRun.args], prRun.cwd);
4417
- }
4418
4387
  async function cloudWriteConfirm(deps, command, cwd, args) {
4419
4388
  if (!deps.prompts || !deps.subscribers) return null;
4420
4389
  const ctx = {
@@ -4446,131 +4415,140 @@ async function cloudWriteConfirm(deps, command, cwd, args) {
4446
4415
  const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx);
4447
4416
  return verdict.answer === "y" ? null : { exitCode: 10, stdout: "", stderr: "denied by user\n" };
4448
4417
  }
4449
- async function runGhRunRpc(action, deps) {
4450
- const op = action.method.slice("gh.run.".length);
4451
- if (!isGhRunOp(op)) {
4452
- return { exitCode: 64, stdout: "", stderr: `unknown gh.run.* op: ${op}
4453
- ` };
4454
- }
4418
+ async function runGhExecRpc(action, deps) {
4455
4419
  const params = action.params ?? {};
4456
4420
  const args = Array.isArray(params.args) ? params.args.filter((a) => typeof a === "string") : [];
4457
- const ghReady = await assertGhReady();
4458
- if (ghReady) return ghReady;
4421
+ if (args.length === 0) {
4422
+ return { exitCode: 64, stdout: "", stderr: "gh: no arguments\n" };
4423
+ }
4424
+ const blocked = refuseBlockedGhCall(args);
4425
+ if (blocked) return blocked;
4426
+ const verb = ghVerbArgv(args);
4427
+ const family = verb[0] ?? "";
4428
+ const op = verb[1] ?? "";
4429
+ if (family === "pr") {
4430
+ const checkoutOptIn = refuseCheckoutByDefault(op);
4431
+ if (checkoutOptIn) return checkoutOptIn;
4432
+ }
4433
+ if (family === "api") {
4434
+ const inputRefusal = refuseGhApiInput(args);
4435
+ if (inputRefusal) return inputRefusal;
4436
+ }
4437
+ const ghTarget = await resolveGhTarget(deps.originUrl);
4438
+ if (ghTarget.error) return ghTarget.error;
4459
4439
  const lookup = await lookupCloudBox(deps.boxId);
4460
- if (!GH_RUN_READ_ONLY_OPS.has(op)) {
4461
- if (deps.autoApproveSafeHostActions !== false) {
4462
- deps.prompts?.noteAutoApprove(
4463
- deps.boxId,
4464
- {
4465
- kind: "confirm",
4466
- message: `gh run ${op} from cloud box ${deps.boxName ?? deps.boxId}`,
4467
- detail: args.join(" ").slice(0, 200),
4468
- context: { command: `gh run ${op}`, cwd: params.path, argv: args }
4469
- },
4470
- `safe: gh run ${op}`
4471
- );
4472
- } else {
4473
- const denied = await cloudWriteConfirm(deps, `gh run ${op}`, params.path, args);
4474
- if (denied) return denied;
4475
- }
4440
+ const ghRevoked = await refuseIfGhDisabled(lookup.workspacePath);
4441
+ if (ghRevoked) return ghRevoked;
4442
+ if (family === "pr" && op === "checkout") {
4443
+ const branches = lookup.sanctionedBranch ? [lookup.sanctionedBranch] : [];
4444
+ const guard = await checkoutGuards(lookup.workspacePath, branches);
4445
+ if (guard) return guard;
4476
4446
  }
4477
- const runRun = ghRunContext(lookup.workspacePath, deps.originUrl, args);
4478
- return runHostGh(["run", op, ...runRun.args], runRun.cwd);
4479
- }
4480
- async function runGhApiRpc(action, deps) {
4481
- const params = action.params ?? {};
4482
- const endpoint = typeof params.endpoint === "string" ? params.endpoint : "";
4483
- if (!isAllowedGhApiEndpoint(endpoint)) return GH_API_ENDPOINT_REFUSAL;
4484
- const args = Array.isArray(params.args) ? params.args.filter((a) => typeof a === "string") : [];
4485
- const callRefusal = refuseGhApiCall(endpoint, args);
4486
- if (callRefusal) return callRefusal;
4487
- const ghReady = await assertGhReady();
4488
- if (ghReady) return ghReady;
4489
- const lookup = await lookupCloudBox(deps.boxId);
4490
- const apiRun = ghRunContext(lookup.workspacePath, void 0, args);
4491
- return runHostGh(["api", endpoint, ...apiRun.args], apiRun.cwd);
4492
- }
4493
- async function runIntegrationRpc(action, deps) {
4494
- const parsed = parseIntegrationMethod(action.method);
4495
- if (!parsed) {
4447
+ const tokenClaimed = typeof params.hostInitiated === "string";
4448
+ const hostInitiatedOk = tokenClaimed && (deps.hostInitiatedTokens?.consume(
4449
+ params.hostInitiated,
4450
+ deps.boxId,
4451
+ "gh.exec",
4452
+ hashRpcParams(params)
4453
+ ) ?? false);
4454
+ if (tokenClaimed && !hostInitiatedOk) {
4496
4455
  return {
4497
- exitCode: 64,
4456
+ exitCode: 10,
4498
4457
  stdout: "",
4499
- stderr: `unknown integration method shape: ${action.method}
4500
- `
4458
+ stderr: "host-initiated token rejected: invalid, expired, or bound to different params\n"
4501
4459
  };
4502
4460
  }
4503
- const connector = getConnector(parsed.service);
4504
- if (!connector) {
4505
- return {
4506
- exitCode: 64,
4507
- stdout: "",
4508
- stderr: `unknown integration service: ${parsed.service}
4509
- `
4510
- };
4461
+ const destructive = ghDestructiveTarget(args);
4462
+ if (!hostInitiatedOk && (destructive || deps.autoApproveSafeHostActions === false)) {
4463
+ const label = destructive ? `gh ${args.slice(0, 2).join(" ")} (destroys a ${destructive})` : `gh ${args.slice(0, 2).join(" ")}`;
4464
+ const denied = await cloudWriteConfirm(deps, label.trim(), params.path, [...args]);
4465
+ if (denied) return denied;
4511
4466
  }
4512
- const opDesc = connector.ops[parsed.op];
4513
- if (!opDesc) {
4514
- return makeIntegrationOpRefusal(
4515
- parsed.service,
4516
- parsed.op,
4517
- connector.hostBin,
4518
- Object.keys(connector.ops)
4519
- );
4467
+ let finalArgs = args;
4468
+ if (family === "pr") {
4469
+ const head = args.slice(0, args.length - verb.length);
4470
+ const rest = injectPrCreateHead(op, lookup.sanctionedBranch, verb.slice(2));
4471
+ if (prCreateNeedsHead(op, rest)) return PR_CREATE_NO_HEAD_REFUSAL;
4472
+ finalArgs = [...head, family, op, ...rest];
4520
4473
  }
4474
+ const run4 = ghRunContext(lookup.workspacePath, deps.originUrl, finalArgs);
4475
+ return runHostGh(run4.args, run4.cwd, { host: ghTarget.host });
4476
+ }
4477
+ async function runToolRpc(action, deps) {
4521
4478
  const params = action.params ?? {};
4522
- const args = Array.isArray(params.args) ? params.args.filter((a) => typeof a === "string") : [];
4523
- const callRefusal = refuseIntegrationCall(opDesc, args);
4524
- if (callRefusal) return callRefusal;
4479
+ const containerPath = typeof params["path"] === "string" ? params["path"] : "/workspace";
4525
4480
  const lookup = await lookupCloudBox(deps.boxId);
4526
- const enableRefusal = await refuseIfIntegrationDisabled(parsed.service, lookup.workspacePath);
4527
- if (enableRefusal) return enableRefusal;
4528
- const ready = await assertIntegrationReady(connector);
4529
- if (ready) return ready;
4530
- if (opDesc.write) {
4531
- if (deps.autoApproveSafeHostActions !== false) {
4532
- deps.prompts?.noteAutoApprove(
4533
- deps.boxId,
4534
- {
4535
- kind: "confirm",
4536
- message: `integration ${parsed.service} ${parsed.op} from cloud box ${deps.boxName ?? deps.boxId}`,
4537
- detail: args.join(" ").slice(0, 200),
4538
- context: {
4539
- command: `integration ${parsed.service} ${parsed.op}`,
4540
- cwd: params.path,
4541
- argv: args
4542
- }
4543
- },
4544
- `safe: integration ${parsed.service} ${parsed.op}`
4545
- );
4546
- } else {
4547
- const tokenClaimed = typeof params.hostInitiated === "string";
4548
- const incomingHash = hashRpcParams(params);
4549
- const tokenOk = tokenClaimed && (deps.hostInitiatedTokens?.consume(
4550
- params.hostInitiated,
4551
- deps.boxId,
4552
- action.method,
4553
- incomingHash
4554
- ) ?? false);
4555
- if (tokenClaimed && !tokenOk) {
4556
- return {
4557
- exitCode: 10,
4558
- stdout: "",
4559
- stderr: "host-initiated token rejected: invalid, expired, or bound to different params\n"
4560
- };
4561
- }
4562
- if (!tokenOk) {
4563
- const denied = await cloudWriteConfirm(
4564
- deps,
4565
- `integration ${parsed.service} ${parsed.op}`,
4566
- params.path,
4567
- args
4568
- );
4569
- if (denied) return denied;
4570
- }
4481
+ const cwd = lookup.workspacePath;
4482
+ if (action.method === "tool.list") {
4483
+ const grants = await loadGrantedTools(cwd);
4484
+ const json = params["format"] === "json";
4485
+ return {
4486
+ exitCode: 0,
4487
+ stdout: json ? renderToolListJson(grants.values()) : renderToolList(grants.values()),
4488
+ stderr: ""
4489
+ };
4490
+ }
4491
+ const name = typeof params["name"] === "string" ? params["name"].trim() : "";
4492
+ if (!name || !isValidToolName(name)) {
4493
+ return { exitCode: 64, stdout: "", stderr: `${action.method}: missing or invalid tool name
4494
+ ` };
4495
+ }
4496
+ if (action.method === "tool.request") {
4497
+ if (!await toolRequestsEnabled(cwd)) {
4498
+ return {
4499
+ exitCode: 65,
4500
+ stdout: "",
4501
+ stderr: "host-tool requests are disabled for this project (`agentbox config set --project tools.request.enabled true` to allow them)\n"
4502
+ };
4503
+ }
4504
+ const existing = await loadGrantedTools(cwd);
4505
+ if (existing.has(name)) {
4506
+ return { exitCode: 0, stdout: `${name} is already granted
4507
+ `, stderr: "" };
4508
+ }
4509
+ if (!await hostToolInstalled(name)) {
4510
+ return {
4511
+ exitCode: 127,
4512
+ stdout: "",
4513
+ stderr: `${name} is not installed on the host \u2014 nothing to grant
4514
+ `
4515
+ };
4571
4516
  }
4517
+ const reason = typeof params["reason"] === "string" ? params["reason"].slice(0, 500) : "";
4518
+ const denied = await cloudWriteConfirm(
4519
+ deps,
4520
+ `tool request ${name}`,
4521
+ containerPath,
4522
+ reason ? [name, `reason: ${reason}`] : [name]
4523
+ );
4524
+ if (denied) return denied;
4525
+ await writeToolGrant(await resolveProjectToolsFile(cwd), {
4526
+ name,
4527
+ bin: name,
4528
+ source: "request",
4529
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
4530
+ });
4531
+ return { exitCode: 0, stdout: `${name} granted for this project
4532
+ `, stderr: "" };
4572
4533
  }
4573
- return runHostIntegration(connector, opDesc, args, lookup.workspacePath);
4534
+ if (action.method !== "tool.run") {
4535
+ return { exitCode: 64, stdout: "", stderr: `unknown tool method: ${action.method}
4536
+ ` };
4537
+ }
4538
+ const resolved = await resolveToolGrant(name, cwd);
4539
+ if ("refusal" in resolved) return resolved.refusal;
4540
+ const grant = resolved.grant;
4541
+ const args = Array.isArray(params["args"]) ? params["args"].filter((a) => typeof a === "string") : [];
4542
+ const credRefusal = refuseCredentialArgv(name, args, grant.bin);
4543
+ if (credRefusal) return credRefusal;
4544
+ const denyRefusal = refuseDeniedArgv(grant, args);
4545
+ if (denyRefusal) return denyRefusal;
4546
+ const silent = argvIsExplicitlyAllowed(grant, args) || deps.autoApproveSafeHostActions !== false;
4547
+ if (!silent) {
4548
+ const denied = await cloudWriteConfirm(deps, `tool ${name}`, containerPath, [...args]);
4549
+ if (denied) return denied;
4550
+ }
4551
+ return runGrantedTool(grant, args, cwd);
4574
4552
  }
4575
4553
  async function runBrowserOpenMirror(action, deps) {
4576
4554
  const params = action.params ?? {};
@@ -4623,6 +4601,35 @@ async function lookupCloudBox(boxId) {
4623
4601
  sanctionedBranch: hit.box.cloud?.sanctionedBranch ?? hit.box.cloud?.workspaceBranch
4624
4602
  };
4625
4603
  }
4604
+ async function cacheCpSources(action, prefix, deps) {
4605
+ try {
4606
+ const { sources } = normalizeCpParams("cp.fromHost", action.params);
4607
+ const workspacePath = await boxWorkspacePath(action.boxId);
4608
+ for (const src of sources) {
4609
+ await captureCpCacheEntry(resolveHostPath(workspacePath, src), prefix, deps, src);
4610
+ }
4611
+ } catch (err2) {
4612
+ deps.logger?.(
4613
+ `cp cache: nothing stored for ${action.boxId}: ${err2 instanceof Error ? err2.message : String(err2)}`
4614
+ );
4615
+ }
4616
+ }
4617
+ async function lookupCloudBoxOwner(boxId) {
4618
+ try {
4619
+ const state = await readState();
4620
+ const hit = findBox(boxId, state);
4621
+ if (hit.kind !== "ok") return null;
4622
+ const backendName = hit.box.cloud?.backend ?? hit.box.provider;
4623
+ if (!backendName) return null;
4624
+ return {
4625
+ name: hit.box.name,
4626
+ backendName,
4627
+ autoApproveSafeHostActions: hit.box.autoApproveSafeHostActions
4628
+ };
4629
+ } catch {
4630
+ return null;
4631
+ }
4632
+ }
4626
4633
  async function boxWorkspacePath(boxId) {
4627
4634
  const state = await readState();
4628
4635
  const hit = findBox(boxId, state);
@@ -4870,17 +4877,17 @@ async function resolveHostGitRepo(workspacePath, deps, remoteName) {
4870
4877
  );
4871
4878
  }
4872
4879
  const origin = httpsOriginForScratchPush(rawOrigin);
4873
- const dir = await mkdtemp(join4(tmpdir2(), "agentbox-git-scratch-"));
4880
+ const dir = await mkdtemp2(join23(tmpdir3(), "agentbox-git-scratch-"));
4874
4881
  const init = await execa("git", ["-C", dir, "init", "--quiet"], { reject: false });
4875
4882
  if ((init.exitCode ?? 1) !== 0) {
4876
- await rm4(dir, { recursive: true, force: true });
4883
+ await rm22(dir, { recursive: true, force: true });
4877
4884
  throw new Error(`could not initialize a scratch git repo: ${init.stderr ?? ""}`);
4878
4885
  }
4879
4886
  return {
4880
4887
  dir,
4881
4888
  remote: origin,
4882
4889
  scratch: true,
4883
- cleanup: () => rm4(dir, { recursive: true, force: true })
4890
+ cleanup: () => rm22(dir, { recursive: true, force: true })
4884
4891
  };
4885
4892
  }
4886
4893
  async function runGitRpc(action, deps) {
@@ -4918,8 +4925,8 @@ async function runGitRpc(action, deps) {
4918
4925
  };
4919
4926
  }
4920
4927
  const dest = resolveLandDest(branch, params.as);
4921
- const stageSave = await mkdtemp(join4(tmpdir2(), "agentbox-git-save-"));
4922
- const hostBundleSave = join4(stageSave, "op.bundle");
4928
+ const stageSave = await mkdtemp2(join23(tmpdir3(), "agentbox-git-save-"));
4929
+ const hostBundleSave = join23(stageSave, "op.bundle");
4923
4930
  const remoteBundleSave = "/tmp/agentbox-rpc-save.bundle";
4924
4931
  try {
4925
4932
  const make = await backend.exec(
@@ -4954,7 +4961,7 @@ ${landed.stdout ?? ""}`,
4954
4961
  stderr: landed.stderr ?? ""
4955
4962
  };
4956
4963
  } finally {
4957
- await rm4(stageSave, { recursive: true, force: true });
4964
+ await rm22(stageSave, { recursive: true, force: true });
4958
4965
  await backend.exec(handle, `rm -f ${shellQuote(remoteBundleSave)}`).catch(() => {
4959
4966
  });
4960
4967
  }
@@ -5050,8 +5057,8 @@ ${landed.stdout ?? ""}`,
5050
5057
  `git.${action.method === "git.push" ? "push" : "fetch"}: no host checkout for box ${deps.boxId}; using a scratch repo against ${repo.remote}`
5051
5058
  );
5052
5059
  }
5053
- const stage = await mkdtemp(join4(tmpdir2(), "agentbox-git-rpc-"));
5054
- const hostBundle = join4(stage, "op.bundle");
5060
+ const stage = await mkdtemp2(join23(tmpdir3(), "agentbox-git-rpc-"));
5061
+ const hostBundle = join23(stage, "op.bundle");
5055
5062
  const remoteBundle = "/tmp/agentbox-rpc.bundle";
5056
5063
  try {
5057
5064
  if (action.method === "git.push") {
@@ -5150,7 +5157,7 @@ relay: post-push in-box origin/upstream sync threw: ${err2 instanceof Error ? er
5150
5157
  stderr: sandboxFetch.stderr
5151
5158
  };
5152
5159
  } finally {
5153
- await rm4(stage, { recursive: true, force: true });
5160
+ await rm22(stage, { recursive: true, force: true });
5154
5161
  await repo.cleanup().catch(() => {
5155
5162
  });
5156
5163
  await backend.exec(handle, `rm -f ${shellQuote(remoteBundle)}`).catch(() => {
@@ -5243,14 +5250,562 @@ var HostActionQueue = class {
5243
5250
  return this.map.get(id)?.action;
5244
5251
  }
5245
5252
  };
5246
- var HubNotifier = class {
5247
- listeners = /* @__PURE__ */ new Set();
5248
- /** Register a listener; returns an unsubscribe fn. */
5249
- subscribe(fn) {
5250
- this.listeners.add(fn);
5251
- return () => this.listeners.delete(fn);
5253
+ var DEFAULT_HOST_REACH_TIMEOUT_MS = 6e4;
5254
+ var HostReachQueue = class {
5255
+ map = /* @__PURE__ */ new Map();
5256
+ waiters = /* @__PURE__ */ new Set();
5257
+ subscribers = /* @__PURE__ */ new Set();
5258
+ reachTimeoutMs;
5259
+ graceMs;
5260
+ now;
5261
+ sweepIntervalMs;
5262
+ lastPollAtMs = null;
5263
+ /** pollerId → last poll time, so "did the owner of this copy go away?" is answerable. */
5264
+ pollerSeen = /* @__PURE__ */ new Map();
5265
+ sweepTimer = null;
5266
+ constructor(opts = {}) {
5267
+ this.reachTimeoutMs = opts.reachTimeoutMs ?? DEFAULT_HOST_REACH_TIMEOUT_MS;
5268
+ this.graceMs = opts.graceMs ?? this.reachTimeoutMs;
5269
+ this.now = opts.now ?? (() => Date.now());
5270
+ this.sweepIntervalMs = opts.sweepIntervalMs ?? 5e3;
5252
5271
  }
5253
- /** Fire every listener. A throwing listener never blocks the others. */
5272
+ /** Whether a machine has polled recently enough to be considered present. */
5273
+ reachable() {
5274
+ if (this.lastPollAtMs === null) return false;
5275
+ return this.now() - this.lastPollAtMs <= this.reachTimeoutMs;
5276
+ }
5277
+ /** Epoch ms of the last poll, or null when no machine has ever connected. */
5278
+ lastPollAt() {
5279
+ return this.lastPollAtMs;
5280
+ }
5281
+ /**
5282
+ * Park an action for the user's machine and wait for its result.
5283
+ *
5284
+ * Resolves with `unreachable` rather than rejecting: "no machine there" is a
5285
+ * normal, expected state (a closed laptop), not an error condition.
5286
+ */
5287
+ request(boxId, method, params, opts = {}) {
5288
+ const id = randomUUID22();
5289
+ const action = {
5290
+ id,
5291
+ boxId,
5292
+ method,
5293
+ params,
5294
+ createdAt: new Date(this.now()).toISOString(),
5295
+ ...opts.cachePrefix ? { cachePrefix: opts.cachePrefix } : {}
5296
+ };
5297
+ return new Promise((resolve) => {
5298
+ const pending = { action, settle: resolve, delivered: false };
5299
+ pending.timer = setTimeout(() => {
5300
+ if (this.map.get(id) === pending && !pending.delivered) {
5301
+ this.map.delete(id);
5302
+ resolve({ kind: "unreachable", reason: "never-connected" });
5303
+ }
5304
+ }, this.graceMs);
5305
+ pending.timer.unref?.();
5306
+ this.map.set(id, pending);
5307
+ this.ensureSweep();
5308
+ this.handOff();
5309
+ });
5310
+ }
5311
+ /**
5312
+ * Long-poll entry point: resolve with every undelivered action, waiting up to
5313
+ * `timeoutMs` for one to appear. An empty array means "nothing for you right
5314
+ * now" — the poller simply polls again.
5315
+ *
5316
+ * Calling this marks the machine present, whether or not anything is queued:
5317
+ * an idle poll is exactly how a laptop says "I'm here".
5318
+ */
5319
+ poll(timeoutMs, pollerId) {
5320
+ this.lastPollAtMs = this.now();
5321
+ if (pollerId !== void 0) this.pollerSeen.set(pollerId, this.lastPollAtMs);
5322
+ const ready = this.takeUndelivered(pollerId);
5323
+ if (ready.length > 0) return Promise.resolve(ready);
5324
+ return new Promise((resolve) => {
5325
+ const waiter = {
5326
+ resolve,
5327
+ pollerId,
5328
+ timer: setTimeout(() => {
5329
+ this.waiters.delete(waiter);
5330
+ resolve([]);
5331
+ }, timeoutMs)
5332
+ };
5333
+ this.waiters.add(waiter);
5334
+ });
5335
+ }
5336
+ /**
5337
+ * Register a machine that stays connected (the SSE stream) instead of asking
5338
+ * again after every batch.
5339
+ *
5340
+ * A subscriber is modelled as a **waiter that is never consumed**: the same
5341
+ * eligibility, ownership, decline and orphan rules apply, because they are the
5342
+ * same code path. That is deliberate — those rules took four review rounds to
5343
+ * get right, and a second delivery mechanism with its own copy of them would
5344
+ * be the obvious place for the fifth bug to live.
5345
+ *
5346
+ * Returns an unsubscribe. Call {@link touch} while the connection is alive so
5347
+ * presence does not lapse on a quiet stream.
5348
+ */
5349
+ subscribe(pollerId, deliver) {
5350
+ this.touch(pollerId);
5351
+ const subscriber = { pollerId, deliver };
5352
+ this.subscribers.add(subscriber);
5353
+ const ready = this.takeUndelivered(pollerId);
5354
+ if (ready.length > 0) deliver(ready);
5355
+ return () => {
5356
+ this.subscribers.delete(subscriber);
5357
+ };
5358
+ }
5359
+ /**
5360
+ * Mark a machine present without handing it anything — what an SSE heartbeat
5361
+ * means. Presence is what decides whether a copy waits for that machine or
5362
+ * falls back, so a live-but-quiet stream must keep it fresh.
5363
+ */
5364
+ touch(pollerId) {
5365
+ const now = this.now();
5366
+ this.lastPollAtMs = now;
5367
+ this.pollerSeen.set(pollerId, now);
5368
+ }
5369
+ /**
5370
+ * Settle a parked action with the machine's result. Returns whether it matched.
5371
+ *
5372
+ * `pollerId`, when given, must be the poller the action was handed to: after a
5373
+ * re-offer the previous owner may still be running, and letting its late
5374
+ * result land would settle the box's request with the answer of a machine that
5375
+ * no longer owns the copy.
5376
+ */
5377
+ resolve(id, result, pollerId) {
5378
+ const pending = this.map.get(id);
5379
+ if (!pending) return false;
5380
+ if (pollerId !== void 0 && pending.deliveredTo !== void 0 && pending.deliveredTo !== pollerId) {
5381
+ return false;
5382
+ }
5383
+ this.map.delete(id);
5384
+ if (pending.timer) clearTimeout(pending.timer);
5385
+ pending.settle({ kind: "result", result });
5386
+ return true;
5387
+ }
5388
+ /**
5389
+ * Hand an action back unexecuted, because the machine that took it does not
5390
+ * own that box.
5391
+ *
5392
+ * Settling it instead would be wrong with more than one machine on a hub: the
5393
+ * first poller to see fresh work is not necessarily the one holding the files,
5394
+ * and its "I don't know that box" would answer a question meant for someone
5395
+ * else. Declining returns the action to the pool, and the grace/heartbeat
5396
+ * timers still bound the case where *nobody* claims it.
5397
+ */
5398
+ decline(id, pollerId) {
5399
+ const pending = this.map.get(id);
5400
+ if (!pending) return false;
5401
+ if (pollerId !== void 0 && pending.deliveredTo !== void 0 && pending.deliveredTo !== pollerId) {
5402
+ return false;
5403
+ }
5404
+ pending.delivered = false;
5405
+ pending.deliveredTo = void 0;
5406
+ if (pollerId !== void 0) (pending.declinedBy ??= /* @__PURE__ */ new Set()).add(pollerId);
5407
+ if (pending.timer) clearTimeout(pending.timer);
5408
+ pending.timer = setTimeout(() => {
5409
+ if (this.map.get(id) === pending && !pending.delivered) {
5410
+ this.map.delete(id);
5411
+ pending.settle({ kind: "unreachable", reason: "never-connected" });
5412
+ }
5413
+ }, this.graceMs);
5414
+ pending.timer.unref?.();
5415
+ this.handOff();
5416
+ return true;
5417
+ }
5418
+ size() {
5419
+ return this.map.size;
5420
+ }
5421
+ /** Test/diagnostic: the parked action with this id (undefined once settled). */
5422
+ peek(id) {
5423
+ return this.map.get(id)?.action;
5424
+ }
5425
+ /** Release timers + fail every parked action, so a relay can shut down cleanly. */
5426
+ stop() {
5427
+ if (this.sweepTimer) {
5428
+ clearInterval(this.sweepTimer);
5429
+ this.sweepTimer = null;
5430
+ }
5431
+ for (const waiter of this.waiters) {
5432
+ clearTimeout(waiter.timer);
5433
+ waiter.resolve([]);
5434
+ }
5435
+ this.waiters.clear();
5436
+ this.subscribers.clear();
5437
+ for (const [id, pending] of this.map) {
5438
+ this.map.delete(id);
5439
+ if (pending.timer) clearTimeout(pending.timer);
5440
+ pending.settle({ kind: "unreachable", reason: "went-away" });
5441
+ }
5442
+ }
5443
+ /** Hand any undelivered actions to a waiting poller. */
5444
+ handOff() {
5445
+ for (const sub of [...this.subscribers]) {
5446
+ const ready = this.takeUndelivered(sub.pollerId);
5447
+ if (ready.length === 0) continue;
5448
+ this.pollerSeen.set(sub.pollerId, this.now());
5449
+ sub.deliver(ready);
5450
+ return;
5451
+ }
5452
+ for (const waiter of [...this.waiters]) {
5453
+ const ready = this.takeUndelivered(waiter.pollerId);
5454
+ if (ready.length === 0) continue;
5455
+ if (waiter.pollerId !== void 0) this.pollerSeen.set(waiter.pollerId, this.now());
5456
+ this.waiters.delete(waiter);
5457
+ clearTimeout(waiter.timer);
5458
+ waiter.resolve(ready);
5459
+ return;
5460
+ }
5461
+ }
5462
+ /**
5463
+ * Hand one specific action to any waiting poller eligible for it (i.e. one
5464
+ * that has not refused it). Returns whether it found a taker.
5465
+ */
5466
+ offerToWaiter(pending) {
5467
+ for (const sub of [...this.subscribers]) {
5468
+ if (pending.declinedBy?.has(sub.pollerId)) continue;
5469
+ pending.delivered = true;
5470
+ pending.deliveredTo = sub.pollerId;
5471
+ this.pollerSeen.set(sub.pollerId, this.now());
5472
+ if (pending.timer) {
5473
+ clearTimeout(pending.timer);
5474
+ pending.timer = void 0;
5475
+ }
5476
+ sub.deliver([pending.action, ...this.takeUndelivered(sub.pollerId)]);
5477
+ return true;
5478
+ }
5479
+ for (const waiter of [...this.waiters]) {
5480
+ const pid = waiter.pollerId;
5481
+ if (pid !== void 0 && pending.declinedBy?.has(pid)) continue;
5482
+ pending.delivered = true;
5483
+ pending.deliveredTo = pid;
5484
+ if (pid !== void 0) this.pollerSeen.set(pid, this.now());
5485
+ if (pending.timer) {
5486
+ clearTimeout(pending.timer);
5487
+ pending.timer = void 0;
5488
+ }
5489
+ this.waiters.delete(waiter);
5490
+ clearTimeout(waiter.timer);
5491
+ waiter.resolve([pending.action, ...this.takeUndelivered(pid)]);
5492
+ return true;
5493
+ }
5494
+ return false;
5495
+ }
5496
+ takeUndelivered(pollerId) {
5497
+ const out = [];
5498
+ const now = this.now();
5499
+ for (const pending of this.map.values()) {
5500
+ const owner = pending.deliveredTo;
5501
+ const ownerSeenAt = owner === void 0 ? void 0 : this.pollerSeen.get(owner);
5502
+ const ownerGone = owner !== void 0 && owner !== pollerId && (ownerSeenAt === void 0 || now - ownerSeenAt > this.reachTimeoutMs);
5503
+ const orphaned = pending.delivered && pollerId !== void 0 && ownerGone;
5504
+ if (pending.delivered && !orphaned) continue;
5505
+ if (pollerId !== void 0 && pending.declinedBy?.has(pollerId)) continue;
5506
+ pending.delivered = true;
5507
+ pending.deliveredTo = pollerId;
5508
+ if (pending.timer) {
5509
+ clearTimeout(pending.timer);
5510
+ pending.timer = void 0;
5511
+ }
5512
+ out.push(pending.action);
5513
+ }
5514
+ return out;
5515
+ }
5516
+ ensureSweep() {
5517
+ if (this.sweepTimer) return;
5518
+ this.sweepTimer = setInterval(() => this.sweep(), this.sweepIntervalMs);
5519
+ this.sweepTimer.unref?.();
5520
+ }
5521
+ /**
5522
+ * Fail delivered-but-unanswered actions once the machine that took them has
5523
+ * stopped polling. Without this a laptop that sleeps mid-copy leaves the box
5524
+ * blocked forever on an RPC nobody will ever answer.
5525
+ */
5526
+ sweep() {
5527
+ if (this.map.size === 0) {
5528
+ if (this.sweepTimer) {
5529
+ clearInterval(this.sweepTimer);
5530
+ this.sweepTimer = null;
5531
+ }
5532
+ return;
5533
+ }
5534
+ const now = this.now();
5535
+ for (const [id, pending] of this.map) {
5536
+ if (!pending.delivered) continue;
5537
+ const owner = pending.deliveredTo;
5538
+ const seenAt = owner === void 0 ? this.lastPollAtMs : this.pollerSeen.get(owner) ?? null;
5539
+ if (seenAt !== null && now - seenAt <= this.reachTimeoutMs) continue;
5540
+ pending.delivered = false;
5541
+ pending.deliveredTo = void 0;
5542
+ if (this.offerToWaiter(pending)) continue;
5543
+ this.map.delete(id);
5544
+ pending.settle({ kind: "unreachable", reason: "went-away" });
5545
+ }
5546
+ }
5547
+ };
5548
+ var UNTAR_TIMEOUT_MS = 12e4;
5549
+ var CP_TIMEOUT_MS = 3e5;
5550
+ async function lookupCpCache(sources, deps) {
5551
+ const entries = [];
5552
+ const missing = [];
5553
+ if (!deps.custody) return { entries, missing: [...sources] };
5554
+ for (const sourcePath of sources) {
5555
+ const metaRaw = await deps.custody.get(cpCacheMetaPath(deps.cachePrefix, sourcePath));
5556
+ const meta = metaRaw ? parseCpCacheMeta(metaRaw.data.toString("utf8")) : null;
5557
+ const tar = await deps.custody.stat(cpCacheTarPath(deps.cachePrefix, sourcePath));
5558
+ if (!meta || !tar) missing.push(sourcePath);
5559
+ else entries.push({ sourcePath, meta });
5560
+ }
5561
+ return { entries, missing };
5562
+ }
5563
+ function describeCpCacheEntries(lookup, now = Date.now()) {
5564
+ return lookup.entries.map(
5565
+ // The path it was captured FROM on the owning machine, not the box's
5566
+ // spelling of it: the person approving is being asked about their own disk.
5567
+ (e) => ` ${e.meta.sourcePath} (${describeCacheAge(e.meta.capturedAt, now)})`
5568
+ ).join("\n");
5569
+ }
5570
+ async function serveCpFromCache(params, resolved, deps) {
5571
+ const log = deps.log ?? (() => {
5572
+ });
5573
+ if (!deps.cliEntry) {
5574
+ return {
5575
+ exitCode: 64,
5576
+ stdout: "",
5577
+ stderr: "relay: AGENTBOX_CLI_ENTRY not set; cannot deliver the cached copy\n"
5578
+ };
5579
+ }
5580
+ const { dest } = normalizeCpParams("cp.fromHost", params);
5581
+ const lookup = await lookupCpCache(resolved, deps);
5582
+ if (lookup.missing.length > 0 || !deps.custody) {
5583
+ return { exitCode: 69, stdout: "", stderr: "" };
5584
+ }
5585
+ let workDir;
5586
+ try {
5587
+ const dir = await mkdtemp3(join32(tmpdir4(), "agentbox-cp-serve-"));
5588
+ workDir = dir;
5589
+ const names = [];
5590
+ for (const entry of lookup.entries) {
5591
+ const found = await deps.custody.getStream(
5592
+ cpCacheTarPath(deps.cachePrefix, entry.sourcePath)
5593
+ );
5594
+ if (!found) return { exitCode: 69, stdout: "", stderr: "" };
5595
+ const tarPath = join32(dir, `${names.length.toString()}.tar`);
5596
+ await pipeline2(found.data, createWriteStream2(tarPath));
5597
+ await run2("tar", ["-xf", tarPath, "-C", dir], UNTAR_TIMEOUT_MS);
5598
+ await rm32(tarPath, { force: true });
5599
+ names.push(basename3(entry.sourcePath));
5600
+ }
5601
+ const staged = names.map((n) => join32(dir, n));
5602
+ const absent = staged.filter((p) => !existsSync32(p));
5603
+ if (absent.length > 0) {
5604
+ return {
5605
+ exitCode: 1,
5606
+ stdout: "",
5607
+ stderr: `the hub's cached copy is unusable: ${absent.join(", ")} missing after unpacking
5608
+ `
5609
+ };
5610
+ }
5611
+ const argv = [deps.cliEntry, "cp", ...staged, `${deps.boxName}:${dest}`, "--yes"];
5612
+ const out = await runCapture(process.execPath, argv, dir, CP_TIMEOUT_MS);
5613
+ if (out.exitCode !== 0) return out;
5614
+ if (!/copied to /.test(out.stdout)) {
5615
+ log(
5616
+ `cp cache: the copy into ${deps.boxName} reported success but said nothing was copied (stdout: ${JSON.stringify(out.stdout.slice(0, 300))}, stderr: ${JSON.stringify(out.stderr.slice(0, 300))})`
5617
+ );
5618
+ return {
5619
+ exitCode: 1,
5620
+ stdout: "",
5621
+ stderr: `the hub had a cached copy but could not deliver it into this box.
5622
+ ${out.stderr.trim()}
5623
+ `
5624
+ };
5625
+ }
5626
+ const age = describeCpCacheEntries(lookup);
5627
+ log(`cp cache: served ${String(lookup.entries.length)} entr(y|ies) for ${deps.boxName}`);
5628
+ return {
5629
+ exitCode: 0,
5630
+ // The provenance goes in stdout, where the agent that asked will read it —
5631
+ // a cached file that looks live is worse than no file.
5632
+ stdout: `${out.stdout.trimEnd()}
5633
+ NOTE: served from the hub's cache \u2014 the machine holding these files is offline.
5634
+ ${age}
5635
+ `,
5636
+ stderr: out.stderr
5637
+ };
5638
+ } catch (err2) {
5639
+ return {
5640
+ exitCode: 1,
5641
+ stdout: "",
5642
+ stderr: `serving the cached copy failed: ${err2 instanceof Error ? err2.message : String(err2)}
5643
+ `
5644
+ };
5645
+ } finally {
5646
+ if (workDir) await rm32(workDir, { recursive: true, force: true }).catch(() => {
5647
+ });
5648
+ }
5649
+ }
5650
+ function run2(bin, args, timeout) {
5651
+ return new Promise((resolve, reject) => {
5652
+ execFile2(bin, args, { timeout }, (err2) => err2 ? reject(err2) : resolve());
5653
+ });
5654
+ }
5655
+ function runCapture(bin, args, cwd, timeout) {
5656
+ return new Promise((resolve) => {
5657
+ execFile2(bin, args, { cwd, timeout }, (err2, stdout, stderr) => {
5658
+ const code = err2 && typeof err2.code === "number" ? err2.code : err2 ? 1 : 0;
5659
+ resolve({ exitCode: code, stdout: stdout || "", stderr: stderr || "" });
5660
+ });
5661
+ });
5662
+ }
5663
+ var PULL_TIMEOUT_MS = 3e5;
5664
+ var TAR_TIMEOUT_MS2 = 12e4;
5665
+ function cpOutboxPrefix(opts) {
5666
+ const slug = (opts.projectSlug ?? "").trim();
5667
+ return slug.length > 0 ? `projects/${slug}/cp-out` : `boxes/${opts.boxId}/cp-out`;
5668
+ }
5669
+ function isCpOutboxMetaPath(path) {
5670
+ return /\/cp-out\/[A-Za-z0-9-]+\.json$/.test(path);
5671
+ }
5672
+ async function listCpOutbox(custody) {
5673
+ const out = [];
5674
+ for (const entry of await custody.list()) {
5675
+ if (!isCpOutboxMetaPath(entry.path)) continue;
5676
+ const found = await custody.get(entry.path);
5677
+ if (!found) continue;
5678
+ try {
5679
+ const meta = JSON.parse(found.data.toString("utf8"));
5680
+ if (!meta || typeof meta.id !== "string" || typeof meta.dest !== "string") continue;
5681
+ out.push({
5682
+ meta,
5683
+ metaPath: entry.path,
5684
+ tarPath: entry.path.replace(/\.json$/, ".tar")
5685
+ });
5686
+ } catch {
5687
+ }
5688
+ }
5689
+ return out.sort((a, b) => a.meta.createdAt < b.meta.createdAt ? 1 : -1);
5690
+ }
5691
+ async function removeCpOutboxItem(custody, item) {
5692
+ await custody.delete(item.tarPath).catch(() => false);
5693
+ await custody.delete(item.metaPath).catch(() => false);
5694
+ }
5695
+ async function parkCpOutbox(sources, dest, deps) {
5696
+ const log = deps.log ?? (() => {
5697
+ });
5698
+ if (!deps.custody || !deps.cliEntry) return null;
5699
+ let workDir;
5700
+ try {
5701
+ const dir = await mkdtemp4(join42(tmpdir5(), "agentbox-cp-outbox-"));
5702
+ workDir = dir;
5703
+ const stage = join42(dir, "payload");
5704
+ await run3("mkdir", ["-p", stage], TAR_TIMEOUT_MS2);
5705
+ for (const src of sources) {
5706
+ await runNode(
5707
+ [deps.cliEntry, "cp", `${deps.boxName}:${src}`, stage, "--yes"],
5708
+ dir,
5709
+ PULL_TIMEOUT_MS
5710
+ );
5711
+ }
5712
+ const names = await readdir3(stage);
5713
+ if (names.length === 0) return null;
5714
+ const tarPath = join42(dir, "outbox.tar");
5715
+ await run3("tar", ["-cf", tarPath, "-C", stage, ...names], TAR_TIMEOUT_MS2);
5716
+ const info = await stat22(tarPath);
5717
+ if (info.size > deps.maxBytes) {
5718
+ log(`cp outbox: ${String(info.size)} bytes exceeds the ${String(deps.maxBytes)}-byte limit`);
5719
+ return null;
5720
+ }
5721
+ const id = randomUUID32();
5722
+ const meta = {
5723
+ id,
5724
+ boxId: deps.boxId,
5725
+ boxName: deps.boxName,
5726
+ dest,
5727
+ sources,
5728
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5729
+ size: info.size
5730
+ };
5731
+ await deps.custody.putStream(`${deps.prefix}/${id}.tar`, createReadStream22(tarPath), {
5732
+ maxBytes: deps.maxBytes
5733
+ });
5734
+ await deps.custody.put(`${deps.prefix}/${id}.json`, Buffer.from(JSON.stringify(meta), "utf8"));
5735
+ log(`cp outbox: parked ${String(names.length)} path(s) from ${deps.boxName} for ${dest}`);
5736
+ return {
5737
+ // 75 = EX_TEMPFAIL: accepted, not yet delivered. A zero here would tell an
5738
+ // agent the file is on the user's disk when it is still in transit.
5739
+ exitCode: 75,
5740
+ stdout: "",
5741
+ stderr: `the machine these files are addressed to is offline, so they are parked on the hub.
5742
+ It will land them at ${dest} \u2014 behind the usual approval \u2014 the next time it connects.
5743
+ `
5744
+ };
5745
+ } catch (err2) {
5746
+ log(`cp outbox: could not park: ${err2 instanceof Error ? err2.message : String(err2)}`);
5747
+ return null;
5748
+ } finally {
5749
+ if (workDir) await rm42(workDir, { recursive: true, force: true }).catch(() => {
5750
+ });
5751
+ }
5752
+ }
5753
+ async function landCpOutboxTar(tarFile, destAbs, opts) {
5754
+ const asDirectory = opts.destEndsWithSlash || existsSync4(destAbs) && (await stat22(destAbs)).isDirectory();
5755
+ if (asDirectory) {
5756
+ await run3("mkdir", ["-p", destAbs], TAR_TIMEOUT_MS2);
5757
+ await run3("tar", ["-xf", tarFile, "-C", destAbs], TAR_TIMEOUT_MS2);
5758
+ return;
5759
+ }
5760
+ await run3("mkdir", ["-p", dirname23(destAbs)], TAR_TIMEOUT_MS2);
5761
+ const staging = await mkdtemp4(join42(dirname23(destAbs), ".agentbox-cp-"));
5762
+ try {
5763
+ await run3("tar", ["-xf", tarFile, "-C", staging], TAR_TIMEOUT_MS2);
5764
+ const members = await readdir3(staging);
5765
+ if (members.length === 1) {
5766
+ if (existsSync4(destAbs) && (await stat22(destAbs)).isDirectory()) {
5767
+ await rm42(destAbs, { recursive: true, force: true });
5768
+ }
5769
+ await rename4(join42(staging, members[0]), destAbs);
5770
+ return;
5771
+ }
5772
+ await run3("mkdir", ["-p", destAbs], TAR_TIMEOUT_MS2);
5773
+ for (const m of members) {
5774
+ const target = join42(destAbs, m);
5775
+ if (existsSync4(target) && (await stat22(target)).isDirectory()) {
5776
+ await rm42(target, { recursive: true, force: true });
5777
+ }
5778
+ await rename4(join42(staging, m), target);
5779
+ }
5780
+ } finally {
5781
+ await rm42(staging, { recursive: true, force: true }).catch(() => {
5782
+ });
5783
+ }
5784
+ }
5785
+ async function stageOutboxTar(data) {
5786
+ const dir = await mkdtemp4(join42(tmpdir5(), "agentbox-cp-land-"));
5787
+ const tarPath = join42(dir, "payload.tar");
5788
+ await pipeline22(data, createWriteStream22(tarPath));
5789
+ return { dir, tarPath };
5790
+ }
5791
+ function run3(bin, args, timeout) {
5792
+ return new Promise((resolve, reject) => {
5793
+ execFile3(bin, args, { timeout }, (err2) => err2 ? reject(err2) : resolve());
5794
+ });
5795
+ }
5796
+ function runNode(argv, cwd, timeout) {
5797
+ return new Promise((resolve, reject) => {
5798
+ execFile3(process.execPath, argv, { cwd, timeout }, (err2) => err2 ? reject(err2) : resolve());
5799
+ });
5800
+ }
5801
+ var HubNotifier = class {
5802
+ listeners = /* @__PURE__ */ new Set();
5803
+ /** Register a listener; returns an unsubscribe fn. */
5804
+ subscribe(fn) {
5805
+ this.listeners.add(fn);
5806
+ return () => this.listeners.delete(fn);
5807
+ }
5808
+ /** Fire every listener. A throwing listener never blocks the others. */
5254
5809
  notify() {
5255
5810
  for (const fn of this.listeners) {
5256
5811
  try {
@@ -5282,7 +5837,7 @@ var BoxNotices = class {
5282
5837
  this.entries.delete(id);
5283
5838
  }
5284
5839
  }
5285
- const ev = { id: randomUUID22(), kind, message };
5840
+ const ev = { id: randomUUID42(), kind, message };
5286
5841
  const ttl = typeof ttlMs === "number" && ttlMs > 0 ? ttlMs : DEFAULT_NOTICE_TTL_MS;
5287
5842
  const timer = setTimeout(() => {
5288
5843
  if (this.entries.delete(ev.id)) {
@@ -5336,7 +5891,7 @@ async function readCreateJobLog(id, offset) {
5336
5891
  const path = queueLogPath(id);
5337
5892
  let size;
5338
5893
  try {
5339
- size = (await stat2(path)).size;
5894
+ size = (await stat3(path)).size;
5340
5895
  } catch {
5341
5896
  return { lines: [], offset: from };
5342
5897
  }
@@ -5479,6 +6034,8 @@ var CP_RPC_TIMEOUT_MS = 3e5;
5479
6034
  var BROWSER_OPEN_RPC_TIMEOUT_MS = 15e3;
5480
6035
  var BROWSER_OPEN_PROMPT_TTL_MS = 25e3;
5481
6036
  var SSE_HEARTBEAT_MS = 15e3;
6037
+ var DEFAULT_HOSTREACH_WAIT_MS = 25e3;
6038
+ var MAX_HOSTREACH_WAIT_MS = 6e4;
5482
6039
  function send(res, status, body, contentType = "application/json") {
5483
6040
  const text3 = body == null ? "" : typeof body === "string" ? body : JSON.stringify(body);
5484
6041
  res.statusCode = status;
@@ -5580,6 +6137,9 @@ function createRelayServer(opts) {
5580
6137
  const host = opts.host ?? "0.0.0.0";
5581
6138
  const mode = opts.mode ?? "host";
5582
6139
  const hostActions = mode === "box" ? new HostActionQueue() : null;
6140
+ const hostReach = opts.controlPlane === true ? new HostReachQueue(
6141
+ typeof opts.hostReachTimeoutMs === "number" && opts.hostReachTimeoutMs > 0 ? { reachTimeoutMs: opts.hostReachTimeoutMs } : {}
6142
+ ) : null;
5583
6143
  const credentialsFanout = mode === "box" ? null : new CredentialsFanout({ log, custody: opts.custody ?? null });
5584
6144
  if (mode === "box" && (!opts.bridgeToken || opts.bridgeToken.length === 0)) {
5585
6145
  throw new Error("relay mode='box' requires a non-empty bridgeToken");
@@ -5597,7 +6157,7 @@ function createRelayServer(opts) {
5597
6157
  let pollers = null;
5598
6158
  async function getPollers() {
5599
6159
  if (!pollers) {
5600
- const mod = await import("./cloud-poller-SUNA6ZQC-7M5LJHHE.js");
6160
+ const mod = await import("./cloud-poller-QJRZXB4W-LJ2BRB3L.js");
5601
6161
  pollers = new mod.CloudBoxPollers();
5602
6162
  }
5603
6163
  return pollers;
@@ -5715,6 +6275,130 @@ function createRelayServer(opts) {
5715
6275
  return;
5716
6276
  }
5717
6277
  }
6278
+ if (url.pathname.startsWith("/admin/hostreach")) {
6279
+ if (!hostReach) {
6280
+ send(res, 404, { error: "host-reach is served only by a control box" });
6281
+ return;
6282
+ }
6283
+ if (custodyAdminToken.length === 0) {
6284
+ send(res, 503, { error: "host-reach not configured: admin token unset" });
6285
+ return;
6286
+ }
6287
+ if (!timingSafeEqualStr5(bearerToken(req) ?? "", custodyAdminToken)) {
6288
+ send(res, 401, { error: "invalid admin token" });
6289
+ return;
6290
+ }
6291
+ if (route === "GET /admin/hostreach/events") {
6292
+ const pollerId = url.searchParams.get("poller") ?? "";
6293
+ if (pollerId.length === 0) {
6294
+ send(res, 400, { error: "missing poller query param" });
6295
+ return;
6296
+ }
6297
+ res.statusCode = 200;
6298
+ res.setHeader("Content-Type", "text/event-stream");
6299
+ res.setHeader("Cache-Control", "no-cache");
6300
+ res.setHeader("Connection", "keep-alive");
6301
+ res.setHeader("X-Accel-Buffering", "no");
6302
+ if (typeof res.flushHeaders === "function") res.flushHeaders();
6303
+ res.write(": connected\n\n");
6304
+ const unsubscribe = hostReach.subscribe(pollerId, (actions) => {
6305
+ try {
6306
+ for (const action of actions) {
6307
+ res.write(`event: action
6308
+ data: ${JSON.stringify(action)}
6309
+
6310
+ `);
6311
+ }
6312
+ } catch {
6313
+ }
6314
+ });
6315
+ const heartbeat = setInterval(() => {
6316
+ try {
6317
+ res.write(`event: ping
6318
+ data: {"ts":"${(/* @__PURE__ */ new Date()).toISOString()}"}
6319
+
6320
+ `);
6321
+ hostReach.touch(pollerId);
6322
+ } catch {
6323
+ }
6324
+ }, SSE_HEARTBEAT_MS);
6325
+ if (typeof heartbeat.unref === "function") heartbeat.unref();
6326
+ res.on("close", () => {
6327
+ clearInterval(heartbeat);
6328
+ unsubscribe();
6329
+ log(`host-reach: machine ${pollerId.slice(0, 8)} disconnected`);
6330
+ });
6331
+ log(`host-reach: machine ${pollerId.slice(0, 8)} streaming`);
6332
+ return;
6333
+ }
6334
+ if (route === "GET /admin/hostreach/poll") {
6335
+ const requested = Number.parseInt(url.searchParams.get("wait") ?? "", 10);
6336
+ const waitMs = Number.isFinite(requested) ? Math.min(Math.max(requested, 0), MAX_HOSTREACH_WAIT_MS) : DEFAULT_HOSTREACH_WAIT_MS;
6337
+ const pollerId = url.searchParams.get("poller") ?? void 0;
6338
+ const actions = await hostReach.poll(waitMs, pollerId);
6339
+ send(res, 200, { actions });
6340
+ return;
6341
+ }
6342
+ if (route === "GET /admin/hostreach/outbox") {
6343
+ const items = custody ? await listCpOutbox(custody) : [];
6344
+ send(res, 200, { items });
6345
+ return;
6346
+ }
6347
+ if (req.method === "DELETE" && url.pathname.startsWith("/admin/hostreach/outbox/")) {
6348
+ const id = decodeURIComponent(url.pathname.slice("/admin/hostreach/outbox/".length));
6349
+ const items = custody ? await listCpOutbox(custody) : [];
6350
+ const hit = items.find((i) => i.meta.id === id);
6351
+ if (!hit || !custody) {
6352
+ send(res, 404, { error: "no such parked copy" });
6353
+ return;
6354
+ }
6355
+ await removeCpOutboxItem(custody, hit);
6356
+ log(`cp outbox: ${id} landed and cleared`);
6357
+ send(res, 204, null);
6358
+ return;
6359
+ }
6360
+ if (route === "POST /admin/hostreach/decline") {
6361
+ const body = await readJsonBody(req);
6362
+ if (!body || typeof body.id !== "string" || body.id.length === 0) {
6363
+ send(res, 400, { error: "expected {id}" });
6364
+ return;
6365
+ }
6366
+ const ok2 = hostReach.decline(
6367
+ body.id,
6368
+ typeof body.poller === "string" ? body.poller : void 0
6369
+ );
6370
+ send(
6371
+ res,
6372
+ ok2 ? 204 : 404,
6373
+ ok2 ? null : { error: "no parked action with that id for this machine" }
6374
+ );
6375
+ return;
6376
+ }
6377
+ if (route === "POST /admin/hostreach/result") {
6378
+ const body = await readJsonBody(req);
6379
+ if (!body || typeof body.id !== "string" || body.id.length === 0 || typeof body.exitCode !== "number") {
6380
+ send(res, 400, { error: "expected {id, exitCode, stdout, stderr}" });
6381
+ return;
6382
+ }
6383
+ const ok2 = hostReach.resolve(
6384
+ body.id,
6385
+ {
6386
+ exitCode: body.exitCode,
6387
+ stdout: typeof body.stdout === "string" ? body.stdout : "",
6388
+ stderr: typeof body.stderr === "string" ? body.stderr : ""
6389
+ },
6390
+ typeof body.poller === "string" ? body.poller : void 0
6391
+ );
6392
+ if (!ok2) {
6393
+ send(res, 404, { error: "no parked action with that id for this machine" });
6394
+ return;
6395
+ }
6396
+ send(res, 204, null);
6397
+ return;
6398
+ }
6399
+ send(res, 404, { error: "not found", route });
6400
+ return;
6401
+ }
5718
6402
  if (url.pathname === "/admin/custody" || url.pathname.startsWith("/admin/custody/")) {
5719
6403
  const bodyText = req.method === "PUT" || req.method === "POST" ? await readRawBody(req, custodyMaxBodyBytes) : "";
5720
6404
  const custodyRes = await handleCustodyRequest(
@@ -5943,21 +6627,78 @@ function createRelayServer(opts) {
5943
6627
  send(res, result.exitCode === 0 ? 200 : 500, result);
5944
6628
  return;
5945
6629
  }
5946
- if (body.method === "cp.toHost" || body.method === "cp.fromHost") {
5947
- const params = body.params;
5948
- let norm;
5949
- try {
5950
- norm = normalizeCpParams(body.method, params);
5951
- } catch (err2) {
5952
- send(res, 400, { error: err2 instanceof Error ? err2.message : String(err2) });
6630
+ if (hostReach && reg.kind === "cloud" && isHostReachMethod(body.method) && !await boxWorkspaceExistsHere(reg.boxId)) {
6631
+ const cachePrefix = cpCachePrefix({
6632
+ projectSlug: reg.originUrl ? projectSlugFromOriginUrl(reg.originUrl) ?? void 0 : void 0,
6633
+ boxId: reg.boxId
6634
+ });
6635
+ const outcome = await hostReach.request(reg.boxId, body.method, body.params, {
6636
+ cachePrefix
6637
+ });
6638
+ if (outcome.kind === "result") {
6639
+ send(res, outcome.result.exitCode === 0 ? 200 : 500, outcome.result);
5953
6640
  return;
5954
6641
  }
5955
- if (params.exclude !== void 0 && (!Array.isArray(params.exclude) || params.exclude.some((p) => typeof p !== "string"))) {
5956
- send(res, 400, { error: "cp.* exclude must be an array of strings" });
6642
+ log(`${body.method} for ${reg.boxId}: host unreachable (${outcome.reason})`);
6643
+ if (body.method.startsWith("tool.")) {
6644
+ send(res, 500, {
6645
+ exitCode: 69,
6646
+ stdout: "",
6647
+ stderr: toolUnreachableMessage(reg.name, outcome.reason)
6648
+ });
5957
6649
  return;
5958
6650
  }
5959
- const direction = body.method === "cp.toHost" ? "box -> host" : "host -> box";
5960
- const workspacePath = await boxWorkspacePath(reg.boxId);
6651
+ if (body.method === "cp.fromHost") {
6652
+ const cached = await serveCachedCp({
6653
+ params: body.params,
6654
+ reg,
6655
+ custody,
6656
+ cachePrefix,
6657
+ prompts,
6658
+ subscribers,
6659
+ log
6660
+ });
6661
+ if (cached) {
6662
+ send(res, cached.exitCode === 0 ? 200 : 500, cached);
6663
+ return;
6664
+ }
6665
+ } else {
6666
+ const parked = await parkOutboundCp({
6667
+ params: body.params,
6668
+ reg,
6669
+ custody,
6670
+ maxBytes: custodyMaxBlobBytes,
6671
+ log
6672
+ });
6673
+ if (parked) {
6674
+ send(res, parked.exitCode === 0 ? 200 : 500, parked);
6675
+ return;
6676
+ }
6677
+ }
6678
+ send(res, 500, {
6679
+ exitCode: 69,
6680
+ stdout: "",
6681
+ stderr: cpUnreachableMessage(body.method, reg.name, outcome.reason, {
6682
+ cacheMiss: body.method === "cp.fromHost"
6683
+ })
6684
+ });
6685
+ return;
6686
+ }
6687
+ if (body.method === "cp.toHost" || body.method === "cp.fromHost") {
6688
+ const params = body.params;
6689
+ let norm;
6690
+ try {
6691
+ norm = normalizeCpParams(body.method, params);
6692
+ } catch (err2) {
6693
+ send(res, 400, { error: err2 instanceof Error ? err2.message : String(err2) });
6694
+ return;
6695
+ }
6696
+ if (params.exclude !== void 0 && (!Array.isArray(params.exclude) || params.exclude.some((p) => typeof p !== "string"))) {
6697
+ send(res, 400, { error: "cp.* exclude must be an array of strings" });
6698
+ return;
6699
+ }
6700
+ const direction = body.method === "cp.toHost" ? "box -> host" : "host -> box";
6701
+ const workspacePath = await boxWorkspacePath(reg.boxId);
5961
6702
  const {
5962
6703
  argv: cpArgs,
5963
6704
  detail,
@@ -6016,14 +6757,8 @@ function createRelayServer(opts) {
6016
6757
  send(res, status, result);
6017
6758
  return;
6018
6759
  }
6019
- if (body.method.startsWith("gh.pr.")) {
6020
- const op = body.method.slice("gh.pr.".length);
6021
- if (!isGhPrOp(op)) {
6022
- send(res, 400, { error: `unknown gh.pr.* op: ${op}` });
6023
- return;
6024
- }
6025
- const result = await handleGhPrRpc(
6026
- op,
6760
+ if (body.method === "gh.exec") {
6761
+ const result = await handleGhExecRpc(
6027
6762
  reg,
6028
6763
  body.params,
6029
6764
  prompts,
@@ -6034,37 +6769,13 @@ function createRelayServer(opts) {
6034
6769
  send(res, status, result);
6035
6770
  return;
6036
6771
  }
6037
- if (body.method.startsWith("gh.run.")) {
6038
- const op = body.method.slice("gh.run.".length);
6039
- if (!isGhRunOp(op)) {
6040
- send(res, 400, { error: `unknown gh.run.* op: ${op}` });
6041
- return;
6042
- }
6043
- const result = await handleGhRunRpc(
6044
- op,
6045
- reg,
6046
- body.params,
6047
- prompts,
6048
- subscribers
6049
- );
6050
- const status = result.exitCode === 0 ? 200 : 500;
6051
- send(res, status, result);
6052
- return;
6053
- }
6054
- if (body.method === "gh.api") {
6055
- const result = await handleGhApiRpc(reg, body.params);
6056
- const status = result.exitCode === 0 ? 200 : 500;
6057
- send(res, status, result);
6058
- return;
6059
- }
6060
- if (body.method.startsWith("integration.")) {
6061
- const result = await handleIntegrationRpc(
6772
+ if (body.method.startsWith("tool.")) {
6773
+ const result = await handleToolRpc(
6062
6774
  body.method,
6063
6775
  reg,
6064
6776
  body.params,
6065
6777
  prompts,
6066
- subscribers,
6067
- hostInitiatedTokens
6778
+ subscribers
6068
6779
  );
6069
6780
  const status = result.exitCode === 0 ? 200 : 500;
6070
6781
  send(res, status, result);
@@ -6329,6 +7040,16 @@ function createRelayServer(opts) {
6329
7040
  send(res, 204, null);
6330
7041
  return;
6331
7042
  }
7043
+ if (route === "POST /admin/stop-poller") {
7044
+ const body = await readJsonBody(req);
7045
+ if (!body || typeof body.boxId !== "string" || body.boxId.length === 0) {
7046
+ send(res, 400, { error: "expected {boxId}" });
7047
+ return;
7048
+ }
7049
+ if (pollers) await pollers.stop(body.boxId);
7050
+ send(res, 204, null);
7051
+ return;
7052
+ }
6332
7053
  if (route === "GET /admin/box-status") {
6333
7054
  const box = url.searchParams.get("box") ?? "";
6334
7055
  const status = box ? await store.getStatus(box) : void 0;
@@ -6542,6 +7263,7 @@ data: {"ts":"${(/* @__PURE__ */ new Date()).toISOString()}"}
6542
7263
  hubNotifier,
6543
7264
  custody,
6544
7265
  hostActions: hostActions ?? void 0,
7266
+ hostReach: hostReach ?? void 0,
6545
7267
  url: `http://${host}:${String(opts.port)}`,
6546
7268
  setQueuePoke: (fn) => {
6547
7269
  queuePoke = fn;
@@ -6549,8 +7271,12 @@ data: {"ts":"${(/* @__PURE__ */ new Date()).toISOString()}"}
6549
7271
  pokeQueue: () => {
6550
7272
  queuePoke?.();
6551
7273
  },
7274
+ stopCloudPoller: async (boxId) => {
7275
+ if (pollers) await pollers.stop(boxId);
7276
+ },
6552
7277
  close: async () => {
6553
7278
  if (pollers) await pollers.stopAll();
7279
+ hostReach?.stop();
6554
7280
  await new Promise((resolve, reject) => {
6555
7281
  server.close((err2) => {
6556
7282
  if (err2) reject(err2);
@@ -6639,11 +7365,24 @@ async function handleGitRpc(reg, method, params) {
6639
7365
  }
6640
7366
  return result;
6641
7367
  }
6642
- async function handleGhPrRpc(op, reg, params, prompts, subscribers, hostInitiatedTokens) {
6643
- const mergeBypass = refuseMergeBypass(op);
6644
- if (mergeBypass) return mergeBypass;
6645
- const checkoutOptIn = refuseCheckoutByDefault(op);
6646
- if (checkoutOptIn) return checkoutOptIn;
7368
+ async function handleGhExecRpc(reg, params, prompts, subscribers, hostInitiatedTokens) {
7369
+ const args = Array.isArray(params?.args) ? params.args.filter((a) => typeof a === "string") : [];
7370
+ if (args.length === 0) {
7371
+ return { exitCode: 64, stdout: "", stderr: "gh: no arguments\n" };
7372
+ }
7373
+ const blocked = refuseBlockedGhCall(args);
7374
+ if (blocked) return blocked;
7375
+ const verb = ghVerbArgv(args);
7376
+ const family = verb[0] ?? "";
7377
+ const op = verb[1] ?? "";
7378
+ if (family === "pr") {
7379
+ const checkoutOptIn = refuseCheckoutByDefault(op);
7380
+ if (checkoutOptIn) return checkoutOptIn;
7381
+ }
7382
+ if (family === "api") {
7383
+ const inputRefusal = refuseGhApiInput(args);
7384
+ if (inputRefusal) return inputRefusal;
7385
+ }
6647
7386
  const containerPath = params?.path ?? "/workspace";
6648
7387
  const worktree = resolveWorktree(reg, containerPath);
6649
7388
  if (!worktree) {
@@ -6653,105 +7392,63 @@ async function handleGhPrRpc(op, reg, params, prompts, subscribers, hostInitiate
6653
7392
  stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`
6654
7393
  };
6655
7394
  }
6656
- const ghReady = await assertGhReady();
6657
- if (ghReady) return ghReady;
6658
- const args = Array.isArray(params?.args) ? params.args.filter((a) => typeof a === "string") : [];
6659
- if (op === "checkout") {
7395
+ const ghRevoked = await refuseIfGhDisabled(worktree.hostMainRepo);
7396
+ if (ghRevoked) return ghRevoked;
7397
+ const ghTarget = await resolveGhTarget(reg.originUrl);
7398
+ if (ghTarget.error) return ghTarget.error;
7399
+ if (family === "pr" && op === "checkout") {
6660
7400
  const branches = (reg.worktrees ?? []).flatMap(
6661
7401
  (w) => w.sanctionedBranch && w.sanctionedBranch !== w.branch ? [w.branch, w.sanctionedBranch] : [w.branch]
6662
7402
  );
6663
7403
  const guard = await checkoutGuards(worktree.hostMainRepo, branches);
6664
7404
  if (guard) return guard;
6665
7405
  }
6666
- const tokenClaimedGh = typeof params?.hostInitiated === "string";
6667
- const incomingHashGh = hashRpcParams(params);
6668
- const hostInitiatedOk = !GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGh && hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, `gh.pr.${op}`, incomingHashGh);
6669
- if (!GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGh && !hostInitiatedOk) {
7406
+ const tokenClaimed = typeof params?.hostInitiated === "string";
7407
+ const hostInitiatedOk = tokenClaimed && hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, "gh.exec", hashRpcParams(params));
7408
+ if (tokenClaimed && !hostInitiatedOk) {
6670
7409
  return {
6671
7410
  exitCode: 10,
6672
7411
  stdout: "",
6673
7412
  stderr: "host-initiated token rejected: invalid, expired, or bound to different params\n"
6674
7413
  };
6675
7414
  }
6676
- const ghSafeAuto = GH_PR_SAFE_AUTO_APPROVE_OPS.has(op) && reg.autoApproveSafeHostActions !== false && !prCreateHasExplicitHead(op, args);
6677
- if (ghSafeAuto && !hostInitiatedOk) {
6678
- prompts.noteAutoApprove(
6679
- reg.boxId,
6680
- {
6681
- kind: "confirm",
6682
- message: `gh pr ${op} from box ${reg.name}`,
6683
- detail: args.join(" ").slice(0, 200),
6684
- context: { command: `gh pr ${op}`, cwd: containerPath, argv: args }
6685
- },
6686
- `safe: gh pr ${op}`
6687
- );
6688
- }
6689
- if (!GH_PR_READ_ONLY_OPS.has(op) && !ghSafeAuto && !hostInitiatedOk) {
6690
- const detail = args.join(" ").slice(0, 200);
6691
- const verdict = await askPrompt(prompts, subscribers, reg.boxId, {
7415
+ if (!hostInitiatedOk) {
7416
+ const destructive = ghDestructiveTarget(args);
7417
+ const label = `gh ${args.slice(0, 2).join(" ")}`.trim();
7418
+ const ctx = {
6692
7419
  kind: "confirm",
6693
- message: `Allow gh pr ${op} from box ${reg.name}?`,
6694
- detail,
6695
- defaultAnswer: "n",
6696
- context: {
6697
- command: `gh pr ${op}`,
6698
- cwd: containerPath,
6699
- argv: args
6700
- }
6701
- });
6702
- if (verdict.answer !== "y") {
6703
- return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
6704
- }
6705
- }
6706
- const finalArgs = injectPrCreateHead(op, worktree.sanctionedBranch ?? worktree.branch, args);
6707
- if (prCreateNeedsHead(op, finalArgs)) return PR_CREATE_NO_HEAD_REFUSAL;
6708
- const prRun = ghRunContext(worktree.hostMainRepo, reg.originUrl, finalArgs);
6709
- return runHostGh(["pr", op, ...prRun.args], prRun.cwd);
6710
- }
6711
- async function handleGhRunRpc(op, reg, params, prompts, subscribers) {
6712
- const containerPath = params?.path ?? "/workspace";
6713
- const worktree = resolveWorktree(reg, containerPath);
6714
- if (!worktree) {
6715
- return {
6716
- exitCode: 64,
6717
- stdout: "",
6718
- stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`
7420
+ message: destructive ? `Allow \`gh ${args.join(" ")}\` from box ${reg.name}? This destroys a ${destructive}.` : `Allow \`gh ${args.join(" ")}\` from box ${reg.name}?`,
7421
+ detail: args.join(" ").slice(0, 200),
7422
+ context: { command: label, cwd: containerPath, argv: args }
6719
7423
  };
6720
- }
6721
- const ghReady = await assertGhReady();
6722
- if (ghReady) return ghReady;
6723
- const args = Array.isArray(params?.args) ? params.args.filter((a) => typeof a === "string") : [];
6724
- if (!GH_RUN_READ_ONLY_OPS.has(op)) {
6725
- const detail = args.join(" ").slice(0, 200);
6726
- if (reg.autoApproveSafeHostActions !== false) {
6727
- prompts.noteAutoApprove(
6728
- reg.boxId,
6729
- {
6730
- kind: "confirm",
6731
- message: `gh run ${op} from box ${reg.name}`,
6732
- detail,
6733
- context: { command: `gh run ${op}`, cwd: containerPath, argv: args }
6734
- },
6735
- `safe: gh run ${op}`
6736
- );
6737
- } else {
7424
+ if (destructive || reg.autoApproveSafeHostActions === false) {
6738
7425
  const verdict = await askPrompt(prompts, subscribers, reg.boxId, {
6739
- kind: "confirm",
6740
- message: `Allow gh run ${op} from box ${reg.name}?`,
6741
- detail,
6742
- defaultAnswer: "n",
6743
- context: { command: `gh run ${op}`, cwd: containerPath, argv: args }
7426
+ ...ctx,
7427
+ defaultAnswer: "n"
6744
7428
  });
6745
7429
  if (verdict.answer !== "y") {
6746
7430
  return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
6747
7431
  }
7432
+ } else {
7433
+ prompts.noteAutoApprove(reg.boxId, ctx, `allow-once: ${label}`);
6748
7434
  }
6749
7435
  }
6750
- const runRun = ghRunContext(worktree.hostMainRepo, reg.originUrl, args);
6751
- return runHostGh(["run", op, ...runRun.args], runRun.cwd);
7436
+ let finalArgs = args;
7437
+ if (family === "pr") {
7438
+ const head = args.slice(0, args.length - verb.length);
7439
+ const rest = injectPrCreateHead(
7440
+ op,
7441
+ worktree.sanctionedBranch ?? worktree.branch,
7442
+ verb.slice(2)
7443
+ );
7444
+ if (prCreateNeedsHead(op, rest)) return PR_CREATE_NO_HEAD_REFUSAL;
7445
+ finalArgs = [...head, family, op, ...rest];
7446
+ }
7447
+ const run4 = ghRunContext(worktree.hostMainRepo, reg.originUrl, finalArgs);
7448
+ return runHostGh(run4.args, run4.cwd, { host: ghTarget.host });
6752
7449
  }
6753
- async function handleGhApiRpc(reg, params) {
6754
- const containerPath = params?.path ?? "/workspace";
7450
+ async function handleToolRpc(method, reg, params, prompts, subscribers) {
7451
+ const containerPath = typeof params?.["path"] === "string" ? params["path"] : "/workspace";
6755
7452
  const worktree = resolveWorktree(reg, containerPath);
6756
7453
  if (!worktree) {
6757
7454
  return {
@@ -6760,107 +7457,206 @@ async function handleGhApiRpc(reg, params) {
6760
7457
  stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`
6761
7458
  };
6762
7459
  }
6763
- const endpoint = typeof params?.endpoint === "string" ? params.endpoint : "";
6764
- if (!isAllowedGhApiEndpoint(endpoint)) return GH_API_ENDPOINT_REFUSAL;
6765
- const args = Array.isArray(params?.args) ? params.args.filter((a) => typeof a === "string") : [];
6766
- const callRefusal = refuseGhApiCall(endpoint, args);
6767
- if (callRefusal) return callRefusal;
6768
- const ghReady = await assertGhReady();
6769
- if (ghReady) return ghReady;
6770
- const apiRun = ghRunContext(worktree.hostMainRepo, void 0, args);
6771
- return runHostGh(["api", endpoint, ...apiRun.args], apiRun.cwd);
6772
- }
6773
- async function handleIntegrationRpc(method, reg, params, prompts, subscribers, hostInitiatedTokens) {
6774
- const parsed = parseIntegrationMethod(method);
6775
- if (!parsed) {
7460
+ const cwd = worktree.hostMainRepo;
7461
+ if (method === "tool.list") {
7462
+ const grants = await loadGrantedTools(cwd);
7463
+ const json = params?.["format"] === "json";
7464
+ return {
7465
+ exitCode: 0,
7466
+ stdout: json ? renderToolListJson(grants.values()) : renderToolList(grants.values()),
7467
+ stderr: ""
7468
+ };
7469
+ }
7470
+ const name = typeof params?.["name"] === "string" ? params["name"].trim() : "";
7471
+ if (!name || !isValidToolName(name)) {
6776
7472
  return {
6777
7473
  exitCode: 64,
6778
7474
  stdout: "",
6779
- stderr: `unknown integration method shape: ${method}
7475
+ stderr: `${method}: missing or invalid tool name
6780
7476
  `
6781
7477
  };
6782
7478
  }
6783
- const connector = getConnector(parsed.service);
6784
- if (!connector) {
7479
+ if (method === "tool.request") {
7480
+ const reason = typeof params?.reason === "string" ? String(params?.["reason"]).slice(0, 500) : "";
7481
+ return handleToolRequest(name, reason, reg, cwd, containerPath, prompts, subscribers);
7482
+ }
7483
+ if (method !== "tool.run") {
7484
+ return { exitCode: 64, stdout: "", stderr: `unknown tool method: ${method}
7485
+ ` };
7486
+ }
7487
+ const resolved = await resolveToolGrant(name, cwd);
7488
+ if ("refusal" in resolved) return resolved.refusal;
7489
+ const grant = resolved.grant;
7490
+ const args = Array.isArray(params?.["args"]) ? params["args"].filter((a) => typeof a === "string") : [];
7491
+ const credRefusal = refuseCredentialArgv(name, args, grant.bin);
7492
+ if (credRefusal) return credRefusal;
7493
+ const denyRefusal = refuseDeniedArgv(grant, args);
7494
+ if (denyRefusal) return denyRefusal;
7495
+ const promptEvent = {
7496
+ kind: "confirm",
7497
+ message: `Allow \`${grant.bin} ${args.join(" ")}\` on the host from box ${reg.name}?`,
7498
+ detail: `runs with the host's own ${grant.bin} credentials in ${cwd}`,
7499
+ context: { command: `tool ${name}`, cwd: containerPath, argv: args }
7500
+ };
7501
+ if (argvIsExplicitlyAllowed(grant, args)) {
7502
+ prompts.noteAutoApprove(reg.boxId, promptEvent, `allow-rule: tool ${name}`);
7503
+ } else if (reg.autoApproveSafeHostActions !== false) {
7504
+ prompts.noteAutoApprove(reg.boxId, promptEvent, `safe: tool ${name}`);
7505
+ } else {
7506
+ const verdict = await askPrompt(prompts, subscribers, reg.boxId, {
7507
+ ...promptEvent,
7508
+ defaultAnswer: "n"
7509
+ });
7510
+ if (verdict.answer !== "y") {
7511
+ return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
7512
+ }
7513
+ }
7514
+ return runGrantedTool(grant, args, cwd);
7515
+ }
7516
+ async function handleToolRequest(name, reason, reg, cwd, containerPath, prompts, subscribers) {
7517
+ if (!await toolRequestsEnabled(cwd)) {
6785
7518
  return {
6786
- exitCode: 64,
7519
+ exitCode: 65,
6787
7520
  stdout: "",
6788
- stderr: `unknown integration service: ${parsed.service}
6789
- `
7521
+ stderr: "host-tool requests are disabled for this project (`agentbox config set --project tools.request.enabled true` to allow them)\n"
6790
7522
  };
6791
7523
  }
6792
- const opDesc = connector.ops[parsed.op];
6793
- if (!opDesc) {
6794
- return makeIntegrationOpRefusal(
6795
- parsed.service,
6796
- parsed.op,
6797
- connector.hostBin,
6798
- Object.keys(connector.ops)
6799
- );
7524
+ const existing = await loadGrantedTools(cwd);
7525
+ if (existing.has(name)) {
7526
+ return { exitCode: 0, stdout: `${name} is already granted
7527
+ `, stderr: "" };
6800
7528
  }
6801
- const containerPath = params?.path ?? "/workspace";
6802
- const worktree = resolveWorktree(reg, containerPath);
6803
- if (!worktree) {
7529
+ if (!await hostToolInstalled(name)) {
6804
7530
  return {
6805
- exitCode: 64,
7531
+ exitCode: 127,
6806
7532
  stdout: "",
6807
- stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`
7533
+ stderr: `${name} is not installed on the host \u2014 nothing to grant
7534
+ `
6808
7535
  };
6809
7536
  }
6810
- const args = Array.isArray(params?.args) ? params.args.filter((a) => typeof a === "string") : [];
6811
- const callRefusal = refuseIntegrationCall(opDesc, args);
6812
- if (callRefusal) return callRefusal;
6813
- const enableRefusal = await refuseIfIntegrationDisabled(parsed.service, worktree.hostMainRepo);
6814
- if (enableRefusal) return enableRefusal;
6815
- const ready = await assertIntegrationReady(connector);
6816
- if (ready) return ready;
6817
- if (opDesc.write) {
6818
- if (reg.autoApproveSafeHostActions !== false) {
6819
- prompts.noteAutoApprove(
6820
- reg.boxId,
6821
- {
6822
- kind: "confirm",
6823
- message: `${parsed.service} ${parsed.op} from box ${reg.name}`,
6824
- detail: args.join(" ").slice(0, 200),
6825
- context: {
6826
- command: `integration ${parsed.service} ${parsed.op}`,
6827
- cwd: containerPath,
6828
- argv: args
6829
- }
6830
- },
6831
- `safe: integration ${parsed.service} ${parsed.op}`
6832
- );
6833
- } else {
6834
- const tokenClaimed = typeof params?.hostInitiated === "string";
6835
- const incomingHash = hashRpcParams(params);
6836
- const tokenOk = tokenClaimed && hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, method, incomingHash);
6837
- if (tokenClaimed && !tokenOk) {
6838
- return {
6839
- exitCode: 10,
6840
- stdout: "",
6841
- stderr: "host-initiated token rejected: invalid, expired, or bound to different params\n"
6842
- };
6843
- }
6844
- if (!tokenOk) {
6845
- const detail = args.join(" ").slice(0, 200);
6846
- const verdict = await askPrompt(prompts, subscribers, reg.boxId, {
6847
- kind: "confirm",
6848
- message: `Allow ${parsed.service} ${parsed.op} from box ${reg.name}?`,
6849
- detail,
6850
- defaultAnswer: "n",
6851
- context: {
6852
- command: `integration ${parsed.service} ${parsed.op}`,
6853
- cwd: containerPath,
6854
- argv: args
6855
- }
6856
- });
6857
- if (verdict.answer !== "y") {
6858
- return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
6859
- }
6860
- }
7537
+ const verdict = await askPrompt(prompts, subscribers, reg.boxId, {
7538
+ kind: "confirm",
7539
+ message: `Box ${reg.name} requests access to the host CLI \`${name}\`. Grant it?`,
7540
+ detail: reason ? `reason: ${reason}` : "no reason given",
7541
+ defaultAnswer: "n",
7542
+ context: { command: `tool request ${name}`, cwd: containerPath, argv: [name] }
7543
+ });
7544
+ if (verdict.answer !== "y") {
7545
+ return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
7546
+ }
7547
+ await writeToolGrant(await resolveProjectToolsFile(cwd), {
7548
+ name,
7549
+ bin: name,
7550
+ source: "request",
7551
+ approvedAt: (/* @__PURE__ */ new Date()).toISOString()
7552
+ });
7553
+ return {
7554
+ exitCode: 0,
7555
+ stdout: `${name} granted for this project
7556
+ `,
7557
+ stderr: ""
7558
+ };
7559
+ }
7560
+ async function parkOutboundCp(args) {
7561
+ const { params, reg, custody, maxBytes, log } = args;
7562
+ if (!custody) return null;
7563
+ let norm;
7564
+ try {
7565
+ norm = normalizeCpParams("cp.toHost", params);
7566
+ } catch {
7567
+ return null;
7568
+ }
7569
+ return parkCpOutbox(norm.sources, norm.dest, {
7570
+ custody,
7571
+ cliEntry: process.env.AGENTBOX_CLI_ENTRY,
7572
+ boxId: reg.boxId,
7573
+ boxName: reg.name,
7574
+ prefix: cpOutboxPrefix({
7575
+ projectSlug: reg.originUrl ? projectSlugFromOriginUrl(reg.originUrl) ?? void 0 : void 0,
7576
+ boxId: reg.boxId
7577
+ }),
7578
+ maxBytes,
7579
+ log
7580
+ });
7581
+ }
7582
+ async function boxWorkspaceExistsHere(boxId) {
7583
+ try {
7584
+ const path = await boxWorkspacePath(boxId);
7585
+ return typeof path === "string" && path.length > 0 && existsSync5(path);
7586
+ } catch {
7587
+ return false;
7588
+ }
7589
+ }
7590
+ function isHostReachMethod(method) {
7591
+ return method === "cp.toHost" || method === "cp.fromHost" || method.startsWith("tool.");
7592
+ }
7593
+ function toolUnreachableMessage(boxName, reason) {
7594
+ const lead = reason === "went-away" ? "the machine that granted these tools stopped responding" : "the machine that granted these tools is not connected to this hub";
7595
+ return [
7596
+ `host tools are unavailable: ${lead}.`,
7597
+ "",
7598
+ "Grants live with the machine that made them, and so do the binaries they name \u2014",
7599
+ "this hub only brokers the call.",
7600
+ "Start AgentBox there (`agentbox relay start`) and retry.",
7601
+ `Its grants are listed by \`agentbox tools list\` on that machine (box: ${boxName}).`,
7602
+ ""
7603
+ ].join("\n");
7604
+ }
7605
+ function cpUnreachableMessage(method, boxName, reason, opts = {}) {
7606
+ const direction = method === "cp.toHost" ? "to" : "from";
7607
+ const lead = reason === "went-away" ? "the machine holding these files stopped responding part-way through the copy" : "the machine holding these files is not connected to this hub";
7608
+ return [
7609
+ `cp ${direction} the host could not run: ${lead}.`,
7610
+ // Naming BOTH facts matters: "offline" alone reads as "wait and retry",
7611
+ // when the fix for a cold cache is to pre-load the file instead.
7612
+ ...opts.cacheMiss ? ["This hub has no cached copy of those paths either."] : [],
7613
+ "",
7614
+ "This hub brokers the copy; it does not hold your project files.",
7615
+ `Start AgentBox on that machine (\`agentbox relay start\`) and retry, or run it there directly:`,
7616
+ ` agentbox cp ${boxName}:<src> <dst>`,
7617
+ ...opts.cacheMiss ? [
7618
+ "To make a file readable with that machine offline, upload it there once:",
7619
+ " agentbox cp <file> hub:"
7620
+ ] : [],
7621
+ ""
7622
+ ].join("\n");
7623
+ }
7624
+ async function serveCachedCp(args) {
7625
+ const { params, reg, custody, cachePrefix, prompts, subscribers, log } = args;
7626
+ if (!custody) return null;
7627
+ let sources;
7628
+ try {
7629
+ sources = normalizeCpParams("cp.fromHost", params).sources;
7630
+ } catch {
7631
+ return null;
7632
+ }
7633
+ const lookup = await lookupCpCache(sources, { custody, cachePrefix });
7634
+ if (lookup.missing.length > 0) return null;
7635
+ const verdict = await askPrompt(prompts, subscribers, reg.boxId, {
7636
+ kind: "confirm",
7637
+ message: `Allow ${reg.name} to read a CACHED copy of these files?`,
7638
+ detail: [
7639
+ "The machine holding them is offline; this hub has an older copy:",
7640
+ describeCpCacheEntries(lookup)
7641
+ ].join("\n"),
7642
+ defaultAnswer: "n",
7643
+ // Shows the paths the entries were CAPTURED from, not the box's spelling:
7644
+ // the user is approving a copy of files on their own disk.
7645
+ context: {
7646
+ command: "cp.fromHost (cached)",
7647
+ argv: lookup.entries.map((e) => e.meta.sourcePath)
6861
7648
  }
7649
+ });
7650
+ if (verdict.answer !== "y") {
7651
+ return { exitCode: 10, stdout: "", stderr: "denied by user\n" };
6862
7652
  }
6863
- return runHostIntegration(connector, opDesc, args, worktree.hostMainRepo);
7653
+ return serveCpFromCache(params, sources, {
7654
+ custody,
7655
+ cliEntry: process.env.AGENTBOX_CLI_ENTRY,
7656
+ boxName: reg.name,
7657
+ cachePrefix,
7658
+ log
7659
+ });
6864
7660
  }
6865
7661
  async function handleCpRpc(cpArgs, cwd) {
6866
7662
  const entry = process.env.AGENTBOX_CLI_ENTRY;
@@ -7218,6 +8014,8 @@ function startCloudKeepaliveLoop(deps) {
7218
8014
  const resolveBackend = deps.resolveBackend ?? resolveCloudBackend;
7219
8015
  const lookupBox = deps.lookupBox ?? defaultLookupBox;
7220
8016
  const persistPaused = deps.persistPaused ?? defaultPersistPaused;
8017
+ const stopPoller = deps.stopPoller ?? (async () => {
8018
+ });
7221
8019
  const fallbackCreateTimeoutMs = deps.fallbackCreateTimeoutMs ?? defaultFallbackCreateTimeoutMs;
7222
8020
  const nowFn = deps.now ?? Date.now;
7223
8021
  const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS22;
@@ -7274,16 +8072,24 @@ function startCloudKeepaliveLoop(deps) {
7274
8072
  if (!lookup) continue;
7275
8073
  let current = tracked.get(d.boxId);
7276
8074
  if (current == null) {
7277
- const createMs = lookup.createdAtMs ?? now;
7278
- const createTimeoutMs = lookup.createTimeoutMs ?? await fallbackCreateTimeoutMs(d.backend);
7279
- current = createMs + createTimeoutMs;
8075
+ if (lookup.sessionDeadlineEpochMs != null) {
8076
+ current = lookup.sessionDeadlineEpochMs;
8077
+ } else {
8078
+ const createMs = lookup.createdAtMs ?? now;
8079
+ const createTimeoutMs = lookup.createTimeoutMs ?? await fallbackCreateTimeoutMs(d.backend);
8080
+ current = createMs + createTimeoutMs;
8081
+ }
7280
8082
  tracked.set(d.boxId, current);
7281
8083
  }
7282
8084
  if (d.targetDeadlineEpochMs <= current + intervalMs) continue;
7283
8085
  try {
7284
8086
  const backend = await resolveCached(d.backend);
7285
8087
  if (!backend?.renewTimeout) continue;
7286
- await backend.renewTimeout({ sandboxId: lookup.sandboxId }, d.targetDeadlineEpochMs, current);
8088
+ await backend.renewTimeout(
8089
+ { sandboxId: lookup.sandboxId },
8090
+ d.targetDeadlineEpochMs,
8091
+ current
8092
+ );
7287
8093
  tracked.set(d.boxId, d.targetDeadlineEpochMs);
7288
8094
  backoffUntil.delete(d.boxId);
7289
8095
  log(
@@ -7309,6 +8115,8 @@ function startCloudKeepaliveLoop(deps) {
7309
8115
  const idleWindowMs = lookup.createTimeoutMs ?? await fallbackCreateTimeoutMs(e.backend);
7310
8116
  if (idleWindowMs <= 0) continue;
7311
8117
  if (!shouldIdlePause(e, idleWindowMs, now)) continue;
8118
+ await stopPoller(boxId).catch(() => {
8119
+ });
7312
8120
  try {
7313
8121
  await backend.pause({
7314
8122
  sandboxId: lookup.sandboxId,
@@ -7316,6 +8124,7 @@ function startCloudKeepaliveLoop(deps) {
7316
8124
  });
7317
8125
  idlePaused.set(boxId, e.lastActivityMs);
7318
8126
  backoffUntil.delete(boxId);
8127
+ tracked.delete(boxId);
7319
8128
  await persistPaused(boxId).catch(() => {
7320
8129
  });
7321
8130
  const mins = e.lastActivityMs != null ? Math.round((now - e.lastActivityMs) / 6e4) : null;
@@ -7365,6 +8174,7 @@ async function defaultLookupBox(boxId) {
7365
8174
  sandboxId,
7366
8175
  createdAtMs: toEpoch2(hit.box.createdAt),
7367
8176
  createTimeoutMs: hit.box.cloud?.sessionTimeoutMs ?? null,
8177
+ sessionDeadlineEpochMs: hit.box.cloud?.sessionDeadlineEpochMs ?? null,
7368
8178
  ...sandboxClass ? { sandboxClass } : {}
7369
8179
  };
7370
8180
  }
@@ -7432,10 +8242,556 @@ function startRetentionLoop(deps) {
7432
8242
  }
7433
8243
  };
7434
8244
  }
8245
+ var SseFrameReader = class {
8246
+ buffer = "";
8247
+ /** Frames completed by this chunk, in order. */
8248
+ push(chunk) {
8249
+ this.buffer += chunk;
8250
+ const out = [];
8251
+ let idx = this.buffer.indexOf("\n\n");
8252
+ while (idx !== -1) {
8253
+ const raw = this.buffer.slice(0, idx);
8254
+ this.buffer = this.buffer.slice(idx + 2);
8255
+ const frame = parseFrame(raw);
8256
+ if (frame) out.push(frame);
8257
+ idx = this.buffer.indexOf("\n\n");
8258
+ }
8259
+ return out;
8260
+ }
8261
+ /** Drop any partial frame — call on reconnect so a torn frame can't merge. */
8262
+ reset() {
8263
+ this.buffer = "";
8264
+ }
8265
+ };
8266
+ function parseFrame(raw) {
8267
+ let event = "message";
8268
+ const data = [];
8269
+ for (const line of raw.split("\n")) {
8270
+ if (line.startsWith(":")) continue;
8271
+ if (line.startsWith("event:")) event = line.slice(6).trim();
8272
+ else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
8273
+ }
8274
+ if (data.length === 0) return null;
8275
+ return { event, data: data.join("\n") };
8276
+ }
8277
+ var POLL_WAIT_MS = 25e3;
8278
+ var REQUEST_TIMEOUT_MS = 4e4;
8279
+ var RESULT_TIMEOUT_MS = 3e4;
8280
+ var BACKOFF_BASE_MS = 2e3;
8281
+ var BACKOFF_MAX_MS = 6e4;
8282
+ var OUTBOX_RECHECK_MS = 5 * 6e4;
8283
+ var SSE_RETRY_MS = 5 * 6e4;
8284
+ var SSE_HANDSHAKE_MS = 1e4;
8285
+ var HostReachPoller = class {
8286
+ constructor(deps) {
8287
+ this.deps = deps;
8288
+ }
8289
+ deps;
8290
+ stopped = false;
8291
+ loopPromise = null;
8292
+ backoffMs = 0;
8293
+ /** Suppresses repeat log lines while a control box stays unreachable. */
8294
+ loggedFailure = false;
8295
+ /**
8296
+ * Identity of THIS process. Sent with every poll so the control box can tell a
8297
+ * restarted relay from the one that took an action and never came back — and
8298
+ * re-offer that orphaned work instead of leaving the box waiting forever.
8299
+ */
8300
+ pollerId = randomUUID5();
8301
+ /** Set while a drain is in flight, so only one runs at a time. */
8302
+ drainingOutbox = false;
8303
+ /** Epoch ms of the last drain, for the periodic re-check. */
8304
+ lastDrainAtMs = 0;
8305
+ /** Serializes execution beside the poll loop (see {@link enqueue}). */
8306
+ workQueue = Promise.resolve();
8307
+ /** Epoch ms before which the stream is not retried (0 = try it now). */
8308
+ sseBlockedUntilMs = 0;
8309
+ /** Logged once per transition so the log answers "which mode am I in?". */
8310
+ mode = null;
8311
+ /**
8312
+ * The in-flight event stream, so {@link stop} can cut it.
8313
+ *
8314
+ * An open stream never ends on its own: without this, stopping the relay
8315
+ * waits for the control box to drop the connection, which it has no reason to
8316
+ * do — `agentbox relay stop` would hang.
8317
+ */
8318
+ activeStream = null;
8319
+ start() {
8320
+ if (this.loopPromise) return;
8321
+ this.loopPromise = this.run().catch((err2) => {
8322
+ this.log(`host-reach poller crashed: ${err2 instanceof Error ? err2.message : String(err2)}`);
8323
+ });
8324
+ }
8325
+ async stop() {
8326
+ this.stopped = true;
8327
+ this.activeStream?.destroy();
8328
+ if (this.loopPromise) await this.loopPromise;
8329
+ await this.workQueue.catch(() => {
8330
+ });
8331
+ }
8332
+ async run() {
8333
+ const base = this.deps.controlPlaneUrl.replace(/\/+$/, "");
8334
+ this.log(`host-reach: connecting to ${base} for host actions`);
8335
+ while (!this.stopped) {
8336
+ if (this.streamingAllowed()) {
8337
+ const outcome = await this.stream(base);
8338
+ if (this.stopped) break;
8339
+ if (outcome === "fatal") return;
8340
+ if (outcome === "unsupported" || outcome === "unusable") {
8341
+ this.sseBlockedUntilMs = Date.now() + SSE_RETRY_MS;
8342
+ this.log(
8343
+ outcome === "unsupported" ? "host-reach: control box has no event stream; falling back to long polling" : "host-reach: event stream did not come through (a proxy may be buffering it); falling back to long polling"
8344
+ );
8345
+ }
8346
+ continue;
8347
+ }
8348
+ try {
8349
+ const res = await this.get(
8350
+ `${base}/admin/hostreach/poll?wait=${String(POLL_WAIT_MS)}&poller=${this.pollerId}`
8351
+ );
8352
+ if (res.status === 404) {
8353
+ this.log(
8354
+ "host-reach: this control box does not serve /admin/hostreach (update it) \u2014 poller stopping"
8355
+ );
8356
+ return;
8357
+ }
8358
+ if (res.status === 401 || res.status === 403) {
8359
+ this.log(
8360
+ "host-reach: control box rejected the admin token \u2014 poller stopping (re-run `agentbox hub setup`)"
8361
+ );
8362
+ return;
8363
+ }
8364
+ if (res.status < 200 || res.status >= 300) {
8365
+ throw new Error(`poll \u2192 ${String(res.status)}: ${res.text.slice(0, 200)}`);
8366
+ }
8367
+ this.backoffMs = 0;
8368
+ if (this.loggedFailure) {
8369
+ this.log("host-reach: control box reachable again");
8370
+ this.loggedFailure = false;
8371
+ }
8372
+ if (this.mode !== "poll") {
8373
+ this.mode = "poll";
8374
+ this.log("host-reach: long polling for host actions");
8375
+ }
8376
+ this.maybeDrainOutbox();
8377
+ const parsed = JSON.parse(res.text.length > 0 ? res.text : "{}");
8378
+ const actions = Array.isArray(parsed.actions) ? parsed.actions : [];
8379
+ for (const action of actions) this.enqueue(base, action);
8380
+ } catch (err2) {
8381
+ if (this.stopped) break;
8382
+ if (!this.loggedFailure) {
8383
+ this.log(
8384
+ `host-reach: control box unreachable (${err2 instanceof Error ? err2.message : String(err2)}); retrying`
8385
+ );
8386
+ this.loggedFailure = true;
8387
+ }
8388
+ this.backoffMs = Math.min(
8389
+ this.backoffMs === 0 ? BACKOFF_BASE_MS : this.backoffMs * 2,
8390
+ BACKOFF_MAX_MS
8391
+ );
8392
+ await delay2(this.backoffMs);
8393
+ }
8394
+ }
8395
+ }
8396
+ /** Whether to attempt the stream, or stay on the poll after it proved unusable. */
8397
+ streamingAllowed() {
8398
+ return Date.now() >= this.sseBlockedUntilMs;
8399
+ }
8400
+ /**
8401
+ * Hold one event stream until it drops.
8402
+ *
8403
+ * Returns why it ended, which is what decides the next move:
8404
+ * - `unsupported` — the route 404s (an older control box). Poll.
8405
+ * - `unusable` — connected but nothing arrived, not even the preamble, within
8406
+ * {@link SSE_HANDSHAKE_MS}. Something between here and there is buffering
8407
+ * the response; polling still works through it. Poll.
8408
+ * - `dropped` — it worked and then ended (idle timeout, network blip, hub
8409
+ * restart). Reconnect; this is the normal case.
8410
+ * - `fatal` — the token was rejected. Neither transport will help.
8411
+ */
8412
+ stream(base) {
8413
+ const url = new URL(`${base}/admin/hostreach/events?poller=${this.pollerId}`);
8414
+ const isHttps = url.protocol === "https:";
8415
+ const transport = isHttps ? httpsRequest2 : httpRequest2;
8416
+ return new Promise((resolve) => {
8417
+ let settled = false;
8418
+ const finish = (outcome) => {
8419
+ if (settled) return;
8420
+ settled = true;
8421
+ clearTimeout(handshake);
8422
+ this.activeStream = null;
8423
+ req.destroy();
8424
+ resolve(outcome);
8425
+ };
8426
+ const handshake = setTimeout(() => finish("unusable"), SSE_HANDSHAKE_MS);
8427
+ handshake.unref?.();
8428
+ const req = transport(
8429
+ {
8430
+ host: url.hostname,
8431
+ port: url.port.length > 0 ? Number.parseInt(url.port, 10) : isHttps ? 443 : 80,
8432
+ method: "GET",
8433
+ path: `${url.pathname}${url.search}`,
8434
+ headers: {
8435
+ Authorization: `Bearer ${this.deps.adminToken}`,
8436
+ Accept: "text/event-stream"
8437
+ }
8438
+ },
8439
+ (res) => {
8440
+ const status = res.statusCode ?? 0;
8441
+ if (status === 404) {
8442
+ res.resume();
8443
+ finish("unsupported");
8444
+ return;
8445
+ }
8446
+ if (status === 401 || status === 403) {
8447
+ res.resume();
8448
+ this.log(
8449
+ "host-reach: control box rejected the admin token \u2014 stopping (re-run `agentbox hub setup`)"
8450
+ );
8451
+ finish("fatal");
8452
+ return;
8453
+ }
8454
+ if (status < 200 || status >= 300) {
8455
+ res.resume();
8456
+ finish("unusable");
8457
+ return;
8458
+ }
8459
+ if (!(res.headers["content-type"] ?? "").includes("text/event-stream")) {
8460
+ res.resume();
8461
+ finish("unusable");
8462
+ return;
8463
+ }
8464
+ const reader = new SseFrameReader();
8465
+ res.setEncoding("utf8");
8466
+ res.on("data", (chunk) => {
8467
+ clearTimeout(handshake);
8468
+ if (this.mode !== "stream") {
8469
+ this.mode = "stream";
8470
+ this.log("host-reach: streaming host actions (event stream)");
8471
+ }
8472
+ this.backoffMs = 0;
8473
+ this.loggedFailure = false;
8474
+ this.maybeDrainOutbox();
8475
+ for (const frame of reader.push(chunk)) {
8476
+ if (frame.event !== "action") continue;
8477
+ try {
8478
+ this.enqueue(base, JSON.parse(frame.data));
8479
+ } catch {
8480
+ }
8481
+ }
8482
+ });
8483
+ res.on("end", () => finish("dropped"));
8484
+ res.on("error", () => finish("dropped"));
8485
+ }
8486
+ );
8487
+ req.on("error", () => finish("unusable"));
8488
+ this.activeStream = req;
8489
+ req.end();
8490
+ });
8491
+ }
8492
+ /**
8493
+ * Kick off an outbox drain, **without** waiting for it.
8494
+ *
8495
+ * Deliberately not awaited inside the poll loop: a drain opens a confirm per
8496
+ * parked copy and blocks until the user answers, so awaiting it here stops
8497
+ * this machine polling — the control box then declares it gone and live
8498
+ * copies start failing over to the cache while the user is sitting right
8499
+ * there. Found exactly that way in a live run.
8500
+ *
8501
+ * Re-checked periodically rather than once per process: a copy can be parked
8502
+ * while this machine is up (a network blip on the control box's side is
8503
+ * enough), and a machine that stays online for days would otherwise never
8504
+ * look again.
8505
+ */
8506
+ maybeDrainOutbox() {
8507
+ if (!this.deps.drainOutbox || this.drainingOutbox) return;
8508
+ if (this.lastDrainAtMs > 0 && Date.now() - this.lastDrainAtMs < OUTBOX_RECHECK_MS) return;
8509
+ this.drainingOutbox = true;
8510
+ this.lastDrainAtMs = Date.now();
8511
+ void this.deps.drainOutbox().catch((err2) => {
8512
+ this.log(
8513
+ `host-reach: could not land parked copies: ${err2 instanceof Error ? err2.message : String(err2)}`
8514
+ );
8515
+ }).finally(() => {
8516
+ this.drainingOutbox = false;
8517
+ });
8518
+ }
8519
+ /**
8520
+ * Queue an action for execution **off** the poll loop.
8521
+ *
8522
+ * Executing inline stops this machine polling for as long as the copy takes —
8523
+ * and a copy takes as long as the user takes to answer its confirm. The
8524
+ * control box reads that silence as "the machine went away", tells the box so,
8525
+ * and then has nowhere to put the result that eventually arrives. The poll
8526
+ * loop's only job is the heartbeat; work happens beside it.
8527
+ *
8528
+ * Still strictly sequential: each action can open a confirm, and two prompts
8529
+ * competing for one terminal is not a UX.
8530
+ */
8531
+ enqueue(base, action) {
8532
+ this.workQueue = this.workQueue.then(() => this.stopped ? void 0 : this.handle(base, action)).catch((err2) => {
8533
+ this.log(
8534
+ `host-reach: ${action.method} failed: ${err2 instanceof Error ? err2.message : String(err2)}`
8535
+ );
8536
+ });
8537
+ }
8538
+ async handle(base, action) {
8539
+ this.log(`host-reach: executing ${action.method} for box ${action.boxId}`);
8540
+ let result;
8541
+ try {
8542
+ result = await this.deps.execute(action);
8543
+ } catch (err2) {
8544
+ result = {
8545
+ exitCode: 1,
8546
+ stdout: "",
8547
+ stderr: `${action.method} failed on this machine: ${err2 instanceof Error ? err2.message : String(err2)}
8548
+ `
8549
+ };
8550
+ }
8551
+ try {
8552
+ if (result === "not-mine") {
8553
+ await this.post(`${base}/admin/hostreach/decline`, {
8554
+ id: action.id,
8555
+ poller: this.pollerId
8556
+ });
8557
+ return;
8558
+ }
8559
+ await this.post(`${base}/admin/hostreach/result`, {
8560
+ id: action.id,
8561
+ poller: this.pollerId,
8562
+ ...result
8563
+ });
8564
+ } catch (err2) {
8565
+ this.log(
8566
+ `host-reach: could not post the result for ${action.id}: ${err2 instanceof Error ? err2.message : String(err2)}`
8567
+ );
8568
+ }
8569
+ }
8570
+ get(url) {
8571
+ return this.send(url, "GET", void 0, REQUEST_TIMEOUT_MS);
8572
+ }
8573
+ post(url, body) {
8574
+ return this.send(url, "POST", JSON.stringify(body), RESULT_TIMEOUT_MS);
8575
+ }
8576
+ send(rawUrl, method, payload, timeoutMs) {
8577
+ const url = new URL(rawUrl);
8578
+ const isHttps = url.protocol === "https:";
8579
+ const transport = isHttps ? httpsRequest2 : httpRequest2;
8580
+ const port = url.port.length > 0 ? Number.parseInt(url.port, 10) : isHttps ? 443 : 80;
8581
+ const headers = {
8582
+ Authorization: `Bearer ${this.deps.adminToken}`
8583
+ };
8584
+ if (payload !== void 0) {
8585
+ headers["Content-Type"] = "application/json";
8586
+ headers["Content-Length"] = Buffer.byteLength(payload).toString();
8587
+ }
8588
+ return new Promise((resolve, reject) => {
8589
+ const req = transport(
8590
+ {
8591
+ host: url.hostname,
8592
+ port,
8593
+ method,
8594
+ path: `${url.pathname}${url.search}`,
8595
+ headers,
8596
+ timeout: timeoutMs
8597
+ },
8598
+ (res) => {
8599
+ const chunks = [];
8600
+ res.on("data", (chunk) => chunks.push(chunk));
8601
+ res.on(
8602
+ "end",
8603
+ () => resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString("utf8") })
8604
+ );
8605
+ res.on("error", reject);
8606
+ }
8607
+ );
8608
+ req.on("error", reject);
8609
+ req.on("timeout", () => {
8610
+ req.destroy();
8611
+ reject(new Error(`${method} ${url.pathname} timed out`));
8612
+ });
8613
+ if (payload !== void 0) req.write(payload);
8614
+ req.end();
8615
+ });
8616
+ }
8617
+ log(line) {
8618
+ this.deps.logger?.(line);
8619
+ }
8620
+ };
8621
+ var REQUEST_TIMEOUT_MS2 = 3e5;
8622
+ async function drainCpOutbox(deps) {
8623
+ const base = deps.controlPlaneUrl.replace(/\/+$/, "");
8624
+ const listed = await getJson(`${base}/admin/hostreach/outbox`, deps.adminToken);
8625
+ const items = Array.isArray(listed.items) ? listed.items : [];
8626
+ if (items.length === 0) return;
8627
+ deps.log(`host-reach: ${String(items.length)} parked cop(y|ies) waiting for this machine`);
8628
+ for (const item of items) {
8629
+ const owner = await lookupCloudBoxOwner(item.meta.boxId);
8630
+ if (!owner) continue;
8631
+ const workspacePath = await boxWorkspacePath(item.meta.boxId);
8632
+ const destAbs = resolveHostPath(workspacePath, item.meta.dest);
8633
+ const verdict = await askPrompt(deps.prompts, deps.subscribers, item.meta.boxId, {
8634
+ kind: "confirm",
8635
+ message: `Land a copy ${owner.name} sent while this machine was offline?`,
8636
+ detail: [
8637
+ `${item.meta.sources.join(", ")} -> ${destAbs}`,
8638
+ `${describeCacheAge(item.meta.createdAt)}, ${String(item.meta.size)} bytes`
8639
+ ].join("\n"),
8640
+ defaultAnswer: "n",
8641
+ context: { command: "cp.toHost (parked)", argv: [...item.meta.sources, destAbs] }
8642
+ });
8643
+ if (verdict.answer !== "y") {
8644
+ deps.log(`host-reach: declined the parked copy from ${owner.name}; leaving it on the hub`);
8645
+ continue;
8646
+ }
8647
+ let stagedDir;
8648
+ try {
8649
+ const stream = await getStream(`${base}/admin/custody-blob/${item.tarPath}`, deps.adminToken);
8650
+ const staged = await stageOutboxTar(stream);
8651
+ stagedDir = staged.dir;
8652
+ await landCpOutboxTar(staged.tarPath, destAbs, {
8653
+ destEndsWithSlash: /[/\\]$/.test(item.meta.dest)
8654
+ });
8655
+ await del(`${base}/admin/hostreach/outbox/${item.meta.id}`, deps.adminToken);
8656
+ deps.log(`host-reach: landed a parked copy from ${owner.name} at ${destAbs}`);
8657
+ } catch (err2) {
8658
+ deps.log(
8659
+ `host-reach: could not land the parked copy from ${owner.name} (left on the hub): ${err2 instanceof Error ? err2.message : String(err2)}`
8660
+ );
8661
+ } finally {
8662
+ if (stagedDir) await rm5(stagedDir, { recursive: true, force: true }).catch(() => {
8663
+ });
8664
+ }
8665
+ }
8666
+ }
8667
+ function getJson(url, token) {
8668
+ return new Promise((resolve, reject) => {
8669
+ const target = new URL(url);
8670
+ const isHttps = target.protocol === "https:";
8671
+ const req = (isHttps ? httpsRequest3 : httpRequest3)(
8672
+ {
8673
+ host: target.hostname,
8674
+ port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,
8675
+ method: "GET",
8676
+ path: target.pathname,
8677
+ headers: { Authorization: `Bearer ${token}` },
8678
+ timeout: REQUEST_TIMEOUT_MS2
8679
+ },
8680
+ (res) => {
8681
+ const chunks = [];
8682
+ res.on("data", (c) => chunks.push(c));
8683
+ res.on("end", () => {
8684
+ const text3 = Buffer.concat(chunks).toString("utf8");
8685
+ const status = res.statusCode ?? 0;
8686
+ if (status < 200 || status >= 300) {
8687
+ reject(new Error(`${target.pathname} \u2192 ${String(status)}`));
8688
+ return;
8689
+ }
8690
+ try {
8691
+ resolve(text3.length > 0 ? JSON.parse(text3) : {});
8692
+ } catch (err2) {
8693
+ reject(err2 instanceof Error ? err2 : new Error(String(err2)));
8694
+ }
8695
+ });
8696
+ }
8697
+ );
8698
+ req.on("error", reject);
8699
+ req.on("timeout", () => {
8700
+ req.destroy();
8701
+ reject(new Error(`${target.pathname} timed out`));
8702
+ });
8703
+ req.end();
8704
+ });
8705
+ }
8706
+ function getStream(url, token) {
8707
+ return new Promise((resolve, reject) => {
8708
+ const target = new URL(url);
8709
+ const isHttps = target.protocol === "https:";
8710
+ const req = (isHttps ? httpsRequest3 : httpRequest3)(
8711
+ {
8712
+ host: target.hostname,
8713
+ port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,
8714
+ method: "GET",
8715
+ path: target.pathname,
8716
+ headers: { Authorization: `Bearer ${token}` },
8717
+ timeout: REQUEST_TIMEOUT_MS2
8718
+ },
8719
+ (res) => {
8720
+ const status = res.statusCode ?? 0;
8721
+ if (status < 200 || status >= 300) {
8722
+ res.resume();
8723
+ reject(new Error(`custody blob GET \u2192 ${String(status)}`));
8724
+ return;
8725
+ }
8726
+ resolve(res);
8727
+ }
8728
+ );
8729
+ req.on("error", reject);
8730
+ req.on("timeout", () => {
8731
+ req.destroy();
8732
+ reject(new Error("custody blob GET timed out"));
8733
+ });
8734
+ req.end();
8735
+ });
8736
+ }
8737
+ function del(url, token) {
8738
+ return new Promise((resolve, reject) => {
8739
+ const target = new URL(url);
8740
+ const isHttps = target.protocol === "https:";
8741
+ const req = (isHttps ? httpsRequest3 : httpRequest3)(
8742
+ {
8743
+ host: target.hostname,
8744
+ port: target.port.length > 0 ? Number.parseInt(target.port, 10) : isHttps ? 443 : 80,
8745
+ method: "DELETE",
8746
+ path: target.pathname,
8747
+ headers: { Authorization: `Bearer ${token}` },
8748
+ timeout: REQUEST_TIMEOUT_MS2
8749
+ },
8750
+ (res) => {
8751
+ res.resume();
8752
+ const status = res.statusCode ?? 0;
8753
+ if (status >= 200 && status < 300) resolve();
8754
+ else reject(new Error(`outbox DELETE \u2192 ${String(status)}`));
8755
+ }
8756
+ );
8757
+ req.on("error", reject);
8758
+ req.on("timeout", () => {
8759
+ req.destroy();
8760
+ reject(new Error("outbox DELETE timed out"));
8761
+ });
8762
+ req.end();
8763
+ });
8764
+ }
7435
8765
  async function startRelayDaemon(opts) {
7436
8766
  const handle = await startRelayServer(opts);
7437
8767
  const log = opts.logger ?? (() => {
7438
8768
  });
8769
+ const controlPlaneUrl = (opts.controlPlaneUrl ?? process.env.AGENTBOX_CONTROL_PLANE_URL ?? "").trim().replace(/\/+$/, "");
8770
+ const hostReachToken = (opts.hostReachAdminToken ?? process.env.AGENTBOX_RELAY_ADMIN_TOKEN ?? "").trim();
8771
+ const hostReachPoller = controlPlaneUrl.length > 0 && hostReachToken.length > 0 && opts.controlPlane !== true ? new HostReachPoller({
8772
+ controlPlaneUrl,
8773
+ adminToken: hostReachToken,
8774
+ logger: log,
8775
+ execute: (action) => executeHostReachAction(action, {
8776
+ prompts: handle.prompts,
8777
+ subscribers: handle.subscribers,
8778
+ log,
8779
+ cache: { controlPlaneUrl, adminToken: hostReachToken }
8780
+ }),
8781
+ drainOutbox: () => drainCpOutbox({
8782
+ controlPlaneUrl,
8783
+ adminToken: hostReachToken,
8784
+ prompts: handle.prompts,
8785
+ subscribers: handle.subscribers,
8786
+ log
8787
+ })
8788
+ }) : null;
8789
+ hostReachPoller?.start();
8790
+ if (controlPlaneUrl.length > 0 && hostReachToken.length === 0 && opts.controlPlane !== true) {
8791
+ log(
8792
+ "host-reach: a control box is configured but no admin token is available; cp between a hub box and this machine will not reach it (re-run `agentbox hub setup`)"
8793
+ );
8794
+ }
7439
8795
  const autopause = startAutopauseLoop({
7440
8796
  registry: handle.registry,
7441
8797
  statusStore: handle.statusStore,
@@ -7445,7 +8801,10 @@ async function startRelayDaemon(opts) {
7445
8801
  const cloudKeepalive = startCloudKeepaliveLoop({
7446
8802
  registry: handle.registry,
7447
8803
  statusStore: handle.statusStore,
7448
- log
8804
+ log,
8805
+ // An idle pause must also silence that box's poller, or an auto-resuming
8806
+ // backend (e2b) revives the box on the poller's next long-poll.
8807
+ stopPoller: (boxId) => handle.stopCloudPoller(boxId)
7449
8808
  });
7450
8809
  const queue = startQueueLoop({
7451
8810
  log,
@@ -7467,12 +8826,37 @@ async function startRelayDaemon(opts) {
7467
8826
  autopause.stop(),
7468
8827
  cloudKeepalive.stop(),
7469
8828
  queue.stop(),
7470
- retention.stop()
8829
+ retention.stop(),
8830
+ hostReachPoller?.stop() ?? Promise.resolve()
7471
8831
  ]);
7472
8832
  await handle.close();
7473
8833
  }
7474
8834
  };
7475
8835
  }
8836
+ async function executeHostReachAction(action, deps) {
8837
+ const owner = await lookupCloudBoxOwner(action.boxId);
8838
+ if (!owner) {
8839
+ deps.log(`host-reach: declining ${action.method} \u2014 box ${action.boxId} is not known here`);
8840
+ return "not-mine";
8841
+ }
8842
+ const result = await executeCloudAction(action, {
8843
+ backendName: owner.backendName,
8844
+ boxId: action.boxId,
8845
+ boxName: owner.name,
8846
+ prompts: deps.prompts,
8847
+ subscribers: deps.subscribers,
8848
+ autoApproveSafeHostActions: owner.autoApproveSafeHostActions,
8849
+ log: deps.log
8850
+ });
8851
+ if (result.exitCode === 0 && action.method === "cp.fromHost" && action.cachePrefix) {
8852
+ await cacheCpSources(action, action.cachePrefix, {
8853
+ controlPlaneUrl: deps.cache.controlPlaneUrl,
8854
+ adminToken: deps.cache.adminToken,
8855
+ logger: deps.log
8856
+ });
8857
+ }
8858
+ return result;
8859
+ }
7476
8860
 
7477
8861
  // ../../packages/relay/dist/index.js
7478
8862
  var BOX_SSH_USER = "vscode";
@@ -7645,6 +9029,7 @@ export {
7645
9029
  toAuthedHttpsUrl,
7646
9030
  toHttpsUrl,
7647
9031
  repoSlugFromRemote,
9032
+ ghHostFromRemote,
7648
9033
  leaseTokenResult,
7649
9034
  isStoreRpcMethod,
7650
9035
  applyStoreOp,
@@ -7710,38 +9095,52 @@ export {
7710
9095
  makeStore,
7711
9096
  DEFAULT_CUSTODY_DIR,
7712
9097
  FsCustodyStore,
7713
- ALL_CONNECTORS,
7714
- GH_PR_OPS,
7715
- isGhPrOp,
7716
- GH_PR_READ_ONLY_OPS,
7717
- GH_RUN_OPS,
7718
- isGhRunOp,
7719
- GH_RUN_READ_ONLY_OPS,
7720
- GH_API_WRITE_ALLOWED_ENDPOINTS,
7721
- GH_API_ALLOWED_ENDPOINTS,
7722
- isAllowedGhApiEndpoint,
7723
- isWriteAllowedGhApiEndpoint,
7724
- GH_API_ENDPOINT_REFUSAL,
7725
- refuseGhApiCall,
9098
+ GH_BLOCKED,
9099
+ GH_DESTRUCTIVE,
9100
+ refuseBlockedGhCall,
9101
+ ghDestructiveTarget,
9102
+ refuseGhApiInput,
7726
9103
  injectPrCreateHead,
9104
+ prCreateHasExplicitHead,
7727
9105
  prCreateNeedsHead,
7728
9106
  PR_CREATE_NO_HEAD_REFUSAL,
9107
+ resolveGhTarget,
7729
9108
  assertGhReady,
9109
+ _resetGhReadyCacheForTests,
9110
+ ghRunContext,
7730
9111
  runHostGh,
7731
9112
  checkoutGuards,
7732
- refuseMergeBypass,
7733
9113
  refuseCheckoutByDefault,
7734
9114
  hashRpcParams,
7735
9115
  HostInitiatedTokens,
7736
- parseIntegrationMethod,
7737
- assertIntegrationReady,
7738
- _resetIntegrationReadyCacheForTests,
7739
- runHostIntegration,
7740
- makeIntegrationOpRefusal,
7741
- refuseIntegrationCall,
7742
- refuseIfIntegrationDisabled,
9116
+ cpCachePrefix,
9117
+ cpCacheKeyInput,
9118
+ cpCacheKey,
9119
+ cpCacheTarPath,
9120
+ cpCacheMetaPath,
9121
+ describeCacheAge,
9122
+ captureCpCacheEntry,
9123
+ HOST_EXEC_DEFAULT_TIMEOUT_MS,
9124
+ runHostBinary,
9125
+ assertHostBinReady,
9126
+ _resetHostBinReadyCacheForTests,
9127
+ hostBinExists,
9128
+ CREDENTIAL_ARGV_PATTERNS,
9129
+ refuseCredentialArgv,
9130
+ refuseDeniedArgv,
9131
+ argvIsExplicitlyAllowed,
9132
+ resolveToolGrant,
9133
+ toolRequestsEnabled,
9134
+ ghToolEnabled,
9135
+ refuseIfGhDisabled,
9136
+ hostToolInstalled,
9137
+ runGrantedTool,
9138
+ renderToolListJson,
9139
+ renderToolList,
7743
9140
  setCloudBackendLoader,
7744
9141
  HostActionQueue,
9142
+ DEFAULT_HOST_REACH_TIMEOUT_MS,
9143
+ HostReachQueue,
7745
9144
  HubNotifier,
7746
9145
  BoxNotices,
7747
9146
  CREDENTIALS_UPDATED_EVENT,
@@ -7754,10 +9153,12 @@ export {
7754
9153
  selectBoxesToRenew,
7755
9154
  startCloudKeepaliveLoop,
7756
9155
  startRetentionLoop,
9156
+ SseFrameReader,
9157
+ HostReachPoller,
7757
9158
  startRelayDaemon,
7758
9159
  normalizeRegistrationAgent,
7759
9160
  buildSshTarget,
7760
9161
  registrationToBoxRecord,
7761
9162
  RemoteStore
7762
9163
  };
7763
- //# sourceMappingURL=chunk-WB6S4W7O.js.map
9164
+ //# sourceMappingURL=chunk-THKVKVRF.js.map