@madarco/agentbox 0.31.4 → 0.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (722) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/_cloud-attach-UXH3VKTM.js +31 -0
  3. package/dist/{chunk-VQONUZE4.js → chunk-2W3W3KNR.js} +4 -4
  4. package/dist/{chunk-RUKTOHK7.js → chunk-3AYSA62C.js} +2 -2
  5. package/dist/{chunk-EXF4PLBN.js → chunk-3ISG5THX.js} +3 -3
  6. package/dist/{chunk-BYZPRB7U.js → chunk-5D46PE5V.js} +5 -5
  7. package/dist/{chunk-IF4VXKJK.js → chunk-5F5NBZG7.js} +3 -3
  8. package/dist/{chunk-ZUTC2JZM.js → chunk-65G5R2HW.js} +27 -5
  9. package/dist/chunk-65G5R2HW.js.map +1 -0
  10. package/dist/{chunk-KCDLAP5Q.js → chunk-66GAYIJZ.js} +3252 -936
  11. package/dist/chunk-66GAYIJZ.js.map +1 -0
  12. package/dist/{chunk-IQMDGAMB.js → chunk-6N7OSMEA.js} +4 -4
  13. package/dist/{chunk-CUIJ2PIN.js → chunk-7PTM6JEX.js} +26 -22
  14. package/dist/{chunk-CUIJ2PIN.js.map → chunk-7PTM6JEX.js.map} +1 -1
  15. package/dist/{chunk-EP4IFSV5.js → chunk-B3C6NQB7.js} +75 -26
  16. package/dist/chunk-B3C6NQB7.js.map +1 -0
  17. package/dist/{chunk-L567TKOK.js → chunk-BJLUG6TE.js} +5 -5
  18. package/dist/{chunk-AYREFYEF.js → chunk-BV2UZ4SG.js} +4 -4
  19. package/dist/{chunk-MBZ4UOWF.js → chunk-EAT5IEWA.js} +3 -3
  20. package/dist/{chunk-ENFWBFBI.js → chunk-GBEV7ETR.js} +4 -4
  21. package/dist/{chunk-4NO5MO2P.js → chunk-GLIWCNFE.js} +6 -6
  22. package/dist/chunk-GVNKIACA.js +223 -0
  23. package/dist/chunk-GVNKIACA.js.map +1 -0
  24. package/dist/{chunk-VWJBQGXD.js → chunk-HCKRUAHW.js} +6 -6
  25. package/dist/{chunk-IFPTD73K.js → chunk-HUVSTEJR.js} +2 -2
  26. package/dist/{chunk-NKHRFR5G.js → chunk-IL7R2X6B.js} +16 -16
  27. package/dist/{chunk-5UX2HAF4.js → chunk-IQ4WLVXE.js} +43 -43
  28. package/dist/{chunk-AAMPHDB2.js → chunk-JL4EJ4EH.js} +5 -5
  29. package/dist/{chunk-OXBWZG2N.js → chunk-KTB7JGPA.js} +4 -4
  30. package/dist/{chunk-YL3VEQTS.js → chunk-LFBCFWG6.js} +5 -5
  31. package/dist/{chunk-MJZPECVQ.js → chunk-M2DWTQRF.js} +2 -2
  32. package/dist/{chunk-PXH3DERD.js → chunk-MB2K74BI.js} +164 -2
  33. package/dist/chunk-MB2K74BI.js.map +1 -0
  34. package/dist/{chunk-2MBELUE6.js → chunk-NGCG3IBH.js} +9 -9
  35. package/dist/{chunk-QT4MOS6R.js → chunk-NX27A3F2.js} +23 -23
  36. package/dist/{chunk-4Y365UYP.js → chunk-OUHDSEVQ.js} +2 -2
  37. package/dist/{chunk-M6VAID7T.js → chunk-QBVRWGXD.js} +2 -2
  38. package/dist/{chunk-VOVRWIBC.js → chunk-QLZPJIWF.js} +13 -13
  39. package/dist/{chunk-GCS5XAPC.js → chunk-R3XDO4SN.js} +3 -3
  40. package/dist/{chunk-IQ6BQ2LX.js → chunk-RF7Q7SHU.js} +3 -3
  41. package/dist/{chunk-YSC4VY43.js → chunk-SAEZJZ5Z.js} +3 -3
  42. package/dist/{chunk-QDVIMN57.js → chunk-TDPHZWJI.js} +4 -4
  43. package/dist/{chunk-QWWDG5B7.js → chunk-U5MUWZOS.js} +6 -6
  44. package/dist/{chunk-LR5RNEVO.js → chunk-ULQPPQ23.js} +3 -3
  45. package/dist/{chunk-75JF44DH.js → chunk-VWSERFTW.js} +2 -2
  46. package/dist/{chunk-4LSLXBFN.js → chunk-XFMCRD2J.js} +6 -6
  47. package/dist/{chunk-X6SZPGL5.js → chunk-YNAJUTYC.js} +6 -6
  48. package/dist/{chunk-C67DVYWA.js → chunk-ZKOLV4ZN.js} +37 -2
  49. package/dist/chunk-ZKOLV4ZN.js.map +1 -0
  50. package/dist/{cli-XRF7WFE5.js → cli-HFZMZWRM.js} +8 -8
  51. package/dist/{cli-KT5X4J74.js → cli-HPYDF5AP.js} +8 -8
  52. package/dist/{cli-HFLU5QTD.js → cli-PWK63DQI.js} +7 -7
  53. package/dist/{cli-7JW54ZTA.js → cli-RC5F6DYP.js} +8 -8
  54. package/dist/{cli-7Z7BD23R.js → cli-S7RGCNHG.js} +7 -7
  55. package/dist/cloud-backends.js +4 -4
  56. package/dist/{control-plane-DGLF4MBB.js → control-plane-HRJRAYKV.js} +19 -19
  57. package/dist/{cp-hub-upload-7YESYCVS.js → cp-hub-upload-N4PPUZHE.js} +6 -6
  58. package/dist/{custody-client-P7SCEDU2.js → custody-client-KYEZET6C.js} +4 -4
  59. package/dist/{deploy-hetzner-FOCNRRB2.js → deploy-hetzner-A42GILM3.js} +8 -8
  60. package/dist/{dist-63YBVZW4.js → dist-5OXP2N6H.js} +8 -8
  61. package/dist/{dist-36WLI6E2.js → dist-64QL2Q5L.js} +6 -6
  62. package/dist/{dist-MITAKWKQ.js → dist-D4LLY6JV.js} +7 -7
  63. package/dist/{dist-TJJ6KBNZ.js → dist-ETGTZQUT.js} +255 -5
  64. package/dist/{dist-54VRDCUU.js → dist-GS36Y2CW.js} +7 -7
  65. package/dist/{dist-CBPQZPQN.js → dist-HGUSK4LL.js} +7 -7
  66. package/dist/{dist-E4VLIH3H.js → dist-JU5COR7Y.js} +7 -7
  67. package/dist/{dist-2CAWJQT5.js → dist-NJ2U42MZ.js} +9 -5
  68. package/dist/{dist-FHPNYDCF.js → dist-URWWHI3X.js} +8 -2
  69. package/dist/{dist-XSAPZOEG.js → dist-Z4S5EKUS.js} +7 -7
  70. package/dist/{host-reach-drainer-XFLSMTSX.js → host-reach-drainer-WIKLZSLZ.js} +2 -2
  71. package/dist/host-session-YP5RKV6T.js +29 -0
  72. package/dist/hub-A6U3YB5D.js +39 -0
  73. package/dist/{hub-adopt-IYZ3WXYN.js → hub-adopt-O4LQLW6N.js} +6 -6
  74. package/dist/{hub-api-client-WOZ2BQ6H.js → hub-api-client-BI3E37CF.js} +3 -3
  75. package/dist/{hub-docker-target-IQHX6OYX.js → hub-docker-target-D67UXZSU.js} +13 -13
  76. package/dist/index.js +1223 -229
  77. package/dist/index.js.map +1 -1
  78. package/dist/{plugin-update-2ACFHFUI.js → plugin-update-LI3QDA4K.js} +4 -4
  79. package/dist/prepare-5Y7DWMZ7.js +45 -0
  80. package/dist/prepared-custody-L6PXXLD3.js +39 -0
  81. package/dist/{prepared-state-FO74QUCP-PZLOM6HD.js → prepared-state-FO74QUCP-M4Q2X3KN.js} +3 -3
  82. package/dist/{publish-credentials-TO5IIW2T.js → publish-credentials-WJ4KLIMW.js} +8 -8
  83. package/dist/{registry-X33JZU6B.js → registry-6VF5VPGD.js} +4 -4
  84. package/dist/relay-732OVYXR.js +22 -0
  85. package/dist/{remote-docker-share-YADHIHXV.js → remote-docker-share-WY5U5USV.js} +10 -10
  86. package/dist/remote-docker-share-WY5U5USV.js.map +1 -0
  87. package/dist/{tool-grant-push-7G2QAN3J.js → tool-grant-push-YQYYNMRQ.js} +3 -3
  88. package/package.json +1 -1
  89. package/runtime/_shared/ctl.cjs +1026 -309
  90. package/runtime/digitalocean/ctl.cjs +1026 -309
  91. package/runtime/docker/packages/ctl/dist/bin.cjs +1026 -309
  92. package/runtime/e2b/ctl.cjs +1026 -309
  93. package/runtime/hetzner/ctl.cjs +1026 -309
  94. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  95. package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +24 -0
  96. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  97. package/runtime/hub/apps/hub/.next/routes-manifest.json +188 -0
  98. package/runtime/hub/apps/hub/.next/server/app/(auth)/signin/page_client-reference-manifest.js +1 -1
  99. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
  100. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
  101. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
  102. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +4 -4
  103. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
  104. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/agent/route.js.nft.json +1 -1
  105. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/backup/route.js +2 -2
  106. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/backup/route.js.nft.json +1 -1
  107. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
  108. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js +2 -2
  109. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js.nft.json +1 -1
  110. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/clone/route.js +2 -2
  111. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/clone/route.js.nft.json +1 -1
  112. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +4 -4
  113. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
  114. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
  115. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/logs/route.js.nft.json +1 -1
  116. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
  117. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
  118. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
  119. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
  120. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
  121. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
  122. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
  123. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
  124. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/upload/route.js +2 -2
  125. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/upload/route.js.nft.json +1 -1
  126. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js.nft.json +1 -1
  127. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/web/route.js.nft.json +1 -1
  128. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +4 -4
  129. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
  130. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/checkpoints/route.js.nft.json +1 -1
  131. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/[...path]/route.js +3 -3
  132. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
  133. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
  134. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
  135. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
  136. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
  137. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
  138. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
  139. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
  140. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/route.js.nft.json +1 -1
  141. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/app-paths-manifest.json +3 -0
  142. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/build-manifest.json +9 -0
  143. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route/server-reference-manifest.json +4 -0
  144. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js +9 -0
  145. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js.map +5 -0
  146. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route.js.nft.json +1 -0
  147. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/attach/route_client-reference-manifest.js +3 -0
  148. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/app-paths-manifest.json +3 -0
  149. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/build-manifest.json +9 -0
  150. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route/server-reference-manifest.json +4 -0
  151. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js +10 -0
  152. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js.map +5 -0
  153. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route.js.nft.json +1 -0
  154. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/message/route_client-reference-manifest.js +3 -0
  155. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/app-paths-manifest.json +3 -0
  156. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/build-manifest.json +9 -0
  157. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route/server-reference-manifest.json +4 -0
  158. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js +10 -0
  159. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js.map +5 -0
  160. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route.js.nft.json +1 -0
  161. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/notes/route_client-reference-manifest.js +3 -0
  162. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/app-paths-manifest.json +3 -0
  163. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/build-manifest.json +9 -0
  164. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route/server-reference-manifest.json +4 -0
  165. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js +9 -0
  166. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js.map +5 -0
  167. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route.js.nft.json +1 -0
  168. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/resume/route_client-reference-manifest.js +3 -0
  169. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/app-paths-manifest.json +3 -0
  170. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/build-manifest.json +9 -0
  171. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route/server-reference-manifest.json +4 -0
  172. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js +10 -0
  173. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js.map +5 -0
  174. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route.js.nft.json +1 -0
  175. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/route_client-reference-manifest.js +3 -0
  176. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/app-paths-manifest.json +3 -0
  177. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/build-manifest.json +9 -0
  178. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route/server-reference-manifest.json +4 -0
  179. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js +9 -0
  180. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js.map +5 -0
  181. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route.js.nft.json +1 -0
  182. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/[id]/stop/route_client-reference-manifest.js +3 -0
  183. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/app-paths-manifest.json +3 -0
  184. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/build-manifest.json +9 -0
  185. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route/server-reference-manifest.json +4 -0
  186. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js +10 -0
  187. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js.map +5 -0
  188. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route.js.nft.json +1 -0
  189. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/detect/route_client-reference-manifest.js +3 -0
  190. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/app-paths-manifest.json +3 -0
  191. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/build-manifest.json +9 -0
  192. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route/server-reference-manifest.json +4 -0
  193. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js +10 -0
  194. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js.map +5 -0
  195. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route.js.nft.json +1 -0
  196. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/managers/route_client-reference-manifest.js +3 -0
  197. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
  198. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/bots/route.js.nft.json +1 -1
  199. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
  200. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/create-preflight/route.js +2 -2
  201. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/create-preflight/route.js.nft.json +1 -1
  202. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/restore/route.js +2 -2
  203. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/restore/route.js.nft.json +1 -1
  204. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
  205. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/seed/route.js.nft.json +1 -1
  206. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
  207. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
  208. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
  209. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
  210. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
  211. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
  212. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/size-check/route.js +2 -2
  213. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/size-check/route.js.nft.json +1 -1
  214. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
  215. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js +2 -2
  216. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js.nft.json +1 -1
  217. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/system/route.js.nft.json +1 -1
  218. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/app-paths-manifest.json +3 -0
  219. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/build-manifest.json +9 -0
  220. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route/server-reference-manifest.json +4 -0
  221. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js +10 -0
  222. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js.map +5 -0
  223. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route.js.nft.json +1 -0
  224. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/tasks/route_client-reference-manifest.js +3 -0
  225. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/app-paths-manifest.json +3 -0
  226. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/build-manifest.json +9 -0
  227. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route/server-reference-manifest.json +4 -0
  228. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js +9 -0
  229. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js.map +5 -0
  230. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route.js.nft.json +1 -0
  231. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/route_client-reference-manifest.js +3 -0
  232. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/app-paths-manifest.json +3 -0
  233. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/build-manifest.json +9 -0
  234. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route/server-reference-manifest.json +4 -0
  235. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js +9 -0
  236. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js.map +5 -0
  237. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.js.nft.json +1 -0
  238. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route_client-reference-manifest.js +3 -0
  239. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/app-paths-manifest.json +3 -0
  240. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/build-manifest.json +9 -0
  241. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route/server-reference-manifest.json +4 -0
  242. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js +10 -0
  243. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js.map +5 -0
  244. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.js.nft.json +1 -0
  245. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route_client-reference-manifest.js +3 -0
  246. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/app-paths-manifest.json +3 -0
  247. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/build-manifest.json +9 -0
  248. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route/server-reference-manifest.json +4 -0
  249. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js +10 -0
  250. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js.map +5 -0
  251. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route.js.nft.json +1 -0
  252. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rename/route_client-reference-manifest.js +3 -0
  253. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/app-paths-manifest.json +3 -0
  254. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/build-manifest.json +9 -0
  255. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route/server-reference-manifest.json +4 -0
  256. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js +9 -0
  257. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js.map +5 -0
  258. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.js.nft.json +1 -0
  259. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/rescan/route_client-reference-manifest.js +3 -0
  260. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/app-paths-manifest.json +3 -0
  261. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/build-manifest.json +9 -0
  262. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route/server-reference-manifest.json +4 -0
  263. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js +10 -0
  264. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js.map +5 -0
  265. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route.js.nft.json +1 -0
  266. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/route_client-reference-manifest.js +3 -0
  267. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/app-paths-manifest.json +3 -0
  268. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/build-manifest.json +9 -0
  269. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route/server-reference-manifest.json +4 -0
  270. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js +10 -0
  271. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js.map +5 -0
  272. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.js.nft.json +1 -0
  273. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route_client-reference-manifest.js +3 -0
  274. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/app-paths-manifest.json +3 -0
  275. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/build-manifest.json +9 -0
  276. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route/server-reference-manifest.json +4 -0
  277. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js +9 -0
  278. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js.map +5 -0
  279. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.js.nft.json +1 -0
  280. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route_client-reference-manifest.js +3 -0
  281. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/app-paths-manifest.json +3 -0
  282. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/build-manifest.json +9 -0
  283. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route/server-reference-manifest.json +4 -0
  284. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js +10 -0
  285. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js.map +5 -0
  286. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.js.nft.json +1 -0
  287. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route_client-reference-manifest.js +3 -0
  288. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/app-paths-manifest.json +3 -0
  289. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/build-manifest.json +9 -0
  290. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route/server-reference-manifest.json +4 -0
  291. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js +9 -0
  292. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js.map +5 -0
  293. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.js.nft.json +1 -0
  294. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route_client-reference-manifest.js +3 -0
  295. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/app-paths-manifest.json +3 -0
  296. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/build-manifest.json +9 -0
  297. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route/server-reference-manifest.json +4 -0
  298. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js +10 -0
  299. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js.map +5 -0
  300. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.js.nft.json +1 -0
  301. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route_client-reference-manifest.js +3 -0
  302. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/app-paths-manifest.json +3 -0
  303. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/build-manifest.json +9 -0
  304. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route/server-reference-manifest.json +4 -0
  305. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js +10 -0
  306. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js.map +5 -0
  307. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.js.nft.json +1 -0
  308. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route_client-reference-manifest.js +3 -0
  309. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/app-paths-manifest.json +3 -0
  310. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/build-manifest.json +9 -0
  311. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route/server-reference-manifest.json +4 -0
  312. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js +10 -0
  313. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js.map +5 -0
  314. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.js.nft.json +1 -0
  315. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/tasks/route_client-reference-manifest.js +3 -0
  316. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/app-paths-manifest.json +3 -0
  317. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/build-manifest.json +9 -0
  318. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route/server-reference-manifest.json +4 -0
  319. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js +10 -0
  320. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js.map +5 -0
  321. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.js.nft.json +1 -0
  322. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/[id]/timeline/route_client-reference-manifest.js +3 -0
  323. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/app-paths-manifest.json +3 -0
  324. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/build-manifest.json +9 -0
  325. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route/server-reference-manifest.json +4 -0
  326. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js +10 -0
  327. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js.map +5 -0
  328. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route.js.nft.json +1 -0
  329. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/workspaces/route_client-reference-manifest.js +3 -0
  330. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  331. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
  332. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
  333. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
  334. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js.nft.json +1 -1
  335. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/web/route.js.nft.json +1 -1
  336. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page.js.nft.json +1 -1
  337. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page_client-reference-manifest.js +1 -1
  338. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  339. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  340. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
  341. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
  342. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  343. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  344. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page.js.nft.json +1 -1
  345. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page_client-reference-manifest.js +1 -1
  346. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +1 -1
  347. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
  348. package/runtime/hub/apps/hub/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  349. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  350. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  351. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  352. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  353. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  354. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  355. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  356. package/runtime/hub/apps/hub/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  357. package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +24 -0
  358. package/runtime/hub/apps/hub/.next/server/chunks/00je_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_assign_route_actions_1sufsej.js +3 -0
  359. package/runtime/hub/apps/hub/.next/server/chunks/00je_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_done_route_actions_216dixx.js +3 -0
  360. package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_managers_route_actions_1_vtgih.js +3 -0
  361. package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_tasks_route_actions_1h8tg_m.js +3 -0
  362. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_managers_sessions_route_actions_16dksub.js +3 -0
  363. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_managers_start_route_actions_1g-vmis.js +3 -0
  364. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_[taskId]_route_actions_03oih6y.js +3 -0
  365. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_assign_route_actions_196zwo9.js +3 -0
  366. package/runtime/hub/apps/hub/.next/server/chunks/05v5_app_(dashboard)_api_v1_workspaces_[id]_tasks_reorder_route_actions_1zkcfk-.js +3 -0
  367. package/runtime/hub/apps/hub/.next/server/chunks/0ssw__next-internal_server_app_(dashboard)_api_v1_workspaces_route_actions_12a7_y8.js +3 -0
  368. package/runtime/hub/apps/hub/.next/server/chunks/0web_next-internal_server_app_(dashboard)_api_v1_managers_[id]_route_actions_07cpyb_.js +3 -0
  369. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_attach_route_actions_0o-khw8.js +3 -0
  370. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_message_route_actions_0rjcqe5.js +3 -0
  371. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_notes_route_actions_1-mf4r_.js +3 -0
  372. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_resume_route_actions_0-cm1mu.js +3 -0
  373. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_[id]_stop_route_actions_16nrl1r.js +3 -0
  374. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_managers_detect_route_actions_1sdbs-_.js +3 -0
  375. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_managers_route_actions_1sxymv0.js +3 -0
  376. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_rename_route_actions_0df5zi2.js +3 -0
  377. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_rescan_route_actions_1yra_w8.js +3 -0
  378. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_route_actions_1f56n_0.js +3 -0
  379. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_tasks_route_actions_1t-6quw.js +3 -0
  380. package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_workspaces_[id]_timeline_route_actions_0pbxblt.js +3 -0
  381. package/runtime/hub/apps/hub/.next/server/chunks/1viy_api_v1_workspaces_[id]_tasks_[taskId]_unassign_route_actions_18a1p_r.js +3 -0
  382. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-c97gb._.js +1 -1
  383. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0spnud2._.js → [root-of-the-server]__0-kl55b._.js} +1 -1
  384. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__028ifqb._.js → [root-of-the-server]__0-xlf9z._.js} +2 -2
  385. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__074mxl5._.js → [root-of-the-server]__0004tsz._.js} +2 -2
  386. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00bupbc._.js +1 -1
  387. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1cpr4qy._.js → [root-of-the-server]__0126167._.js} +1 -1
  388. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01fy5q0._.js +1 -1
  389. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02c077x._.js +3 -0
  390. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1ta1gr1._.js → [root-of-the-server]__02sueng._.js} +1 -1
  391. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0nndlre._.js → [root-of-the-server]__04-gm8c._.js} +2 -2
  392. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05uinnp._.js +1 -1
  393. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__06wy8zz._.js +3 -0
  394. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__071c-t4._.js +3 -0
  395. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__08jg8w8._.js +1 -1
  396. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09059m-._.js +1 -1
  397. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__092y7_z._.js +1 -1
  398. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09ti2-t._.js +3 -0
  399. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09y4pdw._.js +3 -0
  400. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_mog_h._.js +1 -1
  401. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a689u5._.js +3 -0
  402. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a8ere2._.js +3 -0
  403. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0bzqrje._.js +3 -0
  404. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c_r3oe._.js +3 -0
  405. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cdoz9i._.js +1 -1
  406. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cmu4sk._.js +1 -1
  407. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cxjxz0._.js +1 -1
  408. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d27tlu._.js +3 -0
  409. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d3fx1z._.js +3 -0
  410. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dm5oqm._.js +1 -1
  411. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dy5g2k._.js +1 -1
  412. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0e1uaxg._.js +1 -1
  413. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0e6_t-d._.js +3 -0
  414. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ets4cd._.js +1 -1
  415. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f2u0ul._.js +1 -1
  416. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f9p_4f._.js +1 -1
  417. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f_jmq2._.js +1 -1
  418. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0fksz_r._.js +1 -1
  419. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0fpygqn._.js +3 -0
  420. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0gym-rp._.js +1 -1
  421. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0hhlb2_._.js +1 -1
  422. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0i9phow._.js +1 -1
  423. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ikyoac._.js +1 -1
  424. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0j72bti._.js +1 -1
  425. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jb371p._.js +1 -1
  426. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jq6cdw._.js +3 -0
  427. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jt1d2s._.js +3 -0
  428. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0kcw8t0._.js +1 -1
  429. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0kdt9-i._.js +1 -1
  430. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0l27vs0._.js +1 -1
  431. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lc-j_n._.js +3 -0
  432. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lna-vq._.js +3 -0
  433. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0m5woxc._.js +1 -1
  434. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0mi9xib._.js +3 -0
  435. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0muy7eg._.js +3 -0
  436. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nn0_b5._.js +3 -0
  437. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0no30or._.js +3 -0
  438. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0o3sjtx._.js +1 -1
  439. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0onk5r0._.js +1 -1
  440. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0pik2ie._.js +3 -0
  441. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qde3vr._.js +1 -1
  442. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qt_r6a._.js +3 -0
  443. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ry8baf._.js +1 -1
  444. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0sg4y_2._.js +3 -0
  445. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0sgjn2j._.js +1 -1
  446. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0st6oln._.js +1 -1
  447. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t0p64l._.js +1 -1
  448. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0tbl11-._.js +3 -0
  449. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ve_tqz._.js +1 -1
  450. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w4smfx._.js +3 -0
  451. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0wo4sqj._.js +1 -1
  452. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0wujjkl._.js +3 -0
  453. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xbu3yj._.js +3 -0
  454. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xl1-w6._.js +1 -1
  455. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yct1tu._.js +1 -1
  456. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yg67t0._.js +1 -1
  457. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ykw5oe._.js +3 -0
  458. package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1c1rcl-._.js → [root-of-the-server]__0zznyx2._.js} +2 -2
  459. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1--u2xl._.js +3 -0
  460. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-8sj4i._.js +1 -1
  461. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10kmcrt._.js +3 -0
  462. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10l_-cd._.js +3 -0
  463. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10yfcvu._.js +1 -1
  464. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__112hqrh._.js +3 -0
  465. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11c-21i._.js +3 -0
  466. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11qbpq8._.js +3 -0
  467. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11s1mrd._.js +1 -1
  468. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__128w1nz._.js +3 -0
  469. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__12b2kuv._.js +1 -1
  470. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__12gbq5m._.js +1 -1
  471. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13nfpq5._.js +3 -0
  472. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13vl4-h._.js +1 -1
  473. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__153b7kv._.js +1 -1
  474. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__157kmse._.js +1 -1
  475. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16695dw._.js +1 -1
  476. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__166_uek._.js +3 -0
  477. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16o0ij7._.js +1 -1
  478. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__175lucf._.js +1 -1
  479. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17p53e3._.js +3 -0
  480. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17y9pmx._.js +3 -0
  481. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__18ec5_t._.js +3 -0
  482. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__18xpvkc._.js +1 -1
  483. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1925hyw._.js +3 -0
  484. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19ew1r2._.js +3 -0
  485. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19grunx._.js +1 -1
  486. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_4v0mh._.js +3 -0
  487. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_cbcl1._.js +1 -1
  488. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_wb2uh._.js +3 -0
  489. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_xgm2e._.js +3 -0
  490. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1an6-yb._.js +3 -0
  491. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c0ex8m._.js +1 -1
  492. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c1e08-._.js +3 -0
  493. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1c9f4uu._.js +1 -1
  494. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ci8hc2._.js +1 -1
  495. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1cs6d52._.js +3 -0
  496. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d60scp._.js +3 -0
  497. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dicjoc._.js +3 -0
  498. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1diipl4._.js +3 -0
  499. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dp2exz._.js +1 -1
  500. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1epnstn._.js +1 -1
  501. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1fjnz2l._.js +3 -0
  502. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1g5wnt2._.js +1 -1
  503. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1g9v7bq._.js +1 -1
  504. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1gon0_4._.js +3 -0
  505. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h_59cs._.js +1 -1
  506. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h_q3sn._.js +3 -0
  507. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hlugb4._.js +1 -1
  508. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hux-70._.js +1 -1
  509. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i-7bnu._.js +3 -0
  510. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i_el2y._.js +3 -0
  511. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1j6clag._.js +1 -1
  512. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1k6q17t._.js +3 -0
  513. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1khvg39._.js +1 -1
  514. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1lx9lyn._.js +3 -0
  515. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1m36v6k._.js +1 -1
  516. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mgu19x._.js +3 -0
  517. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mhyrr5._.js +3 -0
  518. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mk_lpu._.js +3 -0
  519. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mt32fu._.js +1 -1
  520. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1n1_2tw._.js +1 -1
  521. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1na4sdw._.js +3 -0
  522. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ntihlm._.js +3 -0
  523. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1odu62n._.js +3 -0
  524. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q6xrlt._.js +2 -2
  525. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1r4x1-y._.js +3 -0
  526. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rjs_x0._.js +1 -1
  527. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rxud0j._.js +1 -1
  528. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1s5app0._.js +1 -1
  529. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1sjz59l._.js +3 -0
  530. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1slo4q_._.js +1 -1
  531. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1thrazp._.js +3 -0
  532. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1twtnwr._.js +1 -1
  533. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1txvsbk._.js +3 -0
  534. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1uch-60._.js +1 -1
  535. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1um2jum._.js +3 -0
  536. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1vnnuo1._.js +1 -1
  537. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wegvep._.js +3 -0
  538. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wi5roz._.js +1 -1
  539. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xa9oiv._.js +3 -0
  540. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ypmy86._.js +3 -0
  541. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1zml9me._.js +1 -1
  542. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1zrf_a6._.js +1 -1
  543. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__2019yzl._.js +3 -0
  544. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20jyxyo._.js +2 -2
  545. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20ybhif._.js +1 -1
  546. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20zl5fr._.js +1 -1
  547. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__212dyoi._.js +1 -1
  548. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__218oup-._.js +1 -1
  549. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__21abvx9._.js +3 -0
  550. package/runtime/hub/apps/hub/.next/server/chunks/_0907rw0._.js +2 -1
  551. package/runtime/hub/apps/hub/.next/server/chunks/_0mcxq5g._.js +1 -1
  552. package/runtime/hub/apps/hub/.next/server/chunks/_0vg6gvw._.js +41 -41
  553. package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_openapi_ts_1yokmzt._.js +1 -1
  554. package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_validate_ts_16dhbzz._.js +1 -1
  555. package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +6 -6
  556. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__03-x9xy._.js +1 -1
  557. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1jqga8h._.js +1 -1
  558. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0r2xlss._.js +2 -1
  559. package/runtime/hub/apps/hub/.next/server/chunks/ssr/_14-qzbg._.js +26 -26
  560. package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +1 -1
  561. package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +24 -0
  562. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  563. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  564. package/runtime/hub/apps/hub/.next/static/chunks/{31e1wjin30i__.css → 03_fxfc3849ms.css} +1 -1
  565. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/[action]/route.ts +4 -2
  566. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.ts +6 -4
  567. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/route.ts +2 -1
  568. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/actor.ts +48 -0
  569. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/envelope.ts +5 -2
  570. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/openapi.ts +1687 -52
  571. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/validate.ts +527 -1
  572. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/attach/route.ts +26 -0
  573. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/message/route.ts +34 -0
  574. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/notes/route.ts +26 -0
  575. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/resume/route.ts +26 -0
  576. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/route.ts +34 -0
  577. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/[id]/stop/route.ts +23 -0
  578. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/detect/route.ts +33 -0
  579. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/managers/route.ts +27 -0
  580. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/tasks/route.ts +30 -0
  581. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/route.ts +19 -0
  582. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/sessions/route.ts +22 -0
  583. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/managers/start/route.ts +61 -0
  584. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/rename/route.ts +25 -0
  585. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/rescan/route.ts +20 -0
  586. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/route.ts +34 -0
  587. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/assign/route.ts +33 -0
  588. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/done/route.ts +23 -0
  589. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/route.ts +54 -0
  590. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/[taskId]/unassign/route.ts +25 -0
  591. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/assign/route.ts +34 -0
  592. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/reorder/route.ts +33 -0
  593. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/tasks/route.ts +59 -0
  594. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/[id]/timeline/route.ts +25 -0
  595. package/runtime/hub/apps/hub/app/(dashboard)/api/v1/workspaces/route.ts +31 -0
  596. package/runtime/hub/apps/hub/{chunk-SM2XYDPL.js → chunk-FBNAIUXZ.js} +36 -1
  597. package/runtime/hub/apps/hub/{chunk-F6GOERHP.js → chunk-GGHXBTGL.js} +3 -3
  598. package/runtime/hub/apps/hub/{chunk-7IIG6MIB.js → chunk-LEELYQVR.js} +9 -9
  599. package/runtime/hub/apps/hub/{chunk-AAF4CYVH.js → chunk-MD2UNTZR.js} +5 -5
  600. package/runtime/hub/apps/hub/{chunk-7JBH42LK.js → chunk-MQ7AJUJJ.js} +2 -2
  601. package/runtime/hub/apps/hub/{chunk-AIFVVQPX.js → chunk-OFJRKISZ.js} +3317 -1031
  602. package/runtime/hub/apps/hub/{dist-DS5LGBGK.js → dist-3LDUYWPK.js} +7 -1
  603. package/runtime/hub/apps/hub/{dist-YOTRYCRK.js → dist-DENRW6O5.js} +7 -3
  604. package/runtime/hub/apps/hub/{dist-BKCL4HAA.js → dist-NQYEPZJY.js} +4 -4
  605. package/runtime/hub/apps/hub/{dist-H7NIUVBD.js → dist-RIXE6NHS.js} +5 -5
  606. package/runtime/hub/apps/hub/{dist-YG4RVC24.js → dist-RK6SSH23.js} +5 -5
  607. package/runtime/hub/apps/hub/{dist-MQADLEEQ.js → dist-U5SDGYOA.js} +4 -4
  608. package/runtime/hub/apps/hub/{dist-LV6CHJVA.js → dist-U6XVHUNU.js} +4 -4
  609. package/runtime/hub/apps/hub/{dist-RJBPZWSZ.js → dist-W4YRUL6E.js} +4 -4
  610. package/runtime/hub/apps/hub/{dist-VENYRIRW.js → dist-Y3Q5YEOC.js} +4 -4
  611. package/runtime/hub/apps/hub/{hub-worker-DLFLGKCV.js → hub-worker-DVATYYST.js} +6 -6
  612. package/runtime/hub/apps/hub/lib/backend/background.ts +19 -0
  613. package/runtime/hub/apps/hub/lib/backend/box-facts.ts +97 -0
  614. package/runtime/hub/apps/hub/lib/backend/box-prs.ts +213 -0
  615. package/runtime/hub/apps/hub/lib/backend/deps.ts +99 -0
  616. package/runtime/hub/apps/hub/lib/backend/errors.ts +7 -0
  617. package/runtime/hub/apps/hub/lib/backend/github-prs.ts +302 -0
  618. package/runtime/hub/apps/hub/lib/backend/managers.ts +748 -0
  619. package/runtime/hub/apps/hub/lib/backend/timeline-lanes.ts +150 -0
  620. package/runtime/hub/apps/hub/lib/backend/timeline.ts +611 -0
  621. package/runtime/hub/apps/hub/lib/backend/workspaces.ts +439 -0
  622. package/runtime/hub/apps/hub/lib/boxes/backend-types.ts +355 -10
  623. package/runtime/hub/apps/hub/lib/boxes/postgres-source.ts +3 -0
  624. package/runtime/hub/apps/hub/lib/boxes/source.ts +18 -1
  625. package/runtime/hub/apps/hub/lib/boxes/types.ts +66 -0
  626. package/runtime/hub/apps/hub/lib/hub-backend.ts +114 -7
  627. package/runtime/hub/apps/hub/{prepared-state-FO74QUCP-FZ6PT4LA.js → prepared-state-FO74QUCP-75UBPW5I.js} +2 -2
  628. package/runtime/hub/apps/hub/server.js +2032 -163
  629. package/runtime/hub/apps/hub/test/backend-managers-background.test.ts +336 -0
  630. package/runtime/hub/apps/hub/test/backend-managers.test.ts +493 -0
  631. package/runtime/hub/apps/hub/test/backend-workspaces.test.ts +208 -0
  632. package/runtime/hub/apps/hub/test/box-prs.test.ts +198 -0
  633. package/runtime/hub/apps/hub/test/timeline-lanes.test.ts +261 -0
  634. package/runtime/hub/apps/hub/test/timeline.test.ts +1185 -0
  635. package/runtime/hub/apps/hub/test/validate.test.ts +252 -0
  636. package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
  637. package/runtime/relay/bin.cjs +1399 -616
  638. package/runtime/vercel/ctl.cjs +1026 -309
  639. package/share/host-skills/agentbox-info/SKILL.md +25 -4
  640. package/dist/_cloud-attach-B3BCOZ7U.js +0 -31
  641. package/dist/chunk-C67DVYWA.js.map +0 -1
  642. package/dist/chunk-EP4IFSV5.js.map +0 -1
  643. package/dist/chunk-KCDLAP5Q.js.map +0 -1
  644. package/dist/chunk-PXH3DERD.js.map +0 -1
  645. package/dist/chunk-ZUTC2JZM.js.map +0 -1
  646. package/dist/hub-OMGLWQEV.js +0 -39
  647. package/dist/prepare-OOZF37J6.js +0 -45
  648. package/dist/prepared-custody-E7CSZJ6V.js +0 -39
  649. package/dist/relay-7D5NOFKS.js +0 -22
  650. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00o_3sf._.js +0 -3
  651. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__08xwxyo._.js +0 -3
  652. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-mtsr6._.js +0 -3
  653. /package/dist/{_cloud-attach-B3BCOZ7U.js.map → _cloud-attach-UXH3VKTM.js.map} +0 -0
  654. /package/dist/{chunk-VQONUZE4.js.map → chunk-2W3W3KNR.js.map} +0 -0
  655. /package/dist/{chunk-RUKTOHK7.js.map → chunk-3AYSA62C.js.map} +0 -0
  656. /package/dist/{chunk-EXF4PLBN.js.map → chunk-3ISG5THX.js.map} +0 -0
  657. /package/dist/{chunk-BYZPRB7U.js.map → chunk-5D46PE5V.js.map} +0 -0
  658. /package/dist/{chunk-IF4VXKJK.js.map → chunk-5F5NBZG7.js.map} +0 -0
  659. /package/dist/{chunk-IQMDGAMB.js.map → chunk-6N7OSMEA.js.map} +0 -0
  660. /package/dist/{chunk-L567TKOK.js.map → chunk-BJLUG6TE.js.map} +0 -0
  661. /package/dist/{chunk-AYREFYEF.js.map → chunk-BV2UZ4SG.js.map} +0 -0
  662. /package/dist/{chunk-MBZ4UOWF.js.map → chunk-EAT5IEWA.js.map} +0 -0
  663. /package/dist/{chunk-ENFWBFBI.js.map → chunk-GBEV7ETR.js.map} +0 -0
  664. /package/dist/{chunk-4NO5MO2P.js.map → chunk-GLIWCNFE.js.map} +0 -0
  665. /package/dist/{chunk-VWJBQGXD.js.map → chunk-HCKRUAHW.js.map} +0 -0
  666. /package/dist/{chunk-IFPTD73K.js.map → chunk-HUVSTEJR.js.map} +0 -0
  667. /package/dist/{chunk-NKHRFR5G.js.map → chunk-IL7R2X6B.js.map} +0 -0
  668. /package/dist/{chunk-5UX2HAF4.js.map → chunk-IQ4WLVXE.js.map} +0 -0
  669. /package/dist/{chunk-AAMPHDB2.js.map → chunk-JL4EJ4EH.js.map} +0 -0
  670. /package/dist/{chunk-OXBWZG2N.js.map → chunk-KTB7JGPA.js.map} +0 -0
  671. /package/dist/{chunk-YL3VEQTS.js.map → chunk-LFBCFWG6.js.map} +0 -0
  672. /package/dist/{chunk-MJZPECVQ.js.map → chunk-M2DWTQRF.js.map} +0 -0
  673. /package/dist/{chunk-2MBELUE6.js.map → chunk-NGCG3IBH.js.map} +0 -0
  674. /package/dist/{chunk-QT4MOS6R.js.map → chunk-NX27A3F2.js.map} +0 -0
  675. /package/dist/{chunk-4Y365UYP.js.map → chunk-OUHDSEVQ.js.map} +0 -0
  676. /package/dist/{chunk-M6VAID7T.js.map → chunk-QBVRWGXD.js.map} +0 -0
  677. /package/dist/{chunk-VOVRWIBC.js.map → chunk-QLZPJIWF.js.map} +0 -0
  678. /package/dist/{chunk-GCS5XAPC.js.map → chunk-R3XDO4SN.js.map} +0 -0
  679. /package/dist/{chunk-IQ6BQ2LX.js.map → chunk-RF7Q7SHU.js.map} +0 -0
  680. /package/dist/{chunk-YSC4VY43.js.map → chunk-SAEZJZ5Z.js.map} +0 -0
  681. /package/dist/{chunk-QDVIMN57.js.map → chunk-TDPHZWJI.js.map} +0 -0
  682. /package/dist/{chunk-QWWDG5B7.js.map → chunk-U5MUWZOS.js.map} +0 -0
  683. /package/dist/{chunk-LR5RNEVO.js.map → chunk-ULQPPQ23.js.map} +0 -0
  684. /package/dist/{chunk-75JF44DH.js.map → chunk-VWSERFTW.js.map} +0 -0
  685. /package/dist/{chunk-4LSLXBFN.js.map → chunk-XFMCRD2J.js.map} +0 -0
  686. /package/dist/{chunk-X6SZPGL5.js.map → chunk-YNAJUTYC.js.map} +0 -0
  687. /package/dist/{cli-7JW54ZTA.js.map → cli-HFZMZWRM.js.map} +0 -0
  688. /package/dist/{cli-7Z7BD23R.js.map → cli-HPYDF5AP.js.map} +0 -0
  689. /package/dist/{cli-HFLU5QTD.js.map → cli-PWK63DQI.js.map} +0 -0
  690. /package/dist/{cli-KT5X4J74.js.map → cli-RC5F6DYP.js.map} +0 -0
  691. /package/dist/{cli-XRF7WFE5.js.map → cli-S7RGCNHG.js.map} +0 -0
  692. /package/dist/{control-plane-DGLF4MBB.js.map → control-plane-HRJRAYKV.js.map} +0 -0
  693. /package/dist/{cp-hub-upload-7YESYCVS.js.map → cp-hub-upload-N4PPUZHE.js.map} +0 -0
  694. /package/dist/{custody-client-P7SCEDU2.js.map → custody-client-KYEZET6C.js.map} +0 -0
  695. /package/dist/{deploy-hetzner-FOCNRRB2.js.map → deploy-hetzner-A42GILM3.js.map} +0 -0
  696. /package/dist/{dist-2CAWJQT5.js.map → dist-5OXP2N6H.js.map} +0 -0
  697. /package/dist/{dist-36WLI6E2.js.map → dist-64QL2Q5L.js.map} +0 -0
  698. /package/dist/{dist-63YBVZW4.js.map → dist-D4LLY6JV.js.map} +0 -0
  699. /package/dist/{dist-CBPQZPQN.js.map → dist-ETGTZQUT.js.map} +0 -0
  700. /package/dist/{dist-54VRDCUU.js.map → dist-GS36Y2CW.js.map} +0 -0
  701. /package/dist/{dist-FHPNYDCF.js.map → dist-HGUSK4LL.js.map} +0 -0
  702. /package/dist/{dist-E4VLIH3H.js.map → dist-JU5COR7Y.js.map} +0 -0
  703. /package/dist/{dist-MITAKWKQ.js.map → dist-NJ2U42MZ.js.map} +0 -0
  704. /package/dist/{dist-TJJ6KBNZ.js.map → dist-URWWHI3X.js.map} +0 -0
  705. /package/dist/{dist-XSAPZOEG.js.map → dist-Z4S5EKUS.js.map} +0 -0
  706. /package/dist/{host-reach-drainer-XFLSMTSX.js.map → host-reach-drainer-WIKLZSLZ.js.map} +0 -0
  707. /package/dist/{hub-OMGLWQEV.js.map → host-session-YP5RKV6T.js.map} +0 -0
  708. /package/dist/{hub-adopt-IYZ3WXYN.js.map → hub-A6U3YB5D.js.map} +0 -0
  709. /package/dist/{hub-api-client-WOZ2BQ6H.js.map → hub-adopt-O4LQLW6N.js.map} +0 -0
  710. /package/dist/{prepare-OOZF37J6.js.map → hub-api-client-BI3E37CF.js.map} +0 -0
  711. /package/dist/{hub-docker-target-IQHX6OYX.js.map → hub-docker-target-D67UXZSU.js.map} +0 -0
  712. /package/dist/{plugin-update-2ACFHFUI.js.map → plugin-update-LI3QDA4K.js.map} +0 -0
  713. /package/dist/{prepared-custody-E7CSZJ6V.js.map → prepare-5Y7DWMZ7.js.map} +0 -0
  714. /package/dist/{prepared-state-FO74QUCP-PZLOM6HD.js.map → prepared-custody-L6PXXLD3.js.map} +0 -0
  715. /package/dist/{registry-X33JZU6B.js.map → prepared-state-FO74QUCP-M4Q2X3KN.js.map} +0 -0
  716. /package/dist/{publish-credentials-TO5IIW2T.js.map → publish-credentials-WJ4KLIMW.js.map} +0 -0
  717. /package/dist/{relay-7D5NOFKS.js.map → registry-6VF5VPGD.js.map} +0 -0
  718. /package/dist/{remote-docker-share-YADHIHXV.js.map → relay-732OVYXR.js.map} +0 -0
  719. /package/dist/{tool-grant-push-7G2QAN3J.js.map → tool-grant-push-YQYYNMRQ.js.map} +0 -0
  720. /package/runtime/hub/apps/hub/.next/static/{o9_g9S5JH-r8bfNfmPa5H → psd9s1F7NglKqhj4_onRN}/_buildManifest.js +0 -0
  721. /package/runtime/hub/apps/hub/.next/static/{o9_g9S5JH-r8bfNfmPa5H → psd9s1F7NglKqhj4_onRN}/_clientMiddlewareManifest.js +0 -0
  722. /package/runtime/hub/apps/hub/.next/static/{o9_g9S5JH-r8bfNfmPa5H → psd9s1F7NglKqhj4_onRN}/_ssgManifest.js +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../packages/sandbox-core/src/state.ts","../../../packages/sandbox-core/src/git-detect.ts","../../../packages/sandbox-core/src/host-open.ts","../../../packages/sandbox-core/src/ssh-config.ts","../../../packages/sandbox-core/src/claude-app-config.ts","../../../packages/sandbox-core/src/hub-expose.ts","../../../packages/sandbox-core/src/provider-descriptor.ts","../../../packages/sandbox-core/src/plugin-registry.ts","../../../packages/sandbox-core/src/cloud-ssh.ts","../../../packages/sandbox-core/src/ssh-key.ts","../../../packages/sandbox-core/src/ssh-config-probe.ts","../../../packages/sandbox-core/src/ssh-exec.ts","../../../packages/sandbox-core/src/ssh-tunnel.ts","../../../packages/sandbox-core/src/inbound.ts","../../../packages/sandbox-core/src/box-git.ts","../../../packages/sandbox-core/src/doctor.ts","../../../packages/sandbox-core/src/secrets.ts","../../../packages/sandbox-core/src/credential-publish.ts","../../../packages/sandbox-core/src/hub-process.ts","../../../packages/sandbox-core/src/relay-port.ts","../../../packages/sandbox-core/src/hub-lifecycle.ts","../../../packages/sandbox-core/src/agent-session-env.ts","../../../packages/sandbox-core/src/runtime-root.ts","../../../packages/sandbox-core/src/hub-hooks.ts","../../../packages/sandbox-core/src/credential-refresh.ts","../../../packages/sandbox-core/src/carry-render.ts","../../../packages/sandbox-core/src/per-box-carry.ts","../../../packages/sandbox-core/src/borrowed-credentials.ts","../../../packages/sandbox-core/src/sync/registry.ts","../../../packages/sandbox-core/src/sync/concerns/credentials.ts","../../../packages/sandbox-core/src/model-auth-ingest.ts","../../../packages/sandbox-core/src/sync/recording-transport.ts","../../../packages/sandbox-core/src/sync/claude-pull.ts","../../../packages/sandbox-core/src/sync/agent-pull.ts","../../../packages/sandbox-core/src/sync/agent-descriptor.ts","../../../packages/sandbox-core/src/sync/agent-propagate.ts","../../../packages/sandbox-core/src/sync/index.ts","../../../packages/sandbox-core/src/sync/agent-seed.ts","../../../packages/sandbox-core/src/sync/context.ts","../../../packages/sandbox-core/src/sync/concerns/install.ts","../../../packages/sandbox-core/src/sync/concerns/env.ts","../../../packages/sandbox-core/src/sync/concerns/files.ts","../../../packages/sandbox-core/src/sync/agents/claude/paths.ts","../../../packages/sandbox-core/src/sync/host-links.ts","../../../packages/sandbox-core/src/sync/concerns/skills.ts","../../../packages/sandbox-core/src/sync/concerns/git.ts","../../../packages/sandbox-core/src/sync/concerns/bot-backup.ts","../../../packages/sandbox-core/src/sync/agent-pull-module.ts","../../../packages/sandbox-core/src/sync/concerns/service-url.ts","../../../packages/sandbox-core/src/sync/concerns/workspace-files.ts","../../../packages/sandbox-core/src/sync/concerns/box-files.ts","../../../packages/sandbox-core/src/sync/concerns/workspace-pull.ts","../../../packages/sandbox-core/src/sync/concerns/workspace-clone.ts","../../../packages/sandbox-core/src/sync/concerns/workspace-upload.ts","../../../packages/sandbox-core/src/sync/concerns/dynamic.ts","../../../packages/sandbox-core/src/sync/host-stage.ts","../../../packages/sandbox-core/src/prepared-state.ts","../../../packages/sandbox-core/src/box-registry.ts","../../../packages/sandbox-core/src/project-slug.ts","../../../packages/sandbox-core/src/prompts/carry-gate.ts","../../../packages/sandbox-core/src/prompts/carry-resolve.ts","../../../packages/sandbox-core/src/prompts/dir-breakdown.ts","../../../packages/sandbox-core/src/prompts/model-auth-gate.ts"],"sourcesContent":["import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport type {\n AgentId,\n BoxRecord,\n DockerBoxFields,\n FindBoxResult,\n SshTargetRecord,\n StateFile,\n} from '@agentbox/core';\n\nexport const STATE_DIR = join(homedir(), '.agentbox');\nexport const STATE_FILE = join(STATE_DIR, 'state.json');\n\nconst EMPTY: StateFile = { version: 1, boxes: [] };\n\n// Cross-process lock tunables. The lock guards the read-modify-write of\n// `state.json` so concurrent `agentbox create`/`destroy` processes can't lose\n// each other's records or interleave a half-written file. Held only for the\n// duration of one read+write (sub-millisecond), so contention clears fast even\n// with a burst of parallel creates.\nconst LOCK_STALE_MS = 15_000; // a lock older than this is presumed abandoned\nconst LOCK_ACQUIRE_TIMEOUT_MS = 20_000;\nconst LOCK_RETRY_MS = 25;\n\n/**\n * Run `fn` while holding an exclusive cross-process lock on `${path}.lock`.\n *\n * Acquisition: create the lockfile with `wx` (O_EXCL) — atomic on local FSes.\n * On contention, retry with a short backoff until {@link LOCK_ACQUIRE_TIMEOUT_MS};\n * a lockfile older than {@link LOCK_STALE_MS} is treated as abandoned (crashed\n * holder) and forcibly broken. If the lock still can't be taken before the\n * timeout we proceed anyway — the write is atomic (temp+rename) so the worst\n * case degrades to a possible lost update, never a corrupt file. The lock is\n * always released in `finally`.\n */\nasync function withStateLock<T>(path: string, fn: () => Promise<T>): Promise<T> {\n const lockPath = `${path}.lock`;\n await mkdir(dirname(path), { recursive: true });\n const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;\n let held = false;\n while (!held) {\n try {\n const fh = await open(lockPath, 'wx');\n await fh.writeFile(`${String(process.pid)}\\n`);\n await fh.close();\n held = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n // Break a stale lock left by a crashed holder.\n try {\n const st = await stat(lockPath);\n if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {\n await rm(lockPath, { force: true });\n continue;\n }\n } catch {\n // lock vanished between open and stat — retry immediately\n continue;\n }\n if (Date.now() >= deadline) break; // give up waiting; proceed best-effort\n await delay(LOCK_RETRY_MS);\n }\n }\n try {\n return await fn();\n } finally {\n if (held) await rm(lockPath, { force: true }).catch(() => {});\n }\n}\n\n/**\n * Locked read-modify-write of the state file. `mutator` receives the current\n * state and returns the next one; the read and the (atomic) write happen under\n * the same lock so concurrent mutators serialize instead of clobbering.\n */\nexport async function mutateState(\n mutator: (state: StateFile) => StateFile,\n path: string = STATE_FILE,\n): Promise<void> {\n await withStateLock(path, async () => {\n const state = await readState(path);\n await writeState(mutator(state), path);\n });\n}\n\nexport async function readState(path: string = STATE_FILE): Promise<StateFile> {\n try {\n const raw = await readFile(path, 'utf8');\n const parsed = JSON.parse(raw) as StateFile;\n if (parsed.version !== 1 || !Array.isArray(parsed.boxes)) {\n throw new Error(`unrecognized state file shape at ${path}`);\n }\n // Migrate-on-read: records written before the multi-provider split carry no\n // `provider` field — they are all Docker boxes. Default it so every\n // consumer (provider registry, `findBox`) sees a discriminated record.\n // Also backfill `box.docker` from the flat fields for Docker records so\n // forward-looking readers (7.1) see the nested shape without waiting\n // for the box to be re-recorded.\n for (const b of parsed.boxes) {\n b.provider ??= 'docker';\n if ((b.provider ?? 'docker') === 'docker' && !b.docker) {\n b.docker = projectDockerFields(b);\n }\n // The SSH target moved from `box.cloud.ssh` to top-level `box.ssh`.\n // Backfill on read so an already-created box (e.g. a Hetzner box) keeps its\n // `~/.agentbox/ssh/config` alias — `syncAgentboxSshConfig` only reads\n // `box.ssh`, and it would otherwise vanish until the box is next started.\n const legacySsh = (b.cloud as { ssh?: SshTargetRecord } | undefined)?.ssh;\n if (!b.ssh && legacySsh) b.ssh = legacySsh;\n }\n return parsed;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n return { ...EMPTY };\n }\n throw err;\n }\n}\n\nexport async function writeState(state: StateFile, path: string = STATE_FILE): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n // Atomic: write a sibling temp file then rename over the target. rename(2) is\n // atomic on local filesystems, so a concurrent writer (or a reader) never\n // observes a half-written / interleaved JSON file. The pid+time suffix keeps\n // parallel writers from colliding on the temp path itself.\n const tmp = `${path}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(state, null, 2) + '\\n', 'utf8');\n await rename(tmp, path);\n}\n\nexport async function recordBox(box: BoxRecord, path: string = STATE_FILE): Promise<void> {\n // Forward-looking shape: every Docker write also mirrors the flat\n // docker-specific fields into `box.docker` so readers can move to the\n // nested form opportunistically (7.1). Cloud records skip the mirror —\n // the discriminator is `box.provider !== 'docker'`.\n const toWrite: BoxRecord =\n (box.provider ?? 'docker') === 'docker' && !box.docker\n ? { ...box, docker: projectDockerFields(box) }\n : box;\n await mutateState(\n (state) => ({\n version: 1,\n boxes: [...state.boxes.filter((b) => b.id !== toWrite.id), toWrite],\n }),\n path,\n );\n}\n\n/**\n * Record which agent was last launched in a box (`agentbox claude` / `codex` /\n * `opencode`). A locked read-modify-write so it can't clobber a concurrent\n * state change. No-op when the box isn't in state (a race with `destroy`).\n * `agentbox recover` reads `box.lastAgent` to decide which agent to relaunch.\n */\nexport async function recordLastAgent(\n boxId: string,\n kind: AgentId,\n path: string = STATE_FILE,\n): Promise<void> {\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => (b.id === boxId ? { ...b, lastAgent: kind } : b)),\n }),\n path,\n );\n}\n\n/**\n * Set (or clear) a box's cosmetic `displayName`. A locked read-modify-write so\n * it can't clobber a concurrent state change. Trims the input; an empty/blank\n * value clears the label (falls back to `name`). No-op when the box isn't in\n * state (a race with `destroy`). The label is display/lookup-only — it does not\n * touch the container, git branch, or URL. Reused by the CLI and the hub.\n */\nexport async function setBoxDisplayName(\n boxId: string,\n displayName: string | undefined,\n path: string = STATE_FILE,\n): Promise<void> {\n const trimmed = displayName?.trim();\n const next = trimmed ? trimmed : undefined;\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => {\n if (b.id !== boxId) return b;\n if (next) return { ...b, displayName: next };\n const rest = { ...b };\n delete rest.displayName;\n return rest;\n }),\n }),\n path,\n );\n}\n\n/**\n * Persist a box's last resolved SSH target (`box.ssh`). A locked\n * read-modify-write so it can't clobber a concurrent state change. No-op when\n * the box isn't in state (a race with `destroy`). Works for any provider — the\n * docker localhost sshd (host `127.0.0.1` + ephemeral `port`) and cloud\n * providers (Hetzner VPS IP) both land here. `syncAgentboxSshConfig` reads it\n * back to regenerate `~/.agentbox/ssh/config` offline, without re-resolving the\n * target from the provider.\n */\n/**\n * Forget a box's Portless WEB alias, so its URL falls back to the directly\n * published port. The VNC alias is untouched.\n *\n * For the box that already existed when a proxy-refusing agent was added to it:\n * every URL producer reads `portlessAlias`, so leaving it set would keep handing\n * out a name that resolves and then 403s. A create-time skip cannot cover this\n * case because the box was made before the agent was chosen.\n */\nexport async function clearBoxPortlessWebAlias(\n boxId: string,\n path: string = STATE_FILE,\n): Promise<void> {\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) =>\n b.id === boxId ? { ...b, portlessAlias: undefined, portlessUrl: undefined } : b,\n ),\n }),\n path,\n );\n}\n\nexport async function recordBoxSsh(\n boxId: string,\n ssh: { host: string; user: string; identityFile?: string; port?: number; proxyJump?: string },\n path: string = STATE_FILE,\n): Promise<void> {\n await mutateState(\n (state) => ({\n version: 1,\n boxes: state.boxes.map((b) => (b.id === boxId ? { ...b, ssh } : b)),\n }),\n path,\n );\n}\n\n/**\n * Atomically allocate the next per-project index AND persist `record` claiming\n * it, under the state lock. Returns the reserved index (also stamped onto the\n * persisted record).\n *\n * Callers bake this index into on-disk paths (`<id>-<n>-<mnemonic>` box dir,\n * socket, snapshot), and host helpers re-derive those paths from the *recorded*\n * index — so the index must be settled before the paths are built. Allocating\n * with an unlocked `readState` and bumping a clash at record time would desync\n * the recorded index from the box's actual directory (status/ctl reads would\n * then miss it). Reserving up front, under the lock, guarantees the index a\n * create uses for its dirs is exactly the one in state.json, with no two\n * concurrent creates in the same project claiming the same number.\n */\nexport async function reserveProjectIndex(\n record: BoxRecord,\n projectRoot: string,\n path: string = STATE_FILE,\n): Promise<number> {\n let index = 1;\n await mutateState((state) => {\n index = allocateProjectIndex(state, projectRoot);\n const reserved: BoxRecord = { ...record, projectRoot, projectIndex: index };\n return {\n version: 1,\n boxes: [...state.boxes.filter((b) => b.id !== record.id), reserved],\n };\n }, path);\n return index;\n}\n\n/**\n * Build a `DockerBoxFields` payload from the flat Docker-specific fields\n * still living on `BoxRecord` for back-compat. Pure function, no\n * filesystem; safe for both `readState` migration and `recordBox` mirror.\n *\n * Once every reader uses `box.docker?.<field>` (the rest of 7.1), the\n * flat fields can be dropped and this projection becomes the canonical\n * shape. Until then, every write produces both shapes from the same\n * source so they can't drift.\n */\nfunction projectDockerFields(box: BoxRecord): DockerBoxFields {\n return {\n container: box.container,\n image: box.image,\n snapshotDir: box.snapshotDir ?? null,\n socketPath: box.socketPath,\n claudeConfigVolume: box.claudeConfigVolume,\n codexConfigVolume: box.codexConfigVolume,\n opencodeConfigVolume: box.opencodeConfigVolume,\n agentConfigVolumes: box.agentConfigVolumes,\n vscodeServerVolume: box.vscodeServerVolume,\n cursorServerVolume: box.cursorServerVolume,\n vncHostPort: box.vncHostPort,\n webHostPort: box.webHostPort,\n portlessAlias: box.portlessAlias,\n portlessUrl: box.portlessUrl,\n portlessVncAlias: box.portlessVncAlias,\n portlessVncUrl: box.portlessVncUrl,\n dockerVolume: box.dockerVolume,\n dockerCacheShared: box.dockerCacheShared,\n checkpointImage: box.checkpointImage,\n };\n}\n\nexport async function removeBoxRecord(id: string, path: string = STATE_FILE): Promise<boolean> {\n let removed = false;\n await mutateState((state) => {\n const next = state.boxes.filter((b) => b.id !== id);\n removed = next.length !== state.boxes.length;\n return { version: 1, boxes: next };\n }, path);\n return removed;\n}\n\n/**\n * Resolve a user-supplied identifier against the state file. Matching\n * precedence mirrors `docker`'s container reference resolution:\n *\n * 1. exact id\n * 2. unique id prefix\n * 3. exact name\n * 4. exact displayName (cosmetic label)\n * 5. exact container name\n *\n * Returns `'ambiguous'` if step 2 finds more than one match (steps 1, 3, 4\n * are exact-match so they cannot be ambiguous on their own).\n */\nexport function findBox(idOrName: string, state: StateFile): FindBoxResult {\n const q = idOrName.trim();\n if (q.length === 0) return { kind: 'none' };\n\n const exactId = state.boxes.find((b) => b.id === q);\n if (exactId) return { kind: 'ok', box: exactId };\n\n const prefixMatches = state.boxes.filter((b) => b.id.startsWith(q));\n if (prefixMatches.length === 1) return { kind: 'ok', box: prefixMatches[0]! };\n if (prefixMatches.length > 1) return { kind: 'ambiguous', matches: prefixMatches };\n\n const byName = state.boxes.find((b) => b.name === q);\n if (byName) return { kind: 'ok', box: byName };\n\n // A renamed box is addressable by its cosmetic `displayName`. Lowest-precedence\n // exact match (after id/name) so a label that happens to equal another box's\n // id/name never shadows it; first match wins on displayName collisions.\n const byDisplayName = state.boxes.find((b) => b.displayName === q);\n if (byDisplayName) return { kind: 'ok', box: byDisplayName };\n\n // For docker records `container` is the docker container name; for cloud\n // records it's `cloud:<sandboxId>` (post 7.2 — no more synthetic\n // agentbox-cloud-* prefix). Either form is a valid byContainer lookup\n // key for `findBox`.\n const byContainer = state.boxes.find((b) => b.container === q);\n if (byContainer) return { kind: 'ok', box: byContainer };\n\n return { kind: 'none' };\n}\n\n/**\n * Next monotonic 1-based index for the given project. Reads only `state.boxes`\n * — caller is responsible for persisting the assignment. Boxes without\n * `projectRoot` are ignored (legacy records); boxes in *other* projects are\n * also ignored. Indices are never recycled, so a destroyed #2 leaves a gap.\n */\nexport function allocateProjectIndex(state: StateFile, projectRoot: string): number {\n let max = 0;\n for (const b of state.boxes) {\n if (b.projectRoot !== projectRoot) continue;\n if (typeof b.projectIndex === 'number' && b.projectIndex > max) {\n max = b.projectIndex;\n }\n }\n return max + 1;\n}\n\n/**\n * Auto-pick when a command's `[box]` argument is omitted. Returns the unique\n * box for `projectRoot`, an `ambiguous` carrying all candidates so the CLI can\n * print a chooser, or `none`.\n */\nexport function autoPickProjectBox(state: StateFile, projectRoot: string): FindBoxResult {\n const matches = state.boxes.filter((b) => b.projectRoot === projectRoot);\n if (matches.length === 0) return { kind: 'none' };\n if (matches.length === 1) return { kind: 'ok', box: matches[0]! };\n return { kind: 'ambiguous', matches };\n}\n\n/**\n * Top-level resolver every CLI command goes through. Combines numeric-index\n * lookup with the legacy `findBox` matcher:\n *\n * - `ref === undefined` and `projectRoot` known → autoPickProjectBox.\n * - `ref` is a pure positive integer and `projectRoot` known → resolve as\n * project index. **Never** falls through to `findBox` on miss, so\n * `agentbox open 3` is reserved for the index and won't accidentally\n * match a hex id like `3abc…`.\n * - Otherwise → `findBox` (id → prefix → name → container).\n */\nexport function resolveBoxRef(\n ref: string | undefined,\n state: StateFile,\n projectRoot: string | undefined,\n): FindBoxResult {\n if (ref === undefined) {\n if (projectRoot === undefined) return { kind: 'none' };\n return autoPickProjectBox(state, projectRoot);\n }\n const trimmed = ref.trim();\n if (projectRoot !== undefined && /^[1-9][0-9]*$/.test(trimmed)) {\n const idx = Number.parseInt(trimmed, 10);\n const hit = state.boxes.find((b) => b.projectRoot === projectRoot && b.projectIndex === idx);\n return hit ? { kind: 'ok', box: hit } : { kind: 'none' };\n }\n return findBox(trimmed, state);\n}\n","import { execa } from 'execa';\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport interface DetectedGitRepo {\n kind: 'root' | 'nested';\n /** Absolute host path of the repo working tree (== `<workspace>` for root). */\n hostMainRepo: string;\n /** Path relative to the workspace where the repo lives. Empty string for root. */\n relPathFromWorkspace: string;\n}\n\n/**\n * Look for `.git` directories at the workspace root and at every 1st-level\n * subdirectory. Worktree-form `.git` files (regular file containing\n * `gitdir: …`) are intentionally skipped — turning an existing worktree into\n * another worktree gets weird, and the user case for it is rare.\n *\n * Pure host-side detection: it only tells callers where the repos are. Docker\n * boxes create the worktree inside the container against the bind-mounted\n * `.git/`; cloud boxes clone from a bundle. Either way this is the host probe.\n */\nexport async function detectGitRepos(workspace: string): Promise<DetectedGitRepo[]> {\n const out: DetectedGitRepo[] = [];\n if (await isGitDir(join(workspace, '.git'))) {\n out.push({ kind: 'root', hostMainRepo: workspace, relPathFromWorkspace: '' });\n }\n let entries: Array<{ name: string; isDirectory: () => boolean }>;\n try {\n entries = await readdir(workspace, { withFileTypes: true });\n } catch {\n return out;\n }\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.')) continue;\n const sub = join(workspace, e.name);\n if (await isGitDir(join(sub, '.git'))) {\n out.push({ kind: 'nested', hostMainRepo: sub, relPathFromWorkspace: e.name });\n }\n }\n return out;\n}\n\nasync function isGitDir(path: string): Promise<boolean> {\n try {\n const s = await stat(path);\n return s.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Pick `<base>`, `<base>-2`, `<base>-3`, … until git reports no such branch\n * exists. Avoids collision when the user reruns `agentbox create -n same-name`\n * after destroying — the destroyed box's branch still lives in the host repo.\n */\nexport async function pickFreshBranch(hostMainRepo: string, base: string): Promise<string> {\n let candidate = base;\n let suffix = 2;\n while (await branchExists(hostMainRepo, candidate)) {\n candidate = `${base}-${String(suffix++)}`;\n if (suffix > 100) throw new GitWorktreeError(`could not find a free branch name near ${base}`);\n }\n return candidate;\n}\n\nasync function branchExists(hostMainRepo: string, name: string): Promise<boolean> {\n const result = await execa(\n 'git',\n ['-C', hostMainRepo, 'show-ref', '--verify', '--quiet', `refs/heads/${name}`],\n { reject: false },\n );\n return result.exitCode === 0;\n}\n\nexport class GitWorktreeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitWorktreeError';\n }\n}\n","import { spawn } from 'node:child_process';\n\n/**\n * The host command that opens a URL or file path in the OS default handler.\n *\n * macOS ships `open`; Linux uses `xdg-open` (from `xdg-utils`, present on any\n * desktop install). We deliberately return only the binary name and let each\n * call site keep its own spawn semantics (sync/async, stdio, detached) — the\n * single platform decision lives here so adding a host platform is a one-line\n * change. Callers already treat a non-zero exit / ENOENT as \"couldn't\n * auto-open\" and print the target, so an absent `xdg-open` degrades cleanly.\n */\nexport function hostOpenCommand(): string {\n return process.platform === 'linux' ? 'xdg-open' : 'open';\n}\n\n/**\n * Fire-and-forget open of `target` in the host's default handler. Detached +\n * `unref`ed so the caller's event loop isn't held by a browser process, and\n * never throws: every call site has already printed or logged the target, so a\n * missing `xdg-open` degrades to \"nothing popped up\" rather than an error.\n *\n * The single copy of the spawn semantics for the several places that want\n * exactly this (hub setup, control-plane deploy, the relay's browser-open, the\n * attach footer); {@link hostOpenCommand} stays the primitive for callers that\n * need the exit code.\n */\nexport function openOnHost(target: string): void {\n try {\n const child = spawn(hostOpenCommand(), [target], { detached: true, stdio: 'ignore' });\n // A missing `xdg-open` surfaces as an ASYNC 'error' event, not a throw, and\n // an unlistened 'error' on a ChildProcess is re-thrown — which would take\n // down the relay daemon (or the attach wrapper) on a host with no desktop\n // opener. The listener is what makes this function actually never-throw.\n child.on('error', () => {\n /* no opener on this host; the caller has already surfaced the target */\n });\n child.unref();\n } catch {\n /* the caller has already surfaced the target */\n }\n}\n","import { promises as fs } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { pruneOrphanClaudeSshConfigs } from './claude-app-config.js';\nimport { readState } from './state.js';\n\n/**\n * Host-side SSH-config manager for cloud boxes. AgentBox owns a dedicated file\n * `~/.agentbox/ssh/config` holding one `Host <alias>` block per SSH-capable box,\n * and injects a single managed `Include ~/.agentbox/ssh/config` line into the\n * user's `~/.ssh/config` — so our churn stays out of their hand-maintained\n * config. The owned file is regenerated wholesale from `state.json`\n * (`syncAgentboxSshConfig`), which self-heals stale/destroyed boxes and reads\n * only persisted state (no provider calls, never wakes a paused box).\n *\n * Daytona's SSH gateway authenticates per-token (the User field carries an\n * ephemeral 60-min token from `sb.createSshAccess(60)`), so `agentbox code`\n * re-resolves + re-syncs on every invocation to keep the alias mapped to a live\n * token.\n */\n\nexport interface SshAliasOptions {\n /** Host alias the user (and VS Code Remote-SSH) refers to — the box name, e.g. `myname`. */\n alias: string;\n /** Daytona SSH gateway, typically `ssh.app.daytona.io`. */\n hostname: string;\n /** Ephemeral Daytona token (used as the SSH User). Rotates every call. */\n user: string;\n /**\n * Per-box private key path for providers that authenticate by identity\n * file (docker localhost sshd, Hetzner). Omit for token-in-User auth\n * (Daytona) — without this field VSCode's Remote-SSH would try ~/.ssh/id_*\n * defaults and fail with \"permission denied\" against a Hetzner VPS that only\n * trusts the per-box key under `~/.agentbox/boxes/<id>/ssh/id_ed25519`.\n */\n identityFile?: string;\n /**\n * Non-default SSH port. Docker publishes its in-box sshd on an ephemeral\n * `127.0.0.1:<port>`; omit for cloud providers reachable on 22.\n */\n port?: number;\n /**\n * `ProxyJump` destination for a box reachable only through another machine —\n * remote-docker's box is a container on a remote engine, so ssh hops through\n * that engine and dials the published sshd port on its loopback.\n */\n proxyJump?: string;\n /** Comment-marker flavor; defaults to `cloud box`. */\n kind?: BlockKind;\n}\n\nfunction sshConfigPath(): string {\n return join(homedir(), '.ssh', 'config');\n}\n\n/** AgentBox-owned SSH config file `Include`d from `~/.ssh/config`. */\nexport function agentboxSshConfigPath(): string {\n return join(homedir(), '.agentbox', 'ssh', 'config');\n}\n\nfunction stateFilePath(): string {\n return join(homedir(), '.agentbox', 'state.json');\n}\n\n/** Deploy record written by `agentbox hub setup --deploy hetzner` / `hub deploy hetzner`. */\nexport function controlPlaneDeployPath(): string {\n return join(homedir(), '.agentbox', 'control-plane', 'deploy.json');\n}\n\n/**\n * Host alias for the deployed control box. Fixed rather than derived: there is\n * at most one deployed hub per machine, and a stable `ssh agentbox-hub` is the\n * whole point — the VPS is otherwise reachable only via a per-deploy key buried\n * under `~/.agentbox/control-plane/ssh/<stamp>/`.\n */\nexport const AGENTBOX_HUB_SSH_ALIAS = 'agentbox-hub';\n\nconst INCLUDE_BEGIN = '# BEGIN agentbox ssh include';\nconst INCLUDE_END = '# END agentbox ssh include';\n\nfunction beginMarker(alias: string, kind: BlockKind = 'cloud box'): string {\n return `# BEGIN agentbox ${kind} ${alias}`;\n}\n\nfunction endMarker(alias: string, kind: BlockKind = 'cloud box'): string {\n return `# END agentbox ${kind} ${alias}`;\n}\n\n/** What a managed block describes — only the comment markers differ. */\ntype BlockKind = 'cloud box' | 'control box';\n\n/**\n * Stable `~/.ssh/config` Host alias for a box: the box name itself. Box names\n * are already kebab-safe, so `ssh <boxname>` works and external apps (Codex's\n * `codex://…?name=<alias>` deep link, Claude desktop) get a clean, memorable\n * host. Our BEGIN/END-marked managed block keeps this entry isolated from any\n * user-authored `Host <boxname>` so the two coexist.\n */\nexport function agentboxAliasFor(boxName: string): string {\n return boxName;\n}\n\nasync function readFileOrEmpty(path: string): Promise<string> {\n try {\n return await fs.readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return '';\n throw err;\n }\n}\n\nfunction buildBlock(opts: SshAliasOptions): string {\n // `UserKnownHostsFile /dev/null` + `LogLevel ERROR` is the Vagrant / dev-tool\n // convention: many sandboxes sit behind one DNS name, so pinning a host key\n // locally generates noise + false-positive HostKeyVerificationFailed errors.\n const lines: string[] = [\n beginMarker(opts.alias, opts.kind),\n `Host ${opts.alias}`,\n ` HostName ${opts.hostname}`,\n ` User ${opts.user}`,\n ];\n if (opts.port) {\n lines.push(` Port ${String(opts.port)}`);\n }\n if (opts.proxyJump) {\n // The jump host dials `HostName:Port` itself, which is why a box published\n // on the engine's loopback is reachable at all.\n lines.push(` ProxyJump ${opts.proxyJump}`);\n }\n if (opts.identityFile) {\n // `IdentitiesOnly yes` stops ssh-agent from offering unrelated keys\n // first — some sshd configs cap auth attempts and would lock us out\n // before the right key is tried.\n lines.push(` IdentityFile ${opts.identityFile}`);\n lines.push(` IdentitiesOnly yes`);\n }\n lines.push(\n ` StrictHostKeyChecking accept-new`,\n ` UserKnownHostsFile /dev/null`,\n ` LogLevel ERROR`,\n endMarker(opts.alias, opts.kind),\n '',\n );\n return lines.join('\\n');\n}\n\n/**\n * Old versions wrote per-box `# BEGIN agentbox cloud box <alias>` … `# END …`\n * blocks directly into `~/.ssh/config`. We now own `~/.agentbox/ssh/config`, so\n * strip any such inline leftovers whenever we touch `~/.ssh/config`. AgentBox is\n * unreleased → clean removal, no deprecation shim.\n */\nfunction stripLegacyInlineBlocks(contents: string): string {\n const pattern = /^# BEGIN agentbox cloud box .*\\n[\\s\\S]*?^# END agentbox cloud box .*\\n?/gm;\n return contents.replace(pattern, '');\n}\n\nfunction hasIncludeBlock(contents: string): boolean {\n return (\n contents.includes(INCLUDE_BEGIN) || contents.includes(`Include ${agentboxSshConfigPath()}`)\n );\n}\n\n/**\n * Ensure `~/.ssh/config` contains exactly one managed `Include\n * ~/.agentbox/ssh/config` block, prepended to the top. Prepend (not append)\n * because OpenSSH applies the first value it sees per keyword — putting the\n * Include first lets AgentBox's box entries win over any later user `Host *`\n * defaults. Also strips any legacy inline per-box blocks. Idempotent.\n */\nexport async function ensureSshInclude(): Promise<void> {\n const path = sshConfigPath();\n await fs.mkdir(join(homedir(), '.ssh'), { recursive: true, mode: 0o700 });\n const existing = stripLegacyInlineBlocks(await readFileOrEmpty(path));\n let next = existing;\n if (!hasIncludeBlock(existing)) {\n const block = `${INCLUDE_BEGIN}\\nInclude ${agentboxSshConfigPath()}\\n${INCLUDE_END}\\n`;\n next = existing.length === 0 ? block : `${block}\\n${existing}`;\n }\n await fs.writeFile(path, next, { mode: 0o600 });\n // Re-assert mode in case the file existed with broader perms.\n await fs.chmod(path, 0o600);\n}\n\n/**\n * Where a control-box deploy gets the hub from.\n *\n * `package` (the default) installs the published `@madarco/agentbox` on the VPS\n * and runs the standalone hub it already ships at `runtime/hub/apps/hub/server.js`\n * — the same bundle `agentbox hub` spawns locally. The control box and the PC\n * that deployed it then run the identical published build by construction, which\n * also makes their base-image fingerprints match byte-for-byte.\n *\n * `source` clones the monorepo onto the VPS and builds it there. The escape hatch\n * for deploying unreleased code, and what a dev build (no published version to\n * install) falls back to.\n *\n * Lives here, next to the record that carries it, so the deploy record stays a\n * plain sandbox-core type — provider packages depend on this one, not the reverse.\n */\nexport type HubDeploySource =\n | { kind: 'package'; spec: string }\n | { kind: 'source'; repoUrl: string; repoRef: string };\n\n/**\n * The record `agentbox hub deploy` persists to `deploy.json`. Every field is\n * optional because it is also written mid-deploy (before the hub is healthy)\n * and read back by later commands that must tolerate an older/partial file.\n */\nexport interface ControlPlaneDeployRecord {\n provider?: string;\n /** Public URL the hub serves on, e.g. `https://<ip>.sslip.io`. */\n url?: string;\n serverId?: number;\n ip?: string;\n domain?: string;\n /**\n * Hetzner firewall ids are numeric; DigitalOcean's are UUID strings — one field\n * carries either, so the destroy/update paths tolerate both providers.\n */\n firewallId?: number | string;\n /**\n * DigitalOcean only: the unique per-deploy tag the control-plane firewall is\n * bound to (created before the droplet so the firewall auto-applies at boot).\n * Destroy deletes it once the firewall is gone, or it leaks as an empty tag.\n */\n firewallTag?: string;\n /** Holds `id_ed25519` (+ `.pub`, `known_hosts`) — the only key that VPS trusts. */\n sshKeyDir?: string;\n /**\n * What was deployed. Nothing else records the running build — the VPS keeps no\n * version marker, and in package mode there is not even a git checkout to\n * `rev-parse` — so without this a control box is unattributable after the fact.\n */\n source?: HubDeploySource;\n\n // --- `provider: 'local'` only (agentbox hub expose) -----------------------\n // A control box that IS this machine's own hub, flipped to the deployed\n // profile rather than a separate VPS. These fields describe how it was\n // exposed so `hub start` / autostart / update / destroy reconstruct the mode\n // from disk. `sshKeyDir` is intentionally absent (no ssh alias block).\n /**\n * The box-facing URL: what a cloud box is told to call home on\n * (`AGENTBOX_HUB_PUBLIC_URL`). The LAN address, or the tunnel URL. Distinct\n * from the CLI-facing loopback the local shortcut uses.\n */\n publicUrl?: string;\n /** Port the hub binds (default 8787). */\n port?: number;\n /** Bind address (`0.0.0.0` LAN, `127.0.0.1` loopback-only). */\n bind?: string;\n /** The tunnel kind in front of the hub, if any: `cloudflare` | `tailscale`. */\n tunnel?: string;\n /** Whether an autostart unit (launchd/systemd) was installed. */\n autostart?: boolean;\n /**\n * The admin PC's egress CIDR at expose time — added to a hetzner box's\n * firewall so this machine can still SSH boxes the hub creates. Stored (not\n * recomputed) so the exposed-env assembly stays a pure function of the record.\n */\n adminCidr?: string;\n}\n\n/**\n * The managed block for the deployed control box, or '' when there is no deploy\n * record (or it predates `sshKeyDir`). Read from `deploy.json` rather than\n * `state.json` because the control box is not a box — it is the machine that\n * *runs* the hub, and nothing else in the CLI models it.\n */\nasync function controlPlaneBlock(deployPath: string): Promise<string> {\n let record: ControlPlaneDeployRecord;\n try {\n record = JSON.parse(await fs.readFile(deployPath, 'utf8')) as ControlPlaneDeployRecord;\n } catch {\n // Absent (never deployed) or corrupt — either way there is no host to add.\n return '';\n }\n if (!record.ip || !record.sshKeyDir) return '';\n return buildBlock({\n kind: 'control box',\n alias: AGENTBOX_HUB_SSH_ALIAS,\n hostname: record.ip,\n // The deploy provisions stock Ubuntu and works as root throughout (docker\n // compose, /opt/agentbox); no unprivileged user is ever created.\n user: 'root',\n identityFile: join(record.sshKeyDir, 'id_ed25519'),\n });\n}\n\n/**\n * Regenerate the AgentBox-owned `~/.agentbox/ssh/config` from `state.json`: one\n * `Host <name>` block per box that carries a resolved `box.ssh` target, plus a\n * `Host agentbox-hub` block for the deployed control box (from `deploy.json`).\n * Reads only persisted state — no provider calls, never wakes a paused box — so\n * a destroyed box's block simply disappears on the next sync. Also ensures the\n * `Include` line in `~/.ssh/config`.\n */\nexport async function syncAgentboxSshConfig(\n statePath: string = stateFilePath(),\n deployPath: string = controlPlaneDeployPath(),\n): Promise<void> {\n const state = await readState(statePath);\n const blocks: string[] = [];\n const aliases = new Set<string>();\n for (const box of state.boxes) {\n const ssh = box.ssh;\n if (!ssh) continue;\n aliases.add(agentboxAliasFor(box.name));\n blocks.push(\n buildBlock({\n alias: agentboxAliasFor(box.name),\n hostname: ssh.host,\n user: ssh.user,\n identityFile: ssh.identityFile,\n port: ssh.port,\n proxyJump: ssh.proxyJump,\n }),\n );\n }\n // A box literally named `agentbox-hub` would otherwise emit a second `Host\n // agentbox-hub`; OpenSSH takes the first, so the box (the more specific,\n // user-created thing) wins and we skip ours rather than write a dead stanza.\n if (!aliases.has(AGENTBOX_HUB_SSH_ALIAS)) {\n const hub = await controlPlaneBlock(deployPath);\n if (hub) blocks.push(hub);\n }\n const header =\n '# Managed by agentbox — regenerated on box create/start/destroy and hub deploy.\\n' +\n '# Do not edit; changes are overwritten. Disable with `agentbox config set ssh.autoConfig false`.\\n\\n';\n const path = agentboxSshConfigPath();\n await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });\n await fs.writeFile(path, header + blocks.join('\\n'), { mode: 0o600 });\n await fs.chmod(path, 0o600);\n await ensureSshInclude();\n\n // Sweep Claude desktop's sshConfigs (written by `open --in claude`) of\n // entries whose box is gone — piggybacking on the sync means every destroy\n // path prunes (CLI, hub, dashboard), and any later sync self-heals one that\n // didn't. Aliases are keyed by box NAME (an entry survives a transiently\n // ssh-less record). Best-effort: a corrupt settings.json must never break\n // box lifecycle.\n try {\n pruneOrphanClaudeSshConfigs(new Set(state.boxes.map((b) => agentboxAliasFor(b.name))));\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * True when `~/.ssh/config` has a user-authored `Host <alias>` stanza. With the\n * Include prepended, AgentBox's entry is read first so it wins — but a foreign\n * `Host <alias>` is still worth flagging to the user in case they expected their\n * own entry to take effect.\n */\nexport async function hasUnmanagedHostConflict(alias: string): Promise<boolean> {\n const contents = stripLegacyInlineBlocks(await readFileOrEmpty(sshConfigPath()));\n if (contents === '') return false;\n return contents.split('\\n').some((line) => {\n const m = /^\\s*Host\\s+(.+?)\\s*$/.exec(line);\n if (!m) return false;\n return m[1]!.split(/\\s+/).includes(alias);\n });\n}\n\nexport interface SshTarget {\n user: string;\n host: string;\n /** Path from `-i <path>` if the argv carries one (Hetzner). Undefined for\n * Daytona where auth is via token-in-User. */\n identityFile?: string;\n}\n\n/**\n * Pluck the SSH connect target (and identity file, if any) out of an argv\n * returned by a provider's `attachArgv` / `buildAttach`. The argv shape is\n * `ssh [-i <path>] [-o ...] <user>@<host> [command...]` — we walk from the\n * end to find the user@host token and scan forward for `-i`.\n */\nexport function parseSshTarget(argv: readonly string[]): SshTarget | undefined {\n let target: { user: string; host: string } | undefined;\n for (let i = argv.length - 1; i >= 0; i--) {\n const v = argv[i];\n if (!v || v.startsWith('-')) continue;\n const at = v.indexOf('@');\n if (at <= 0) continue;\n target = { user: v.slice(0, at), host: v.slice(at + 1) };\n break;\n }\n if (!target) return undefined;\n let identityFile: string | undefined;\n for (let i = 0; i < argv.length - 1; i++) {\n if (argv[i] === '-i') {\n identityFile = argv[i + 1];\n break;\n }\n }\n return { ...target, identityFile };\n}\n\n/**\n * Read back the `HostName` / `IdentityFile` from the managed block for `alias`\n * in `~/.agentbox/ssh/config`, if one exists. Used by `inspect` to surface the\n * SSH connection details without re-deriving them from a provider (which would\n * require bringing the box online). Returns undefined when no managed block is\n * present for the alias.\n */\nexport async function readAgentboxSshAlias(\n alias: string,\n): Promise<{ hostName?: string; identityFile?: string } | undefined> {\n const contents = await readFileOrEmpty(agentboxSshConfigPath());\n if (contents === '') return undefined;\n const begin = beginMarker(alias);\n const end = endMarker(alias);\n const escape = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const match = new RegExp(`^${escape(begin)}\\\\n([\\\\s\\\\S]*?)${escape(end)}`, 'm').exec(contents);\n if (!match) return undefined;\n const body = match[1] ?? '';\n const field = (name: string): string | undefined =>\n new RegExp(`^\\\\s*${name}\\\\s+(.+)$`, 'm').exec(body)?.[1]?.trim();\n return { hostName: field('HostName'), identityFile: field('IdentityFile') };\n}\n","/**\n * Writer for the Claude desktop app's own settings (`~/.claude/settings.json`)\n * — the app-local analogue of Codex's `codex://settings/connections/ssh/add`\n * deep link, which Claude.app doesn't have. The app reads SSH environments\n * from a `sshConfigs` array in its user settings (schema verified against\n * Claude.app v1.19367): `{ id, name, sshHost, sshPort?, sshIdentityFile?,\n * startDirectory? }`, where `sshHost` may be an alias from `~/.ssh/config` —\n * which is exactly what AgentBox maintains per box.\n *\n * This file is the user's REAL Claude Code settings: preserve every key we\n * don't own, and fail loud (never overwrite) when it exists but doesn't parse.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\nexport interface ClaudeSshConfigEntry {\n /** Unique id; the app matches configs across settings sources by it. */\n id: string;\n /** Display name shown in the app's Environment dropdown. */\n name: string;\n /** \"user@host\", \"host\", or an alias from ~/.ssh/config. */\n sshHost: string;\n sshPort?: number;\n sshIdentityFile?: string;\n /** Default working directory on the remote (tilde-expanded by the app). */\n startDirectory?: string;\n}\n\nexport function claudeSettingsPath(): string {\n return join(homedir(), '.claude', 'settings.json');\n}\n\n/** The sshConfigs entry for a box: the alias carries port + identity file. */\nexport function claudeSshEntryFor(alias: string, boxName: string): ClaudeSshConfigEntry {\n return {\n id: `agentbox-${alias}`,\n name: `AgentBox: ${boxName}`,\n sshHost: alias,\n startDirectory: '/workspace',\n };\n}\n\ninterface ClaudeSettings {\n sshConfigs?: unknown[];\n [key: string]: unknown;\n}\n\nfunction readSettings(path: string): ClaudeSettings {\n if (!existsSync(path)) return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(path, 'utf8'));\n } catch (err) {\n throw new Error(\n `${path} exists but is not valid JSON (${err instanceof Error ? err.message : String(err)}) — ` +\n `not touching it. Fix the file and retry.`,\n );\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${path} is not a JSON object — not touching it. Fix the file and retry.`);\n }\n return parsed as ClaudeSettings;\n}\n\nfunction writeSettings(path: string, settings: ClaudeSettings): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(settings, null, 2) + '\\n');\n}\n\nfunction entryId(e: unknown): string | undefined {\n if (e !== null && typeof e === 'object' && typeof (e as { id?: unknown }).id === 'string') {\n return (e as { id: string }).id;\n }\n return undefined;\n}\n\n/**\n * Insert or replace (by `id`) one entry in `sshConfigs`, preserving every\n * other entry and every other settings key. Throws on an unparseable file.\n */\nexport function upsertClaudeSshConfig(entry: ClaudeSshConfigEntry): void {\n const path = claudeSettingsPath();\n const settings = readSettings(path);\n const configs = Array.isArray(settings.sshConfigs) ? settings.sshConfigs : [];\n const idx = configs.findIndex((e) => entryId(e) === entry.id);\n if (idx >= 0) {\n configs[idx] = entry;\n } else {\n configs.push(entry);\n }\n settings.sshConfigs = configs;\n writeSettings(path, settings);\n}\n\n/**\n * Drop every AgentBox-owned (`agentbox-`-prefixed) entry whose alias no longer\n * matches a live box. Called (best-effort) from `syncAgentboxSshConfig`, which\n * every lifecycle path runs — CLI destroy, hub/dashboard destroys via\n * `provider.destroy`+sync, and any later create/start — so an entry left by a\n * path that skipped the sync is swept on the next one. Foreign entries (no\n * `agentbox-` prefix) are never touched.\n */\nexport function pruneOrphanClaudeSshConfigs(liveAliases: ReadonlySet<string>): number {\n return removeClaudeSshConfigs(\n (id) => id.startsWith('agentbox-') && !liveAliases.has(id.slice('agentbox-'.length)),\n );\n}\n\n/**\n * Drop every `sshConfigs` entry whose id matches `predicate`. No-op when the\n * file is missing, has no `sshConfigs`, or nothing matches — the file is only\n * rewritten on a change. Throws on an unparseable file (callers treat this as\n * best-effort).\n */\nexport function removeClaudeSshConfigs(predicate: (id: string) => boolean): number {\n const path = claudeSettingsPath();\n if (!existsSync(path)) return 0;\n const settings = readSettings(path);\n if (!Array.isArray(settings.sshConfigs)) return 0;\n const kept = settings.sshConfigs.filter((e) => {\n const id = entryId(e);\n return id === undefined || !predicate(id);\n });\n const removed = settings.sshConfigs.length - kept.length;\n if (removed === 0) return 0;\n settings.sshConfigs = kept;\n writeSettings(path, settings);\n return removed;\n}\n","/**\n * Pure assembly of the exposed hub's spawn env — the flip `agentbox hub expose`\n * applies to the ONE local hub process to make it the control box (deployed\n * `hetzner` profile) instead of the plain localhost hub.\n *\n * Lives in sandbox-core (not the CLI) because BOTH sides need it: the CLI's\n * expose flow writes the record, and `ensureHub()` in sandbox-docker reads the\n * record back on every `hub start` / restart / autostart to bring the hub up in\n * the same mode. Keeping it pure (record + env-file map in, env out) makes the\n * flip unit-testable and keeps a single source of truth for the env.\n */\nimport type { ControlPlaneDeployRecord } from './ssh-config.js';\n\n/** The profile an exposed hub runs in (password auth + SQLite store + worker). */\nexport const EXPOSED_HUB_PROFILE = 'hetzner';\n\n/**\n * Parse an `.env`-style file body into a map. Same shape as the CLI's env-file\n * reader; duplicated here (one tiny regex) so sandbox-core needs no CLI import.\n */\nexport function parseEnvFileBody(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const line of body.split('\\n')) {\n const m = /^([A-Z_]+)=(.*)$/.exec(line.trim());\n if (m) out[m[1]!] = m[2]!;\n }\n return out;\n}\n\n/**\n * The env overrides that turn the localhost hub into the exposed control box.\n * Applied over the base spawn env, so `AGENTBOX_HUB_HOST` (loopback by default)\n * becomes the LAN/loopback bind, the profile flips to `hetzner` (password +\n * SQLite + worker), and the box-facing public URL + secrets are carried in.\n *\n * `env` is the parsed `control-plane.env` (admin token, API key, GH token, and\n * — after `hub expose` prompts — the auth block). Missing keys are simply\n * omitted; the hub fails closed on a missing secret rather than this function.\n */\nexport function buildExposedHubEnv(\n record: ControlPlaneDeployRecord,\n env: Record<string, string>,\n): Record<string, string> {\n const out: Record<string, string> = {\n AGENTBOX_HUB_HOST: record.bind || '0.0.0.0',\n AGENTBOX_HUB_PROFILE: EXPOSED_HUB_PROFILE,\n AGENTBOX_HUB_AUTH: 'on',\n AGENTBOX_HUB_WORKER: 'on',\n };\n if (record.port) out.AGENTBOX_HUB_PORT = String(record.port);\n if (record.publicUrl) out.AGENTBOX_HUB_PUBLIC_URL = record.publicUrl;\n if (record.adminCidr) out.AGENTBOX_HUB_ADMIN_CIDR = record.adminCidr;\n // Secrets from control-plane.env — the /admin wire token, the headless\n // /api/v1 key, the login secret + admin creds, and the hub's own git token.\n for (const k of [\n 'AGENTBOX_RELAY_ADMIN_TOKEN',\n 'AGENTBOX_HUB_API_KEY',\n 'BETTER_AUTH_SECRET',\n 'AGENTBOX_HUB_ADMIN_EMAIL',\n 'AGENTBOX_HUB_ADMIN_PASSWORD',\n 'GH_TOKEN',\n 'GITHUB_APP_ID',\n 'GITHUB_APP_PRIVATE_KEY',\n ]) {\n if (env[k]) out[k] = env[k]!;\n }\n return out;\n}\n","/**\n * Resolve a {@link ProviderDescriptor} for ANY runtime provider — built-in or\n * registered plugin — synchronously and offline.\n *\n * Built-ins declare their descriptor in `@agentbox/config`'s `PROVIDERS` table.\n * A plugin declares one on `ProviderModule.descriptor`, which `agentbox plugin\n * add` snapshots into `~/.agentbox/plugins.json`. Both are plain data by the\n * time anything asks, which is the point: the CLI's `open --targets` probe and\n * the hub's `listProviders` are hot, sync paths that must never `import()` an\n * external package to answer \"does this provider support checkpoints?\".\n *\n * A plugin that predates descriptors (or simply declares none) still resolves —\n * see {@link deriveDescriptor} for the fallback and why each default is what it\n * is.\n */\n\nimport { PROVIDERS, isProviderKind, providerMeta } from '@agentbox/config';\nimport type { ProviderCapabilities, ProviderDescriptor } from '@agentbox/config';\nimport type { ProviderModule } from './doctor.js';\nimport {\n PLUGINS_FILE,\n pluginForProvider,\n readPluginRegistrySync,\n recordPluginDescriptor,\n} from './plugin-registry.js';\n\n/**\n * The descriptor for `name`, or undefined when nothing provides it.\n *\n * Built-in table first — a plugin can never shadow a built-in (`plugin add`\n * rejects that), so the order is a formality that also keeps the common case\n * off the filesystem.\n */\nexport function resolveProviderDescriptor(\n name: string,\n path: string = PLUGINS_FILE,\n): ProviderDescriptor | undefined {\n if (isProviderKind(name)) return providerMeta(name);\n return pluginForProvider(name, path)?.descriptors?.[name];\n}\n\n/** Every resolvable descriptor: built-ins in canonical order, then plugins. */\nexport function listProviderDescriptors(path: string = PLUGINS_FILE): ProviderDescriptor[] {\n // PROVIDERS is already in canonical order (docker first).\n const builtIns: ProviderDescriptor[] = [...PROVIDERS];\n const plugins: ProviderDescriptor[] = [];\n for (const rec of readPluginRegistrySync(path).plugins) {\n for (const providerName of rec.providers) {\n const d = rec.descriptors?.[providerName];\n // A plugin with no snapshot yet is still a real, creatable provider — list\n // it on a placeholder rather than hiding it until something back-fills.\n plugins.push(d ?? placeholderDescriptor(providerName));\n }\n }\n return [...builtIns, ...plugins];\n}\n\n/**\n * Defaults for a provider we know exists but have no descriptor for. Every value\n * is chosen to reproduce what AgentBox did for a plugin BEFORE descriptors — a\n * \"safe = false\" default would silently delete working UI (see `vnc`/`dind`/\n * `pauseSemantics`).\n */\nconst FALLBACK_CAPABILITIES: ProviderCapabilities = {\n // Cloud plugins are near-universally built on `createCloudProvider`, which\n // gives them a working `checkpoint`. `deriveDescriptor` refines this from the\n // real module when one is available.\n checkpoints: false,\n checkpointReboots: false,\n ssh: false,\n // Plugins were excluded from PERSISTENT_SSH_PROVIDERS / the direct-ssh list,\n // so false IS the status quo — a plugin opts in by declaring a descriptor.\n persistentSsh: false,\n directBoxSsh: false,\n inbound: false,\n directGit: false,\n resync: true,\n prune: false,\n // TRUE on purpose: `createCloudProvider` wires VNC unconditionally and\n // degrades best-effort, and `launchDockerd` defaults true. Defaulting these\n // false would remove a VNC button / DinD that works today.\n vnc: true,\n dind: true,\n // The pre-descriptor UI showed an unqualified Pause for every running box.\n pauseSemantics: 'freeze',\n hubRoutable: true,\n};\n\n/**\n * Display label for a provider that declared none. Capitalising the first letter\n * is the whole transform, and it is a display concern only — every other\n * placeholder field keeps the raw name, and nothing resolves a provider by label.\n *\n * It earns its place because the raw id reaches the UI: a plugin showed as\n * `sprites` in the create picker while the tray's own progress line capitalises\n * the same id, so one panel rendered two spellings of one provider. Anything\n * cleverer — title-casing, expanding `remote-docker` — would be guessing at a\n * name only the plugin author knows, which is what `descriptor.label` is for.\n */\nfunction placeholderLabel(name: string): string {\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\nfunction placeholderDescriptor(name: string): ProviderDescriptor {\n return {\n name,\n kind: 'cloud',\n label: placeholderLabel(name),\n loginHint: '',\n credentials: { envKeys: [], fields: [] },\n // NOT `true`: the hub's create gate deliberately skips the configured check\n // for plugins, so demanding a bake here would newly block creates that work.\n bake: { required: false, approxMinutes: '1' },\n capabilities: { ...FALLBACK_CAPABILITIES },\n blurb: `the ${name} provider`,\n sizeDesc: `Per-provider override of \\`box.size\\` for ${name}.`,\n imageDesc: `Per-provider override of \\`box.image\\` for ${name}.`,\n };\n}\n\n/**\n * Build a descriptor for a LOADED plugin module: what it declares, else what can\n * be honestly derived from it, else the fallback defaults.\n *\n * Derivation reads `CloudBackend` methods, never `Provider` ones. Provider\n * methods are supplied by `createCloudProvider` for every cloud provider\n * (`setInbound`, `repairReachability`, `enableDirectGit`, `checkpoint`), so their\n * presence says which scaffold was used, not what the provider supports. Backend\n * methods are written by the provider author, so they mean something.\n *\n * `provider.checkpoint` and `provider.sshTarget` are the two exceptions worth\n * reading: unlike the built-in table (where docker has working checkpoints and no\n * `provider.checkpoint`), a plugin that has the scaffold-supplied `checkpoint`\n * really does get working checkpoints from it.\n */\nexport function deriveDescriptor(name: string, mod: ProviderModule): ProviderDescriptor {\n const declared = mod.descriptor;\n if (declared) return declared;\n const base = placeholderDescriptor(name);\n const { provider, backend } = mod;\n return {\n ...base,\n kind: backend ? 'cloud' : 'local',\n credentials: {\n envKeys: [],\n // Only offer a credential form when the module can actually consume one.\n fields: mod.setCredentials ? [{ key: 'apiKey', label: 'API key' }] : [],\n },\n capabilities: {\n ...base.capabilities,\n checkpoints: !!provider.checkpoint,\n ssh: !!provider.sshTarget,\n resync: !!provider.resyncWorkspace,\n prune: !!backend?.list,\n inbound: !!backend?.setInbound,\n ...(backend?.timeoutModel ? { timeoutModel: backend.timeoutModel } : {}),\n },\n };\n}\n\n/**\n * Resolve `name`'s descriptor, deriving and back-filling the registry snapshot\n * when the plugin has none. Call this from paths that are loading the module\n * anyway; everything else should use the sync {@link resolveProviderDescriptor}.\n *\n * The write is best-effort: a lost snapshot only costs the next caller another\n * derivation, so a read-only HOME or a concurrent writer must not fail a create.\n */\nexport async function ensureProviderDescriptor(\n name: string,\n mod: ProviderModule,\n path: string = PLUGINS_FILE,\n): Promise<ProviderDescriptor> {\n const existing = resolveProviderDescriptor(name, path);\n if (existing) return existing;\n const derived = deriveDescriptor(name, mod);\n await recordPluginDescriptor(name, derived, path).catch(() => {});\n return derived;\n}\n","/**\n * The external-provider plugin registry: `~/.agentbox/plugins.json`.\n *\n * A community provider ships as its own npm package (`agentbox-provider-<name>`)\n * built against `@madarco/agentbox-provider-sdk`. The user installs it themselves, then\n * `agentbox plugin add <pkg>` validates it and records it here; the CLI and the\n * host relay both read this file to resolve + lazily `import()` the package at\n * runtime (a true variable specifier — built-ins are bundle-inlined, external\n * providers are not).\n *\n * Concurrency + durability mirror `state.ts`: an O_EXCL lockfile guards the\n * read-modify-write, and writes are atomic (temp + rename). Reads have a sync\n * variant so the CLI's synchronous `isKnownProvider`/name-list checks can\n * consult it without going async.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport type { ProviderDescriptor } from '@agentbox/config';\n\nexport const PLUGINS_FILE = join(homedir(), '.agentbox', 'plugins.json');\n\n/**\n * `SDK_API_VERSION` majors this CLI can load. A plugin built against an SDK\n * whose major is not listed is refused at `plugin add` and skipped at load\n * (with a warning) rather than crashing the CLI. Extend this array when the CLI\n * keeps back-compat with an older provider contract.\n */\n// v2: BoxRecord.cloud.ssh moved to top-level BoxRecord.ssh (+port, docker sshd\n// fields). v1 plugins still load — only ones reading box.cloud.ssh notice.\n//\n// v3: the three per-agent staging exports (`stage<Agent>StaticForUpload`) are\n// replaced by the registry-driven `stageAllAgentStatic`. Unlike v2 this is a\n// CLEAN BREAK — v1 and v2 are no longer accepted — because a v2 provider stages\n// a hardcoded three agents, so on a host with a fourth it bakes a snapshot that\n// silently lacks it. Loading such a plugin would produce wrong boxes rather\n// than a missing feature, which is worse than refusing it. A v2 plugin is\n// refused at `plugin add` and skipped at load with a message naming the version.\n//\n// v4: agent settings. `PrepareOptions.claudeInstall` is replaced by the generic\n// `agentSettings` map, `resolveAgentInstall` takes that agent's settings rather\n// than a mode string, `Provider.baseFingerprint` takes no arguments (an\n// agentless base folds no agent setting), and `claudeInstallFingerprint` is\n// gone. A CLEAN BREAK for the same reason v3 was: a v3 provider silently drops\n// every agent setting, so on a host that set `claude.install: npm` it bakes a\n// base with the recipe the user chose specifically because it fails there — a\n// wrong artifact rather than a missing feature.\nexport const SUPPORTED_SDK_API_VERSIONS: readonly number[] = [4];\n\nexport function isSupportedApiVersion(v: number): boolean {\n return SUPPORTED_SDK_API_VERSIONS.includes(v);\n}\n\n/** One registered external provider package. */\nexport interface PluginRecord {\n /** Package name as installed (e.g. `agentbox-provider-digitalocean`). */\n packageName: string;\n /** Absolute path to the package's resolved entry module, recorded at add time. */\n resolvedEntry: string;\n /** Package version at add time (informational). */\n version: string;\n /** Provider names this package contributes (from each `providerModule.provider.name`). */\n providers: string[];\n /**\n * Per-provider descriptor snapshot, captured at `plugin add` from the module's\n * declared `ProviderModule.descriptor` merged with what could be derived from\n * the loaded module. Keyed by provider name.\n *\n * Snapshotting is what lets every consumer — the CLI's sync `open --targets`\n * probe, the hub's hot `listProviders` path — resolve capabilities WITHOUT an\n * `import()` of an external package. Absent on a v1 record; back-filled the\n * first time something loads the module anyway.\n */\n descriptors?: Record<string, ProviderDescriptor>;\n /** `SDK_API_VERSION` the package declared (compat gate). */\n apiVersion: number;\n /** ISO timestamp the package was added. */\n addedAt: string;\n}\n\n/**\n * v2 added `PluginRecord.descriptors`. A v1 file is read as-is and upgraded in\n * place on the next write — the field is optional, so nothing breaks in between.\n */\nexport type PluginsFileVersion = 1 | 2;\n\nexport interface PluginsFile {\n version: PluginsFileVersion;\n plugins: PluginRecord[];\n}\n\nexport const PLUGINS_FILE_VERSION = 2;\n\nconst EMPTY: PluginsFile = { version: PLUGINS_FILE_VERSION, plugins: [] };\n\nfunction isKnownVersion(v: unknown): v is PluginsFileVersion {\n return v === 1 || v === 2;\n}\n\nconst LOCK_STALE_MS = 15_000;\nconst LOCK_ACQUIRE_TIMEOUT_MS = 20_000;\nconst LOCK_RETRY_MS = 25;\n\n/** Exclusive cross-process lock around `${path}.lock` (mirrors state.ts). */\nasync function withFileLock<T>(path: string, fn: () => Promise<T>): Promise<T> {\n const lockPath = `${path}.lock`;\n await mkdir(dirname(path), { recursive: true });\n const deadline = Date.now() + LOCK_ACQUIRE_TIMEOUT_MS;\n let held = false;\n while (!held) {\n try {\n const fh = await open(lockPath, 'wx');\n await fh.writeFile(`${String(process.pid)}\\n`);\n await fh.close();\n held = true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;\n try {\n const st = await stat(lockPath);\n if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {\n await rm(lockPath, { force: true });\n continue;\n }\n } catch {\n continue;\n }\n if (Date.now() >= deadline) break;\n await delay(LOCK_RETRY_MS);\n }\n }\n try {\n return await fn();\n } finally {\n if (held) await rm(lockPath, { force: true }).catch(() => {});\n }\n}\n\nfunction normalize(raw: unknown): PluginsFile {\n const parsed = raw as PluginsFile;\n if (!parsed || !isKnownVersion(parsed.version) || !Array.isArray(parsed.plugins)) {\n // Unrecognized shape → treat as empty (a fresh registry), never throw:\n // a corrupt plugins.json must not brick every CLI command.\n return { ...EMPTY };\n }\n return parsed;\n}\n\n/** Synchronous read for the CLI's sync name-list / validation checks. Missing file → empty. */\nexport function readPluginRegistrySync(path: string = PLUGINS_FILE): PluginsFile {\n try {\n if (!existsSync(path)) return { ...EMPTY };\n return normalize(JSON.parse(readFileSync(path, 'utf8')));\n } catch {\n return { ...EMPTY };\n }\n}\n\nexport async function readPluginRegistry(path: string = PLUGINS_FILE): Promise<PluginsFile> {\n try {\n return normalize(JSON.parse(await readFile(path, 'utf8')));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY };\n return { ...EMPTY };\n }\n}\n\n/**\n * Read for a read-modify-WRITE. Unlike the lenient readers (which degrade a\n * corrupt file to empty so the CLI never bricks), this REFUSES to proceed when\n * an existing file is unparseable/unrecognized — otherwise `addPluginRecord`\n * would overwrite a recoverable `plugins.json` and silently drop every other\n * registered plugin. A genuinely missing file (ENOENT) is still an empty start.\n */\nasync function readForWrite(path: string): Promise<PluginsFile> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ...EMPTY };\n throw err;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `refusing to modify a corrupt plugin registry at ${path} (${(err as Error).message}) — fix or delete the file and retry.`,\n );\n }\n const p = parsed as PluginsFile;\n if (!p || !isKnownVersion(p.version) || !Array.isArray(p.plugins)) {\n throw new Error(\n `refusing to modify an unrecognized plugin registry at ${path} — fix or delete the file and retry.`,\n );\n }\n return p;\n}\n\nasync function writeRegistry(file: PluginsFile, path: string = PLUGINS_FILE): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const tmp = `${path}.tmp.${String(process.pid)}.${String(Date.now())}`;\n // Any write upgrades a v1 file: the added field is optional, so an older CLI\n // reading the result still sees every record it understands.\n const out: PluginsFile = { ...file, version: PLUGINS_FILE_VERSION };\n await writeFile(tmp, JSON.stringify(out, null, 2) + '\\n', 'utf8');\n await rename(tmp, path);\n}\n\n/**\n * Record a descriptor snapshot for one provider of an already-registered\n * package (the back-fill path for a v1 record, or a plugin that declared none).\n * A no-op when the package isn't registered — losing a snapshot only costs the\n * next caller another derivation, so this must never throw into a hot path.\n */\nexport async function recordPluginDescriptor(\n providerName: string,\n descriptor: ProviderDescriptor,\n path: string = PLUGINS_FILE,\n): Promise<void> {\n await withFileLock(path, async () => {\n const file = await readForWrite(path);\n const rec = file.plugins.find((p) => p.providers.includes(providerName));\n if (!rec) return;\n rec.descriptors = { ...rec.descriptors, [providerName]: descriptor };\n await writeRegistry(file, path);\n });\n}\n\n/** Upsert a plugin by `packageName` (idempotent re-add updates the record). */\nexport async function addPluginRecord(\n record: PluginRecord,\n path: string = PLUGINS_FILE,\n): Promise<void> {\n await withFileLock(path, async () => {\n const file = await readForWrite(path);\n const next = file.plugins.filter((p) => p.packageName !== record.packageName);\n next.push(record);\n await writeRegistry({ version: PLUGINS_FILE_VERSION, plugins: next }, path);\n });\n}\n\n/**\n * Remove a plugin by package name OR by a provider name it contributes.\n * Returns the removed record(s) count.\n */\nexport async function removePluginRecord(\n nameOrPackage: string,\n path: string = PLUGINS_FILE,\n): Promise<number> {\n let removed = 0;\n await withFileLock(path, async () => {\n const file = await readForWrite(path);\n const next = file.plugins.filter((p) => {\n const match = p.packageName === nameOrPackage || p.providers.includes(nameOrPackage);\n if (match) removed += 1;\n return !match;\n });\n await writeRegistry({ version: PLUGINS_FILE_VERSION, plugins: next }, path);\n });\n return removed;\n}\n\n/** All provider names contributed by registered plugins (sync). */\nexport function pluginProviderNames(path: string = PLUGINS_FILE): string[] {\n return readPluginRegistrySync(path).plugins.flatMap((p) => p.providers);\n}\n\n/** The plugin record that contributes `providerName`, or null (sync). */\nexport function pluginForProvider(\n providerName: string,\n path: string = PLUGINS_FILE,\n): PluginRecord | null {\n return (\n readPluginRegistrySync(path).plugins.find((p) => p.providers.includes(providerName)) ?? null\n );\n}\n","import type { BoxRecord, Provider } from '@agentbox/core';\nimport { resolveProviderDescriptor } from './provider-descriptor.js';\nimport { recordBoxSsh } from './state.js';\nimport { agentboxAliasFor, parseSshTarget, syncAgentboxSshConfig } from './ssh-config.js';\n\n/**\n * Resolve + persist a cloud box's SSH connection target and regenerate\n * `~/.agentbox/ssh/config`. Lives in sandbox-core (not the CLI) so BOTH the CLI\n * commands AND the hub can write the SSH config after create/start/resume — the\n * caller supplies the already-resolved `Provider` (the CLI via `providerForBox`,\n * the hub via its own provider seam), so this code takes no dependency on either\n * one's provider registry.\n */\n\nexport interface CloudSshAlias {\n /** Host alias written to `~/.ssh/config` (the box name). */\n alias: string;\n /** SSH host — VPS IP (Hetzner) or gateway domain (Daytona). */\n host: string;\n /** SSH user — `vscode` (Hetzner) or an ephemeral token (Daytona). */\n user: string;\n /**\n * Per-box private key path when the provider authenticates by identity file\n * (Hetzner). Undefined for token-in-User providers (Daytona) — callers that\n * need a persistent connection (external apps) should treat its absence as\n * \"not supported\".\n */\n identityFile?: string;\n /** Non-default SSH port (remote-docker: the box's sshd published on the engine). */\n port?: number;\n /** Jump host, when the box is only reachable through another machine. */\n proxyJump?: string;\n}\n\nexport interface CloudSshOptions {\n /**\n * Bring the box online (resume/start) before resolving the target. Default\n * true. Callers that already brought the box online (e.g. `agentbox code`\n * after its own wait-ready) pass false to skip a redundant lifecycle pass.\n */\n bringOnline?: boolean;\n /** Optional progress logger for the bring-online path (CLI passes clack's `log.info`). */\n logInfo?: (msg: string) => void;\n}\n\n/**\n * Resolve a cloud box's SSH connection target WITHOUT touching `~/.ssh/config`.\n * Lets callers inspect the target (e.g. gate on a persistent `identityFile`)\n * before deciding to persist an alias.\n *\n * The SSH-support check runs FIRST, before any lifecycle action — so an\n * unsupported provider (e.g. Docker, which has no `buildAttach`) errors without\n * resuming/starting the box. `buildAttach(..., { noTmux: true })` yields the\n * plain `ssh ... <user>@<host>` argv; the identity path (if any) is parsed\n * straight out of it so we never hardcode a provider-specific key path.\n */\nexport async function resolveCloudSshTarget(\n box: BoxRecord,\n provider: Provider,\n opts: CloudSshOptions = {},\n): Promise<CloudSshAlias> {\n if (!provider.buildAttach) {\n throw new Error(`cloud provider '${provider.name}' does not support SSH attach`);\n }\n\n if (opts.bringOnline ?? true) {\n const state = await provider.probeState(box);\n if (state === 'paused') {\n opts.logInfo?.('box is paused; resuming');\n await provider.resume(box);\n } else if (state === 'stopped') {\n opts.logInfo?.('box is stopped; starting');\n await provider.start(box);\n } else if (state === 'missing') {\n throw new Error(`cloud sandbox for ${box.name} is missing; was it deleted?`);\n }\n }\n\n const alias = agentboxAliasFor(box.name);\n\n // A provider that knows its own SSH target says so. Reverse-engineering the\n // target out of the attach argv only works when that argv is a plain `ssh …\n // <user>@<box>`; it isn't when the attach has to go THROUGH a machine to\n // reach the box (remote-docker), and such a provider supplies `sshTarget`\n // instead — including bringing its sshd up and installing the per-box key.\n if (provider.sshTarget) {\n const t = await provider.sshTarget(box);\n if (!t) {\n throw new Error(`no SSH target for ${box.name} (its sshd did not come up)`);\n }\n return {\n alias,\n host: t.host,\n user: t.user,\n identityFile: t.identityFile,\n port: t.port,\n proxyJump: t.proxyJump,\n };\n }\n\n const spec = await provider.buildAttach(box, 'shell', { noTmux: true });\n const target = parseSshTarget(spec.argv);\n if (!target) {\n throw new Error(`could not parse <user>@<host> from cloud SSH argv: ${spec.argv.join(' ')}`);\n }\n return { alias, host: target.host, user: target.user, identityFile: target.identityFile };\n}\n\n/**\n * Bring a cloud box online, persist its resolved SSH target to `box.ssh`,\n * and regenerate `~/.agentbox/ssh/config` (+ the `~/.ssh/config` Include),\n * returning the connection target. Shared by `agentbox code` (VS Code\n * Remote-SSH), `agentbox open` (sshfs mount), and `agentbox shell --ssh-config`\n * (external app handoff) — all three need the same alias mapped to a live SSH\n * target. These are explicit user actions, so they write regardless of the\n * `ssh.autoConfig` toggle (which only governs the proactive create/start path).\n */\nexport async function ensureCloudSshAlias(\n box: BoxRecord,\n provider: Provider,\n opts: CloudSshOptions = {},\n): Promise<CloudSshAlias> {\n const conn = await resolveCloudSshTarget(box, provider, opts);\n await recordBoxSsh(box.id, {\n host: conn.host,\n user: conn.user,\n identityFile: conn.identityFile,\n port: conn.port,\n proxyJump: conn.proxyJump,\n });\n await syncAgentboxSshConfig();\n return conn;\n}\n\n/**\n * Whether a provider's `buildAttach` yields a plain `ssh … <user>@<host>` argv\n * pointing AT the box — the only shape `resolveCloudSshTarget` can parse a box\n * SSH target out of. Vercel/E2B have no SSH at all, and must not warn about it\n * on every start. A provider with its own `sshTarget` needs this false.\n *\n * Read from the provider's descriptor rather than a hardcoded name list, so a\n * community provider that attaches over plain SSH gets its `~/.ssh/config`\n * entry written too.\n */\nfunction hasDirectBoxSsh(name: string): boolean {\n return resolveProviderDescriptor(name)?.capabilities.directBoxSsh ?? false;\n}\n\n/**\n * Proactive, default-on SSH-config write on create/start/resume — gated by the\n * `ssh.autoConfig` config key so a user who manages `~/.ssh/config` themselves\n * can opt out. Only persistent-identity providers qualify (Hetzner/DigitalOcean:\n * a per-box identity file that survives across sessions); Daytona's ephemeral\n * token and Docker/Vercel/E2B (no SSH) are skipped. Best-effort: a failure here\n * must never break the lifecycle command/action that triggered it — but it is no\n * longer swallowed silently, so `logWarn` surfaces the reason (CLI stderr, hub log).\n *\n * The box is assumed already online (create just finished, or start/resume\n * brought it up), so `bringOnline: false` avoids a redundant lifecycle pass.\n * Re-resolving on start is what refreshes a Hetzner box's changed public IP.\n */\nexport async function autoWriteSshConfig(\n box: BoxRecord,\n provider: Provider,\n enabled: boolean,\n logWarn?: (msg: string) => void,\n): Promise<void> {\n if (!enabled) return;\n // A provider with neither its own `sshTarget` nor a direct-ssh attach argv has\n // no box target to write (vercel/e2b have no SSH at all). That is a shape, not\n // a failure, and must not warn on every start/unpause.\n if (!provider.sshTarget && !hasDirectBoxSsh(provider.name)) return;\n try {\n const conn = await resolveCloudSshTarget(box, provider, { bringOnline: false });\n if (!conn.identityFile) return;\n await recordBoxSsh(box.id, {\n host: conn.host,\n user: conn.user,\n identityFile: conn.identityFile,\n port: conn.port,\n proxyJump: conn.proxyJump,\n });\n await syncAgentboxSshConfig();\n } catch (err) {\n // Best-effort: SSH-config auto-write must never break create/start. But\n // surface the reason rather than swallowing it (this masked the hub-create\n // gap for a whole release).\n logWarn?.(\n `ssh-config auto-write for ${box.name} failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n","/**\n * Per-box SSH key minting, shared by every provider that authenticates a box\n * over SSH by identity file: the docker localhost sshd and the Hetzner VPS both\n * mint a fresh ed25519 keypair per box and never let the private key leave the\n * host. The public key is installed into the box's `authorized_keys` (docker via\n * `docker exec`, Hetzner via cloud-init).\n */\n\nimport { mkdir, readFile } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport { execa } from 'execa';\n\nexport interface MintedSshKey {\n /** Directory holding the key files. */\n dir: string;\n /** Absolute path to the private key. */\n privatePath: string;\n /** Absolute path to the public key. */\n publicPath: string;\n /** Public key contents (one OpenSSH-format line). */\n publicKey: string;\n}\n\n/**\n * Mint a fresh ed25519 keypair into `targetDir/id_ed25519` (+ `.pub`). The\n * directory is created if missing (0700). `comment` is embedded in the public\n * key so the key is identifiable in `authorized_keys` on a forensic look.\n *\n * Reuses the existing keypair when `targetDir/id_ed25519` is already present\n * (idempotent across `agentbox start`), reading its `.pub` back — callers on the\n * restart path can call this blindly without clobbering the key the box already\n * trusts.\n */\nexport async function mintSshKey(targetDir: string, comment: string): Promise<MintedSshKey> {\n const dir = resolve(targetDir);\n const priv = join(dir, 'id_ed25519');\n const pub = `${priv}.pub`;\n await mkdir(dir, { recursive: true, mode: 0o700 });\n\n const existing = await readFile(pub, 'utf8').catch(() => null);\n if (existing !== null) {\n return { dir, privatePath: priv, publicPath: pub, publicKey: existing.trim() };\n }\n\n // `ssh-keygen -N ''` for no passphrase; `-q` to suppress the random art.\n await execa('ssh-keygen', ['-t', 'ed25519', '-N', '', '-C', comment, '-f', priv, '-q'], {\n stdio: 'pipe',\n });\n\n const publicKey = (await readFile(pub, 'utf8')).trim();\n return { dir, privatePath: priv, publicPath: pub, publicKey };\n}\n","/**\n * Ask OpenSSH what it would do for a destination.\n *\n * An `~/.ssh/config` alias (`buildbox`) is a perfectly good destination on the\n * machine that owns that config, and meaningless anywhere else. Sharing a\n * remote-docker host with a control box therefore has to EXPAND it first:\n * `ssh -G` prints the fully-resolved settings — hostname, user, port, identity\n * files — which is exactly the portable form another machine can dial.\n *\n * `ssh -G` never connects, so this is cheap and safe to run on any input; an\n * unresolvable destination simply comes back as itself.\n */\n\nimport { stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { execa } from 'execa';\n\nexport interface SshConfigTarget {\n /** The real hostname/IP ssh would dial (`hostname` in `ssh -G`). */\n host: string;\n user?: string;\n port?: number;\n /** First `identityfile` that actually exists on disk, tilde-expanded. */\n identityFile?: string;\n}\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n return (await stat(path)).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Expand `destination` through `ssh -G`. Returns `null` when ssh is unavailable\n * or the destination doesn't resolve — callers fall back to the raw string,\n * which is what every pre-existing registry entry already relies on.\n *\n * `port` is omitted when it is the default 22 so the expansion stays as close to\n * what the user wrote as possible.\n */\nexport async function resolveSshConfigTarget(destination: string): Promise<SshConfigTarget | null> {\n let stdout: string;\n try {\n const res = await execa('ssh', ['-G', destination], { reject: false, timeout: 10_000 });\n if (res.exitCode !== 0) return null;\n stdout = res.stdout ?? '';\n } catch {\n return null;\n }\n\n const fields = new Map<string, string[]>();\n for (const line of stdout.split('\\n')) {\n const m = /^([a-z0-9]+)\\s+(.+)$/i.exec(line.trim());\n if (!m) continue;\n const key = m[1]!.toLowerCase();\n const list = fields.get(key);\n if (list) list.push(m[2]!);\n else fields.set(key, [m[2]!]);\n }\n\n const host = fields.get('hostname')?.[0]?.trim();\n if (!host) return null;\n const out: SshConfigTarget = { host };\n\n const user = fields.get('user')?.[0]?.trim();\n if (user) out.user = user;\n\n const port = Number.parseInt(fields.get('port')?.[0]?.trim() ?? '', 10);\n if (Number.isInteger(port) && port > 0 && port !== 22) out.port = port;\n\n // ssh prints every candidate identity, including the built-in defaults it\n // would try. Take the first that exists so we name a key the user actually\n // has, rather than `~/.ssh/id_rsa` because ssh always lists it.\n for (const raw of fields.get('identityfile') ?? []) {\n const path = raw.trim().replace(/^~(?=\\/)/, homedir());\n if (await fileExists(path)) {\n out.identityFile = path;\n break;\n }\n }\n return out;\n}\n","/**\n * Thin wrappers around the system `ssh` / `scp` binaries — the shared transport\n * for every provider whose box is reached over SSH (hetzner, digitalocean,\n * remote-docker).\n *\n * We shell out to the system OpenSSH rather than a JS SSH library because\n * OpenSSH's ControlMaster + dynamic port forwarding (see `./ssh-tunnel.ts`) is\n * exactly the primitive these providers need and is hard to replicate in pure\n * JS — with no native-dep crutch.\n *\n * Two shapes of target share this module:\n *\n * - **VPS providers** (hetzner, digitalocean) mint a per-box key and pin the\n * host key in a per-box `known_hosts`. They pass `identity` + `knownHosts`,\n * and the target is fully self-describing.\n * - **remote-docker** connects to a machine the user already reaches, so it\n * passes NEITHER: the identity, port, and even the username come from the\n * user's own `~/.ssh/config` (an alias like `buildbox` is a legal `host`).\n * Emitting `-i` / `UserKnownHostsFile` there would override exactly the\n * configuration we want to inherit, so both are omitted when unset.\n */\n\nimport { execa, type ResultPromise } from 'execa';\n\nexport interface SshTargetArgs {\n /** Host, IP, or an `~/.ssh/config` alias — passed to ssh as `[user@]host`. */\n host: string;\n /**\n * Remote user. Omit to let `~/.ssh/config` (or the ssh default) decide —\n * required for the remote-docker \"alias\" targets, where forcing a user would\n * override the alias's own `User`.\n */\n user?: string;\n /** Absolute path to the private key. Omit to use the agent / ssh_config identities. */\n identity?: string;\n /** Absolute path to a dedicated known_hosts file. Omit to use the user's own. */\n knownHosts?: string;\n /** Non-default SSH port. Emitted as `-o Port=` so ssh AND scp both honor it. */\n port?: number;\n /** ControlMaster socket to reuse (see `SshTunnelManager`). */\n controlPath?: string;\n /** Extra `-o key=value` settings (e.g. ConnectTimeout for prepare polling). */\n options?: Record<string, string>;\n}\n\n/** `user@host`, or bare `host` when the user comes from `~/.ssh/config`. */\nexport function sshDestination(target: SshTargetArgs): string {\n return target.user ? `${target.user}@${target.host}` : target.host;\n}\n\n/** Compose the `-o … -i … -o UserKnownHostsFile=…` flags for ssh/scp. */\nexport function sshOptArgs(target: SshTargetArgs): string[] {\n const out: string[] = [];\n if (target.identity) {\n // `IdentitiesOnly` so a loaded agent can't offer its keys first: sshd counts\n // every offer against MaxAuthTries (6 by default), so a developer with a\n // handful of keys in their agent gets \"Too many authentication failures\"\n // before the key we explicitly passed is ever tried.\n out.push('-i', target.identity, '-o', 'IdentitiesOnly=yes');\n }\n if (target.knownHosts) {\n // A dedicated known_hosts only makes sense when we also isolate the global\n // one; without `knownHosts` we deliberately fall through to the user's.\n out.push(\n '-o',\n 'StrictHostKeyChecking=accept-new',\n '-o',\n `UserKnownHostsFile=${target.knownHosts}`,\n '-o',\n 'GlobalKnownHostsFile=/dev/null',\n );\n }\n out.push(\n '-o',\n 'BatchMode=yes',\n '-o',\n 'LogLevel=ERROR',\n // Detect a dead/stalled peer and drop the connection instead of hanging\n // forever. If the host's IP flaps mid-command (roaming Wi-Fi, VPN toggle)\n // the return traffic is silently dropped and the ssh channel would\n // otherwise block with no EOF — seen as an `exec` that never returns.\n // 15s * 4 = a ~60s fail-fast so callers (retry wrappers, cleanup) can react.\n '-o',\n 'ServerAliveInterval=15',\n '-o',\n 'ServerAliveCountMax=4',\n );\n // `-o Port=` rather than `-p`, because scp spells the same flag `-P`.\n if (target.port !== undefined) {\n out.push('-o', `Port=${String(target.port)}`);\n }\n if (target.controlPath) {\n out.push('-o', `ControlPath=${target.controlPath}`);\n }\n for (const [k, v] of Object.entries(target.options ?? {})) {\n out.push('-o', `${k}=${v}`);\n }\n return out;\n}\n\nexport interface SshExecOptions {\n /** Stream stdout/stderr line-by-line into this callback. */\n onLine?: (line: string) => void;\n /** Pipe extra env into the LOCAL ssh process (not the remote shell). */\n env?: Record<string, string>;\n /** Per-command wall-clock cap (ms). */\n timeoutMs?: number;\n}\n\nexport interface SshExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/**\n * Run a one-shot command on the target over ssh. Returns the exit code +\n * captured stdout/stderr; non-zero exits do NOT throw — callers decide what to\n * do with them.\n *\n * Text in / text out. A caller that needs to stream binary through the same\n * connection (remote-docker's `docker exec -i … cat`) drives `execa` itself\n * with `sshOptArgs(target)` — layering `input`/`encoding` onto this signature\n * costs more in overload gymnastics than the two call sites are worth.\n */\nexport async function sshExec(\n target: SshTargetArgs,\n remoteCmd: string,\n opts: SshExecOptions = {},\n): Promise<SshExecResult> {\n const argv = [...sshOptArgs(target), sshDestination(target), remoteCmd];\n const child = execa('ssh', argv, {\n reject: false,\n timeout: opts.timeoutMs,\n env: { ...process.env, ...opts.env },\n stdio: ['ignore', 'pipe', 'pipe'],\n }) as ResultPromise;\n\n if (opts.onLine) {\n const handle = (chunk: Buffer | string): void => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');\n for (const line of text.split(/\\r?\\n/)) {\n if (line.length > 0) opts.onLine?.(line);\n }\n };\n child.stdout?.on('data', handle);\n child.stderr?.on('data', handle);\n }\n\n const res = await child;\n return {\n exitCode: typeof res.exitCode === 'number' ? res.exitCode : 1,\n stdout: typeof res.stdout === 'string' ? res.stdout : '',\n stderr: typeof res.stderr === 'string' ? res.stderr : '',\n };\n}\n\n/** Copy a local file to the target via `scp`. Throws on non-zero exit. */\nexport async function scpUpload(\n target: SshTargetArgs,\n localPath: string,\n remotePath: string,\n opts: SshExecOptions = {},\n): Promise<void> {\n const argv = [...sshOptArgs(target), localPath, `${sshDestination(target)}:${remotePath}`];\n const res = await execa('scp', argv, { reject: false, timeout: opts.timeoutMs });\n if (res.exitCode !== 0) {\n throw new Error(\n `scp upload failed (exit ${String(res.exitCode)}): ${localPath} → ${remotePath}\\n${res.stderr ?? ''}`,\n );\n }\n}\n\n/** Copy a remote file to the host via `scp`. Throws on non-zero exit. */\nexport async function scpDownload(\n target: SshTargetArgs,\n remotePath: string,\n localPath: string,\n opts: SshExecOptions = {},\n): Promise<void> {\n const argv = [...sshOptArgs(target), `${sshDestination(target)}:${remotePath}`, localPath];\n const res = await execa('scp', argv, { reject: false, timeout: opts.timeoutMs });\n if (res.exitCode !== 0) {\n throw new Error(\n `scp download failed (exit ${String(res.exitCode)}): ${remotePath} → ${localPath}\\n${res.stderr ?? ''}`,\n );\n }\n}\n\n/**\n * Poll the target until ssh succeeds (or `deadlineMs` elapses). Used by the VPS\n * prepare orchestrators after `createServer` to wait for cloud-init to bring\n * sshd up. Returns true on success, false on timeout — callers throw with\n * appropriate context.\n */\nexport async function waitForSsh(\n target: SshTargetArgs,\n deadlineMs: number,\n intervalMs = 5_000,\n): Promise<boolean> {\n const stop = Date.now() + deadlineMs;\n while (Date.now() < stop) {\n const res = await sshExec(\n { ...target, options: { ...target.options, ConnectTimeout: '5' } },\n 'true',\n { timeoutMs: 10_000 },\n );\n if (res.exitCode === 0) return true;\n await new Promise((r) => setTimeout(r, intervalMs));\n }\n return false;\n}\n","/**\n * `SshTunnelManager` — one persistent `ssh` ControlMaster per box, plus dynamic\n * `-L` port forwards minted on demand. Shared by every SSH-reached provider\n * (hetzner, digitalocean, remote-docker).\n *\n * This is the load-bearing piece that makes those providers' preview-URL +\n * exec/file-I/O paths work without paying the SSH handshake on every call.\n *\n * Layout:\n *\n * ~/.agentbox/[<namespace>/]boxes/<box-id>/ssh/\n * id_ed25519 per-box private key (VPS providers only; 0600)\n * known_hosts per-box host-key pinning (VPS providers only)\n * ~/.agentbox/cm/<hash>.sock\n * ssh ControlMaster socket (created at runtime, removed by\n * `-O exit`). Lives in a short, flat dir — NOT under the deep\n * per-box dir — because a Unix socket path is capped at ~104\n * bytes and remote-docker's box-id-derived path overflows it.\n * See `controlSockPath`.\n *\n * `namespace` exists because provider sandbox-ids are only unique *within* a\n * provider — a DigitalOcean droplet id and a Hetzner server id can collide as\n * bare integers.\n *\n * Lifecycle:\n *\n * - open() → spawn `ssh -fNT -M -S control.sock [-i key] <dest>` once per box.\n * - forward() → `ssh -O forward -L 127.0.0.1:<localPort>:127.0.0.1:<remotePort> -S control.sock dummy`.\n * Picks a free local port. Idempotent per (boxId, remotePort)\n * ACROSS PROCESSES, not just within one: the map is persisted\n * beside the control socket, because the ControlMaster\n * outlives any single CLI invocation while an in-memory cache\n * does not. Without that every `agentbox` command that\n * resolved a preview URL minted another forward on the same\n * master and nothing ever reaped them.\n * - unforward() → `ssh -O cancel -L …`.\n * - refresh() → tear down a dead master + every cached forward, reopen.\n * - close() → `ssh -O exit -S control.sock dummy`; removes the socket.\n *\n * Thread-safety: a single AgentBox process owns one manager per CLI invocation.\n * Concurrent `forward()` calls for the same (boxId, remotePort) race-resolve to\n * the same localPort because the cache is checked first and `ssh -O forward` is\n * idempotent on the SSH side. Two separate PROCESSES racing can still mint one\n * extra forward; the persisted map keeps that to a one-off rather than one per\n * invocation.\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { createConnection, createServer } from 'node:net';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { execa } from 'execa';\n\nconst HOST = '127.0.0.1';\n\n/**\n * Where the cross-process forward map lives: beside the control socket, which is\n * already the one path that identifies a master. A regular file, so the ~104-byte\n * `sun_path` cap that shapes `controlSockPath` does not apply.\n */\nfunction forwardsPath(controlPath: string): string {\n return `${controlPath}.forwards.json`;\n}\n\ninterface PersistedForwards {\n /** The master these ports belong to. A different pid means a different master. */\n masterPid: number;\n /** remotePort -> localPort. */\n forwards: Record<string, number>;\n}\n\nasync function readForwards(controlPath: string, masterPid: number): Promise<Map<number, number>> {\n try {\n const raw = JSON.parse(await readFile(forwardsPath(controlPath), 'utf8')) as PersistedForwards;\n // A restarted master reuses the socket path but not its forwards, so a pid\n // mismatch invalidates the whole map rather than handing out dead ports.\n if (raw.masterPid !== masterPid) return new Map();\n return new Map(Object.entries(raw.forwards).map(([r, l]) => [Number(r), l]));\n } catch {\n return new Map();\n }\n}\n\nasync function writeForwards(\n controlPath: string,\n masterPid: number,\n forwards: Map<number, number>,\n): Promise<void> {\n const body: PersistedForwards = {\n masterPid,\n forwards: Object.fromEntries([...forwards].map(([r, l]) => [String(r), l])),\n };\n try {\n await writeFile(forwardsPath(controlPath), JSON.stringify(body), { mode: 0o600 });\n } catch {\n // Losing the map costs an extra forward, never correctness — never fatal.\n }\n}\n\n/**\n * Is something accepting connections on this local port?\n *\n * Belt-and-braces on top of the pid check: a forward normally lives as long as\n * its master, but `-O cancel` can remove one, and handing back a port nothing\n * listens on would look exactly like the box being down.\n */\nasync function isListening(port: number): Promise<boolean> {\n return new Promise((resolvePromise) => {\n const sock = createConnection({ host: HOST, port });\n const done = (ok: boolean): void => {\n sock.destroy();\n resolvePromise(ok);\n };\n sock.setTimeout(400);\n sock.once('connect', () => done(true));\n sock.once('timeout', () => done(false));\n sock.once('error', () => done(false));\n });\n}\n\n\n/**\n * ControlMaster socket path. It must be SHORT: a Unix domain socket path is\n * capped at ~104 bytes (`sun_path`) on macOS / ~108 on Linux, and ssh appends\n * its own `.XXXXXXXXXXXXXXXX` temp suffix (17 bytes) while creating the master.\n * The per-box ssh dir (`~/.agentbox/[ns/]boxes/<sanitized-box-id>/ssh/`) blows\n * past that for remote-docker, whose box-id embeds the SSH destination\n * (`macmini_agentbox-<project>-<hash>`). So we hang the socket off a short,\n * flat `~/.agentbox/cm/<hash>.sock` keyed by the full box ssh dir, while\n * known_hosts / keys stay in the deep per-box dir.\n */\nexport function controlSockPath(boxSshDir: string): string {\n const hash = createHash('sha1').update(boxSshDir).digest('hex').slice(0, 12);\n return resolve(homedir(), '.agentbox', 'cm', `${hash}.sock`);\n}\n\nexport interface SshTunnelOpenOptions {\n boxId: string;\n /** Host, IP, or `~/.ssh/config` alias to connect to. */\n vpsHost: string;\n /** Remote user. Omit to let `~/.ssh/config` decide (remote-docker aliases). */\n vpsUser?: string;\n /** Absolute path to the private key. Omit to use the agent / ssh_config identities. */\n identity?: string;\n /** Non-default SSH port. */\n port?: number;\n /** Override the derived `~/.agentbox/[ns/]boxes/<box-id>/ssh/` (tests inject this). */\n boxSshDir?: string;\n /** Override the connect-timeout (default 10s — fast-fail on a dropped firewall rule). */\n connectTimeoutSeconds?: number;\n}\n\nexport interface PortForward {\n localPort: number;\n remotePort: number;\n}\n\ninterface BoxTunnel {\n controlPath: string;\n vpsHost: string;\n vpsUser?: string;\n identity?: string;\n port?: number;\n boxSshDir: string;\n // remotePort → localPort. Used so repeated `forward()` calls for the same\n // remote port return the same local port without re-asking sshd.\n forwards: Map<number, number>;\n}\n\nexport class SshTunnelManager {\n private boxes = new Map<string, BoxTunnel>();\n\n /**\n * `namespace` scopes the on-disk ssh dir so sandbox-ids from different\n * providers can't collide (a droplet id and a server id are both integers).\n */\n constructor(private readonly namespace?: string) {}\n\n /**\n * Open the ControlMaster for `boxId`. Idempotent: if a master is already up\n * for this box (socket exists + responsive), no-op. Otherwise spawn a fresh\n * `ssh -fNT -M` and wait for the socket to appear.\n */\n async open(opts: SshTunnelOpenOptions): Promise<void> {\n const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId, this.namespace);\n await mkdir(boxSshDir, { recursive: true, mode: 0o700 });\n const controlPath = controlSockPath(boxSshDir);\n await mkdir(join(controlPath, '..'), { recursive: true, mode: 0o700 });\n const knownHosts = join(boxSshDir, 'known_hosts');\n const tunnel: BoxTunnel = {\n controlPath,\n vpsHost: opts.vpsHost,\n vpsUser: opts.vpsUser,\n identity: opts.identity,\n port: opts.port,\n boxSshDir,\n forwards: new Map(),\n };\n\n // Reuse an existing live master if the socket already responds.\n if (existsSync(controlPath) && (await this.isAlive(controlPath))) {\n this.boxes.set(opts.boxId, tunnel);\n return;\n }\n // Stale socket from a prior crashed process — remove before re-opening.\n if (existsSync(controlPath)) {\n await rm(controlPath, { force: true });\n }\n\n const connectTimeout = opts.connectTimeoutSeconds ?? 10;\n const argv = ['-fNT', '-M', '-S', controlPath];\n // A provider that mints its own key pins the host key too. One that rides\n // the user's `~/.ssh/config` (remote-docker) must inherit BOTH — see\n // `sshOptArgs` in ./ssh-exec.ts.\n if (opts.identity) {\n argv.push(\n '-i',\n opts.identity,\n '-o',\n 'IdentitiesOnly=yes',\n '-o',\n 'StrictHostKeyChecking=accept-new',\n '-o',\n `UserKnownHostsFile=${knownHosts}`,\n '-o',\n 'GlobalKnownHostsFile=/dev/null',\n );\n }\n if (opts.port !== undefined) {\n argv.push('-o', `Port=${String(opts.port)}`);\n }\n argv.push(\n '-o',\n 'BatchMode=yes',\n '-o',\n 'LogLevel=ERROR',\n '-o',\n 'ExitOnForwardFailure=yes',\n '-o',\n 'ServerAliveInterval=30',\n '-o',\n 'ServerAliveCountMax=3',\n '-o',\n `ConnectTimeout=${String(connectTimeout)}`,\n opts.vpsUser ? `${opts.vpsUser}@${opts.vpsHost}` : opts.vpsHost,\n );\n const res = await execa('ssh', argv, { reject: false });\n if (res.exitCode !== 0 || !existsSync(controlPath)) {\n throw new Error(\n `ssh ControlMaster failed for ${opts.boxId} (exit ${String(res.exitCode)}): ${res.stderr || res.stdout || '(no output)'}`,\n );\n }\n this.boxes.set(opts.boxId, tunnel);\n }\n\n /**\n * Mint (or fetch the cached) `127.0.0.1:<localPort> → remote:127.0.0.1:<remotePort>`\n * forward. Returns the local port. Idempotent per (boxId, remotePort).\n *\n * The cached entry is only returned when the underlying ControlMaster is\n * still alive — without that check we'd happily hand back a localPort that\n * stopped listening when the master died (e.g. transient network blip, host\n * sleep/wake). When the master is dead we drop ALL cached forwards for this\n * box (they all share one tunnel) and re-mint from scratch.\n */\n async forward(boxId: string, remotePort: number): Promise<number> {\n const tunnel = this.getTunnelOrThrow(boxId);\n const { alive, pid } = await this.masterState(tunnel.controlPath);\n if (!alive) {\n // Master died — every cached local port stopped listening. Drop them all;\n // callers that still hold a stale `localPort` get a fresh one next call.\n tunnel.forwards.clear();\n await rm(forwardsPath(tunnel.controlPath), { force: true });\n } else {\n const cached = tunnel.forwards.get(remotePort);\n if (cached !== undefined) return cached;\n // Not in THIS process's cache, but the master outlives any one process, so\n // a forward for this port may already exist from an earlier invocation.\n // Adopting it is what stops every command that resolves a preview URL from\n // minting another one. Needs the pid: without it we cannot tell this\n // master's forwards from a previous master's, so we mint instead.\n if (pid !== null) {\n const persisted = await readForwards(tunnel.controlPath, pid);\n const known = persisted.get(remotePort);\n if (known !== undefined && (await isListening(known))) {\n tunnel.forwards.set(remotePort, known);\n return known;\n }\n }\n }\n const localPort = await pickFreePort();\n const argv = [\n '-O',\n 'forward',\n '-L',\n `${HOST}:${String(localPort)}:${HOST}:${String(remotePort)}`,\n '-S',\n tunnel.controlPath,\n 'dummy', // the target host is ignored when -O is used, but argv needs one\n ];\n const res = await execa('ssh', argv, { reject: false });\n if (res.exitCode !== 0) {\n throw new Error(\n `ssh -O forward failed for ${boxId} (exit ${String(res.exitCode)}): ${res.stderr || res.stdout || '(no output)'}`,\n );\n }\n tunnel.forwards.set(remotePort, localPort);\n if (pid !== null) {\n // Re-read before writing so a concurrent process's entries survive.\n const persisted = await readForwards(tunnel.controlPath, pid);\n persisted.set(remotePort, localPort);\n await writeForwards(tunnel.controlPath, pid, persisted);\n }\n return localPort;\n }\n\n /**\n * Tear down a dead ControlMaster + every cached forward for this box, then\n * re-open from scratch. Idempotent. Returns when the master is open and the\n * box's forwards map is empty (ready for fresh forward() calls).\n *\n * Use case: the cloud-poller observes ECONNREFUSED on the local port and asks\n * the backend to refresh the preview URL — that path calls into here so the\n * master + forward both come back fresh.\n */\n async refresh(opts: SshTunnelOpenOptions): Promise<void> {\n const existing = this.boxes.get(opts.boxId);\n if (existing) {\n const alive = await this.isAlive(existing.controlPath);\n if (!alive && existsSync(existing.controlPath)) {\n // Stale socket from a dead master — best-effort cleanup, then reopen.\n try {\n await rm(forwardsPath(existing.controlPath), { force: true });\n await execa('ssh', ['-O', 'exit', '-S', existing.controlPath, 'dummy'], {\n reject: false,\n });\n } catch {\n // ignore — `-O exit` on a dead master can fail\n }\n await rm(existing.controlPath, { force: true });\n }\n // Either way drop the cached forwards: even if the master happened to be\n // alive, the caller asked us to refresh because *something* upstream (the\n // local port) wasn't responding.\n existing.forwards.clear();\n }\n await this.open(opts);\n }\n\n /** Tear down a single forward. Idempotent — unknown ports are no-ops. */\n async unforward(boxId: string, remotePort: number): Promise<void> {\n const tunnel = this.getTunnelOrThrow(boxId);\n const localPort = tunnel.forwards.get(remotePort);\n if (localPort === undefined) return;\n const argv = [\n '-O',\n 'cancel',\n '-L',\n `${HOST}:${String(localPort)}:${HOST}:${String(remotePort)}`,\n '-S',\n tunnel.controlPath,\n 'dummy',\n ];\n await execa('ssh', argv, { reject: false });\n tunnel.forwards.delete(remotePort);\n // Also out of the persisted map, or the next process adopts a port that no\n // longer forwards anywhere.\n const { pid } = await this.masterState(tunnel.controlPath);\n if (pid !== null) {\n const persisted = await readForwards(tunnel.controlPath, pid);\n if (persisted.delete(remotePort)) {\n await writeForwards(tunnel.controlPath, pid, persisted);\n }\n }\n }\n\n /**\n * Close the ControlMaster (and all its forwards). Idempotent — if no master\n * is recorded, no-op. Removes the socket file.\n */\n async close(boxId: string): Promise<void> {\n const tunnel = this.boxes.get(boxId);\n if (!tunnel) return;\n if (existsSync(tunnel.controlPath)) {\n await execa('ssh', ['-O', 'exit', '-S', tunnel.controlPath, 'dummy'], { reject: false });\n await rm(forwardsPath(tunnel.controlPath), { force: true });\n await rm(tunnel.controlPath, { force: true });\n }\n this.boxes.delete(boxId);\n }\n\n /** Tear down every open box. */\n async closeAll(): Promise<void> {\n const ids = Array.from(this.boxes.keys());\n await Promise.all(ids.map((id) => this.close(id)));\n }\n\n /** Path to the ControlMaster socket for `boxId`, if open. */\n controlPath(boxId: string): string | undefined {\n return this.boxes.get(boxId)?.controlPath;\n }\n\n /** True if a ControlMaster is registered for `boxId` (regardless of liveness). */\n has(boxId: string): boolean {\n return this.boxes.has(boxId);\n }\n\n /** Per-box ssh dir (tests use this to verify the layout). */\n boxSshDir(boxId: string): string | undefined {\n return this.boxes.get(boxId)?.boxSshDir;\n }\n\n /** Re-open the manager record for an existing-on-disk control socket. */\n registerExisting(boxId: string, opts: SshTunnelOpenOptions): void {\n const boxSshDir = opts.boxSshDir ?? defaultBoxSshDir(opts.boxId, this.namespace);\n this.boxes.set(boxId, {\n controlPath: controlSockPath(boxSshDir),\n vpsHost: opts.vpsHost,\n vpsUser: opts.vpsUser,\n identity: opts.identity,\n port: opts.port,\n boxSshDir,\n forwards: new Map(),\n });\n }\n\n private async isAlive(controlPath: string): Promise<boolean> {\n return (await this.masterState(controlPath)).alive;\n }\n\n /**\n * Whether a master is running, and which one.\n *\n * Liveness and IDENTITY are separate answers and only the first is\n * guaranteed: `ssh -O check` exits 0 when a master answers and prints\n * `Master running (pid=NNN)`, but the pid is the only handle OpenSSH gives on\n * identity (there is no \"list forwards\" query) and a build that does not print\n * it still has a perfectly live master. So an unparsed pid means \"alive, but\n * we cannot safely adopt its forwards\" — never \"dead\".\n */\n private async masterState(\n controlPath: string,\n ): Promise<{ alive: boolean; pid: number | null }> {\n const res = await execa('ssh', ['-O', 'check', '-S', controlPath, 'dummy'], { reject: false });\n if (res.exitCode !== 0) return { alive: false, pid: null };\n const m = /pid=(\\d+)/.exec(`${res.stderr}${res.stdout}`);\n return { alive: true, pid: m?.[1] ? Number(m[1]) : null };\n }\n\n private getTunnelOrThrow(boxId: string): BoxTunnel {\n const t = this.boxes.get(boxId);\n if (!t) throw new Error(`no SSH ControlMaster registered for box ${boxId}; call open() first`);\n return t;\n }\n}\n\n/**\n * Default per-box ssh dir: `~/.agentbox/[<namespace>/]boxes/<box-id>/ssh/`.\n *\n * `boxId` is sanitized because a provider may key its sandboxes by something\n * that isn't path-safe (remote-docker's sandbox-id embeds the SSH destination,\n * so it carries `@`, `:` and `/`).\n */\nexport function defaultBoxSshDir(boxId: string, namespace?: string): string {\n const safe = boxId.replace(/[^A-Za-z0-9._-]/g, '_');\n return namespace\n ? resolve(homedir(), '.agentbox', namespace, 'boxes', safe, 'ssh')\n : resolve(homedir(), '.agentbox', 'boxes', safe, 'ssh');\n}\n\n/**\n * The per-box ssh-dir namespace for a provider, or `undefined` for none. Kept in\n * ONE place because it is easy to get wrong: hetzner stores keys **un-namespaced**\n * (`~/.agentbox/boxes/<id>/ssh/`), digitalocean namespaces by `'digitalocean'`.\n * `null` means the provider mints no per-box keypair (e2b/vercel/daytona/docker),\n * so there is no ssh dir to read, mirror to custody, or download on adoption.\n */\nexport function boxSshNamespaceForProvider(provider: string): string | null | undefined {\n switch (provider) {\n case 'hetzner':\n return undefined;\n case 'digitalocean':\n return 'digitalocean';\n default:\n // remote-docker keys are keyed by an embedded SSH destination the host\n // already owns, not by a downloadable per-box key; everything else mints\n // nothing. Neither participates in SSH-key custody.\n return null;\n }\n}\n\n/**\n * The on-disk ssh dir for a provider's box, or `null` when the provider mints no\n * downloadable per-box keypair. Shared by the hub-worker custody mirror, the\n * PC-side custody push-up, and `agentbox hub pull`, so all three agree on the\n * exact path and never re-introduce a namespace mismatch.\n */\nexport function boxSshDirForProvider(provider: string, sandboxId: string): string | null {\n const ns = boxSshNamespaceForProvider(provider);\n if (ns === null) return null;\n return defaultBoxSshDir(sandboxId, ns);\n}\n\n/**\n * Ask the kernel for a free port in the ephemeral range: bind a fresh server on\n * `127.0.0.1:0`, capture the port the kernel assigned, and close. There's a tiny\n * race where the port could be claimed before `ssh -O forward` lands, but in\n * practice ssh's idempotent socket re-creation doesn't conflict.\n */\nexport async function pickFreePort(): Promise<number> {\n return new Promise((resolveOk, reject) => {\n const srv = createServer();\n srv.unref();\n srv.on('error', reject);\n srv.listen(0, HOST, () => {\n const addr = srv.address();\n if (!addr || typeof addr === 'string') {\n srv.close();\n reject(new Error('could not get a free local port'));\n return;\n }\n const port = addr.port;\n srv.close(() => resolveOk(port));\n });\n });\n}\n","/**\n * Provider-neutral parsing/resolution for the `--inbound` / `box.inbound`\n * surface — the per-box firewall inbound-access policy shared by the VPS\n * backends (hetzner, digitalocean). Pure (no network); the backend supplies the\n * detected host-egress CIDR.\n *\n * Modes:\n * - `locked` (default) — SSH reachable only from the host's egress IP.\n * - `open` — SSH reachable from anywhere (0.0.0.0/0 + ::/0). For\n * driving a box from a phone / other device with the\n * laptop off. sshd is key-only (baked hardening), so\n * this is the standard hardened-VPS posture.\n * - `whitelist` — the host egress IP PLUS explicit CIDRs.\n *\n * The persisted `InboundPolicy.sources` holds only the extra whitelist CIDRs;\n * the host egress is re-detected and merged on every apply so a host-IP drift\n * never clobbers the whitelist.\n */\n\nimport type { InboundPolicy } from '@agentbox/core';\n\n/** Open-to-the-world source set (IPv4 + IPv6). */\nexport const OPEN_INBOUND_SOURCES: readonly string[] = ['0.0.0.0/0', '::/0'];\n\n/**\n * Normalize a source spec into a CIDR. Bare IPv4 → `/32`, bare IPv6 → `/128`,\n * anything already containing `/` → returned trimmed. Does not validate the\n * address (the cloud API rejects a bad one). Mirrors the providers' historic\n * `normalizeSourceCidr`.\n */\nexport function normalizeInboundCidr(raw: string): string {\n const trimmed = raw.trim();\n if (trimmed.includes('/')) return trimmed;\n if (trimmed.includes(':')) return `${trimmed}/128`;\n return `${trimmed}/32`;\n}\n\n/**\n * Parse a raw `--inbound` / `box.inbound` spec into a policy. Accepts:\n * - '' / undefined / 'locked' / 'lock' → locked\n * - 'open' → open\n * - 'whitelist:1.2.3.4/32,5.6.7.8' → whitelist (prefix stripped)\n * - bare CIDR list '1.2.3.4/32 5.6.7.8' → whitelist\n * Throws on `whitelist` with no CIDRs.\n */\nexport function parseInboundSpec(spec: string | undefined): InboundPolicy {\n let s = (spec ?? '').trim();\n if (s === '' || /^lock(ed)?$/i.test(s)) return { mode: 'locked', sources: [] };\n if (/^open$/i.test(s)) return { mode: 'open', sources: [] };\n if (/^whitelist\\b:?/i.test(s)) s = s.replace(/^whitelist\\b:?/i, '').trim();\n const sources = s\n .split(/[\\s,]+/)\n .map((x) => x.trim())\n .filter((x) => x.length > 0)\n .map(normalizeInboundCidr);\n if (sources.length === 0) {\n throw new Error(\n \"inbound 'whitelist' needs at least one CIDR, e.g. `--inbound 203.0.113.5/32` or `--inbound whitelist:203.0.113.0/24`\",\n );\n }\n return { mode: 'whitelist', sources };\n}\n\n/**\n * Resolve a policy + the detected host-egress CIDR into the actual list of\n * inbound source CIDRs for the firewall rule. `open` ignores the host egress;\n * `locked`/`whitelist` always include it (so the laptop's tunnel keeps working)\n * plus any whitelist CIDRs, de-duplicated. A null/empty `hostEgressCidr` is\n * tolerated (e.g. open mode) — but for locked/whitelist the caller should pass\n * a real egress or the box would be unreachable.\n */\nexport function resolveInboundSources(\n policy: InboundPolicy,\n hostEgressCidr: string | null | undefined,\n): string[] {\n if (policy.mode === 'open') return [...OPEN_INBOUND_SOURCES];\n const out = new Set<string>();\n if (hostEgressCidr && hostEgressCidr.trim().length > 0) {\n out.add(normalizeInboundCidr(hostEgressCidr));\n }\n if (policy.mode === 'whitelist') {\n for (const s of policy.sources) out.add(normalizeInboundCidr(s));\n }\n return [...out];\n}\n\n/** One-line human description of a policy for logs / `--show`. */\nexport function describeInbound(policy: InboundPolicy): string {\n switch (policy.mode) {\n case 'open':\n return 'open (SSH reachable from anywhere — 0.0.0.0/0, key-only)';\n case 'whitelist':\n return `whitelist (host egress + ${policy.sources.join(', ')})`;\n default:\n return 'locked (SSH reachable only from the host egress IP)';\n }\n}\n","/**\n * Provider-agnostic box git + service-control helpers, shared by the host CLI\n * (`agentbox git …` / `agentbox services …`) and the hub backend so the argv and\n * RPC-param contracts never drift between the two frontends.\n *\n * Credentialed git RPCs (push / pull-fetch) carry a one-time host-initiated\n * token; minting is a relay concern, so the caller injects it via\n * `deps.hostInitiatedArgs`. Keeping the mint out of this module is deliberate:\n * `@agentbox/relay` depends on `@agentbox/sandbox-core`, so this package must not\n * reach back to relay/ctl (that would be a dependency cycle).\n *\n * The predicted `GitRpcParams` built here MUST match, byte-for-byte, what the\n * in-box `agentbox-ctl git` sends, or the relay's params-hash binding rejects\n * the minted token. This mirrors `buildParams` in `packages/ctl/src/commands/git.ts`.\n */\nimport type { BoxRecord, ExecResult, GitRpcParams, Provider } from '@agentbox/core';\nimport { isScratchBranch, SCRATCH_BRANCH_PREFIX } from '@agentbox/core';\n\n/** The box workspace is always mounted here; ctl mirrors `process.cwd()` into `params.path`. */\nexport const BOX_WORKSPACE = '/workspace';\n\n/**\n * Mint a `--host-initiated-token <tok>` argv fragment bound to a git RPC's\n * `(method, params)`. Returns `[]` when no token could be minted — the call\n * still proceeds through the relay's normal prompt path (and `agentbox/*`\n * scratch pushes auto-allow with no prompt regardless).\n */\nexport type HostInitiatedArgs = (method: string, params: GitRpcParams) => Promise<string[]>;\n\nexport interface BoxGitDeps {\n hostInitiatedArgs?: HostInitiatedArgs;\n}\n\nfunction run(provider: Provider, box: BoxRecord, argv: string[]): Promise<ExecResult> {\n return provider.exec(box, argv, { cwd: BOX_WORKSPACE });\n}\n\n/** Normalize a user-supplied name to an `agentbox/<name>` scratch branch (idempotent). */\nexport function scratchBranchName(name: string): string {\n const trimmed = name.trim();\n return isScratchBranch(trimmed) ? trimmed : `${SCRATCH_BRANCH_PREFIX}${trimmed}`;\n}\n\n/** `git checkout <branch>` — switch the box's worktree. No relay: local to the worktree. */\nexport function boxGitCheckout(\n provider: Provider,\n box: BoxRecord,\n branch: string,\n extraArgs: string[] = [],\n): Promise<ExecResult> {\n return run(provider, box, ['git', 'checkout', branch, ...extraArgs]);\n}\n\n/**\n * The branch the box's worktree is on; undefined when HEAD is detached (a\n * checkout of a SHA, a tag or a remote ref) or the exec fails.\n */\nexport async function boxGitCurrentBranch(\n provider: Provider,\n box: BoxRecord,\n): Promise<string | undefined> {\n const r = await run(provider, box, ['git', 'symbolic-ref', '--quiet', '--short', 'HEAD']).catch(\n () => undefined,\n );\n return r?.exitCode === 0 ? r.stdout.trim() || undefined : undefined;\n}\n\n/**\n * `git checkout -b agentbox/<name> [from]` — create AND switch onto a fresh\n * scratch branch (from HEAD by default, or the given base ref). Local to the\n * worktree; for docker the branch lands in the bind-mounted host `.git/`\n * immediately, for cloud it stays in-box until pushed to the host.\n */\nexport function boxGitNewBranch(\n provider: Provider,\n box: BoxRecord,\n name: string,\n from?: string,\n): Promise<ExecResult> {\n const argv = ['git', 'checkout', '-b', scratchBranchName(name)];\n if (from && from.trim()) argv.push(from.trim());\n return run(provider, box, argv);\n}\n\n/** Build the `{ path, remote?, args? }` ctl sends for a git.push / git.fetch RPC. */\nfunction gitRpcParams(remote: string | undefined, extraArgs: string[]): GitRpcParams {\n const params: GitRpcParams = { path: BOX_WORKSPACE };\n if (remote) params.remote = remote;\n if (extraArgs.length > 0) params.args = extraArgs;\n return params;\n}\n\n/** `agentbox-ctl git push` — push the box's branch to the remote via the host relay. */\nexport async function boxGitPush(\n provider: Provider,\n box: BoxRecord,\n opts: { remote?: string; force?: boolean; args?: string[] },\n deps: BoxGitDeps = {},\n): Promise<ExecResult> {\n // `--force` is a real remote-push flag; ctl normalizes it back onto the args\n // tail, so it must be part of the predicted params hash (force last, matching\n // the host CLI).\n const extraArgs = [...(opts.args ?? []), ...(opts.force ? ['--force'] : [])];\n const params = gitRpcParams(opts.remote, extraArgs);\n const tokenArgs = deps.hostInitiatedArgs ? await deps.hostInitiatedArgs('git.push', params) : [];\n const argv = ['agentbox-ctl', 'git', 'push', ...tokenArgs];\n if (opts.remote) argv.push('--remote', opts.remote);\n argv.push(...extraArgs);\n return run(provider, box, argv);\n}\n\n/**\n * `agentbox-ctl git pull` — fetch via the relay then merge in /workspace. Only\n * `git.fetch` crosses the relay (the merge is local, no creds), so the token is\n * scoped to `git.fetch`. `--ff-only` is consumed by ctl (not forwarded to the\n * relay) so it stays out of the predicted params hash.\n */\nexport async function boxGitPull(\n provider: Provider,\n box: BoxRecord,\n opts: { remote?: string; ffOnly?: boolean; args?: string[] },\n deps: BoxGitDeps = {},\n): Promise<ExecResult> {\n const extraArgs = opts.args ?? [];\n const params = gitRpcParams(opts.remote, extraArgs);\n const tokenArgs = deps.hostInitiatedArgs ? await deps.hostInitiatedArgs('git.fetch', params) : [];\n const argv = ['agentbox-ctl', 'git', 'pull', ...tokenArgs];\n if (opts.remote) argv.push('--remote', opts.remote);\n if (opts.ffOnly) argv.push('--ff-only');\n argv.push(...extraArgs);\n return run(provider, box, argv);\n}\n\n/**\n * `agentbox-ctl git push --host-only` — land the box's branch in the host's\n * *local* repo, publishing nothing. The relay skips its confirm/token gate\n * (that gate guards remote pushes), so no host-initiated token is needed.\n */\nexport function boxGitPushHost(\n provider: Provider,\n box: BoxRecord,\n opts: { as?: string; force?: boolean; args?: string[] } = {},\n): Promise<ExecResult> {\n const argv = ['agentbox-ctl', 'git', 'push', '--host-only'];\n if (opts.as) argv.push('--as', opts.as);\n if (opts.force) argv.push('--force');\n argv.push(...(opts.args ?? []));\n return run(provider, box, argv);\n}\n\n// ── service control (in-box supervisor) ──\n// The argv is single-sourced here; parsing the `--json` StatusReply stays in the\n// callers (they can import `@agentbox/ctl`; this module can't — cycle, see above).\n\n/** `agentbox-ctl status --json` — dump the live task/service/port snapshot. */\nexport function servicesStatusArgv(): string[] {\n return ['agentbox-ctl', 'status', '--json'];\n}\n\n/** Run the live status pull and return the raw exec result (caller parses stdout). */\nexport function boxServicesStatusRaw(provider: Provider, box: BoxRecord): Promise<ExecResult> {\n return run(provider, box, servicesStatusArgv());\n}\n\n/** `agentbox-ctl restart <name>` — restart one supervised service. */\nexport function restartServiceArgv(name: string): string[] {\n return ['agentbox-ctl', 'restart', name];\n}\n\n/**\n * `agentbox-ctl logs <service> --tail <n> [--follow]` — the in-box service-log\n * tail. Single-sourced here so the non-follow exec (hub `boxLogSnapshot`) and the\n * follow-mode attach argv agree on the exact command the CLI used to shell inline.\n */\nexport function boxLogsArgv(service: string, opts: { tail: number; follow?: boolean }): string[] {\n const argv = ['agentbox-ctl', 'logs', service, '--tail', String(opts.tail)];\n if (opts.follow) argv.push('--follow');\n return argv;\n}\n\n/** Run a non-follow service-log tail and return the raw exec result. */\nexport function boxLogsRaw(\n provider: Provider,\n box: BoxRecord,\n service: string,\n tail: number,\n): Promise<ExecResult> {\n return run(provider, box, boxLogsArgv(service, { tail, follow: false }));\n}\n\n/** Restart a single supervised service by name. */\nexport function boxRestartService(\n provider: Provider,\n box: BoxRecord,\n name: string,\n): Promise<ExecResult> {\n return run(provider, box, restartServiceArgv(name));\n}\n\n/**\n * Restart every named service in sequence (host-side loop — no in-box wire op,\n * so it works on already-baked boxes). Returns each service's exec result so the\n * caller can report partial failures. Sequential (not parallel) to keep the box\n * from thrashing when services depend on one another.\n */\nexport async function boxRestartServices(\n provider: Provider,\n box: BoxRecord,\n names: string[],\n): Promise<{ name: string; result: ExecResult }[]> {\n const out: { name: string; result: ExecResult }[] = [];\n for (const name of names) {\n out.push({ name, result: await boxRestartService(provider, box, name) });\n }\n return out;\n}\n","/**\n * Shared shape for a provider health-check row, produced by each provider's\n * `doctorChecks()` and consumed by `agentbox doctor` / the install wizard, plus\n * the `ProviderModule` contract the CLI loads each `@agentbox/sandbox-<name>`\n * through.\n *\n * Lives in sandbox-core (not apps/cli) so each provider package can own its own\n * probes and login/credential surface without depending on the CLI — a new\n * provider ships all of this in its own package and the CLI dispatches to it\n * generically via a lazy `import()`.\n */\n\nimport type { ProviderDescriptor } from '@agentbox/config';\nimport type { CloudBackend, Provider } from '@agentbox/core';\nimport type { FileManifest } from './prepared-state.js';\n\n/**\n * `info` is for rows that are intentionally inert (e.g. a host tool the\n * user hasn't enabled). It surfaces as a distinct glyph but rolls up like\n * `ok` so it never pushes the overall doctor status to \"warn\".\n */\nexport type CheckStatus = 'ok' | 'info' | 'warn' | 'fail';\n\nexport interface CheckResult {\n label: string;\n status: CheckStatus;\n detail: string;\n hint?: string;\n}\n\n/** Normalized credential state used by the install wizard's re-auth prompt. */\nexport interface CredStatusSummary {\n configured: boolean;\n /** Optional detail shown in the \"already configured (…)\" line (e.g. auth kind). */\n label?: string;\n}\n\n/**\n * Outcome of a non-interactive `setCredentials` call (the headless path the hub\n * drives). `status` reflects the store *after* the attempt, so a caller can\n * report `configured` without a second read.\n */\nexport interface CredSetResult {\n ok: boolean;\n /** One-line failure reason when `ok` is false (e.g. a rejected token). */\n error?: string;\n status: CredStatusSummary;\n}\n\n/**\n * The uniform surface every `@agentbox/sandbox-<name>` package exposes as\n * `export const providerModule`. The CLI's provider loader resolves this via a\n * lazy `import()` and drives create / doctor / install / checkpoint through it,\n * so adding a provider needs no per-provider `switch` arm in the CLI.\n */\nexport interface ProviderModule {\n /** The `Provider` implementation (lifecycle, exec, attach, checkpoint…). */\n provider: Provider;\n /** Cloud backend (host-side executor). Absent for the local docker provider. */\n backend?: CloudBackend;\n /**\n * Declarative metadata — label, credential fields, bake story, capabilities —\n * for UIs and the CLI. Built-in providers declare this in `@agentbox/config`'s\n * `PROVIDERS` table instead; an external plugin declares it here and\n * `agentbox plugin add` snapshots it into `~/.agentbox/plugins.json`.\n *\n * OPTIONAL, and safe to omit: a plugin without one gets a descriptor derived\n * from this module plus defaults chosen to reproduce pre-descriptor behavior\n * (see `provider-descriptor.ts`). Declaring one buys a real label, a credential\n * form, and correct SSH / pause / VNC gating.\n */\n descriptor?: ProviderDescriptor;\n /**\n * First-run credential gate. Called before `create`/`claude`/etc. hand out\n * the provider. Absent for docker (no login). `force` re-runs the flow.\n */\n ensureCredentials?: (opts?: { force?: boolean }) => Promise<void>;\n /** Normalized credential state for the install wizard. Absent for docker. */\n readCredStatus?: () => Promise<CredStatusSummary> | CredStatusSummary;\n /**\n * Non-interactive credential write (the headless path a hub/API driver uses,\n * bypassing the TTY-gated `ensureCredentials` prompts). Validates the given\n * fields against the cloud, then persists them to `~/.agentbox/secrets.env`.\n * The `fields` shape is provider-specific (e.g. `{ apiKey }`, `{ token }`,\n * `{ token, teamId?, projectId? }`). Absent for docker (no login). Never\n * returns the secret values.\n */\n setCredentials?: (fields: Record<string, string>) => Promise<CredSetResult>;\n /**\n * CURRENT build-context fingerprint of the provider's base image/snapshot,\n * for staleness nagging. Absent for docker (its base self-heals).\n */\n currentBaseFingerprintLive?: () => Promise<string | undefined>;\n /**\n * Per-file digests behind that fingerprint (relpath → sha256), so a `stale`\n * verdict can be explained rather than only asserted. Diffed against the\n * manifest stored at bake time.\n *\n * Each provider resolves its OWN asset list, which is why this is a\n * per-provider hook and not a shared helper — docker hashes\n * `DOCKER_CONTEXT_FILE_MAP`, the cloud providers each hash their own\n * `resolveRuntimeAssets()`. `undefined` when the assets can't be resolved.\n */\n currentBaseFileHashes?: () => Promise<FileManifest | undefined>;\n /**\n * Reason `size` won't take effect, or `null` if it will.\n *\n * Some backends fix CPU/memory/disk when the base image is BAKED and reject\n * per-create resources (daytona on the snapshot path, e2b always), so a\n * `--size` / `box.size<Provider>` there is silently discarded at provision.\n * The CLI calls this early — on `config set` and before a create is queued —\n * so the warning reaches a terminal instead of only a detached job's log.\n *\n * Per-provider rather than shared for the same reason as\n * `currentBaseFileHashes` above: each parses its own size grammar\n * (`cpu-mem-disk` vs `cpu-mem`) and reads the baked value from its own\n * prepared-state shape. Must stay PURE and LOCAL — no network, no\n * credentials — because it runs on every `agentbox config set box.size…`.\n * Absent for backends that apply size live (hetzner, vercel, docker).\n */\n sizeIgnoredReason?: (size: string) => string | null;\n /** Local, offline-safe health probes for `agentbox doctor`. */\n doctorChecks: () => Promise<CheckResult[]>;\n}\n\n/**\n * The `[ ok ]` / `[warn]` / `[FAIL]` / `[info]` badge prefix used by\n * `agentbox doctor`'s detailed report and the `remote-docker doctor` subcommand.\n * Colorless by design — same width per status so labels line up.\n */\nexport function statusBadge(s: CheckStatus): string {\n if (s === 'ok') return '[ ok ]';\n if (s === 'info') return '[info]';\n if (s === 'warn') return '[warn]';\n return '[FAIL]';\n}\n\n/** First line of a multi-line string (for compact error summaries). */\nexport function firstLine(s: string): string {\n const i = s.indexOf('\\n');\n return i === -1 ? s : s.slice(0, i);\n}\n\n/** Compact one-line summary of an unknown thrown value. */\nexport function errSummary(err: unknown): string {\n return err instanceof Error ? firstLine(err.message) : String(err);\n}\n","/**\n * Shared writer for the managed cloud-credential store at\n * `~/.agentbox/secrets.env`. Every cloud provider (`daytona`, `hetzner`,\n * `vercel`, `e2b`) persists its API keys/tokens here so the per-provider\n * env-loaders pick them up for every command. The write logic was copy-pasted\n * across four `credentials.ts` files (`writeManaged` / `persistCredentials`);\n * this consolidates it.\n *\n * The file is a plain `KEY=value` env file (optionally `export KEY=value`),\n * mode 0600, written atomically (temp + rename, atomic on the same filesystem).\n */\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\n\n/** Canonical path of the managed secrets file: `~/.agentbox/secrets.env`. */\nexport function secretsEnvPath(): string {\n return resolve(homedir(), '.agentbox', 'secrets.env');\n}\n\n/**\n * Atomically rewrite a set of managed keys in `~/.agentbox/secrets.env`: strip\n * every prior value for a `managedKeys` entry (whether written as `KEY=` or\n * `export KEY=`), then append exactly the keys in `record`. Unrelated lines the\n * user dropped in the file are preserved untouched. Also mirrors the change into\n * `process.env` — every `managedKeys` entry is cleared first, then `record` is\n * applied — so the current process uses the new values immediately (and a stale\n * alternate auth method, e.g. an old JWT when switching to an API key, is gone).\n *\n * File is written mode 0600.\n */\nexport function writeManagedSecrets(\n managedKeys: readonly string[],\n record: Record<string, string>,\n): void {\n for (const k of managedKeys) delete process.env[k];\n for (const [k, v] of Object.entries(record)) process.env[k] = v;\n\n const path = secretsEnvPath();\n mkdirSync(dirname(path), { recursive: true });\n\n let existing = '';\n if (existsSync(path)) {\n try {\n existing = readFileSync(path, 'utf8');\n } catch {\n existing = '';\n }\n }\n\n const kept = existing\n .split(/\\r?\\n/)\n .filter((line) => {\n const stripped = line.startsWith('export ') ? line.slice('export '.length) : line;\n const eq = stripped.indexOf('=');\n if (eq <= 0) return true;\n const key = stripped.slice(0, eq).trim();\n return !managedKeys.includes(key);\n })\n .join('\\n')\n .replace(/\\s+$/u, '');\n\n const lines = Object.entries(record).map(([k, v]) => `${k}=${v}`);\n const body = (kept ? `${kept}\\n` : '') + lines.join('\\n') + '\\n';\n\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // chmod best-effort; writeFileSync mode already covers most filesystems.\n }\n renameSync(tmp, path);\n try {\n chmodSync(path, 0o600);\n } catch {\n // ignore — already attempted on the temp file\n }\n}\n\n/**\n * Mask a secret for display: keep the first and last 4 chars, hide the middle.\n * Short values are fully masked. Never returns the raw secret.\n */\nexport function maskSecret(value: string): string {\n if (value.length <= 8) return '*'.repeat(value.length);\n return `${value.slice(0, 4)}…${'*'.repeat(8)}${value.slice(-4)}`;\n}\n","/**\n * A one-slot hook the CLI uses to mirror a freshly-set provider credential to the\n * hub's `POST /api/v1/providers/:id/credentials` (which validates it against the\n * cloud and persists it on the hub's machine).\n *\n * Why a hook and not a direct call: the interactive login flows live in the\n * `@agentbox/sandbox-<provider>` packages, which must not depend on the CLI (the\n * hub client, target resolution). So the CLI installs a publisher at startup and\n * each provider's `ensureXCredentials` calls {@link publishManagedCredentials}\n * after it has written the local `secrets.env`.\n *\n * TEMPORARY — the two writes (local `secrets.env` + the hub POST) are deliberate\n * while the IO plane stays direct: the PC still needs provider credentials for\n * `cp`/`attach` against the SDK providers (e2b/vercel/daytona), so a login writes\n * locally AND pushes to the hub. Do not \"clean up\" the local write; it goes away\n * only when the IO plane moves behind the hub (see\n * `docs/hub-api-single-path-plan.md` → \"Explicitly out of scope\").\n *\n * Only the INTERACTIVE credential setter publishes — never the headless\n * `setCredentials` the hub itself drives, or a POST would loop back into the hub.\n */\n\n/** Publishes a provider's canonical credential fields to the configured hub. */\nexport type CredentialPublisher = (\n providerId: string,\n fields: Record<string, string>,\n) => Promise<void>;\n\nlet activePublisher: CredentialPublisher | undefined;\n\n/**\n * Install (or clear, with `undefined`) the publisher. The CLI calls this once at\n * startup; a provider package used on its own — or any process that never\n * installs one — publishes nothing.\n */\nexport function setCredentialPublisher(fn: CredentialPublisher | undefined): void {\n activePublisher = fn;\n}\n\n/**\n * Push a just-set credential to the hub, if a publisher is installed. Best-effort:\n * a failed push must never break a local login (the local `secrets.env` write is\n * the guaranteed outcome), so this never throws — the publisher owns any\n * user-facing success/warn message.\n */\nexport async function publishManagedCredentials(\n providerId: string,\n fields: Record<string, string>,\n): Promise<void> {\n const fn = activePublisher;\n if (!fn) return;\n try {\n await fn(providerId, fields);\n } catch {\n /* best-effort — the publisher already reports failures it wants surfaced */\n }\n}\n","/**\n * Low-level process + `/healthz` probes shared by the host relay\n * (`@agentbox/sandbox-docker`'s `relay.ts`) and the hub lifecycle\n * (`hub-lifecycle.ts`). Pure node HTTP / signal / path helpers — none touch\n * docker — so they live in `@agentbox/sandbox-core`: a docker-free host that\n * only needs to start / probe the hub imports these, not the docker package.\n *\n * The relay and the embedded hub are mutually exclusive on the same port, so a\n * single `127.0.0.1:<relayPort()>` probe serves both.\n */\nimport { existsSync } from 'node:fs';\nimport { request as httpRequest } from 'node:http';\nimport { connect as netConnect } from 'node:net';\nimport { dirname, resolve } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { fileURLToPath } from 'node:url';\nimport { relayPort } from './relay-port.js';\n\nexport interface RelayReuseHealth {\n cliEntry?: boolean;\n version?: string;\n}\n\n/**\n * Decide whether an already-alive relay/hub must be reclaimed + respawned. Pure\n * (no fs/network) so it's unit-testable. Two independent gates, OR'd:\n * - capability: `cliEntry === false` → it can't run cp/download/checkpoint and\n * would 64 forever, so reclaim it.\n * - version: both sides report a known non-empty version that DIFFERS → it was\n * spawned by a different agentbox install (a stale npx cache entry, say) and\n * must be replaced so its code matches the CLI.\n * Either version unknown → reuse (don't churn processes predating the field).\n * Match on VERSION only, never commit, so dev rebuilds ('0.0.0-dev' constant)\n * never cycle it every build.\n */\nexport function shouldReclaimForVersion(\n health: RelayReuseHealth,\n currentVersion: string | undefined,\n): boolean {\n if (health.cliEntry === false) return true;\n if (\n typeof health.version === 'string' &&\n health.version.length > 0 &&\n typeof currentVersion === 'string' &&\n currentVersion.length > 0 &&\n health.version !== currentVersion\n ) {\n return true;\n }\n return false;\n}\n\nexport async function processAlive(pid: number): Promise<boolean> {\n try {\n // Signal 0 is the existence probe: throws if no such process.\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** SIGTERM, wait for exit, then SIGKILL. */\nexport async function killPid(pid: number): Promise<void> {\n try {\n process.kill(pid, 'SIGTERM');\n } catch {\n return; // already gone\n }\n for (let i = 0; i < 20; i++) {\n if (!(await processAlive(pid))) return;\n await delay(100);\n }\n try {\n process.kill(pid, 'SIGKILL');\n } catch {\n // best-effort\n }\n}\n\n/**\n * Raw TCP liveness on the relay/hub port, independent of what speaks HTTP there.\n *\n * The difference between this and {@link fetchHealthz} is the whole diagnostic:\n * TCP open + `/healthz` invalid means SOMETHING ELSE holds the port, which is\n * the case a relay that dies on EADDRINUSE needs to name.\n */\nexport function portIsOccupied(timeoutMs: number, port: number = relayPort()): Promise<boolean> {\n return new Promise<boolean>((resolveP) => {\n const sock = netConnect({ host: '127.0.0.1', port });\n const done = (occupied: boolean): void => {\n sock.destroy();\n resolveP(occupied);\n };\n sock.setTimeout(timeoutMs);\n sock.once('connect', () => done(true));\n sock.once('timeout', () => done(false));\n sock.once('error', () => done(false));\n });\n}\n\nexport function pingHealthz(timeoutMs: number): Promise<boolean> {\n return new Promise<boolean>((resolveP) => {\n const req = httpRequest(\n {\n host: '127.0.0.1',\n port: relayPort(),\n method: 'GET',\n path: '/healthz',\n timeout: timeoutMs,\n },\n (res) => {\n res.resume();\n const status = res.statusCode ?? 0;\n resolveP(status >= 200 && status < 300);\n },\n );\n req.on('error', () => resolveP(false));\n req.on('timeout', () => {\n req.destroy();\n resolveP(false);\n });\n req.end();\n });\n}\n\nexport interface HealthzBody {\n ok: boolean;\n boxes: number;\n events: number;\n /** The relay's own pid (for reclaiming). Absent on relays predating this field. */\n pid?: number;\n /** True when a Next UI is delegated (the embedded hub) vs a bare relay. Absent on old relays. */\n ui?: boolean;\n /** Whether the relay has AGENTBOX_CLI_ENTRY (can run cp/download/checkpoint). Absent on old relays. */\n cliEntry?: boolean;\n /** The agentbox version that spawned the relay. Absent on relays predating this field. */\n version?: string;\n /** The agentbox short commit that spawned the relay (observability only). Absent on old relays. */\n commit?: string;\n /** The hub's profile (`localhost` | `hetzner` | `vercel`). Absent on a lean relay / old hubs. */\n profile?: string;\n /** True when the resident create worker is running (`hub expose`). Absent otherwise. */\n worker?: boolean;\n}\n\nexport function fetchHealthz(timeoutMs: number): Promise<HealthzBody | null> {\n return new Promise<HealthzBody | null>((resolveP) => {\n const req = httpRequest(\n {\n host: '127.0.0.1',\n port: relayPort(),\n method: 'GET',\n path: '/healthz',\n timeout: timeoutMs,\n },\n (res) => {\n const status = res.statusCode ?? 0;\n if (status < 200 || status >= 300) {\n res.resume();\n resolveP(null);\n return;\n }\n const chunks: Buffer[] = [];\n res.on('data', (c: Buffer) => chunks.push(c));\n res.on('end', () => {\n try {\n const parsed = JSON.parse(\n Buffer.concat(chunks).toString('utf8'),\n ) as Partial<HealthzBody>;\n if (\n typeof parsed.ok === 'boolean' &&\n typeof parsed.boxes === 'number' &&\n typeof parsed.events === 'number'\n ) {\n resolveP({\n ok: parsed.ok,\n boxes: parsed.boxes,\n events: parsed.events,\n pid: typeof parsed.pid === 'number' ? parsed.pid : undefined,\n ui: typeof parsed.ui === 'boolean' ? parsed.ui : undefined,\n cliEntry: typeof parsed.cliEntry === 'boolean' ? parsed.cliEntry : undefined,\n version:\n typeof parsed.version === 'string' && parsed.version.length > 0\n ? parsed.version\n : undefined,\n commit:\n typeof parsed.commit === 'string' && parsed.commit.length > 0\n ? parsed.commit\n : undefined,\n profile:\n typeof parsed.profile === 'string' && parsed.profile.length > 0\n ? parsed.profile\n : undefined,\n worker: parsed.worker === true ? true : undefined,\n });\n } else {\n resolveP(null);\n }\n } catch {\n resolveP(null);\n }\n });\n res.on('error', () => resolveP(null));\n },\n );\n req.on('error', () => resolveP(null));\n req.on('timeout', () => {\n req.destroy();\n resolveP(null);\n });\n req.end();\n });\n}\n\n/**\n * Locate the agentbox CLI entry the relay/hub spawns for `checkpoint.create`\n * (and the hub child's `AGENTBOX_CLI_ENTRY`). Layouts:\n * 1. Bundled CLI (dev + published): this module IS bundled into the CLI entry,\n * so the entry is `index.js` next to it.\n * 2. installed: `.../agentbox/node_modules/@agentbox/<pkg>/dist` next to\n * `.../agentbox/dist/index.js`.\n * Best-effort: returns null when not found (the caller reports a clear error).\n */\nexport function resolveCliEntry(): string | null {\n const override = process.env.AGENTBOX_CLI_ENTRY;\n if (override && existsSync(override)) return override;\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, 'index.js'),\n resolve(here, '..', '..', '..', 'apps', 'cli', 'dist', 'index.js'),\n resolve(here, '..', '..', '..', '..', 'dist', 'index.js'),\n ];\n for (const c of candidates) {\n if (existsSync(c)) return c;\n }\n return null;\n}\n","/**\n * The single resolver for the port the host daemon binds.\n *\n * Relay and hub share it: the hub IS the relay daemon plus a Next UI in one\n * process, so the two are mutually exclusive there (see `hub-lifecycle.ts`).\n * One resolver means one answer for both — and for the probes in\n * `hub-process.ts`, the box-facing `host.docker.internal:<port>` URL, and the\n * `--port` handed to the spawned `agentbox-relay serve`.\n *\n * Resolution order:\n * 1. an explicit {@link setRelayPort} (the CLI seeds this from `relay.port`\n * at startup, before commander parses argv)\n * 2. `AGENTBOX_RELAY_PORT`\n * 3. {@link FALLBACK_RELAY_PORT}\n *\n * The env mirror is not a second config surface — it is how CHILD processes\n * learn the port. The relay daemon, the hub's `server.ts`, the detached queue\n * worker and the `AGENTBOX_CLI_ENTRY` the relay shells back into for host\n * actions all inherit `process.env`, and none of them should re-read the\n * layered config to agree with their parent. Same idiom as the\n * `AGENTBOX_CLI_VERSION` / `AGENTBOX_CLI_RUNTIME_DIR` stamps in the CLI entry.\n */\n\n/**\n * Mirrors `DEFAULT_RELAY_PORT` in `@agentbox/relay`, which this package cannot\n * import (`@agentbox/relay` depends on `@agentbox/sandbox-core`, so the edge\n * would be a cycle). This is the ONLY duplicate of the number, and everything\n * else in the tree now resolves through {@link relayPort}.\n */\nexport const FALLBACK_RELAY_PORT = 8787;\n\n/** Env var carrying the resolved port to child processes. */\nexport const RELAY_PORT_ENV = 'AGENTBOX_RELAY_PORT';\n\nlet override: number | null = null;\n\n/** True for a value that can actually be bound. */\nexport function isValidRelayPort(port: number): boolean {\n return Number.isInteger(port) && port >= 1 && port <= 65535;\n}\n\n/**\n * Pin the port for this process and every child it spawns. Called once from the\n * CLI entrypoint with the effective `relay.port`. Invalid values are ignored so\n * a typo in a config file can never leave the daemon unbindable — the caller\n * validates and warns.\n */\nexport function setRelayPort(port: number): void {\n if (!isValidRelayPort(port)) return;\n override = port;\n process.env[RELAY_PORT_ENV] = String(port);\n}\n\n/** The port the relay/hub binds here. Cheap — safe to call per request. */\nexport function relayPort(): number {\n if (override !== null) return override;\n const fromEnv = Number.parseInt(process.env[RELAY_PORT_ENV] ?? '', 10);\n return isValidRelayPort(fromEnv) ? fromEnv : FALLBACK_RELAY_PORT;\n}\n\n/** Test seam: drop the pinned value (and the env mirror). */\nexport function resetRelayPort(): void {\n override = null;\n delete process.env[RELAY_PORT_ENV];\n}\n","import { spawn } from 'node:child_process';\nimport { existsSync, openSync } from 'node:fs';\nimport { mkdir, readFile, stat, unlink, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join, resolve } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { fileURLToPath } from 'node:url';\nimport { scrubAgentSessionEnv } from './agent-session-env.js';\nimport { buildExposedHubEnv, EXPOSED_HUB_PROFILE, parseEnvFileBody } from './hub-expose.js';\nimport { controlPlaneDeployPath, type ControlPlaneDeployRecord } from './ssh-config.js';\nimport { resolveStagedRuntimeRoot, RUNTIME_ROOT_ENV } from './runtime-root.js';\nimport { isValidRelayPort, relayPort, setRelayPort } from './relay-port.js';\nimport {\n fetchHealthz,\n killPid,\n pingHealthz,\n processAlive,\n resolveCliEntry,\n shouldReclaimForVersion,\n type HealthzBody,\n} from './hub-process.js';\nimport {\n hubDockerContext,\n hubPortlessCurrent,\n hubPortlessSync,\n hubPortlessTeardown,\n} from './hub-hooks.js';\n\n/**\n * `agentbox hub` lifecycle. The hub is the embedded relay + Next UI in ONE\n * process on the relay port (`relayPort()`, default 8787) — a superset of the\n * lean `agentbox-relay`. The two are mutually exclusive on the port, so:\n * - starting the hub reclaims any lean relay already holding it;\n * - a running hub answers /healthz with `ui:true`, so the create path's\n * `ensureRelay()` reuses it (it also sets AGENTBOX_CLI_ENTRY so the capability\n * gate is satisfied and it's never reclaimed for that reason).\n *\n * Lives in `@agentbox/sandbox-core` (not `@agentbox/sandbox-docker`) so a\n * docker-free host can start / probe / stop the hub without importing docker\n * machinery. The two docker-side niceties it used to reach for directly — the\n * Portless friendly URL and the docker build context — come through the\n * `hub-hooks.ts` seam, which the CLI fills from the docker package at startup;\n * an unset hook degrades to the plain loopback URL / no docker context.\n *\n * Shares the low-level probes (fetchHealthz/pingHealthz/killPid/processAlive)\n * and the version-reclaim gate with `relay.ts` (both import them from\n * `hub-process.ts`); keeps its own pid/log/token files so its status is\n * independent of the lean relay's.\n */\n\nconst STATE_DIR = join(homedir(), '.agentbox');\nconst HUB_PID_FILE = join(STATE_DIR, 'hub.pid');\n/** The lean relay's pidfile — cleared when the hub takes the port from a relay. */\nconst RELAY_PID_FILE = join(STATE_DIR, 'relay.pid');\nconst HUB_LOG_FILE = join(STATE_DIR, 'hub.log');\nexport const HUB_TOKEN_FILE = join(STATE_DIR, 'hub', 'token');\n// Bind wide (like the bare relay in relay.ts) so docker boxes can reach the hub's\n// embedded relay at host.docker.internal:8787 for their box-initiated RPCs (git\n// push/cp/download, and the /api/v1 prompt stream the attach footer subscribes to\n// once approvals moved off the bare relay onto the hub). The profile stays\n// `localhost` (token gate) — decoupled from the bind host in server.ts — so this\n// is not the hetzner control-box profile. `/admin/*` remains loopback-only by\n// peer address (the localhost hub sets no admin token, so adminGateAllows\n// fail-closes non-loopback callers); the LAN-reachable surface is only the\n// token-gated `/api/v1` + UI and the box-facing `/rpc` + `/events`, matching the\n// bare relay this replaces. INVARIANT (plan Step 12): this wide bind is what the\n// token-profile custody byte-read peer-gate (apps/hub/lib/peer.ts) protects — do\n// not narrow it back to loopback without keeping that gate.\nconst HOST = '0.0.0.0';\n// The address to advertise in URLs (status output, the `?token=` open URL) and to\n// health-probe — the hub binds wide (HOST) but is reached from THIS machine over\n// loopback; `0.0.0.0` is not a usable browser/client address.\nconst LOOPBACK_HOST = '127.0.0.1';\n\n/** Minimum Node for the hub server (node:sqlite in password mode + Next 16). */\nconst NODE_MIN = { major: 22, minor: 5 };\n\nexport interface HubEndpoint {\n /** Base URL the browser opens (127.0.0.1:8787). */\n hostUrl: string;\n /** Full open URL including `?token=` when the token gate is on. */\n openUrl: string;\n port: number;\n /** The token gate secret, when auth is on (localhost token mode). */\n token: string | null;\n}\n\nexport interface EnsureHubOptions {\n onLog?: (line: string) => void;\n /**\n * Effective `portless.enabled`. When not `false` (and Portless is installed on\n * a non-OrbStack host) the hub registers `https://agentbox.localhost`. Pass\n * `false` to force teardown. Undefined → register best-effort.\n */\n portlessEnabled?: boolean | undefined;\n}\n\n/** CP dir on this machine, holding deploy.json + control-plane.env. */\nconst CP_DIR = join(STATE_DIR, 'control-plane');\n\n/**\n * Resolve the exposed-hub spawn env from `~/.agentbox/control-plane`, or null\n * when this machine isn't exposed. This is the seam that makes EVERY `ensureHub`\n * caller — `hub start`, `restart`, autostart, the post-update refresh — bring\n * the hub up in the SAME mode without any of them knowing about it: the flip\n * lives entirely in the on-disk record `agentbox hub expose` writes.\n *\n * Best-effort: a missing/partial record or env file → null (the plain localhost\n * hub). The hub itself fails closed on a genuinely missing secret.\n */\nasync function resolveExposedSpawn(): Promise<{\n env: Record<string, string>;\n profile: string;\n} | null> {\n try {\n const record = JSON.parse(\n await readFile(controlPlaneDeployPath(), 'utf8'),\n ) as ControlPlaneDeployRecord;\n if (record.provider !== 'local') return null;\n const envBody = await readFile(join(CP_DIR, 'control-plane.env'), 'utf8').catch(() => '');\n const env = buildExposedHubEnv(record, parseEnvFileBody(envBody));\n return { env, profile: EXPOSED_HUB_PROFILE };\n } catch {\n return null;\n }\n}\n\nfunction nodeVersion(): { major: number; minor: number } {\n const [major, minor] = process.versions.node.split('.').map((n) => Number.parseInt(n, 10));\n return { major: major ?? 0, minor: minor ?? 0 };\n}\n\n/** Throw a clear error below the hub's Node floor (the CLI floor is lower). */\nfunction assertNodeSupported(): void {\n const v = nodeVersion();\n if (v.major < NODE_MIN.major || (v.major === NODE_MIN.major && v.minor < NODE_MIN.minor)) {\n throw new Error(\n `agentbox hub needs Node >= ${NODE_MIN.major}.${NODE_MIN.minor} (running ${process.versions.node}). ` +\n 'Upgrade Node, or run the lean relay with `agentbox relay start`.',\n );\n }\n}\n\n/**\n * Node flags for the hub spawn. `node:sqlite` (better-auth on the password\n * profile) is behind `--experimental-sqlite` on Node 22.5–23; unflagged on 24+.\n */\nfunction nodeFlags(): string[] {\n const v = nodeVersion();\n return v.major < 24 ? ['--experimental-sqlite'] : [];\n}\n\nasync function readPid(file: string): Promise<number | null> {\n try {\n const pid = Number.parseInt((await readFile(file, 'utf8')).trim(), 10);\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null;\n }\n}\n\nasync function readToken(): Promise<string | null> {\n try {\n const t = (await readFile(HUB_TOKEN_FILE, 'utf8')).trim();\n return t.length > 0 ? t : null;\n } catch {\n return null;\n }\n}\n\n/** The hub's token gate secret (`~/.agentbox/hub/token`), or null when unset. */\nexport function readHubToken(): Promise<string | null> {\n return readToken();\n}\n\nasync function endpointFor(portlessUrl?: string): Promise<HubEndpoint> {\n const token = await readToken();\n // Prefer the friendly Portless URL when one is registered; else the loopback\n // (NOT the bind host — `http://0.0.0.0` is not a usable browser/client URL).\n const hostUrl = portlessUrl ?? `http://${LOOPBACK_HOST}:${String(relayPort())}`;\n return {\n hostUrl,\n openUrl: token ? `${hostUrl}/?token=${token}` : hostUrl,\n port: relayPort(),\n token,\n };\n}\n\n/**\n * Locate the built hub server (`server.js`) the CLI spawns. Mirrors\n * relay.ts:resolveRelayBin. Layouts:\n * 0. env override: AGENTBOX_HUB_BIN\n * 1. bundled CLI: <root>/runtime/hub/apps/hub/server.js (sibling of dist/)\n * 2. workspace dev: <repo>/apps/hub/dist-standalone/apps/hub/server.js\n */\nexport function resolveHubServer(): string {\n const override = process.env.AGENTBOX_HUB_BIN;\n if (override && existsSync(override)) return override;\n const here = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n resolve(here, '..', 'runtime', 'hub', 'apps', 'hub', 'server.js'),\n resolve(here, '..', '..', '..', 'apps', 'hub', 'dist-standalone', 'apps', 'hub', 'server.js'),\n resolve(here, '..', '..', 'apps', 'hub', 'dist-standalone', 'apps', 'hub', 'server.js'),\n ];\n for (const c of candidates) {\n if (existsSync(c)) return c;\n }\n throw new Error(\n 'could not locate the built hub server; run `pnpm --filter @agentbox/hub build:standalone` ' +\n `(dev), or set AGENTBOX_HUB_BIN. Tried:\\n ${candidates.join('\\n ')}`,\n );\n}\n\n/**\n * The env the hub child needs beyond `process.env` to find files its own bundle\n * doesn't carry.\n *\n * The hub bundle lives at `<cli>/runtime/hub/apps/hub`, three levels BELOW the\n * staged runtime root — and every provider is inlined into it. So each\n * self-relative lookup those providers do (`<self>/../runtime`,\n * `<self>/../../runtime`) misses the real `<cli>/runtime`, and the hub silently\n * degrades: cloud base fingerprints come back undefined (`baseStatus: unknown`\n * → \"baked, unverified\"), and custody bake adoption — which gates creates on a\n * control box — skips every shared record. A dev tree hides it by falling back\n * to the monorepo sources; an npm install has no such fallback. Handing over the\n * roots the CLI already resolved is the fix, same as the docker context below.\n *\n * The docker build context is supplied through the `hub-hooks.ts` seam (the CLI\n * installs its `BUILD_CONTEXT_DIR`); a docker-free host omits it. The runtime\n * root is marker-verified, and `resolveStagedRuntimeRoot` checks\n * `AGENTBOX_RUNTIME_ROOT` first, so an operator override propagates. When no\n * staged root exists (a workspace-only build) the key is OMITTED rather than set\n * to a path that doesn't resolve — it would otherwise sit ahead of the child's\n * own correct lookup.\n */\nexport function hubRuntimeEnv(\n opts: { dockerContext?: string; runtimeRoot?: string } = {},\n): Record<string, string> {\n const env: Record<string, string> = {};\n const dockerContext = opts.dockerContext ?? hubDockerContext();\n if (dockerContext) env.AGENTBOX_DOCKER_CONTEXT = dockerContext;\n const runtimeRoot =\n opts.runtimeRoot ??\n resolveStagedRuntimeRoot(dirname(fileURLToPath(import.meta.url)), 'docker/Dockerfile.box');\n if (runtimeRoot) env[RUNTIME_ROOT_ENV] = runtimeRoot;\n return env;\n}\n\n/** Kill whatever holds the port (a lean relay or a stale hub) and confirm it freed. */\nasync function reclaimPort(\n reportedPid: number | undefined,\n log: (line: string) => void,\n): Promise<void> {\n const pidFromFile = await readPid(HUB_PID_FILE);\n const seen = new Set<number>();\n for (const pid of [reportedPid, pidFromFile]) {\n if (typeof pid !== 'number' || pid <= 0 || seen.has(pid)) continue;\n seen.add(pid);\n if (!(await processAlive(pid))) continue;\n log(`stopping process on :${String(relayPort())} (pid ${String(pid)})`);\n await killPid(pid);\n }\n await unlink(HUB_PID_FILE).catch(() => {});\n // Same reason as the relay side: a stale sibling pidfile makes `relay status`\n // report a process this call just killed.\n await unlink(RELAY_PID_FILE).catch(() => {});\n if (await pingHealthz(300)) {\n throw new Error(\n `something is still listening on :${String(relayPort())} and could not be stopped ` +\n `(reported pid ${String(reportedPid ?? 'unknown')}); kill it manually and retry`,\n );\n }\n}\n\n/**\n * Idempotently bring up the embedded hub on 8787. Reuses an already-running hub\n * (`ui:true`, version match); reclaims a lean relay or a version-mismatched hub\n * first. Best-effort like ensureRelay: failures throw.\n */\nexport async function ensureHub(opts: EnsureHubOptions = {}): Promise<HubEndpoint> {\n const log = opts.onLog ?? (() => {});\n assertNodeSupported();\n await mkdir(STATE_DIR, { recursive: true });\n\n // Exposed? Resolve the flip from disk so this call (whoever made it) brings the\n // hub up in the machine's configured mode. `desiredProfile` defaults to\n // `localhost` — a plain hub.\n const exposed = await resolveExposedSpawn();\n const desiredProfile = exposed?.profile ?? 'localhost';\n // An exposed hub's port is a DEPLOYMENT fact: the bind address, the tunnel and\n // the firewall rule were all provisioned against the port in the record, so it\n // is what the child will bind. Adopt it as this process's relay port before any\n // probing, or every /healthz here targets `relay.port` while the hub listens on\n // the record's port — the hub then reads as dead (or as a collision) when it is\n // running fine. Whoever changes the port must re-run `hub expose --port`, which\n // moves the tunnel and firewall with it.\n const exposedPort = Number.parseInt(exposed?.env['AGENTBOX_HUB_PORT'] ?? '', 10);\n if (isValidRelayPort(exposedPort) && exposedPort !== relayPort()) {\n log(\n `this machine's hub is exposed on :${String(exposedPort)}, so relay.port ` +\n `(${String(relayPort())}) does not apply here — re-run \\`agentbox hub expose --port\\` to move it`,\n );\n setRelayPort(exposedPort);\n }\n\n const currentVersion = process.env.AGENTBOX_CLI_VERSION;\n // A hub running in the wrong profile (a plain localhost hub while this machine\n // is exposed, or the reverse) must be reclaimed, not reused: the two differ in\n // bind, auth and the resident worker.\n const reusable = (h: HealthzBody): boolean =>\n h.ui === true &&\n !shouldReclaimForVersion(h, currentVersion) &&\n (h.profile ?? 'localhost') === desiredProfile;\n\n const health = await fetchHealthz(500);\n if (health !== null) {\n const profileMismatch = (health.profile ?? 'localhost') !== desiredProfile;\n if (reusable(health)) {\n return endpointFor(await hubPortlessSync(opts.portlessEnabled, relayPort())); // a hub already runs here\n }\n log(\n profileMismatch\n ? `a hub in the ${health.profile ?? 'localhost'} profile holds :${String(relayPort())} — reclaiming to run ${desiredProfile}`\n : health.ui === true\n ? 'a hub from a different agentbox version holds :8787 — reclaiming'\n : 'a lean relay holds :8787 — reclaiming to start the hub',\n );\n await reclaimPort(health.pid, log);\n // fall through to spawn\n } else {\n const pid = await readPid(HUB_PID_FILE);\n if (pid !== null && (await processAlive(pid))) {\n // A hub process exists but isn't answering /healthz yet — give startup a\n // beat before deciding it's wedged. It has to clear the SAME bar as an\n // already-answering hub above: a bare \"it responds\" accepted a plain\n // localhost hub (or a lean relay) on a machine whose record asks for the\n // exposed control-box profile, so the flip silently didn't happen.\n let late: HealthzBody | null = null;\n for (let i = 0; i < 10; i++) {\n late = await fetchHealthz(300);\n if (late !== null) break;\n await delay(200);\n }\n if (late !== null && reusable(late)) {\n return endpointFor(await hubPortlessSync(opts.portlessEnabled, relayPort()));\n }\n if (late !== null) {\n log(\n `a hub in the ${late.profile ?? 'localhost'} profile holds :${String(relayPort())} — reclaiming to run ${desiredProfile}`,\n );\n }\n // Still unresponsive after ~2s: replace it rather than report a false\n // \"running\" for a hub that never came up.\n log(`hub pid ${String(pid)} alive but /healthz unresponsive — restarting it`);\n await reclaimPort(pid, log);\n // fall through to a fresh spawn\n } else if (pid !== null) {\n await unlink(HUB_PID_FILE).catch(() => {});\n }\n }\n\n const hubServer = resolveHubServer();\n const cliEntry = resolveCliEntry();\n if (cliEntry === null) {\n throw new Error(\n 'cannot start the hub: agentbox CLI entry not found (is the build complete?). ' +\n 'Set AGENTBOX_CLI_ENTRY to override.',\n );\n }\n if (exposed) log(`bringing the hub up exposed (${desiredProfile} profile, worker on)`);\n return spawnHub(hubServer, cliEntry, log, opts.portlessEnabled, exposed?.env);\n}\n\nasync function spawnHub(\n hubServer: string,\n cliEntry: string,\n log: (line: string) => void,\n portlessEnabled: boolean | undefined,\n exposedEnv?: Record<string, string>,\n): Promise<HubEndpoint> {\n const logFd = openSync(HUB_LOG_FILE, 'a');\n const child = spawn(process.execPath, [...nodeFlags(), hubServer], {\n detached: true,\n stdio: ['ignore', logFd, logFd],\n env: {\n // A hub started from inside an agent session must not pass that session's\n // identity to the managers it runs.\n ...scrubAgentSessionEnv(process.env),\n // The staged hub is a production Next build; force production so server.ts\n // takes the standalone path (dev mode would load webpack, which the\n // standalone build prunes).\n NODE_ENV: 'production',\n AGENTBOX_CLI_ENTRY: cliEntry,\n // The hub is the localhost profile (token gate). It binds 0.0.0.0 (see HOST)\n // so docker boxes reach its embedded relay via host.docker.internal; the\n // profile is set independently of the bind host in server.ts.\n AGENTBOX_HUB_HOST: HOST,\n // Load-bearing for `relay.port`: server.ts defaults to 8787 on its own, so\n // without this the hub keeps binding 8787 while everything here probes the\n // configured port.\n AGENTBOX_HUB_PORT: String(relayPort()),\n // The hub bundle ships no staged build context of its own, so its\n // in-process freshness checks couldn't fingerprint (degrading to\n // 'unknown'). Hand it the CLI's resolved roots so hub-side fingerprints\n // match what the create/prepare workers compute. See hubRuntimeEnv.\n ...hubRuntimeEnv(),\n // `hub expose` overrides the above (bind 0.0.0.0, profile hetzner, auth,\n // worker, public URL, tokens). Empty/absent → the plain localhost hub.\n ...(exposedEnv ?? {}),\n },\n });\n child.unref();\n // Note when the child dies before it ever answers /healthz. The common cause is\n // a startup crash (e.g. a missing runtime dep) whose stack the child already\n // wrote to HUB_LOG_FILE — we surface that tail rather than making the user wait\n // out the full timeout and then go read the log by hand.\n let exit: { code: number | null; signal: NodeJS.Signals | null } | null = null;\n child.on('exit', (code, signal) => {\n exit = { code, signal };\n });\n if (typeof child.pid === 'number') {\n await writeFile(HUB_PID_FILE, String(child.pid), 'utf8');\n log(`spawned hub process (pid ${String(child.pid)}, port ${String(relayPort())})`);\n }\n // Next prepare takes a beat longer than the lean relay; give it ~25s.\n for (let i = 0; i < 50; i++) {\n if (await pingHealthz(300)) {\n log(`hub reachable on http://${LOOPBACK_HOST}:${String(relayPort())}`);\n const purl = await hubPortlessSync(portlessEnabled, relayPort());\n if (purl) log(`hub also reachable on ${purl}`);\n return endpointFor(purl);\n }\n if (exit !== null) {\n await unlink(HUB_PID_FILE).catch(() => {});\n // Let the child flush its last stderr line into the log before we tail it.\n await delay(150);\n throw new Error(\n await hubStartupError(`hub process exited (${describeExit(exit)}) during startup`),\n );\n }\n await delay(200);\n }\n throw new Error(\n await hubStartupError(\n `hub did not become reachable on http://${LOOPBACK_HOST}:${String(relayPort())} within ~25s`,\n ),\n );\n}\n\nfunction describeExit(exit: { code: number | null; signal: NodeJS.Signals | null }): string {\n if (exit.signal !== null) return `killed by ${exit.signal}`;\n return `exit code ${String(exit.code ?? 'unknown')}`;\n}\n\n/** Build a startup-failure message with the tail of the hub log inlined. */\nasync function hubStartupError(headline: string): Promise<string> {\n const tail = await tailFile(HUB_LOG_FILE, 20);\n const suffix = tail\n ? `\\n--- last lines of ${HUB_LOG_FILE} ---\\n${tail}`\n : `; see ${HUB_LOG_FILE}`;\n return `${headline}${suffix}`;\n}\n\n/** Last `maxLines` non-empty lines of a file, or '' when unreadable/empty. */\nasync function tailFile(file: string, maxLines: number): Promise<string> {\n try {\n const lines = (await readFile(file, 'utf8')).split('\\n').filter((l) => l.trim().length > 0);\n return lines.slice(-maxLines).join('\\n');\n } catch {\n return '';\n }\n}\n\nexport interface StopHubResult {\n stopped: boolean;\n pid: number | null;\n}\n\n/** Stop the hub process + clear its pidfile. SIGTERM then SIGKILL. Idempotent. */\nexport async function stopHub(): Promise<StopHubResult> {\n const pid = await readPid(HUB_PID_FILE);\n if (pid === null) {\n await hubPortlessTeardown();\n return { stopped: false, pid: null };\n }\n if (!(await processAlive(pid))) {\n await unlink(HUB_PID_FILE).catch(() => {});\n await hubPortlessTeardown();\n return { stopped: false, pid };\n }\n await killPid(pid);\n await unlink(HUB_PID_FILE).catch(() => {});\n await hubPortlessTeardown();\n return { stopped: true, pid };\n}\n\nexport interface HubStatus {\n /** /healthz responded. */\n running: boolean;\n /** /healthz reported a delegated Next UI (vs a bare relay on the port). */\n ui: boolean;\n pid: number | null;\n pidAlive: boolean;\n port: number;\n hostUrl: string;\n openUrl: string;\n token: string | null;\n pidFile: string;\n logFile: string;\n /** The running hub's profile (`localhost` | `hetzner`). Absent on old hubs / a lean relay. */\n profile?: string;\n /** True when the resident create worker is running (exposed hub). */\n worker?: boolean;\n /**\n * The running hub predates the bundle it was spawned from — something rebuilt\n * `server.js` underneath it (a `pnpm build`, or `npm publish`, whose\n * `prepublishOnly` rebuilds the workspace). Its eagerly-loaded chunks are still\n * in memory, but the next LAZY `import()` resolves against the new\n * content-hashed filenames and dies with `Cannot find module 'dist-XXXX.js'`.\n * Only surfaces later, on whichever command first needs a lazy module.\n */\n staleBundle?: boolean;\n}\n\n/** Read-only snapshot of the hub's liveness (mirrors getRelayStatus). */\nexport async function getHubStatus(): Promise<HubStatus> {\n const pid = await readPid(HUB_PID_FILE);\n const pidAlive = pid !== null && (await processAlive(pid));\n const health = await fetchHealthz(300);\n const ep = await endpointFor((await hubPortlessCurrent()) ?? undefined);\n return {\n running: health !== null,\n ui: health?.ui === true,\n pid,\n pidAlive,\n port: relayPort(),\n hostUrl: ep.hostUrl,\n openUrl: ep.openUrl,\n token: ep.token,\n pidFile: HUB_PID_FILE,\n logFile: HUB_LOG_FILE,\n ...(health?.profile ? { profile: health.profile } : {}),\n ...(health?.worker ? { worker: true } : {}),\n ...((await bundleIsNewerThanHub(pid)) ? { staleBundle: true } : {}),\n };\n}\n\n/**\n * Whether `server.js` was rewritten after the running hub started. The hub writes\n * its pidfile at boot, so that file's mtime IS the process start time — no `ps`\n * shell-out, and it works the same for a published install as for a dev tree.\n * False whenever either side can't be read: this drives a warning, so an\n * unknown must not read as \"stale\".\n */\nasync function bundleIsNewerThanHub(pid: number | null): Promise<boolean> {\n if (pid === null) return false;\n try {\n const [startedAt, builtAt] = await Promise.all([\n stat(HUB_PID_FILE).then((st) => st.mtimeMs),\n stat(resolveHubServer()).then((st) => st.mtimeMs),\n ]);\n return builtAt > startedAt;\n } catch {\n return false;\n }\n}\n","/**\n * Variables that name the agent session a process runs in. A process AgentBox\n * launches on the host (the hub daemon, a manager's tmux session) must not\n * inherit them from whoever started it: a hub started from inside a claude\n * session would otherwise hand that session's identity to every manager it runs,\n * and their own `agentbox` calls would be attributed to it. User configuration\n * (`CLAUDE_EFFORT`, `CLAUDE_CODE_USE_*`, API keys) is left alone.\n */\nexport const AGENT_SESSION_ENV_VARS: readonly string[] = [\n 'CLAUDECODE',\n 'CLAUDE_PID',\n 'CLAUDE_CODE_SESSION_ID',\n 'CLAUDE_CODE_BRIDGE_SESSION_ID',\n 'CLAUDE_CODE_CHILD_SESSION',\n 'CLAUDE_CODE_ENTRYPOINT',\n 'CLAUDE_CODE_EXECPATH',\n 'CLAUDE_CODE_MESSAGING_SOCKET',\n 'CLAUDE_CODE_MESSAGING_TOKEN',\n 'CLAUDE_CODE_SESSION_ATTENDED',\n 'CLAUDE_CODE_SESSION_KIND',\n 'CLAUDE_AGENTS_SELECT',\n 'CLAUDE_BG_BACKEND',\n 'CLAUDE_BG_SOCKET_TOKENS_PATH',\n 'CODEX_THREAD_ID',\n 'AGENTBOX_MANAGER',\n 'AGENTBOX_WORKSPACE',\n];\n\n/**\n * `env` without the agent-session variables, and without TMUX/TMUX_PANE: those\n * name a pane the child does not run in (and make tmux refuse to nest).\n */\nexport function scrubAgentSessionEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const out = { ...env };\n for (const key of [...AGENT_SESSION_ENV_VARS, 'TMUX', 'TMUX_PANE']) delete out[key];\n return out;\n}\n","/**\n * Locate the staged CLI runtime tree — the `runtime/` directory holding the\n * per-provider subtrees (`e2b/`, `vercel/`, `hetzner/`, `digitalocean/`,\n * `docker/`, `daytona/`) whose bytes the base fingerprint hashes.\n *\n * Every provider resolves this the same two ways: relative to its own bundle\n * (`<dist>/../runtime`, `<dist>/../../runtime`) which works for the CLI (staged\n * next to `apps/cli/dist`) and a published install. That relative lookup fails\n * for a **source-deployed control-box hub**: its bundle lives under\n * `apps/hub/dist-standalone/**`, nowhere near the staged tree at\n * `apps/cli/runtime`, so it silently falls back to hashing the monorepo\n * `packages/**` source instead — which differs from the staged tree and yields\n * a different fingerprint than the CLI baked with. The hub then rejects every\n * PC-baked custody record as \"a different build context\" and never adopts it.\n *\n * The same miss hits a PACKAGE-installed hub, for a different reason: its bundle\n * sits at `<cli>/runtime/hub/apps/hub`, three levels below the staged root, so\n * neither candidate reaches `<cli>/runtime` — and with no monorepo to fall back\n * to, every cloud provider's live fingerprint comes back undefined.\n *\n * `AGENTBOX_RUNTIME_ROOT` closes both gaps: point it at the staged `runtime/`\n * dir and any consumer (hub included) computes the same fingerprint the CLI\n * does. Two places set it: `spawnHub` (@agentbox/sandbox-docker) for every\n * CLI-spawned hub, and the VPS deploy Dockerfile for the hub container.\n */\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\n/** Env override naming the staged `runtime/` root explicitly. */\nexport const RUNTIME_ROOT_ENV = 'AGENTBOX_RUNTIME_ROOT';\n\n/**\n * Candidate staged-runtime roots, override first. `self` is the caller module's\n * directory (`dirname(fileURLToPath(import.meta.url))`).\n */\nexport function stagedRuntimeRootCandidates(self: string): string[] {\n const candidates: string[] = [];\n const override = process.env[RUNTIME_ROOT_ENV];\n if (override) candidates.push(override);\n candidates.push(resolve(self, '..', 'runtime'), resolve(self, '..', '..', 'runtime'));\n return candidates;\n}\n\n/**\n * Resolve the staged runtime root, verifying it via a provider-specific marker\n * (a relative path known to exist under a valid root, e.g.\n * `e2b/scripts/build-template.sh`). Returns `undefined` when no candidate holds\n * the marker — callers then fall back to the monorepo source tree.\n */\nexport function resolveStagedRuntimeRoot(self: string, marker: string): string | undefined {\n for (const candidate of stagedRuntimeRootCandidates(self)) {\n if (existsSync(resolve(candidate, marker))) return candidate;\n }\n return undefined;\n}\n\n/**\n * Env var the CLI stamps at startup with its staged `runtime/` root. Mirrors\n * `CLI_RUNTIME_DIR_ENV` in `@madarco/agentbox-provider-sdk` — deliberately a\n * second literal rather than an import, because the SDK inlines this package\n * and depending on it here would be a cycle.\n */\nexport const CLI_RUNTIME_DIR_ENV = 'AGENTBOX_CLI_RUNTIME_DIR';\n\n/**\n * Absolute host path to a provider-NEUTRAL asset staged under\n * `runtime/_shared/`, or null when it can't be found.\n *\n * Null rather than throwing: the one caller is best-effort seeding, where a\n * missing host copy just means we fall back to whatever the box image baked.\n */\nexport function sharedRuntimeAssetPath(basename: string): string | null {\n const roots: string[] = [];\n const stamped = process.env[CLI_RUNTIME_DIR_ENV];\n if (stamped) roots.push(stamped);\n const self = dirname(fileURLToPath(import.meta.url));\n const found = resolveStagedRuntimeRoot(self, `_shared/${basename}`);\n if (found) roots.push(found);\n for (const root of roots) {\n const p = resolve(root, '_shared', basename);\n if (existsSync(p)) return p;\n }\n return null;\n}\n","/**\n * One-slot hooks the hub lifecycle (`hub-lifecycle.ts`) uses to reach the two\n * docker-side conveniences it can't depend on directly — the Portless friendly\n * URL and the docker build context. Same pattern as `credential-publish.ts`:\n * the docker package (`@agentbox/sandbox-docker`) owns the implementation and\n * the CLI installs it at startup, so a docker-free host that starts / probes the\n * hub imports neither Portless nor docker image machinery.\n *\n * Both are best-effort niceties, so an unset hook degrades cleanly: no hook →\n * the hub advertises its plain loopback URL and sets no `AGENTBOX_DOCKER_CONTEXT`.\n */\n\n/**\n * The hub's Portless (`https://agentbox.localhost`) integration. Each method is\n * best-effort and must never throw — a Portless failure leaves the hub on its\n * loopback URL.\n */\nexport interface HubPortlessHooks {\n /**\n * Register (or, with `enabled === false`, tear down) the hub's Portless alias\n * for `port` and return its resolved URL, or `undefined` when no proxy is live.\n */\n sync(enabled: boolean | undefined, port: number): Promise<string | undefined>;\n /** The hub's Portless URL right now, re-checked against a live proxy, or null. */\n current(): Promise<string | null>;\n /** Tear down the alias + its cached URL (on `hub stop`). */\n teardown(): Promise<void>;\n}\n\nlet activePortless: HubPortlessHooks | undefined;\n\n/** Install (or clear) the Portless hooks. The CLI calls this once at startup. */\nexport function setHubPortlessHooks(hooks: HubPortlessHooks | undefined): void {\n activePortless = hooks;\n}\n\n/** Sync the hub's Portless alias, or `undefined` when no hooks are installed. */\nexport async function hubPortlessSync(\n enabled: boolean | undefined,\n port: number,\n): Promise<string | undefined> {\n if (!activePortless) return undefined;\n try {\n return await activePortless.sync(enabled, port);\n } catch {\n return undefined;\n }\n}\n\n/** The hub's current Portless URL, or `null` when no hooks are installed. */\nexport async function hubPortlessCurrent(): Promise<string | null> {\n if (!activePortless) return null;\n try {\n return await activePortless.current();\n } catch {\n return null;\n }\n}\n\n/** Tear down the hub's Portless alias, if hooks are installed. */\nexport async function hubPortlessTeardown(): Promise<void> {\n if (!activePortless) return;\n try {\n await activePortless.teardown();\n } catch {\n /* best-effort */\n }\n}\n\nlet dockerContext: string | undefined;\n\n/**\n * Set the docker build-context dir the hub child should see as\n * `AGENTBOX_DOCKER_CONTEXT` (the CLI installs its resolved `BUILD_CONTEXT_DIR`).\n * Unset on a docker-free host → the key is omitted, which is correct there.\n */\nexport function setHubDockerContext(dir: string | undefined): void {\n dockerContext = dir;\n}\n\n/** The installed docker build-context dir, or `undefined`. */\nexport function hubDockerContext(): string | undefined {\n return dockerContext;\n}\n","/**\n * A one-slot hook the cloud create path uses to refresh the host-side agent\n * credential backups (`~/.agentbox/{claude,codex,opencode}-credentials.json`)\n * from the live docker shared volumes before it seeds a cloud box from them.\n *\n * Why a hook: the refresh is a docker `docker run` against the shared credential\n * volumes, so it belongs in `@agentbox/sandbox-docker`. `@agentbox/sandbox-cloud`\n * must not reach into docker (a docker-free host that only builds cloud boxes\n * would otherwise import docker machinery, and the reach-in would fail there).\n * So the CLI installs the docker refresher at startup and the cloud seed path\n * calls {@link runDockerCredentialRefresh}; with no hook installed it is a no-op\n * and the seed uses whatever backup already exists.\n *\n * Best-effort, exactly like the reach-in it replaces: every underlying docker\n * helper already swallows its own failures, and this never throws.\n */\n\n/** Refreshes the host credential backups from the docker shared volumes. */\nexport type DockerCredentialRefresher = (opts: { onLog?: (line: string) => void }) => Promise<void>;\n\nlet activeRefresher: DockerCredentialRefresher | undefined;\n\n/** Install (or clear, with `undefined`) the refresher. The CLI calls this once. */\nexport function setDockerCredentialRefresh(fn: DockerCredentialRefresher | undefined): void {\n activeRefresher = fn;\n}\n\n/**\n * Refresh the host credential backups from docker, if a refresher is installed.\n * No-op (and never throws) when none is — the cloud seed proceeds against the\n * existing backup.\n */\nexport async function runDockerCredentialRefresh(opts: {\n onLog?: (line: string) => void;\n}): Promise<void> {\n if (!activeRefresher) return;\n try {\n await activeRefresher(opts);\n } catch {\n /* best-effort — the refresher swallows its own failures */\n }\n}\n","import { mkdtemp, readFile, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, join } from 'node:path';\nimport { applyReplacements, deriveBoxHost, type ResolvedCarryEntry } from '@agentbox/core';\n\n/**\n * Box facts used to fill `{{AGENTBOX_*}}` placeholders in carried files. The\n * placeholder *names* match the in-box `agentbox-ctl render` whitelist; here the\n * values come from the create context (the box is named but not yet booted).\n */\nexport interface CarryBoxContext {\n name?: string;\n id?: string;\n kind?: string;\n /** Host workspace path (mirrors in-box AGENTBOX_HOST_WORKSPACE). */\n hostWorkspace?: string;\n projectRoot?: string;\n}\n\n/** Build the whitelist placeholder context (and derive AGENTBOX_BOX_HOST). */\nexport function carryPlaceholderContext(ctx: CarryBoxContext): Record<string, string> {\n const out: Record<string, string> = {};\n if (ctx.name) out.AGENTBOX_BOX_NAME = ctx.name;\n if (ctx.id) out.AGENTBOX_BOX_ID = ctx.id;\n if (ctx.kind) out.AGENTBOX_BOX_KIND = ctx.kind;\n if (ctx.hostWorkspace) out.AGENTBOX_HOST_WORKSPACE = ctx.hostWorkspace;\n if (ctx.projectRoot) out.AGENTBOX_PROJECT_ROOT = ctx.projectRoot;\n return deriveBoxHost(out);\n}\n\n/** Whether an entry opts into host-side rendering (file entries only). */\nfunction wantsRender(e: ResolvedCarryEntry): boolean {\n return e.kind === 'file' && (!!e.replaceEnvs || (e.replace?.length ?? 0) > 0);\n}\n\n/**\n * Render carry entries that opt into `replaceEnvs`/`replace`: read each file\n * host-side, apply the substitutions, write the result to a temp file, and\n * repoint `absSrc` at it so the existing per-provider tar/copy step transfers\n * the rendered content. Entries without replace options pass through unchanged.\n * Returns a new array (inputs are not mutated).\n */\nexport async function renderCarryEntries(\n entries: ResolvedCarryEntry[],\n ctx: CarryBoxContext,\n onLog?: (line: string) => void,\n): Promise<ResolvedCarryEntry[]> {\n if (!entries.some(wantsRender)) return entries;\n\n const context = carryPlaceholderContext(ctx);\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-carry-render-'));\n const out: ResolvedCarryEntry[] = [];\n for (const [i, entry] of entries.entries()) {\n if (!wantsRender(entry)) {\n out.push(entry);\n continue;\n }\n const content = await readFile(entry.absSrc, 'utf8');\n const rendered = applyReplacements(content, {\n env: entry.replaceEnvs,\n rules: entry.replace,\n context,\n onWarn: (msg) => onLog?.(`carry: ${entry.rawSrc}: ${msg}`),\n });\n const tmp = join(stage, `${String(i)}-${basename(entry.absSrc)}`);\n await writeFile(tmp, rendered, 'utf8');\n out.push({ ...entry, absSrc: tmp, bytes: Buffer.byteLength(rendered) });\n const what = [\n ...(entry.replaceEnvs ? ['env'] : []),\n ...(entry.replace?.length ? [`${String(entry.replace.length)} rule(s)`] : []),\n ].join('+');\n onLog?.(`carry: rendered ${entry.rawSrc} (${what})`);\n }\n return out;\n}\n","/**\n * Per-box carry: the host files an agent needs a SEPARATE copy of for every box\n * it runs in (`AgentSyncSpec.clone.perBoxCarry`).\n *\n * The problem it solves is specific. A bot's channel tokens — the Telegram bot\n * token, the Discord secret — are what make it a distinct identity to the\n * outside world. A project-wide `carry:` entry hands the same token to every box\n * created from that project, so a spawned second bot answers as the first one.\n * Keying the SOURCE path by box name (`~/.agentbox/openclaw/<box>.env`) makes a\n * per-bot secret the default rather than a convention someone has to remember.\n *\n * Resolved here rather than in `apps/cli`'s `resolveCarry` for two reasons: the\n * hub runs clones and cannot import apps/cli, and these entries are declared by\n * the agent rather than by the user, so they never face the carry prompt (the\n * gate exists to ask about the USER's files leaving their machine; this is the\n * agent asking for a path it named itself, under `~/.agentbox/`).\n */\n\nimport { stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, resolve } from 'node:path';\nimport type { AgentPerBoxCarry, AgentSyncSpec, ResolvedCarryEntry } from '@agentbox/core';\nimport { substitutePlaceholders } from '@agentbox/core';\n\nexport interface PerBoxCarryContext {\n /** The FINAL box name — the same value `{{AGENTBOX_BOX_NAME}}` renders to. */\n boxName: string;\n /** Host home, injectable for tests. */\n home?: string;\n}\n\n/** One entry whose host file is missing. */\nexport interface MissingPerBoxCarry {\n /** The host path, placeholders expanded — what the user has to create. */\n path: string;\n /** What the spec asked for, for a message that matches the yaml. */\n rawSrc: string;\n optional: boolean;\n}\n\nexport interface PerBoxCarryResolution {\n entries: ResolvedCarryEntry[];\n missing: MissingPerBoxCarry[];\n}\n\n/** Expand `~/` and `{{AGENTBOX_BOX_NAME}}` in a spec-declared host path. */\nexport function perBoxCarrySrc(src: string, ctx: PerBoxCarryContext): string {\n const home = ctx.home ?? homedir();\n const named = substitutePlaceholders(src, { AGENTBOX_BOX_NAME: ctx.boxName });\n if (named.startsWith('~/')) return resolve(home, named.slice(2));\n if (isAbsolute(named)) return resolve(named);\n // A relative source has no anchor here (the agent, not the user, wrote it and\n // there is no project dir in scope), so refuse rather than guess a cwd.\n throw new Error(`perBoxCarry src must be absolute or start with \"~/\": ${src}`);\n}\n\n/**\n * Resolve one agent's `perBoxCarry` entries against a box name.\n *\n * Never throws for a missing file — it reports them, because the two callers\n * want opposite things: a create logs an optional miss and continues, a clone\n * refuses. Deciding here would force one of them to un-decide it.\n */\nexport async function resolvePerBoxCarry(\n spec: Pick<AgentSyncSpec, 'clone'> | undefined,\n ctx: PerBoxCarryContext,\n): Promise<PerBoxCarryResolution> {\n const declared: readonly AgentPerBoxCarry[] = spec?.clone?.perBoxCarry ?? [];\n const entries: ResolvedCarryEntry[] = [];\n const missing: MissingPerBoxCarry[] = [];\n for (const item of declared) {\n const absSrc = perBoxCarrySrc(item.src, ctx);\n let bytes: number | undefined;\n try {\n const st = await stat(absSrc);\n // A directory would silently change the copy's shape (tar of a tree, not a\n // file) and no agent has asked for one; refuse rather than half-support it.\n if (!st.isFile()) {\n throw new Error(`perBoxCarry src is not a regular file: ${absSrc}`);\n }\n bytes = st.size;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n missing.push({ path: absSrc, rawSrc: item.src, optional: item.optional === true });\n continue;\n }\n entries.push({\n rawSrc: item.src,\n rawDest: item.dest,\n absSrc,\n // `~/` is expanded in the box, against the box user's own $HOME — the box\n // user's uid differs per provider, so the host must not guess the path.\n absDest: item.dest,\n kind: 'file',\n bytes,\n ...(item.mode !== undefined ? { mode: item.mode } : {}),\n optional: item.optional === true,\n });\n }\n return { entries, missing };\n}\n\n/**\n * The refusal a CLONE raises when a per-box file is absent.\n *\n * `optional` is deliberately ignored: on a first box there is nobody to collide\n * with, but a clone exists precisely because a second bot is being made, and\n * letting it boot with no channel secrets produces a bot that either does\n * nothing or — if the workspace's own config names the source's token — answers\n * as the bot it was cloned from.\n */\nexport function clonePerBoxCarryRefusal(\n missing: readonly MissingPerBoxCarry[],\n boxName: string,\n): string | null {\n if (missing.length === 0) return null;\n const paths = missing.map((m) => m.path).join(', ');\n return (\n `${boxName} needs its own secrets before it can be a separate bot — create ${paths} ` +\n `(0600) and run this again`\n );\n}\n\n/**\n * Merge an agent's declared per-box entries into the user-approved `carry:`\n * list for one create.\n *\n * Appended, so a user entry with the same destination is applied first and the\n * agent's own file wins — the agent declared the path it reads, and a user who\n * targets it deliberately is doing something the agent cannot know about.\n *\n * A missing OPTIONAL source is logged rather than skipped silently: \"your bot\n * has no channel tokens\" is the single most likely reason a fresh box does\n * nothing, and the log line names the exact path to create.\n */\nexport async function withPerBoxCarry(\n approved: readonly ResolvedCarryEntry[] | undefined,\n specs: readonly (Pick<AgentSyncSpec, 'clone'> | undefined)[],\n ctx: PerBoxCarryContext,\n onLog?: (line: string) => void,\n): Promise<ResolvedCarryEntry[]> {\n const out = [...(approved ?? [])];\n for (const spec of specs) {\n if (!spec?.clone?.perBoxCarry?.length) continue;\n const { entries, missing } = await resolvePerBoxCarry(spec, ctx);\n const required = missing.filter((m) => !m.optional);\n if (required.length > 0) {\n throw new Error(\n `carry: ${ctx.boxName} needs ${required.map((m) => m.path).join(', ')} — create the file and run this again`,\n );\n }\n for (const m of missing) {\n onLog?.(`carry: no ${m.path} — ${ctx.boxName} starts without it`);\n }\n for (const e of entries) onLog?.(`carry: ${e.absSrc} -> ${e.rawDest} (per-box)`);\n out.push(...entries);\n }\n return out;\n}\n","/**\n * Seeded model-provider credentials: a host-held login a box may consume as its\n * model auth (`AgentSyncSpec.modelAuth`).\n *\n * The host's whole job is to decide WHICH login may enter the box and to land\n * it at that login's own canonical path, 0600, before the first supervisor\n * task runs. It rides the carry step for that reason: carry is the one step\n * every provider already runs at exactly that moment, with the same ownership\n * and mode rules a `perBoxCarry` channel token gets. What happens to the file\n * afterwards is the consuming agent's `ingest`, declared on its own row.\n *\n * One-way by construction. The entry is a host->box copy; `box.agents` still\n * gates the credential watch, extraction and the resume reconcile, so a copy\n * the daemon has since refreshed in its own store never flows back.\n */\n\nimport { stat } from 'node:fs/promises';\nimport {\n modelAuthEnvKey,\n modelAuthSourceId,\n type AgentModelAuthIngest,\n type AgentSyncSpec,\n type ResolvedCarryEntry,\n} from '@agentbox/core';\nimport { findAgentSpec, resolveAgentSpec } from './sync/registry.js';\nimport { resolveHostCredentialFile } from './sync/concerns/credentials.js';\n\n/**\n * Validate a create's requested model-auth sources against the agent's row.\n *\n * Refuses, rather than ignoring, an id the agent does not declare or one that\n * names an agent with no host-side `credential`: a silently dropped entry would\n * produce a box with no model auth and no message, which is the failure this\n * feature exists to end.\n *\n * A declared `env` source whose var is unset on this host is NOT an error — it\n * is reported and skipped where it is applied, the same way a missing login file\n * is (see {@link borrowedCredentialCarry}).\n */\nexport function resolveModelAuthSources(\n spec: Pick<AgentSyncSpec, 'id' | 'modelAuth'>,\n requested: readonly string[] | undefined,\n): string[] {\n const wanted = [...new Set((requested ?? []).map((s) => s.trim()).filter(Boolean))];\n if (wanted.length === 0) return [];\n const sources = spec.modelAuth?.sources ?? [];\n const declared = new Map(sources.map((s) => [modelAuthSourceId(s), s]));\n for (const id of wanted) {\n const source = declared.get(id);\n if (!source) {\n const options = declared.size > 0 ? [...declared.keys()].join(', ') : 'nothing';\n throw new Error(`${spec.id} cannot use \"${id}\" as model auth — it declares ${options}`);\n }\n if (source.kind === 'agent' && !findAgentSpec(source.agent)?.credential) {\n throw new Error(\n `${spec.id} declares a borrow of \"${source.agent}\", which has no host-side credential`,\n );\n }\n }\n return wanted;\n}\n\n/** The agent-kind ids in a source list — the key the credential fan-out matches on. */\nexport function agentSourceIds(ids: readonly string[]): string[] {\n return ids.filter((id) => modelAuthEnvKey(id) === undefined);\n}\n\n/** The env var names in a source list. */\nexport function envSourceKeys(ids: readonly string[]): string[] {\n return ids.map((id) => modelAuthEnvKey(id)).filter((k): k is string => k !== undefined);\n}\n\n/**\n * The carry entries that seed each borrowed login into the box.\n *\n * A login the host does not hold is reported and skipped, never fatal: the\n * box still comes up, its ingest task finds nothing and says so, and the user\n * can log in on the host and create again. Failing the create would leave no\n * box behind for a condition the message already explains.\n */\nexport async function borrowedCredentialCarry(\n /** A full source-id list; env sources are ignored, they carry no file. */\n agents: readonly string[],\n onLog?: (line: string) => void,\n /** Injectable for tests: where the host's login for an agent lives. */\n resolveFile: (\n agent: string,\n ) => Promise<{ path: string; text: string } | null> = resolveHostCredentialFile,\n): Promise<ResolvedCarryEntry[]> {\n const out: ResolvedCarryEntry[] = [];\n for (const agent of agentSourceIds(agents)) {\n const spec = resolveAgentSpec(agent);\n const credential = spec.credential;\n if (!credential) continue;\n const source = await resolveFile(spec.id);\n if (!source) {\n onLog?.(`model auth: no ${spec.id} login on this host — the box starts without it`);\n continue;\n }\n const st = await stat(source.path);\n onLog?.(`model auth: ${source.path} -> ${credential.boxAbsPath} (borrowed ${spec.id} login)`);\n out.push({\n rawSrc: source.path,\n rawDest: credential.boxAbsPath,\n absSrc: source.path,\n absDest: credential.boxAbsPath,\n kind: 'file',\n bytes: st.size,\n mode: 0o600,\n optional: true,\n });\n }\n return out;\n}\n\n/** How this agent ingests a seeded login, when it needs to. */\nexport function resolveModelAuthIngest(\n spec: Pick<AgentSyncSpec, 'modelAuth'>,\n): AgentModelAuthIngest | undefined {\n return spec.modelAuth?.ingest;\n}\n","/**\n * The agent registry — now a thin view over `@agentbox/agent-registry`.\n *\n * The rows used to be a literal table here. They live in the agent packages\n * themselves (`@agentbox/agent-<id>/spec`), which the aggregator imports and\n * this module re-exports, so the ~40 call sites that reach for\n * `AGENT_SYNC_SPECS` / `resolveAgentSpec` through `@agentbox/sandbox-core` keep\n * working unchanged.\n *\n * The direction matters: `sandbox-core` depends on the aggregator, never on an\n * agent's behavior. An agent package's main entry depends on `sandbox-core` in\n * turn, and only the CLI — at the top of the graph — pulls that in. Exactly the\n * provider split, where the data is a table in a leaf and the code is a package\n * loaded from a literal-import map.\n */\n\nimport { AGENT_SPECS, visibleAgentSpecs } from '@agentbox/agent-registry';\nimport type { AgentId, AgentSettings, AgentSyncSpec } from '@agentbox/core';\n\nexport const AGENT_SYNC_SPECS: readonly AgentSyncSpec[] = AGENT_SPECS;\n\n/** Resolve a spec by canonical id or any alias (e.g. `'claude-code'` → the claude spec). */\nexport function resolveAgentSpec(name: string): AgentSyncSpec {\n const spec = AGENT_SYNC_SPECS.find((s) => s.id === name || s.aliases.includes(name));\n if (!spec) throw new Error(`no agent sync spec for '${name}'`);\n return spec;\n}\n\n/** Resolve by id or alias, or undefined — for callers that must not throw. */\nexport function findAgentSpec(name: string): AgentSyncSpec | undefined {\n return AGENT_SYNC_SPECS.find((s) => s.id === name || s.aliases.includes(name));\n}\n\n/** The canonical ids, in registry order. */\nexport function agentIds(): AgentId[] {\n return AGENT_SYNC_SPECS.map((s) => s.id);\n}\n\n/**\n * The agents a HUMAN should be offered — pickers, the install wizard, the bake\n * list. Re-exported from the aggregator (where the filter lives) so surfaces\n * that already reach for the registry through `@agentbox/sandbox-core` don't\n * have to take a second dependency to ask the one question that matters to a\n * picker: which of these is this build willing to advertise.\n */\nexport { visibleAgentSpecs };\n\n/**\n * True for any agent this build knows about, by canonical id or alias.\n *\n * The open counterpart to `isAgentKind` in `@agentbox/core`: that one answers\n * from a hardcoded list because a dependency-free leaf has no registry to ask,\n * this one answers from the registry. Same split as `isProviderKind`\n * (`@agentbox/config`) vs `isRuntimeProvider` (the CLI's provider loaders), and\n * the same reason — the registry is the authority, but not everyone can reach it.\n */\nexport function isRuntimeAgent(name: string): boolean {\n return AGENT_SYNC_SPECS.some((s) => s.id === name || s.aliases.includes(name));\n}\n\n/**\n * True when any of these agents hosts a daemon that refuses proxied requests,\n * so the box must publish its port directly.\n *\n * Answers from the registry rather than from an id, and takes the agents a box\n * was created FOR (`CreateRequest.agents` / `BoxRecord.agents`) rather than\n * `lastAgent`: `lastAgent` is whichever agent most recently RAN, is written\n * after `create` returns, and a later `agentbox claude` in the same box\n * overwrites it — none of which changes whether the box hosts a gateway.\n *\n * Unknown ids are simply not a match: the registry is open (`agentbox agent\n * add`), and a name this build has never heard of must not make a box lose its\n * friendly URL.\n */\nexport function agentsRejectProxyHeaders(agents: readonly string[] | undefined): boolean {\n return (agents ?? []).some((a) => findAgentSpec(a)?.service?.rejectsProxyHeaders === true);\n}\n\n/**\n * The env that pins `binary`'s in-box terminal renderer, for the agent's own\n * resolved settings.\n *\n * The generic counterpart of `agentLaunchFlags`: reads `AgentSyncSpec.tuiEnv`\n * through the `tuiEnvFrom` setting the agent declared, and answers `{}` for an\n * agent that declares neither. Replaces the `binary === 'claude'` branches the\n * cloud launch sites used to carry — claude is still the only agent with an\n * entry, but that is now a fact about the registry rather than about the code.\n *\n * `binary` is an open string here and an unknown one must not throw.\n */\nexport function agentTuiEnv(binary: string, settings?: AgentSettings): Record<string, string> {\n const spec = findAgentSpec(binary);\n if (!spec?.tuiEnv || !spec.tuiEnvFrom) return {};\n const declared = spec.settings?.find((s) => s.key === spec.tuiEnvFrom);\n const mode = settings?.[spec.tuiEnvFrom] ?? declared?.default;\n if (typeof mode !== 'string') return {};\n return { ...(spec.tuiEnv[mode] ?? {}) };\n}\n","/**\n * Concern: credentials — the per-agent login secrets (`~/.claude/.credentials.json`\n * for claude, `auth.json` for codex/opencode) that ride separately from static\n * config because they change per login and must never be baked into a shared\n * snapshot.\n *\n * What lives here is the provider-neutral core of the concern:\n * - the pure host-side guards (`isRealAgentCredential`,\n * `hostBackupHasCredentials`) — the \"is this blob real / expired?\" decisions,\n * driven by the registry's `credential.realShape` so the per-agent switch has\n * one home;\n * - the box→host extract (`extractCredentials`) expressed against the\n * `SyncTransport.readText` seam, so cloud's `extractCloudAgentCredentials`\n * becomes a thin transport-injecting wrapper;\n * - the seed-once marker name (`SEED_MARKER`) shared by the cloud volume seed.\n *\n * What deliberately does NOT live here (yet): the *seed* mechanisms. Docker\n * seeds claude via a throwaway root helper container that bidirectionally syncs\n * the shared config volume with the host backup (`syncClaudeCredentials`,\n * `SYNC_SCRIPT`) — it predates any running box, so it has no `SyncTransport`\n * (box-bound) analog and no polymorphic caller; codex/opencode ride the whole-\n * dir volume rsync. Cloud seeds via `seedCredentialsOne` (marker/force gate +\n * `uploadFile` + a volume-vs-ephemeral extract split). Those stay in their\n * providers; their transport-seam collapse folds into the Phase 7 driver, the\n * same call carry's apply mechanism and skills' box→host pull already made.\n */\n\nimport { chmod, mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { SyncTransport } from '@agentbox/core';\nimport { AGENT_SYNC_SPECS, resolveAgentSpec } from '../registry.js';\nimport type { AgentId } from '@agentbox/core';\n\n/** Agents whose credentials we extract from a box back to the host. Mirrors `AgentId`. */\nexport type CredentialAgentKind = AgentId;\n\n/**\n * Marker filename written inside a cloud agent's credentials subpath recording\n * when we last seeded it (a single ISO-8601 timestamp on disk). Absent marker =\n * first time on this volume → seed. Volume/idempotency-only: ephemeral cloud\n * backends can't persist it and push every create; docker uses a content check\n * (real-vs-empty) instead of a marker.\n */\nexport const SEED_MARKER = '.agentbox-seeded-at';\n\n/**\n * Host backup of the claude OAuth blob — the registry is the single source of\n * truth. Claude always declares a credential; the `?? ''` is the type's, not a\n * real case (an empty path simply fails the `readFile` below).\n */\nconst CLAUDE_HOST_BACKUP = resolveAgentSpec('claude').credential?.hostBackup ?? '';\n\n/**\n * True iff `text` looks like a real (usable) credential for `agent`, not an\n * empty/placeholder file. Used so the box→host extract never clobbers a good\n * host backup with an empty box file. The per-agent shape comes from the\n * registry (`credential.realShape`): claude requires a non-empty\n * `claudeAiOauth.refreshToken`; codex/opencode auth files just have to parse as\n * a non-empty JSON object. Unknown agents fall back to the JSON-object check\n * (never throws — matches the pre-registry `if (agent === 'claude')` switch).\n */\nexport function isRealAgentCredential(agent: CredentialAgentKind, text: string): boolean {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return false;\n }\n if (typeof parsed !== 'object' || parsed === null) return false;\n const spec = AGENT_SYNC_SPECS.find((s) => s.id === agent);\n if (spec?.credential?.realShape === 'claude-oauth') {\n const rt = (parsed as { claudeAiOauth?: { refreshToken?: unknown } }).claudeAiOauth\n ?.refreshToken;\n return typeof rt === 'string' && rt.length > 0;\n }\n return Object.keys(parsed as Record<string, unknown>).length > 0;\n}\n\n/**\n * True iff the claude host backup file holds a real OAuth blob (a non-empty\n * `claudeAiOauth.refreshToken`). Used to decide whether to offer an interactive\n * sign-in before creating a box. Tolerant of a missing or garbage file — returns\n * false.\n */\nexport async function hostBackupHasCredentials(\n path: string = CLAUDE_HOST_BACKUP,\n): Promise<boolean> {\n try {\n const parsed = JSON.parse(await readFile(path, 'utf8')) as {\n claudeAiOauth?: { refreshToken?: unknown };\n };\n const rt = parsed?.claudeAiOauth?.refreshToken;\n return typeof rt === 'string' && rt.length > 0;\n } catch {\n return false;\n }\n}\n\nexport interface ExtractCredentialsOptions {\n onLog?: (line: string) => void;\n /** Override host backup paths per agent (tests). Defaults to the registry `hostBackup`. */\n backups?: Partial<Record<AgentId, string>>;\n}\n\n/**\n * Extract each agent's login credential from a running box back to the host\n * backups under `~/.agentbox/`, so the next box (seeded from those backups)\n * inherits the login. The provider-neutral core of docker's\n * `syncClaudeCredentials` extract direction and cloud's\n * `extractCloudAgentCredentials`, expressed against `transport.readText`.\n *\n * Reads the canonical in-box path (`credential.boxAbsPath`) via\n * `transport.readText`; only writes the host backup (mode 0600) when the content\n * passes `isRealAgentCredential`, so an empty / not-logged-in box never clobbers\n * a good backup. Best-effort per agent (never throws). Returns the agents whose\n * backup was updated.\n */\nexport async function extractCredentials(\n transport: SyncTransport,\n opts: ExtractCredentialsOptions = {},\n): Promise<AgentId[]> {\n const log = opts.onLog ?? (() => {});\n const extracted: AgentId[] = [];\n for (const spec of AGENT_SYNC_SPECS) {\n // No credential declared → nothing on the box to read and nowhere on the\n // host to put it. Skipped before the `readText`, so a credential-less agent\n // costs no round-trip per box.\n if (!spec.credential) continue;\n const hostBackup = opts.backups?.[spec.id] ?? spec.credential.hostBackup;\n try {\n // `readText` is `cat <path> 2>/dev/null` with noRetry → null on a missing\n // file; tolerate that silently. `!text` also covers an empty stdout.\n const text = await transport.readText(spec.credential.boxAbsPath);\n if (!text || !isRealAgentCredential(spec.id, text)) continue;\n await mkdir(dirname(hostBackup), { recursive: true });\n await writeFile(hostBackup, text, { mode: 0o600 });\n await chmod(hostBackup, 0o600).catch(() => {});\n extracted.push(spec.id);\n log(`extracted ${spec.id} login from box to ${hostBackup}`);\n } catch (err) {\n log(\n `WARN: ${spec.id} credential extract failed (${err instanceof Error ? err.message : String(err)}) — skipping`,\n );\n }\n }\n return extracted;\n}\n\n// ---------------------------------------------------------------------------\n// credential fan-out (box → host backup → other boxes)\n// ---------------------------------------------------------------------------\n\n/** Wire payload of the ctl watcher's `credentials-updated` relay event. */\nexport interface CredentialsUpdate {\n agent: CredentialAgentKind;\n /** The decoded credential file content. */\n content: string;\n}\n\n/** Refuse absurd payloads before parsing (a credential file is ~1-5 KB). */\nconst MAX_CREDENTIAL_BYTES = 256 * 1024;\n\n/**\n * Parse + validate a `credentials-updated` event payload. Returns null for\n * anything malformed: unknown agent, oversized/undecodable content, or a blob\n * that fails the agent's `isRealAgentCredential` shape.\n */\nexport function parseCredentialsUpdate(payload: unknown): CredentialsUpdate | null {\n if (payload === null || typeof payload !== 'object') return null;\n const obj = payload as Record<string, unknown>;\n const agent = obj['agent'];\n // Unknown agent, or one that declares no credential: there is no host backup\n // to write and no fan-out to run, so an event naming it is malformed.\n // Rejecting here keeps every writer below total.\n if (typeof agent !== 'string' || !AGENT_SYNC_SPECS.some((s) => s.id === agent && s.credential))\n return null;\n const b64 = obj['contentBase64'];\n if (typeof b64 !== 'string' || b64.length === 0 || b64.length > MAX_CREDENTIAL_BYTES) return null;\n let content: string;\n try {\n content = Buffer.from(b64, 'base64').toString('utf8');\n } catch {\n return null;\n }\n if (!isRealAgentCredential(agent as CredentialAgentKind, content)) return null;\n return { agent: agent as CredentialAgentKind, content };\n}\n\n/**\n * The finite number at `path` in a JSON blob, or null.\n *\n * Generic on purpose: this used to be `claudeAiOauth.expiresAt` inlined behind a\n * role-shaped name, so the naming guard could not see it and any other agent\n * with an OAuth expiry got `null` and fell through to last-writer-wins.\n */\nexport function jsonNumberAt(text: string, path: readonly string[]): number | null {\n try {\n let cur: unknown = JSON.parse(text);\n for (const key of path) {\n if (!cur || typeof cur !== 'object') return null;\n cur = (cur as Record<string, unknown>)[key];\n }\n return typeof cur === 'number' && Number.isFinite(cur) ? cur : null;\n } catch {\n return null;\n }\n}\n\n/** The agent's declared freshness value for a blob, or null when it declares none. */\nexport function credentialFreshness(agent: CredentialAgentKind, text: string): number | null {\n const path = resolveAgentSpec(agent).credential?.freshness?.jsonPath;\n return path ? jsonNumberAt(text, path) : null;\n}\n\n/**\n * `claudeAiOauth.refreshTokenExpiresAt` (ms epoch) of a claude blob, or null.\n * The refresh token's own life (~30 days from the original sign-in) — the field\n * that says whether the login is still renewable, unlike `expiresAt`.\n */\nexport function oauthRefreshExpiresAt(text: string): number | null {\n return jsonNumberAt(text, ['claudeAiOauth', 'refreshTokenExpiresAt']);\n}\n\n/**\n * Newest-wins acceptance gate for an incoming credential vs the current host\n * backup. Claude blobs carry `expiresAt`, which strictly increases on every\n * OAuth refresh (verified live) — accept only a strictly newer one. Codex /\n * opencode auth files carry no ordering field: accept whenever the content\n * differs (last-writer-wins). Identical content is always a no-op.\n */\nexport function shouldAcceptCredentialUpdate(\n agent: CredentialAgentKind,\n incoming: string,\n existing: string | null,\n): { accept: boolean; reason: string } {\n if (existing === null) return { accept: true, reason: 'no existing backup' };\n if (existing === incoming) return { accept: false, reason: 'unchanged' };\n const path = resolveAgentSpec(agent).credential?.freshness?.jsonPath;\n if (path) {\n const field = path.join('.');\n const incomingExp = jsonNumberAt(incoming, path);\n const existingExp = jsonNumberAt(existing, path);\n if (incomingExp === null) return { accept: false, reason: `incoming blob has no ${field}` };\n if (existingExp !== null && incomingExp <= existingExp) {\n return { accept: false, reason: 'not newer than backup' };\n }\n return { accept: true, reason: `newer ${field}` };\n }\n return { accept: true, reason: 'content changed' };\n}\n\n/** Atomically write an agent's host credential backup (0600, tmp + rename). */\nexport async function writeCredentialBackup(\n agent: CredentialAgentKind,\n content: string,\n opts: { backupPath?: string } = {},\n): Promise<void> {\n const path = opts.backupPath ?? resolveAgentSpec(agent).credential?.hostBackup;\n // An agent with no credential has no backup file. Reaching here means a caller\n // skipped a gate (`parseCredentialsUpdate` and `extractCredentials` both drop\n // these agents), so say so rather than writing to `undefined`.\n if (path === undefined) {\n throw new Error(`agent '${agent}' declares no credential — there is no host backup to write`);\n }\n await mkdir(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${String(process.pid)}`;\n await writeFile(tmp, content, { mode: 0o600 });\n await rename(tmp, path);\n await chmod(path, 0o600).catch(() => {});\n}\n\n/** Read an agent's host credential backup, or null when absent. */\nexport async function readCredentialBackup(\n agent: CredentialAgentKind,\n opts: { backupPath?: string } = {},\n): Promise<string | null> {\n const path = opts.backupPath ?? resolveAgentSpec(agent).credential?.hostBackup;\n // No credential declared ⇒ no backup, which reads the same as \"absent\".\n if (path === undefined) return null;\n try {\n return await readFile(path, 'utf8');\n } catch {\n return null;\n }\n}\n\n/**\n * Push a credential blob into a live box at the agent's canonical path over a\n * `SyncTransport`, normalizing owner to the box user and mode to 0600. The\n * chown/chmod runs as the transport's default exec user first and falls back\n * to sudo (upload primitives on some backends write as root; the box user has\n * passwordless sudo). Never hardcode uid 1000 — the vscode uid varies per\n * provider.\n */\n/**\n * The host's current credential for `agent`, or null when there isn't a usable\n * one. Prefers the `~/.agentbox/<agent>-credentials.json` backup (the\n * newest-wins copy the relay's fan-out maintains) over the tool's real path,\n * which may hold an older token.\n *\n * Shape-validated, so a placeholder or a half-written file is treated as\n * absent rather than pushed into a box where it would fail confusingly.\n */\nexport async function resolveHostCredential(agent: CredentialAgentKind): Promise<string | null> {\n const spec = resolveAgentSpec(agent);\n // The agent declares no host-side credential, so there is no backup AND no\n // tool path to fall back to.\n if (!spec.credential) return null;\n const backup = await readCredentialBackup(agent);\n if (backup !== null && isRealAgentCredential(agent, backup)) return backup;\n\n const source = spec.staticPaths[0];\n if (!source) return null;\n const real = join(homedir(), ...source.hostHomeRel, spec.credential.boxRelPath);\n try {\n const text = await readFile(real, 'utf8');\n return isRealAgentCredential(agent, text) ? text : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The host FILE an agent's credential should be read from, with its text.\n *\n * `resolveHostCredential` prefers the backup unconditionally, which is right\n * for the fan-out (a rotating agent keeps the backup newest) but wrong for a\n * seed of a codex-shaped login: the host's own `codex` refreshes its real file\n * and nothing copies that into the backup, so the backup can be days older.\n * Candidates that pass the shape gate are ordered by the agent's `freshness`\n * rule when it declares one, and by mtime otherwise — the closest generic proxy\n * for \"most recently refreshed\".\n */\nexport async function resolveHostCredentialFile(\n agent: CredentialAgentKind,\n /** Injectable for tests: the files to consider, in place of backup + real path. */\n opts: { candidates?: readonly string[] } = {},\n): Promise<{ path: string; text: string } | null> {\n const spec = resolveAgentSpec(agent);\n if (!spec.credential) return null;\n const source = spec.staticPaths[0];\n const candidates = opts.candidates ?? [\n spec.credential.hostBackup,\n ...(source ? [join(homedir(), ...source.hostHomeRel, spec.credential.boxRelPath)] : []),\n ];\n const valid: { path: string; text: string; mtimeMs: number }[] = [];\n for (const path of candidates) {\n try {\n const text = await readFile(path, 'utf8');\n if (!isRealAgentCredential(agent, text)) continue;\n valid.push({ path, text, mtimeMs: (await stat(path)).mtimeMs });\n } catch {\n // absent or unreadable: not a candidate\n }\n }\n if (valid.length === 0) return null;\n const freshness = spec.credential.freshness?.jsonPath;\n valid.sort((a, b) => {\n if (freshness) {\n const fa = jsonNumberAt(a.text, freshness) ?? -Infinity;\n const fb = jsonNumberAt(b.text, freshness) ?? -Infinity;\n if (fa !== fb) return fb - fa;\n }\n return b.mtimeMs - a.mtimeMs;\n });\n const best = valid[0]!;\n return { path: best.path, text: best.text };\n}\n\nexport async function pushCredentialToBox(\n transport: SyncTransport,\n agent: CredentialAgentKind,\n content: string,\n): Promise<void> {\n const abs = resolveAgentSpec(agent).credential?.boxAbsPath;\n // Same reasoning as `writeCredentialBackup`: no declared credential means no\n // canonical in-box path, so there is nowhere to push. A caller that got here\n // skipped its gate.\n if (abs === undefined) {\n throw new Error(\n `agent '${agent}' declares no credential — there is nothing to push into a box`,\n );\n }\n const dir = abs.slice(0, abs.lastIndexOf('/'));\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-cred-push-'));\n try {\n const tmp = join(stage, 'credential');\n await writeFile(tmp, content, { mode: 0o600 });\n const mk = await transport.exec(['sh', '-c', `mkdir -p '${dir}'`]);\n if (mk.exitCode !== 0) {\n throw new Error(`mkdir ${dir} in box failed: ${mk.stderr.trim()}`);\n }\n await transport.pushFile(tmp, abs);\n const normalize = `chown \"$(id -un):\" '${abs}' && chmod 600 '${abs}'`;\n const norm = await transport.exec([\n 'sh',\n '-c',\n `{ ${normalize}; } 2>/dev/null || sudo sh -c \"${normalize.replaceAll('\"', '\\\\\"')}\"`,\n ]);\n if (norm.exitCode !== 0) {\n throw new Error(`chown/chmod of ${abs} in box failed: ${norm.stderr.trim()}`);\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n}\n","/**\n * Run an agent's model-auth ingest inside a box.\n *\n * The host has already landed the borrowed login at the LENDER's own canonical\n * path; this turns it into the consuming agent's own auth state. AgentBox never\n * learns that format — the row owns the script — so all this does is pick the\n * right way to run it:\n *\n * - `serviceTask` goes through ctl, which owns the agent's DAG.\n * - `command` is run directly, because a TUI agent has no supervisor unit to\n * hang a task on: ctl's wire cannot express a task without a service, and\n * that narrowing lives in a BAKED binary, so a new branch there would be\n * silently skipped by every box built from an existing image or snapshot.\n *\n * Best-effort by contract. A box whose ingest fails must still come up — the\n * agent then has no model auth and says so, which is a better outcome than a\n * box that does not exist. The row's script is itself gated on a hash of the\n * seed, so running this on every launch is a no-op after the first.\n */\n\nimport type { AgentSyncSpec } from '@agentbox/core';\nimport { resolveModelAuthIngest } from './borrowed-credentials.js';\n\nexport interface IngestExecResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface ModelAuthIngestResult {\n /** False when the row declares no ingest — an `env`-only agent, say. */\n ran: boolean;\n exitCode?: number;\n /** The task or command name, for logging. */\n name?: string;\n}\n\nexport interface ModelAuthIngestOptions {\n /** Re-import even if the row's own gate would skip. Used by the fan-out. */\n force?: boolean;\n onLog?: (line: string) => void;\n}\n\n/** The argv that runs this agent's ingest in the box. */\nexport function modelAuthIngestArgv(\n spec: Pick<AgentSyncSpec, 'modelAuth'>,\n force = false,\n): string[] | undefined {\n const ingest = resolveModelAuthIngest(spec);\n if (!ingest) return undefined;\n return ingest.kind === 'serviceTask'\n ? ['agentbox-ctl', 'run-task', ingest.task, ...(force ? ['--force'] : [])]\n : ['bash', '-lc', ingest.command];\n}\n\nexport async function runModelAuthIngest(\n spec: Pick<AgentSyncSpec, 'id' | 'modelAuth'>,\n exec: (argv: string[]) => Promise<IngestExecResult>,\n opts: ModelAuthIngestOptions = {},\n): Promise<ModelAuthIngestResult> {\n const ingest = resolveModelAuthIngest(spec);\n const argv = modelAuthIngestArgv(spec, opts.force);\n if (!ingest || !argv) return { ran: false };\n const name = ingest.kind === 'serviceTask' ? ingest.task : ingest.name;\n try {\n const res = await exec(argv);\n // Not prefixed with `name`: an ingest script tags its own output (both\n // openclaw's and the Codex import do), so adding one here read as\n // \"pi-model-auth: pi-model-auth: imported ...\".\n const out = `${res.stdout}${res.stderr}`.trim();\n if (out.length > 0) for (const line of out.split('\\n')) opts.onLog?.(line);\n return { ran: true, exitCode: res.exitCode, name };\n } catch (err) {\n // Never fatal: see the contract above.\n opts.onLog?.(`${name}: ${err instanceof Error ? err.message : String(err)}`);\n return { ran: true, name };\n }\n}\n","/**\n * `RecordingSyncTransport` — the parity net for the sync refactor. Every concern\n * module is a pure function of `(ctx, transport, …)`, so a concern's entire\n * observable effect IS its ordered sequence of transport calls. This fake\n * `SyncTransport` records that sequence deterministically — no host FS, no git,\n * no relay, no docker, no randomness — so a concern can be golden-snapshotted\n * and a refactor that changes what we emit fails the snapshot.\n *\n * Mirrors the `MockCloudBackend` (`@agentbox/sandbox-cloud`) pattern: a\n * reference double shipped in `src/` and driven by tests.\n */\n\nimport type {\n PushOptions,\n SyncExecOptions,\n SyncExecResult,\n SyncTransport,\n TransportCaps,\n VolumeHostSource,\n} from '@agentbox/core';\n\n/** One recorded transport call, in invocation order. */\nexport interface RecordedOp {\n op:\n | 'exec'\n | 'applyTarball'\n | 'pushTree'\n | 'pushFile'\n | 'pullTree'\n | 'pullFile'\n | 'readText'\n | 'ensureVolume'\n | 'seedVolumeFromHost';\n /** Normalized, snapshot-stable arguments for this call. */\n args: Record<string, unknown>;\n}\n\nexport interface RecordingTransportOptions {\n /** Override capability flags (default: docker-like). */\n caps?: Partial<TransportCaps>;\n /**\n * Whether the volume primitives are present. Default true (docker-like). Set\n * false to model an ephemeral cloud backend (no `ensureVolume` /\n * `seedVolumeFromHost`), so a concern that feature-detects them takes the\n * push-every-create branch.\n */\n withVolumes?: boolean;\n /** Canned `exec` result. Default `{ exitCode: 0, stdout: '', stderr: '' }`. */\n execResult?: (cmd: string[], opts?: SyncExecOptions) => SyncExecResult;\n /** Canned `readText` responses keyed by box path. Default: null (absent). */\n readText?: (boxPath: string) => string | null;\n}\n\nexport interface RecordingSyncTransport extends SyncTransport {\n /** Recorded calls in invocation order. */\n readonly ops: ReadonlyArray<RecordedOp>;\n /** Drop the recorded ops (between assertions in one test). */\n clear(): void;\n}\n\nconst DEFAULT_CAPS: TransportCaps = {\n persistentVolumes: true,\n helperContainer: true,\n ephemeralFs: false,\n};\n\nexport function makeRecordingTransport(\n opts: RecordingTransportOptions = {},\n): RecordingSyncTransport {\n const ops: RecordedOp[] = [];\n const caps: TransportCaps = { ...DEFAULT_CAPS, ...opts.caps };\n const withVolumes = opts.withVolumes ?? true;\n const push = (op: RecordedOp['op'], args: Record<string, unknown>) => ops.push({ op, args });\n\n const base: SyncTransport = {\n caps,\n async exec(cmd: string[], execOpts?: SyncExecOptions): Promise<SyncExecResult> {\n push('exec', { cmd, opts: execOpts });\n return opts.execResult?.(cmd, execOpts) ?? { exitCode: 0, stdout: '', stderr: '' };\n },\n async applyTarball(hostTarPath: string, boxDestDir: string, o?: PushOptions): Promise<void> {\n push('applyTarball', { hostTarPath, boxDestDir, opts: o });\n },\n async pushTree(hostSrcDir: string, boxDestDir: string, o?: PushOptions): Promise<void> {\n push('pushTree', { hostSrcDir, boxDestDir, opts: o });\n },\n async pushFile(hostSrcPath: string, boxDestPath: string, o?: PushOptions): Promise<void> {\n push('pushFile', { hostSrcPath, boxDestPath, opts: o });\n },\n async pullTree(\n boxSrcDir: string,\n hostDestDir: string,\n o?: { exclude?: string[] },\n ): Promise<void> {\n push('pullTree', { boxSrcDir, hostDestDir, opts: o });\n },\n async pullFile(boxSrcPath: string, hostDestPath: string): Promise<void> {\n push('pullFile', { boxSrcPath, hostDestPath });\n },\n async readText(boxPath: string): Promise<string | null> {\n push('readText', { boxPath });\n return opts.readText?.(boxPath) ?? null;\n },\n };\n\n if (withVolumes) {\n base.ensureVolume = async (name: string): Promise<{ volumeId: string }> => {\n push('ensureVolume', { name });\n return { volumeId: `vol-${name}` };\n };\n base.seedVolumeFromHost = async (\n volume: string,\n sources: VolumeHostSource[],\n ): Promise<void> => {\n push('seedVolumeFromHost', { volume, sources });\n };\n }\n\n return {\n ...base,\n get ops() {\n return ops;\n },\n clear(): void {\n ops.length = 0;\n },\n };\n}\n","/**\n * Pure helpers for `agentbox download claude` (box -> host pull of Claude\n * extensions): the delta + JSON-merge logic, unit-testable without spawning\n * containers. Consumed by `agent-pull.ts` (the shared pull core) and, through\n * it, by both the docker volume pull and the cloud transport pull.\n *\n * The forward sync (`ensureClaudeVolume` in sandbox-docker) is host-authoritative\n * and rewrites `$HOST_HOME/.claude/plugins/` -> `/home/vscode/.claude/plugins/`\n * in the plugin registry JSONs. This module is the reverse: additive (host\n * wins, only missing items are added) and rewrites the container path back to\n * the host path.\n */\n\n/** Categories under ~/.claude we pull box-side additions for. */\nexport const PULL_CATEGORIES = ['skills', 'plugins', 'agents', 'commands'] as const;\nexport type PullCategory = (typeof PULL_CATEGORIES)[number];\n\n/**\n * Skills whose directory name starts with one of these prefixes are agentbox's\n * own (currently just `agentbox-setup`, seeded box-only into the claude-config\n * volume from claude's `seeds` declaration — never on the host).\n * Pulling them back would re-introduce them onto the host, which is exactly\n * what the box-only design avoids, so we never treat them as user-authored\n * additions.\n */\nexport const SKILL_EXCLUDE_PREFIXES = ['agentbox-'] as const;\n\n/** Container path prefix the forward sync rewrites host plugin paths to. */\nexport const CONTAINER_PLUGINS_PREFIX = '/home/vscode/.claude/plugins/';\n\n/**\n * Set-difference of `boxNames` against `hostNames`, dropping any name that\n * starts with one of `excludePrefixes`. Result is sorted for stable output.\n * Used for skills/agents/commands (top-level dir names) and plugin cache\n * (`<marketplace>/<plugin>` keys).\n */\nexport function pickNewItems(\n boxNames: string[],\n hostNames: string[],\n excludePrefixes: readonly string[] = [],\n): string[] {\n const host = new Set(hostNames);\n const seen = new Set<string>();\n const out: string[] = [];\n for (const name of boxNames) {\n if (name.length === 0 || host.has(name) || seen.has(name)) continue;\n if (excludePrefixes.some((p) => name.startsWith(p))) continue;\n seen.add(name);\n out.push(name);\n }\n return out.sort();\n}\n\n/**\n * Rewrite the forward sync's container plugin prefix back to the host's, in\n * every string anywhere in `value`. Generic over the JSON shape so it covers\n * both `installLocation` (known_marketplaces.json) and `installPath`\n * (installed_plugins.json) plus any future path-bearing field.\n */\nfunction rewritePluginPaths<T>(value: T, hostPluginsPrefix: string): T {\n if (typeof value === 'string') {\n return value.split(CONTAINER_PLUGINS_PREFIX).join(hostPluginsPrefix) as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map((v) => rewritePluginPaths(v, hostPluginsPrefix)) as unknown as T;\n }\n if (value !== null && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n out[k] = rewritePluginPaths(v, hostPluginsPrefix);\n }\n return out as T;\n }\n return value;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v);\n}\n\nexport interface MergeResult {\n /** Merged JSON to write back to the host (the host object plus added keys). */\n data: unknown;\n /** True when at least one key was added (caller should write on true only). */\n changed: boolean;\n /** Keys added to the host map, for the preview/summary. */\n addedKeys: string[];\n}\n\n/**\n * Additive object-key merge. For every key in `boxMap` absent from `hostMap`,\n * copy the box's value in (with plugin paths rewritten to the host prefix).\n * Existing host keys are never touched. Tolerant of missing / non-object\n * inputs: returns the host value unchanged with `changed: false` (matches\n * `maybeFilterTo`'s defensiveness in claude.ts).\n *\n * `selectMap` projects the registry object to the map being merged\n * (identity for known_marketplaces.json, `.plugins` for installed_plugins.json)\n * and `withMap` writes the merged map back into a clone of the host registry.\n */\nfunction additiveMerge(\n hostRoot: unknown,\n boxRoot: unknown,\n hostPluginsPrefix: string,\n selectMap: (root: unknown) => unknown,\n withMap: (hostRoot: unknown, mergedMap: Record<string, unknown>) => unknown,\n): MergeResult {\n const hostMap = selectMap(hostRoot);\n const boxMap = selectMap(boxRoot);\n if (!isPlainObject(boxMap)) {\n return { data: hostRoot, changed: false, addedKeys: [] };\n }\n const base: Record<string, unknown> = isPlainObject(hostMap) ? { ...hostMap } : {};\n const addedKeys: string[] = [];\n for (const [key, value] of Object.entries(boxMap)) {\n if (Object.prototype.hasOwnProperty.call(base, key)) continue;\n base[key] = rewritePluginPaths(value, hostPluginsPrefix);\n addedKeys.push(key);\n }\n if (addedKeys.length === 0) {\n return { data: hostRoot, changed: false, addedKeys: [] };\n }\n return { data: withMap(hostRoot, base), changed: true, addedKeys: addedKeys.sort() };\n}\n\n/**\n * known_marketplaces.json is a flat object keyed by marketplace name\n * (`{ \"<name>\": { source, installLocation, lastUpdated } }`). Add box-only\n * marketplaces; rewrite their `installLocation` back to the host path.\n */\nexport function mergeKnownMarketplaces(\n hostJson: unknown,\n boxJson: unknown,\n opts: { hostHome: string },\n): MergeResult {\n const prefix = `${opts.hostHome}/.claude/plugins/`;\n return additiveMerge(\n isPlainObject(hostJson) ? hostJson : {},\n boxJson,\n prefix,\n (root) => root,\n (_host, merged) => merged,\n );\n}\n\n/**\n * installed_plugins.json is `{ version, plugins: { \"<name>@<mkt>\": [...] } }`.\n * Add box-only entries under `.plugins`; rewrite each entry's `installPath`\n * back to the host path. The top-level `version` and any other host keys are\n * preserved as-is.\n */\nexport function mergeInstalledPlugins(\n hostJson: unknown,\n boxJson: unknown,\n opts: { hostHome: string },\n): MergeResult {\n const prefix = `${opts.hostHome}/.claude/plugins/`;\n const hostRoot = isPlainObject(hostJson) ? hostJson : { plugins: {} };\n return additiveMerge(\n hostRoot,\n boxJson,\n prefix,\n (root) => (isPlainObject(root) ? (root as Record<string, unknown>)['plugins'] : undefined),\n (host, merged) => ({ ...(host as Record<string, unknown>), plugins: merged }),\n );\n}\n\n/**\n * Collect the set of `<marketplace>/<plugin>/<version>` cache keys that\n * `installed_plugins.json` actively references — every entry's `installPath`\n * reduced to its last three path segments. The plugin cache is a fixed\n * three-level tree (`cache/<m>/<p>/<v>/`), so the last three segments uniquely\n * identify the version dir regardless of whether the path is host-rooted\n * (`/Users/...`) or container-rooted (`/home/vscode/...`).\n *\n * Used to tell stale plugin-version dirs (an old version Claude left behind\n * after an update) apart from live ones, so a rebuild pass can prune the stale\n * ones' `node_modules` and never reinstall them. Returns an empty set for\n * missing / non-object input or entries without a usable `installPath` — the\n * caller treats \"empty\" as \"can't determine, do nothing\".\n */\nexport function referencedPluginVersionKeys(installedPluginsJson: unknown): Set<string> {\n const keys = new Set<string>();\n if (!isPlainObject(installedPluginsJson)) return keys;\n const plugins = installedPluginsJson['plugins'];\n if (!isPlainObject(plugins)) return keys;\n for (const entries of Object.values(plugins)) {\n if (!Array.isArray(entries)) continue;\n for (const entry of entries) {\n if (!isPlainObject(entry)) continue;\n const installPath = entry['installPath'];\n if (typeof installPath !== 'string') continue;\n const segments = installPath.split('/').filter((s) => s.length > 0);\n if (segments.length < 3) continue;\n keys.add(segments.slice(-3).join('/'));\n }\n }\n return keys;\n}\n","/**\n * Provider-neutral box→host pull of agent extensions/config — the shared core\n * behind `agentbox download claude|codex|opencode`. Additive only: an item\n * already present on the host is never overwritten.\n *\n * Two execution paths share this module:\n * - docker (`@agentbox/sandbox-docker`): reads the agent-config *volume* via\n * throwaway helper containers (works while the box is stopped) — it runs the\n * inventory scripts built here with the volume mounted at `/src` and keeps\n * its own container-based copy step;\n * - cloud (any provider with a `SyncTransport`): reads the live box FS via\n * `pullClaudeExtrasViaTransport` / `pullCodexConfigViaTransport` /\n * `pullOpencodeConfigViaTransport`. The box-side relative layout matches the\n * docker volume layout by construction (opencode's config dir is relocated\n * to `<data>/config` in boxes exactly like in the volume).\n */\n\nimport { chmod, mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { AgentSyncSpec, SyncTransport } from '@agentbox/core';\nimport { resolveAgentSpec } from './registry.js';\nimport type { AgentId } from '@agentbox/core';\nimport {\n mergeInstalledPlugins,\n mergeKnownMarketplaces,\n pickNewItems,\n SKILL_EXCLUDE_PREFIXES,\n type MergeResult,\n} from './claude-pull.js';\n\n/**\n * Box-side agent config root, DERIVED from the registry rather than restated.\n *\n * `staticPaths[0].boxDir` is the same value the host->box push already syncs to,\n * so the two directions can no longer disagree. It used to be three literals\n * here plus three more in `registry.ts` — the box->host direction restating what\n * the push direction already knew, with nothing to catch a divergence.\n *\n * Note `staticPaths[0]` specifically: opencode has three roots and the DATA one\n * is first (`~/.local/share/opencode`); its config root is that same `boxDir`\n * plus the entry's `relocToSubpath`, which `pullOpencodeConfigViaTransport`\n * applies itself.\n */\n/** A pull spec's flat item names for one group, from the registry. */\nexport function pullItems(agent: AgentId, group: string): readonly string[] {\n const g = resolveAgentSpec(agent).pull?.items?.find((i) => i.group === group);\n return g?.names ?? [];\n}\n\n/** A pull spec's category dirs, from the registry. */\nexport function pullCategories(agent: AgentId): readonly string[] {\n return resolveAgentSpec(agent).pull?.categories ?? [];\n}\n\nexport function agentBoxDir(agent: AgentId): string {\n const dir = resolveAgentSpec(agent).staticPaths[0]?.boxDir;\n if (!dir) throw new Error(`agent ${agent} declares no staticPaths[0].boxDir`);\n return dir;\n}\n\n/** Box-side agent config roots (identical to the docker volume layout). */\nexport const CLAUDE_BOX_CONFIG_DIR = agentBoxDir('claude');\nexport const CODEX_BOX_CONFIG_DIR = agentBoxDir('codex');\nexport const OPENCODE_BOX_DATA_DIR = agentBoxDir('opencode');\n\n// ---------------------------------------------------------------------------\n// claude\n// ---------------------------------------------------------------------------\n\n/** Claude's category dirs, from the registry. */\nexport const CLAUDE_PULL_DIR_CATEGORIES = pullCategories('claude');\n\nexport interface PullClaudeResult {\n /**\n * Box-installed extensions not present on the host. `category` is one of\n * skills/agents/commands (then `name` is the dir name) or `plugins` (then\n * `name` is the `<marketplace>/<plugin>` cache key).\n */\n newItems: Array<{ category: string; name: string }>;\n /** Registry JSONs that gained box-only entries (e.g. `known_marketplaces.json`). */\n mergedRegistries: string[];\n /**\n * The source's raw plugin registries (container-prefixed paths), keyed\n * `installed_plugins` / `known_marketplaces`. Carried so a subsequent\n * propagate step can additively merge them into *other* boxes (same\n * container prefix on both sides — no path rewrite).\n */\n sourceRegistries?: Record<string, unknown>;\n}\n\n/**\n * Shell script that inventories a claude config tree rooted at `src`:\n * `DIR <cat> <name>` per skills/agents/commands child dir, `PLUGIN <m>/<p>`\n * per plugin-cache entry, and `JSON <which> <base64>` for each plugin\n * registry. `base64 -w0` keeps each registry JSON on one parseable line.\n */\nexport function claudeInventoryScript(src: string): string {\n return [\n 'for cat in skills agents commands; do',\n ` [ -d \"${src}/$cat\" ] || continue;`,\n ` for d in \"${src}/$cat\"/*/; do`,\n ' [ -d \"$d\" ] || continue;',\n ' printf \"DIR %s %s\\\\n\" \"$cat\" \"$(basename \"$d\")\";',\n ' done;',\n 'done;',\n `if [ -d ${src}/plugins/cache ]; then`,\n ` for m in ${src}/plugins/cache/*/; do`,\n ' [ -d \"$m\" ] || continue;',\n ' for p in \"$m\"*/; do',\n ' [ -d \"$p\" ] || continue;',\n ' printf \"PLUGIN %s/%s\\\\n\" \"$(basename \"$m\")\" \"$(basename \"$p\")\";',\n ' done;',\n ' done;',\n 'fi;',\n 'for f in installed_plugins known_marketplaces; do',\n ` [ -f \"${src}/plugins/$f.json\" ] || continue;`,\n ' printf \"JSON %s \" \"$f\";',\n ` base64 -w0 \"${src}/plugins/$f.json\";`,\n ' printf \"\\\\n\";',\n 'done',\n ].join(' ');\n}\n\nexport interface ClaudeInventory {\n dirs: Record<string, string[]>;\n plugins: string[];\n registries: Record<string, unknown>;\n}\n\nexport function parseClaudeInventory(stdout: string): ClaudeInventory {\n const dirs: Record<string, string[]> = { skills: [], agents: [], commands: [] };\n const plugins: string[] = [];\n const registries: Record<string, unknown> = {};\n for (const line of stdout.split('\\n')) {\n if (line.startsWith('DIR ')) {\n const rest = line.slice(4);\n const sp = rest.indexOf(' ');\n if (sp === -1) continue;\n const cat = rest.slice(0, sp);\n const name = rest.slice(sp + 1);\n if (cat in dirs) dirs[cat]!.push(name);\n } else if (line.startsWith('PLUGIN ')) {\n plugins.push(line.slice(7));\n } else if (line.startsWith('JSON ')) {\n const rest = line.slice(5);\n const sp = rest.indexOf(' ');\n if (sp === -1) continue;\n const which = rest.slice(0, sp);\n try {\n registries[which] = JSON.parse(Buffer.from(rest.slice(sp + 1), 'base64').toString('utf8'));\n } catch {\n // Leave undefined; the merge helpers tolerate it.\n }\n }\n }\n return { dirs, plugins, registries };\n}\n\nexport interface ClaudePullPlan {\n newItems: PullClaudeResult['newItems'];\n /** Config-root-relative paths to copy (`skills/<n>`, `plugins/cache/<m>/<p>`). */\n copyRels: string[];\n mergedInstalled: MergeResult;\n mergedMarkets: MergeResult;\n mergedRegistries: string[];\n}\n\n/**\n * Immediate child item names of `dir`, or [] if it doesn't exist. Symlinks\n * count: the host's `~/.claude/skills/<name>` is a symlink into `~/.agents`\n * (Claude Code's user-skills convention), so `isDirectory()` alone would miss\n * them and every host skill would look \"new\".\n */\nasync function listChildDirs(dir: string): Promise<string[]> {\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n return entries.filter((e) => e.isDirectory() || e.isSymbolicLink()).map((e) => e.name);\n } catch {\n return [];\n }\n}\n\nasync function readJsonFile(path: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(path, 'utf8'));\n } catch {\n return undefined;\n }\n}\n\n/**\n * Compute the additive delta of a box claude inventory against the host's\n * `~/.claude` (`hostHome` overridable for tests): which items are new, which\n * config-root-relative paths to copy, and the merged plugin registries.\n */\nexport async function computeClaudePullPlan(\n inv: ClaudeInventory,\n opts: { hostHome?: string } = {},\n): Promise<ClaudePullPlan> {\n const hostHome = opts.hostHome ?? homedir();\n const hostClaude = join(hostHome, '.claude');\n\n const newItems: PullClaudeResult['newItems'] = [];\n const copyRels: string[] = [];\n for (const cat of CLAUDE_PULL_DIR_CATEGORIES) {\n const hostNames = await listChildDirs(join(hostClaude, cat));\n const excludes = cat === 'skills' ? SKILL_EXCLUDE_PREFIXES : [];\n for (const name of pickNewItems(inv.dirs[cat] ?? [], hostNames, excludes)) {\n newItems.push({ category: cat, name });\n copyRels.push(`${cat}/${name}`);\n }\n }\n const hostPluginKeys: string[] = [];\n for (const m of await listChildDirs(join(hostClaude, 'plugins', 'cache'))) {\n for (const p of await listChildDirs(join(hostClaude, 'plugins', 'cache', m))) {\n hostPluginKeys.push(`${m}/${p}`);\n }\n }\n for (const key of pickNewItems(inv.plugins, hostPluginKeys)) {\n newItems.push({ category: 'plugins', name: key });\n copyRels.push(`plugins/cache/${key}`);\n }\n\n const hostInstalled = await readJsonFile(join(hostClaude, 'plugins', 'installed_plugins.json'));\n const hostMarkets = await readJsonFile(join(hostClaude, 'plugins', 'known_marketplaces.json'));\n const mergedInstalled = mergeInstalledPlugins(\n hostInstalled,\n inv.registries['installed_plugins'],\n {\n hostHome,\n },\n );\n const mergedMarkets = mergeKnownMarketplaces(hostMarkets, inv.registries['known_marketplaces'], {\n hostHome,\n });\n const mergedRegistries: string[] = [];\n if (mergedInstalled.changed) mergedRegistries.push('installed_plugins.json');\n if (mergedMarkets.changed) mergedRegistries.push('known_marketplaces.json');\n\n return { newItems, copyRels, mergedInstalled, mergedMarkets, mergedRegistries };\n}\n\n/**\n * Write the merged plugin registries host-side — only the ones the merge\n * actually changed (host paths are directly writable; no container needed).\n */\nexport async function writeClaudeMergedRegistries(\n plan: ClaudePullPlan,\n opts: { hostHome?: string } = {},\n): Promise<void> {\n if (!plan.mergedInstalled.changed && !plan.mergedMarkets.changed) return;\n const hostClaude = join(opts.hostHome ?? homedir(), '.claude');\n await mkdir(join(hostClaude, 'plugins'), { recursive: true });\n if (plan.mergedMarkets.changed) {\n await writeFile(\n join(hostClaude, 'plugins', 'known_marketplaces.json'),\n `${JSON.stringify(plan.mergedMarkets.data, null, 2)}\\n`,\n );\n }\n if (plan.mergedInstalled.changed) {\n await writeFile(\n join(hostClaude, 'plugins', 'installed_plugins.json'),\n `${JSON.stringify(plan.mergedInstalled.data, null, 2)}\\n`,\n );\n }\n}\n\n/**\n * Pull box-installed Claude extensions from a *live* box over a\n * `SyncTransport` (the cloud counterpart of sandbox-docker's volume-based\n * `pullClaudeExtras`). Additive: only items missing on the host are copied.\n */\nexport async function pullClaudeExtrasViaTransport(\n t: SyncTransport,\n opts: { boxDir?: string; hostHome?: string; dryRun?: boolean } = {},\n): Promise<PullClaudeResult> {\n const boxDir = opts.boxDir ?? CLAUDE_BOX_CONFIG_DIR;\n const inv = await t.exec(['sh', '-c', claudeInventoryScript(boxDir)]);\n if (inv.exitCode !== 0) {\n throw new Error(\n `failed to inventory ${boxDir} in the box: ${inv.stderr.trim() || `exit ${String(inv.exitCode)}`}`,\n );\n }\n const inventory = parseClaudeInventory(inv.stdout);\n const plan = await computeClaudePullPlan(inventory, { hostHome: opts.hostHome });\n const result: PullClaudeResult = {\n newItems: plan.newItems,\n mergedRegistries: plan.mergedRegistries,\n sourceRegistries: inventory.registries,\n };\n if (opts.dryRun || (plan.newItems.length === 0 && plan.mergedRegistries.length === 0)) {\n return result;\n }\n\n const hostClaude = join(opts.hostHome ?? homedir(), '.claude');\n for (const rel of plan.copyRels) {\n const hostDest = join(hostClaude, rel);\n await mkdir(hostDest, { recursive: true });\n // node_modules excluded for the same reason as the docker pull: the box\n // carries linux binaries useless on the host (claude rebuilds lazily).\n await t.pullTree(`${boxDir}/${rel}`, hostDest, { exclude: ['node_modules'] });\n }\n await writeClaudeMergedRegistries(plan, { hostHome: opts.hostHome });\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// codex / opencode — flat item lists, shared with the docker volume pulls\n// ---------------------------------------------------------------------------\n\n/** Top-level codex-config items `download codex` considers. */\nexport const CODEX_PULL_ITEMS = pullItems('codex', 'data');\n\n/** Data-dir items (data root → host ~/.local/share/opencode). */\nexport const OPENCODE_PULL_DATA_ITEMS = pullItems('opencode', 'data');\n/**\n * Config-dir items (`config/` under the data root → host ~/.config/opencode).\n * Covers both the `.json` and `.jsonc` global config and OpenCode's\n * user-extension subdirs.\n */\nexport const OPENCODE_PULL_CONFIG_ITEMS = pullItems('opencode', 'config');\n\n/**\n * Inventory script for flat item lists: prints `<group> <FILE|DIR> <name>` per\n * present item. `groups` maps a group label to `{ dir, items }`.\n */\nexport function flatInventoryScript(\n groups: Record<string, { dir: string; items: readonly string[] }>,\n): string {\n const parts: string[] = [];\n for (const [group, { dir, items }] of Object.entries(groups)) {\n parts.push(\n `for f in ${items.join(' ')}; do` +\n ` if [ -d \"${dir}/$f\" ]; then echo \"${group} DIR $f\";` +\n ` elif [ -e \"${dir}/$f\" ]; then echo \"${group} FILE $f\"; fi;` +\n ` done;`,\n );\n }\n parts.push('true');\n return parts.join(' ');\n}\n\n/**\n * Inventory the CHILDREN of each declared category dir.\n *\n * `AgentPullSpec.categories` names directories whose children are the unit\n * (Pi's `skills`/`extensions`/`prompts`/`themes`, claude's\n * `skills`/`agents`/`commands`). Listing the category itself as a flat item is\n * WRONG for these: the pull is additive and skips anything the host already\n * has, so one pre-existing `skills/` dir on the host would make every\n * box-created skill permanently unpullable.\n *\n * Emits the same `<group> <KIND> <name>` lines `flatInventoryScript` does, with\n * the category as the group and the child's basename as the name.\n */\nexport function categoryInventoryScript(categories: Record<string, { dir: string }>): string {\n const parts: string[] = [];\n for (const [group, { dir }] of Object.entries(categories)) {\n parts.push(\n `if [ -d \"${dir}\" ]; then for f in \"${dir}\"/*; do` +\n ` [ -e \"$f\" ] || continue; n=$(basename \"$f\");` +\n ` if [ -d \"$f\" ]; then echo \"${group} DIR $n\"; else echo \"${group} FILE $n\"; fi;` +\n ` done; fi;`,\n );\n }\n parts.push('true');\n return parts.join(' ');\n}\n\nexport interface FlatInventoryEntry {\n group: string;\n kind: 'file' | 'dir';\n name: string;\n}\n\nexport function parseFlatInventory(stdout: string): FlatInventoryEntry[] {\n const out: FlatInventoryEntry[] = [];\n for (const line of stdout.split('\\n')) {\n const m = /^(\\S+) (FILE|DIR) (\\S+)$/.exec(line.trim());\n if (!m) continue;\n out.push({ group: m[1]!, kind: m[2] === 'DIR' ? 'dir' : 'file', name: m[3]! });\n }\n return out;\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Pull one flat-inventory entry to the host, preserving 0600 on auth files. */\nasync function pullFlatEntry(\n t: SyncTransport,\n entry: FlatInventoryEntry,\n boxPath: string,\n hostPath: string,\n): Promise<void> {\n if (entry.kind === 'dir') {\n await mkdir(hostPath, { recursive: true });\n await t.pullTree(boxPath, hostPath, { exclude: ['node_modules'] });\n return;\n }\n await mkdir(dirname(hostPath), { recursive: true });\n await t.pullFile(boxPath, hostPath);\n if (entry.name === 'auth.json') await chmod(hostPath, 0o600);\n}\n\n/**\n * Resolve one pull group to its box dir and host dir, per the rule\n * `AgentPullSpec` documents: `data` is `staticPaths[0]`, any other group is\n * that dir plus the entry whose `relocToSubpath` matches. `pull.roots` overrides\n * for a root that exists ONLY in the pull direction.\n */\nfunction pullRootFor(\n spec: AgentSyncSpec,\n group: string,\n hostHome: string,\n): { boxDir: string; hostDir: string } | null {\n const declared = spec.pull?.roots?.find((r) => r.group === group);\n if (declared) {\n return { boxDir: declared.boxDir, hostDir: join(hostHome, ...declared.hostHomeRel) };\n }\n const base = spec.staticPaths[0];\n if (!base) return null;\n if (group === 'data') {\n return { boxDir: base.boxDir, hostDir: join(hostHome, ...base.hostHomeRel) };\n }\n const reloc = spec.staticPaths.find((p) => p.relocToSubpath === group);\n if (!reloc) return null;\n return { boxDir: `${base.boxDir}/${group}`, hostDir: join(hostHome, ...reloc.hostHomeRel) };\n}\n\n/**\n * The DEFAULT box->host pull: flat items under one or more declared roots.\n *\n * Driven entirely by `AgentPullSpec.items` + the group rule above, so an agent\n * whose config is a flat set of files needs no pull code — declaring the row is\n * the whole job. This replaced the codex and opencode functions, which were the\n * same body differing only in the group->root mapping the spec already\n * described.\n *\n * Additive: an item the host already has is never overwritten, so a pull can\n * only ever add. `pullFlatEntry` restores `auth.json`'s 0600.\n */\nexport async function pullFlatConfigViaTransport(\n agent: AgentId,\n t: SyncTransport,\n opts: { hostHome?: string; dryRun?: boolean } = {},\n): Promise<{ newItems: string[] }> {\n const spec = resolveAgentSpec(agent);\n const hostHome = opts.hostHome ?? homedir();\n const groups: Record<string, { dir: string; items: readonly string[] }> = {};\n const roots: Record<string, { boxDir: string; hostDir: string }> = {};\n for (const item of spec.pull?.items ?? []) {\n const root = pullRootFor(spec, item.group, hostHome);\n if (!root) continue;\n roots[item.group] = root;\n groups[item.group] = { dir: root.boxDir, items: item.names };\n }\n // Categories hang off the DEFAULT root and are addressed as `<cat>/<child>`.\n // An agent that declares none is completely unaffected by this block.\n const categories: Record<string, { dir: string }> = {};\n const defaultRoot = pullRootFor(spec, spec.pull?.items?.[0]?.group ?? 'data', hostHome);\n for (const cat of spec.pull?.categories ?? []) {\n if (!defaultRoot) break;\n roots[cat] = {\n boxDir: `${defaultRoot.boxDir}/${cat}`,\n hostDir: join(defaultRoot.hostDir, cat),\n };\n categories[cat] = { dir: `${defaultRoot.boxDir}/${cat}` };\n }\n\n if (Object.keys(groups).length === 0 && Object.keys(categories).length === 0) {\n return { newItems: [] };\n }\n\n const script = [\n Object.keys(groups).length > 0 ? flatInventoryScript(groups) : '',\n Object.keys(categories).length > 0 ? categoryInventoryScript(categories) : '',\n ]\n .filter((p) => p.length > 0)\n // `; ` and not ' ': each builder ends with a bare `true`, so a plain space\n // splices it onto the next segment's `if` and sh dies on \"then unexpected\".\n .join('; ');\n const inv = await t.exec(['sh', '-c', script]);\n if (inv.exitCode !== 0) {\n throw new Error(\n `failed to inventory ${spec.id} config in the box: ${inv.stderr.trim() || `exit ${String(inv.exitCode)}`}`,\n );\n }\n\n // The default group's items keep their bare name; any other group is labelled\n // `<group>/<name>` so the two cannot collide in the report.\n const defaultGroup = spec.pull?.items?.[0]?.group;\n const pending: Array<{ entry: FlatInventoryEntry; label: string; box: string; host: string }> =\n [];\n // Agentbox-OWNED files never travel to the host. `seeds` already declares\n // them (`destRel`, relative to the same root the pull walks), so this needs\n // no new field and no naming convention: Pi's activity extension is seeded\n // into `extensions/agentbox-state.js` and would otherwise be offered back as\n // if the user had written it, installing our extension into their real Pi.\n const seeded = new Set((spec.seeds ?? []).map((s) => s.destRel));\n\n for (const entry of parseFlatInventory(inv.stdout)) {\n const root = roots[entry.group];\n if (!root) continue;\n const rel = entry.group in categories ? `${entry.group}/${entry.name}` : entry.name;\n if (seeded.has(rel)) continue;\n const host = join(root.hostDir, entry.name);\n if (await pathExists(host)) continue; // additive\n pending.push({\n entry,\n label:\n entry.group === defaultGroup && !(entry.group in categories)\n ? entry.name\n : `${entry.group}/${entry.name}`,\n box: `${root.boxDir}/${entry.name}`,\n host,\n });\n }\n const newItems = pending.map((p) => p.label);\n if (opts.dryRun || pending.length === 0) return { newItems };\n for (const p of pending) await pullFlatEntry(t, p.entry, p.box, p.host);\n return { newItems };\n}\n","/**\n * The projection of `AGENT_SYNC_SPECS` that ctl consumes over the `agents.list`\n * RPC.\n *\n * A PROJECTION, not the raw table, for two reasons:\n *\n * - `credential.hostBackup` is an absolute HOST path baked at module load\n * (`join(STATE_DIR, 'claude-credentials.json')`). Inside a box it is\n * meaningless, and shipping it leaks the host's home directory layout.\n * - The box only needs what it acts on. Install recipes, docker volume names\n * and host static-path sources are host-side concerns; sending them would\n * make every one of them part of a wire contract for no reason.\n *\n * Deliberately delivered by RPC rather than a file the host writes into the box:\n * a file has to be written by the PROVIDER (cloud bootstrap, docker box-env, and\n * a hand-written equivalent in every community provider), which would make this\n * shape a contract each of them implements — so any future field would mean\n * updating all of them. Over RPC the shape stays host-side and providers stay\n * uninvolved.\n *\n * Forward compatibility runs one way: ctl must ignore fields it doesn't know, so\n * a newer host never breaks an older box. Mirrors how the in-box `agentbox.yaml`\n * parser warns on unknown keys instead of failing.\n */\n\nimport type { AgentConfigRenderSpec, AgentServiceSpec } from '@agentbox/core';\nimport { AGENT_SYNC_SPECS } from './registry.js';\n\n/** One file ctl watches in the box, and what the host should do when it changes. */\nexport interface AgentWatchDescriptor {\n /** Absolute in-box path. */\n path: string;\n /**\n * What the sync is FOR.\n *\n * - `fanout` — a rotating secret. The host accepts it newest-wins and\n * re-distributes it to every other box. Correct ONLY for credentials: an\n * OAuth refresh rotates the token, so one box refreshing kills every other\n * copy unless the fresh blob is pushed back out.\n * - `backup` — everything else. Lands on the host and stops there. Fanning\n * out non-credential content (session transcripts, logs) would copy one\n * box's data into every other box.\n */\n sync: 'fanout' | 'backup';\n /** Validator selector for `fanout` payloads; absent for `backup`. */\n shape?: 'claude-oauth' | 'nonempty-json';\n /** Host destination for a `backup` watch, relative to the box's host workspace. */\n hostDest?: string;\n}\n\n/** What ctl needs to know about one agent. */\nexport interface AgentDescriptor {\n id: string;\n /** Files to watch in-box, with their intent. */\n watch: readonly AgentWatchDescriptor[];\n /**\n * The tmux session name ctl probes for this agent's liveness and pane title.\n *\n * Shipped rather than assumed because ctl is baked: its compiled-in list ends\n * at the agents that existed when the image was built, so an agent added later\n * would never be probed and could never report activity at all.\n */\n sessionName: string;\n /**\n * How this agent reports activity — see `AgentCapabilities.activitySource`.\n * An empty list means it reports none, and ctl skips probing it entirely\n * rather than adding a permanently-`unknown` entry to every snapshot.\n */\n activitySource: readonly string[];\n /**\n * `'tui'` (a tmux session ctl probes) or `'service'` (a daemon ctl RUNS).\n *\n * Always sent, even though the spec's own field is optional: on the wire an\n * absent field means \"an older host that predates the surface\", which ctl must\n * read as `tui`. Sending the resolved value keeps that default in ONE place.\n */\n surface: 'tui' | 'service';\n /**\n * The supervisor units this agent contributes, verbatim from its spec. Present\n * only for `surface: 'service'`.\n *\n * This — not a file the provider writes — is why a box booted from a snapshot\n * baked before this agent existed can still run it: the shape stays host-side,\n * and no provider (community ones included) implements anything for it.\n */\n service?: AgentServiceSpec;\n /**\n * Layered-config descriptor for `agentbox-ctl agent render <id>`, verbatim\n * from the spec. Also what tells ctl that `<overlayKey>:` is a legitimate\n * top-level `agentbox.yaml` key rather than a typo.\n */\n configRender?: AgentConfigRenderSpec;\n}\n\n/**\n * The wire payload of `agents.list`. Versioned host-side; ctl tolerates extras.\n *\n * `2` added `surface` / `service` / `configRender`. The bump is informational —\n * ctl NEVER gates on it, because the forward-compatibility rule runs the other\n * way (ignore what you don't know), and an older ctl reading a `2` payload must\n * keep working on the fields it does know rather than rejecting the lot.\n */\nexport interface AgentDescriptorPayload {\n schema: 2;\n agents: readonly AgentDescriptor[];\n}\n\n/**\n * Build the payload from the registry.\n *\n * Every agent's credential is a `fanout` watch — that is exactly today's\n * behaviour, restated as data. Additional watches come from the spec, and\n * default to `backup`: `fanout` has to be asked for, because getting it wrong\n * overwrites files in every other box.\n *\n * An agent that declares NO `credential` emits no credential watch at all: this\n * watch is fanout, so a file named here is copied into every other box.\n */\n/**\n * Fold the agent's declared `boxRunEnv` into the units it contributes.\n *\n * WHY THIS IS NOT THE PROVIDER'S JOB. `boxRunEnv` reaches a box's processes\n * differently on every provider, and on two of them it did not arrive at all:\n * docker sets it on `docker run`, Vercel and E2B hand it to the SDK as a\n * sandbox-wide env, but a VPS has no such primitive, so Hetzner and\n * DigitalOcean carry it by writing `/etc/agentbox/box.env` — which both filter\n * to `AGENTBOX_*` keys, because that file is world-readable and the filter is\n * what keeps the relay and bridge tokens out of it. openclaw's\n * `OPENCLAW_WORKSPACE_DIR` was silently dropped there, so `openclaw onboard`\n * ran against `~/.openclaw/workspace` and \"your project dir is the agent's\n * workspace\" — the headline behaviour — was quietly false on both VPS\n * providers. Nothing failed: the gateway still bound its port and passed its\n * health check, so every smoke test called the box ready.\n *\n * Carrying it on the UNITS fixes all five providers with one rule, needs no\n * provider to implement anything, and keeps non-secret paths out of a\n * world-readable file. The supervisor already applies a unit's `env` on top of\n * what it inherited, so this is the channel the values should always have used.\n *\n * A unit's own `env` still wins: `boxRunEnv` is the agent-wide default and a\n * task that sets the same key meant to.\n *\n * This does NOT reach a shell you open yourself, where `box.env` is still the\n * only channel — a hand-run `openclaw` on a VPS box will disagree with the\n * service until that is widened too.\n */\nexport function serviceWithRunEnv(\n service: AgentServiceSpec,\n runEnv: Record<string, string>,\n): AgentServiceSpec {\n if (Object.keys(runEnv).length === 0) return service;\n return {\n ...service,\n env: { ...runEnv, ...(service.env ?? {}) },\n ...(service.tasks\n ? {\n tasks: service.tasks.map((t) => ({ ...t, env: { ...runEnv, ...(t.env ?? {}) } })),\n }\n : {}),\n };\n}\n\nexport interface BuildAgentDescriptorsOptions {\n /**\n * The agents the asking box was created FOR (its registration's `agent`).\n * A `surface: 'service'` agent contributes its units and config render ONLY\n * to a box that runs it: every box asks `agents.list` at daemon start, and\n * without this gate a claude box also ran `openclaw onboard` (exit 127 — not\n * installed) and showed a permanently `waiting` openclaw service. Undefined\n * — a registration that predates the field — keeps the old ship-everything\n * answer, so an openclaw box registered by an older host still gets its\n * daemon. The credential/activity fields are unaffected: they are what\n * makes a TUI agent's login fan out, and every box wants those.\n */\n boxAgents?: readonly string[];\n}\n\nexport function buildAgentDescriptors(\n opts: BuildAgentDescriptorsOptions = {},\n): AgentDescriptorPayload {\n const runsHere = (id: string): boolean =>\n opts.boxAgents === undefined || opts.boxAgents.includes(id);\n return {\n schema: 2,\n agents: AGENT_SYNC_SPECS.map((spec) => ({\n id: spec.id,\n sessionName: spec.sessionName,\n activitySource: spec.caps.activitySource,\n surface: spec.caps.surface ?? ('tui' as const),\n ...(spec.service && runsHere(spec.id)\n ? { service: serviceWithRunEnv(spec.service, spec.boxRunEnv) }\n : {}),\n ...(spec.configRender && runsHere(spec.id) ? { configRender: spec.configRender } : {}),\n watch: [\n ...(spec.credential\n ? [\n {\n path: spec.credential.boxAbsPath,\n sync: 'fanout' as const,\n shape: spec.credential.realShape,\n },\n ]\n : []),\n ...(spec.watch ?? []).map((w) => ({\n path: w.path,\n sync: w.sync ?? ('backup' as const),\n ...(w.hostDest ? { hostDest: w.hostDest } : {}),\n })),\n ],\n })),\n };\n}\n","/**\n * Propagate pulled agent settings (skills/plugins/config items) from one box\n * to other boxes — the sync-layer core behind the `agentbox download <agent>`\n * propagate step. Everything here is additive: an item a target already has\n * is never overwritten, and plugin-registry merges are target-wins.\n *\n * Targets are abstracted behind `SettingsTarget`:\n * - a live box over its provider's `SyncTransport` (`transportSettingsTarget`)\n * — any cloud provider, or a running docker box;\n * - a docker config *volume* via throwaway helper containers\n * (`volumeSettingsTarget` in `@agentbox/sandbox-docker`) — covers every\n * docker box sharing that volume, running or paused.\n *\n * Items are staged host-side first (`stageItemsViaTransport` /\n * sandbox-docker's `stageItemsFromVolume`) in the volume-style relative\n * layout, so propagation works even when the user declined the host\n * `~/.claude` write.\n */\n\nimport { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport type { BoxRecord, SyncTransport } from '@agentbox/core';\nimport type { AgentId } from '@agentbox/core';\nimport { agentConfigVolume } from '@agentbox/core';\nimport { resolveAgentSpec } from './registry.js';\nimport { mergeInstalledPlugins, mergeKnownMarketplaces } from './claude-pull.js';\nimport { agentBoxDir } from './agent-pull.js';\n\n/** One staged settings item, in the volume-style relative layout. */\nexport interface StagedItem {\n /** Config-root-relative path (`skills/foo`, `plugins/cache/m/p`, `config.toml`). */\n rel: string;\n /** Human label for summaries (`skills/foo`, `config/skills`). */\n label: string;\n kind: 'dir' | 'file';\n}\n\n/** A pulled settings set staged host-side, ready to propagate to targets. */\nexport interface StagedSettings {\n agent: AgentId;\n /** Host dir holding the items at their `rel` paths. */\n stagingDir: string;\n items: StagedItem[];\n /** claude only: the source box's raw plugin registries for target merges. */\n sourceRegistries?: Record<string, unknown>;\n}\n\n/**\n * The box-side config root the staged rels apply under, per agent.\n *\n * Derived from the registry (`staticPaths[0].boxDir`). It used to be a switch\n * whose `default:` arm returned opencode's dir, so every agent but the named\n * two — including the demo agent and any plugin agent — was told its config\n * lived under `~/.local/share/opencode`.\n */\nexport function agentBoxConfigDir(agent: AgentId): string {\n return agentBoxDir(agent);\n}\n\n// The three `<agent>StagedItems` mappers lived here — a per-agent table in a\n// layer that must not know about agents. Each knew only its own agent's pull\n// shape, so each moved to `packages/agent-<id>/src/staged-items.ts`. The\n// `StagedItem` contract and the transport that consumes it stay shared.\n\n/** Stage box-side items into `stagingDir` (volume-style layout) over a transport. */\nexport async function stageItemsViaTransport(\n t: SyncTransport,\n boxDir: string,\n items: StagedItem[],\n stagingDir: string,\n): Promise<void> {\n for (const item of items) {\n const dest = join(stagingDir, item.rel);\n if (item.kind === 'dir') {\n await mkdir(dest, { recursive: true });\n await t.pullTree(`${boxDir}/${item.rel}`, dest, { exclude: ['node_modules'] });\n } else {\n await mkdir(dirname(dest), { recursive: true });\n await t.pullFile(`${boxDir}/${item.rel}`, dest);\n }\n }\n}\n\n/** Create a scratch staging dir for a propagate run (caller rm's it). */\nexport async function makeStagingDir(agent: AgentId): Promise<string> {\n return mkdtemp(join(tmpdir(), `agentbox-${agent}-propagate-`));\n}\n\nexport async function removeStagingDir(stagingDir: string): Promise<void> {\n await rm(stagingDir, { recursive: true, force: true });\n}\n\n/**\n * Minimal write seam for one propagate target — a live box over a transport or\n * a docker config volume via helper containers. All paths are config-root\n * relative (same layout as `StagedItem.rel`).\n */\nexport interface SettingsTarget {\n /** Human label for the per-target summary (box name or volume name). */\n label: string;\n exists(rel: string): Promise<boolean>;\n readText(rel: string): Promise<string | null>;\n /** `opts.mode` sets the file mode (e.g. 0o600 for credential blobs). */\n writeText(rel: string, content: string, opts?: { mode?: number }): Promise<void>;\n /** Copy a staged item into the target at `rel` (parents created, additive). */\n copyIn(stagingAbs: string, rel: string, kind: 'dir' | 'file'): Promise<void>;\n}\n\n/**\n * A `SettingsTarget` over a live box's `SyncTransport`, rooted at the agent's\n * box config dir. Ownership follows the transport's default exec user (the\n * box's `vscode`, whatever uid that is on the provider).\n */\nexport function transportSettingsTarget(\n t: SyncTransport,\n boxDir: string,\n label: string,\n): SettingsTarget {\n const abs = (rel: string) => `${boxDir}/${rel}`;\n return {\n label,\n async exists(rel: string): Promise<boolean> {\n const r = await t.exec(['sh', '-c', `test -e '${abs(rel)}'`]);\n return r.exitCode === 0;\n },\n readText(rel: string): Promise<string | null> {\n return t.readText(abs(rel));\n },\n async writeText(rel: string, content: string, opts?: { mode?: number }): Promise<void> {\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-target-write-'));\n try {\n const tmp = join(stage, 'file');\n await writeFile(tmp, content);\n await t.exec(['sh', '-c', `mkdir -p '${dirname(abs(rel))}'`]);\n await t.pushFile(tmp, abs(rel));\n if (opts?.mode !== undefined) {\n await t.exec(['sh', '-c', `chmod ${opts.mode.toString(8)} '${abs(rel)}'`]);\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n },\n async copyIn(stagingAbs: string, rel: string, kind: 'dir' | 'file'): Promise<void> {\n if (kind === 'dir') {\n await t.exec(['sh', '-c', `mkdir -p '${abs(rel)}'`]);\n await t.pushTree(stagingAbs, abs(rel), { exclude: ['node_modules'] });\n } else {\n await t.exec(['sh', '-c', `mkdir -p '${dirname(abs(rel))}'`]);\n await t.pushFile(stagingAbs, abs(rel));\n }\n },\n };\n}\n\nexport interface PropagateTargetResult {\n target: string;\n copied: string[];\n skipped: string[];\n mergedRegistries: string[];\n error?: string;\n}\n\n/** The two claude plugin registries a propagate merges into targets. */\nconst CLAUDE_REGISTRY_FILES: ReadonlyArray<{ key: string; rel: string }> = [\n { key: 'installed_plugins', rel: 'plugins/installed_plugins.json' },\n { key: 'known_marketplaces', rel: 'plugins/known_marketplaces.json' },\n];\n\n/**\n * Push one staged settings set into one target: copy items the target lacks,\n * then (claude) additively merge the source's plugin registries into the\n * target's — target-wins, and since source and target both use the container\n * plugin prefix, passing `/home/vscode` as the \"host home\" makes the merge\n * helpers' path rewrite the identity.\n */\nexport async function propagateStagedSettings(\n target: SettingsTarget,\n staged: StagedSettings,\n): Promise<PropagateTargetResult> {\n const result: PropagateTargetResult = {\n target: target.label,\n copied: [],\n skipped: [],\n mergedRegistries: [],\n };\n for (const item of staged.items) {\n if (await target.exists(item.rel)) {\n result.skipped.push(item.label);\n continue;\n }\n await target.copyIn(join(staged.stagingDir, item.rel), item.rel, item.kind);\n result.copied.push(item.label);\n }\n\n if (staged.agent === 'claude' && staged.sourceRegistries) {\n for (const { key, rel } of CLAUDE_REGISTRY_FILES) {\n const source = staged.sourceRegistries[key];\n if (source === undefined) continue;\n const raw = await target.readText(rel);\n let targetJson: unknown;\n try {\n targetJson = raw === null ? undefined : JSON.parse(raw);\n } catch {\n targetJson = undefined;\n }\n const merged =\n key === 'installed_plugins'\n ? mergeInstalledPlugins(targetJson, source, { hostHome: '/home/vscode' })\n : mergeKnownMarketplaces(targetJson, source, { hostHome: '/home/vscode' });\n if (!merged.changed) continue;\n await target.writeText(rel, `${JSON.stringify(merged.data, null, 2)}\\n`);\n result.mergedRegistries.push(rel);\n }\n }\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// target planning\n// ---------------------------------------------------------------------------\n\n/** The BoxRecord fields target planning needs (structural, for pure tests). */\nexport interface PropagateBoxLike {\n id: string;\n name: string;\n provider?: string;\n projectRoot?: string;\n claudeConfigVolume?: string;\n codexConfigVolume?: string;\n opencodeConfigVolume?: string;\n /** Every agent's config volume, keyed by id. The three above are its mirror. */\n agentConfigVolumes?: Record<string, string>;\n /** Agents the box was created for. Absent = created before per-agent selection. */\n agents?: string[];\n /** Other agents' logins the box consumes as model auth (`borrowCredentials`). */\n borrowedCredentials?: string[];\n}\n\nexport interface PropagatePlan<B extends PropagateBoxLike> {\n /**\n * Docker config volumes to write, each covering the named boxes (the shared\n * volume groups every non-isolated docker box — one write covers them all,\n * running or paused).\n */\n dockerVolumes: Array<{ volume: string; boxNames: string[]; shared: boolean }>;\n /** Cloud boxes to push to (caller checks each is running / resumable). */\n cloudBoxes: B[];\n /**\n * Boxes that BORROW this agent's login as model auth (any provider). They\n * mount no config volume for it, so the push goes over the box's transport\n * to the agent's canonical path, and the consuming agent's ingest task is\n * re-run afterwards. A box that both runs and borrows the agent is listed\n * once, under the running set.\n */\n borrowingBoxes: B[];\n}\n\n/**\n * The box's docker config volume for `agent`, or undefined when it has none.\n *\n * `agentConfigVolume` reads the keyed map and falls back to the three legacy\n * named fields. This was a switch with a `default:` arm returning opencode's\n * volume, which would have fanned a fourth agent's credentials into opencode's\n * store.\n */\nfunction isolatedVolumeOf(box: PropagateBoxLike, agent: AgentId): string | undefined {\n return agentConfigVolume(box as BoxRecord, agent);\n}\n\n/**\n * Plan which stores a propagate run must write: dedup docker boxes onto their\n * config volumes (shared volume once) and list cloud boxes individually.\n * `scope: 'project'` keeps only boxes whose `projectRoot` matches the source's.\n * `excludeVolume` drops the source box's own volume (propagating a docker\n * box's items back into the volume they came from is a guaranteed no-op).\n */\nexport function planPropagateTargets<B extends PropagateBoxLike>(\n boxes: B[],\n opts: {\n agent: AgentId;\n sourceBoxId: string;\n scope: 'project' | 'all';\n projectRoot?: string;\n excludeVolume?: string;\n },\n): PropagatePlan<B> {\n const sharedVolume = resolveAgentSpec(opts.agent).dockerVolume;\n const inScope = boxes.filter(\n (b) =>\n b.id !== opts.sourceBoxId &&\n (opts.scope === 'all' || (b.projectRoot ?? '') === (opts.projectRoot ?? '')),\n );\n const volumes = new Map<string, { boxNames: string[]; shared: boolean }>();\n const cloudBoxes: B[] = [];\n const borrowingBoxes: B[] = [];\n for (const box of inScope) {\n // A box created for a specific agent set must not be handed another agent's\n // credential. This is the fan-out's own gate: it pushes STRAIGHT INTO a\n // cloud box, so without it a resume re-seeds every agent's token and\n // silently undoes the create-time isolation. Docker is unaffected — its\n // push targets a volume the box doesn't mount.\n if (box.agents && !box.agents.includes(opts.agent)) {\n // Unless the box consumes that login as model auth, in which case the\n // fresh blob goes to the canonical path its ingest task reads.\n if (box.borrowedCredentials?.includes(opts.agent)) borrowingBoxes.push(box);\n continue;\n }\n if ((box.provider ?? 'docker') !== 'docker') {\n cloudBoxes.push(box);\n continue;\n }\n const volume = isolatedVolumeOf(box, opts.agent) ?? sharedVolume;\n if (volume === opts.excludeVolume) continue;\n const entry = volumes.get(volume) ?? { boxNames: [], shared: volume === sharedVolume };\n entry.boxNames.push(box.name);\n volumes.set(volume, entry);\n }\n return {\n dockerVolumes: [...volumes.entries()].map(([volume, v]) => ({ volume, ...v })),\n cloudBoxes,\n borrowingBoxes,\n };\n}\n","/**\n * `@agentbox/sandbox-core`'s `sync/` layer — the provider-neutral, fs/execa-\n * bearing implementation of the sync contracts declared in `@agentbox/core`.\n * The per-tool registry, concern modules (git/env/files/credentials/skills/\n * dynamic), and the data-driven driver land here across the refactor phases.\n *\n * Today it exports the parity net used to golden-test each concern as it is\n * migrated onto the `SyncTransport` seam.\n */\n\nexport {\n makeRecordingTransport,\n type RecordingSyncTransport,\n type RecordingTransportOptions,\n type RecordedOp,\n} from './recording-transport.js';\nexport {\n AGENT_SYNC_SPECS,\n resolveAgentSpec,\n agentIds,\n visibleAgentSpecs,\n isRuntimeAgent,\n agentTuiEnv,\n agentsRejectProxyHeaders,\n findAgentSpec,\n} from './registry.js';\nexport {\n mergeInstalledPlugins,\n mergeKnownMarketplaces,\n pickNewItems,\n referencedPluginVersionKeys,\n PULL_CATEGORIES,\n SKILL_EXCLUDE_PREFIXES,\n CONTAINER_PLUGINS_PREFIX,\n type MergeResult,\n type PullCategory,\n} from './claude-pull.js';\nexport {\n claudeInventoryScript,\n parseClaudeInventory,\n computeClaudePullPlan,\n writeClaudeMergedRegistries,\n pullClaudeExtrasViaTransport,\n pullFlatConfigViaTransport,\n flatInventoryScript,\n categoryInventoryScript,\n parseFlatInventory,\n CLAUDE_PULL_DIR_CATEGORIES,\n CODEX_PULL_ITEMS,\n OPENCODE_PULL_DATA_ITEMS,\n OPENCODE_PULL_CONFIG_ITEMS,\n CLAUDE_BOX_CONFIG_DIR,\n CODEX_BOX_CONFIG_DIR,\n OPENCODE_BOX_DATA_DIR,\n type ClaudeInventory,\n type ClaudePullPlan,\n type PullClaudeResult,\n type FlatInventoryEntry,\n agentBoxDir,\n} from './agent-pull.js';\nexport {\n buildAgentDescriptors,\n type AgentDescriptor,\n type AgentDescriptorPayload,\n type BuildAgentDescriptorsOptions,\n type AgentWatchDescriptor,\n} from './agent-descriptor.js';\nexport {\n agentBoxConfigDir,\n makeStagingDir,\n removeStagingDir,\n stageItemsViaTransport,\n transportSettingsTarget,\n propagateStagedSettings,\n planPropagateTargets,\n type StagedItem,\n type StagedSettings,\n type SettingsTarget,\n type PropagateTargetResult,\n type PropagateBoxLike,\n type PropagatePlan,\n} from './agent-propagate.js';\n// The agent spec contract lives in `@agentbox/core` (the zero-internal-dep leaf)\n// so an agent package can declare its own row without importing anything that\n// imports it back. Re-exported here because ~40 call sites already reach for it\n// through `@agentbox/sandbox-core`.\nexport type {\n AgentId,\n AgentSyncSpec,\n AgentPathMap,\n AgentCredential,\n AgentCapabilities,\n AgentInstall,\n AgentInstallRecipe,\n AgentSeedSpec,\n} from '@agentbox/core';\nexport { resolveAgentInstall } from '@agentbox/core';\nexport {\n agentSeedPlacements,\n buildAgentSeedScript,\n parseSeedMarkers,\n planAgentSeeds,\n AGENT_SEED_MARKER,\n type AgentSeedPlacement,\n} from './agent-seed.js';\nexport { makeSyncContext, type SyncContext, type SyncContextInit } from './context.js';\nexport {\n ensureAgentInstalled,\n AgentInstallError,\n renderInstallRecipe,\n renderPackageInstall,\n renderAgentSettingEnv,\n type EnsureAgentInstalledResult,\n} from './concerns/install.js';\nexport {\n pushEnvFiles,\n scanHostEnvFiles,\n buildHostEnvFindArgs,\n DEFAULT_ENV_PATTERNS,\n ENV_PRUNE_DIRS,\n type PushEnvFilesResult,\n} from './concerns/env.js';\nexport {\n planCarryEntry,\n BOX_HOME,\n dirnameUnix,\n basenameUnix,\n type CarryPlan,\n} from './concerns/files.js';\nexport {\n encodeClaudeProjectsKey,\n resolveClaudeMemoryDir,\n BOX_CLAUDE_PROJECT_DIR,\n} from './agents/claude/paths.js';\nexport { findUnsyncableSymlinks } from './host-links.js';\nexport {\n seedAgentsVolume,\n type SeedAgentsVolumeArgs,\n type SeedAgentsVolumeResult,\n} from './concerns/skills.js';\nexport {\n isRealAgentCredential,\n hostBackupHasCredentials,\n extractCredentials,\n parseCredentialsUpdate,\n jsonNumberAt,\n credentialFreshness,\n oauthRefreshExpiresAt,\n shouldAcceptCredentialUpdate,\n writeCredentialBackup,\n readCredentialBackup,\n pushCredentialToBox,\n resolveHostCredential,\n resolveHostCredentialFile,\n SEED_MARKER,\n type CredentialAgentKind,\n type CredentialsUpdate,\n type ExtractCredentialsOptions,\n} from './concerns/credentials.js';\nexport {\n classifyUntrackedOverlay,\n makeHostGitPorts,\n NON_REGULAR_TOKEN,\n resyncWorkspace,\n} from './concerns/git.js';\nexport {\n BACKUP_GITIGNORE_ENTRY,\n BOTS_DIR_REL,\n backupAgentState,\n backupStamp,\n botBackupDir,\n boxRefWithRestoreRefusal,\n botDir,\n botWorkspaceRoot,\n DEFAULT_BACKUP_KEEP,\n ensureBackupGitignored,\n existingBoxRefusal,\n linkLatest,\n listBackups,\n listBots,\n prepareBackupDir,\n pruneBackups,\n readBackupManifest,\n resolveBackupTarget,\n resolveBotBundle,\n restoreAgentState,\n restoreScope,\n restoreWorkspaceDir,\n sourceBoxRunningRefusal,\n stageRestoreWorkspace,\n writeBackupManifest,\n type AgentStateBackupResult,\n type AgentStateRestoreResult,\n type BackupManifest,\n type BackupTarget,\n type BackupTargetOptions,\n type BotBundle,\n type BotListing,\n} from './concerns/bot-backup.js';\nexport {\n readServiceUrlFields,\n serviceAgentForBox,\n serviceSignInUrl,\n withServiceSignIn,\n type ServiceUrlFieldValue,\n} from './concerns/service-url.js';\nexport {\n GIT_MODE_EXCLUDE_DIRS,\n WORKSPACE_EXCLUDE_DIR_NAMES,\n agentStateExcludePaths,\n agentCloneDropPaths,\n agentWorkspaceArtifactPaths,\n buildWorkspaceListScript,\n dropHostOnlyPaths,\n existingPathsIn,\n gitModeExcludePathspecs,\n seedExcludeTarArgs,\n isAgentWorkspaceArtifact,\n parseItemizedEntries,\n isExcludedPath,\n listHostFiles,\n overlayHostDirIntoBox,\n parseItemizedChanges,\n parseWorkspaceList,\n rsyncPullToHost,\n workspaceExcludes,\n type OverlayHostDirArgs,\n type ParsedWorkspaceList,\n type RsyncPullArgs,\n type WorkspaceExcludeOptions,\n type ItemizedChange,\n type WorkspaceListMode,\n type WorkspaceListScriptOptions,\n type WorkspaceOverlayPorts,\n type WorkspaceOverlayResult,\n} from './concerns/workspace-files.js';\nexport {\n BoxProbeError,\n boxOverlayPorts,\n chunkPathsForExec,\n providerBoxFilePorts,\n type BoxFilePorts,\n} from './concerns/box-files.js';\nexport {\n pullWorkspaceToHost,\n readStagedWorkspace,\n stageBoxWorkspace,\n type PullWorkspaceArgs,\n type PullWorkspaceResult,\n type StageWorkspaceArgs,\n type StagedWorkspace,\n} from './concerns/workspace-pull.js';\nexport {\n assertEmptyDir,\n exportBoxWorkspace,\n type ExportWorkspaceArgs,\n type ExportWorkspaceResult,\n} from './concerns/workspace-clone.js';\nexport {\n uploadWorkspaceToBox,\n type UploadWorkspaceArgs,\n type UploadWorkspaceResult,\n} from './concerns/workspace-upload.js';\nexport {\n BOX_WORKFLOWS_DIR,\n BOX_MEMORY_DIR,\n BOX_DYNAMIC_SYNC_MANIFEST,\n buildHostSyncManifest,\n computeSyncDelta,\n stageDynamicSyncTarball,\n type DynamicSyncManifest,\n type DynamicSyncSet,\n type DynamicSyncSetName,\n type DynamicSyncDelta,\n type DynamicSyncUpload,\n type DynamicSyncDeletion,\n type HostSyncManifest,\n type StagedTarball,\n} from './concerns/dynamic.js';\nexport {\n stageAgentsStaticForUpload,\n stageAgentStaticForUpload,\n AGENTS_STATIC_BOX_DIR,\n // Staging primitives. Exported so an agent package can build its OWN stager\n // when a copy of its declared paths is not enough (claude filters host-path\n // hooks, codex sanitizes config.toml) without re-implementing the rsync/tar\n // plumbing or the cleanup contract.\n pathExists,\n findBrokenSymlinks,\n mkStageDir,\n emptyResult,\n tarballFromDir,\n makeCleanup,\n stageSingleFileTarball,\n STAGE_NO_SPECIALS,\n STAGE_WRITABLE_CHMOD,\n type AgentStaticStage,\n type StageResult,\n} from './host-stage.js';\n","/**\n * Placement of the agentbox-OWNED files an agent needs in its config root —\n * `AgentSyncSpec.seeds`, turned into one shell snippet both transports run.\n *\n * There used to be three of these, hand-written, in `@agentbox/sandbox-docker`\n * (`seedSetupSkillIntoVolume`, `seedCodexHooks`, `seedOpencodePlugin`). They\n * differed only in which file went where, and living in the docker package meant\n * the cloud providers did not do it at all: a cloud OpenCode box never received\n * the state plugin that is its ONLY activity source, so it reported `unknown`\n * forever. Same class of drift as `boxRunEnv` before it was wired.\n *\n * The two transports differ in exactly two ways, both parameters here:\n * - docker copies into a MOUNTED VOLUME (`/dst`) from a throwaway container\n * running as root, so it must chown what it creates;\n * - cloud copies into the live box's real config dir as the box user, so it\n * must not.\n * Everything else — which file, where it lands, which parent dirs to create —\n * comes from the registry, and a drift test pins the two plans together.\n */\n\nimport { resolveAgentSpec } from './registry.js';\nimport type { AgentId, AgentSeedSpec } from '@agentbox/core';\n\n/** One resolved copy: absolute source, absolute destination, dirs to create. */\nexport interface AgentSeedPlacement {\n /**\n * Absolute source IN THE BOX. Normally the baked asset; the cloud path\n * substitutes an uploaded staging path when the base snapshot predates it.\n */\n src: string;\n /** Absolute destination. */\n dest: string;\n /**\n * Ancestor dirs of `dest` below the root, outermost first. Listed rather than\n * left to `mkdir -p` because ownership has to be fixed on EACH of them: a\n * root-run `mkdir -p a/b/c` leaves the intermediates root-owned, and the later\n * static-config stage then cannot write into them. That exact trap cost a live\n * DigitalOcean bake to find (see `SEED_SETUP_SKILL` in the registry).\n */\n ancestors: string[];\n /** Registry `destRel`, echoed as the success marker. */\n destRel: string;\n /** Human label for log lines. */\n label: string;\n}\n\n/** Join without importing node:path — these are always POSIX box paths. */\nfunction boxJoin(root: string, rel: string): string {\n return `${root.replace(/\\/+$/, '')}/${rel.replace(/^\\/+/, '')}`;\n}\n\n/**\n * Resolve an agent's declared seeds against a root — `/dst` for the docker\n * volume mount, the agent's real `staticPaths[0].boxDir` for a live box.\n */\nexport function planAgentSeeds(\n seeds: readonly AgentSeedSpec[],\n root: string,\n opts: { srcFor?: (seed: AgentSeedSpec) => string } = {},\n): AgentSeedPlacement[] {\n return seeds.map((seed) => {\n const parts = seed.destRel.split('/').filter((p) => p.length > 0);\n const dirs = parts.slice(0, -1);\n const ancestors: string[] = [];\n let acc = root.replace(/\\/+$/, '');\n for (const d of dirs) {\n acc = `${acc}/${d}`;\n ancestors.push(acc);\n }\n return {\n src: opts.srcFor ? opts.srcFor(seed) : seed.bakedPath,\n dest: boxJoin(root, seed.destRel),\n ancestors,\n destRel: seed.destRel,\n label: seed.label,\n };\n });\n}\n\n/** An agent's declared seeds, resolved against its real in-box config dir. */\nexport function agentSeedPlacements(agent: AgentId, root?: string): AgentSeedPlacement[] {\n const spec = resolveAgentSpec(agent);\n const boxDir = root ?? spec.staticPaths[0]?.boxDir;\n if (!boxDir || !spec.seeds || spec.seeds.length === 0) return [];\n return planAgentSeeds(spec.seeds, boxDir);\n}\n\n/** Marker each successful copy prints, so callers can report what landed. */\nexport const AGENT_SEED_MARKER = 'AGENTBOX_SEEDED';\n\nfunction shq(p: string): string {\n return `'${p.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * The shell that performs the copies. Every step is guarded and the whole\n * per-seed group ends in `|| true`: a missing baked asset (older base image) is\n * a clean no-op, never a non-zero exit, because seeding must never fail a box\n * create. Always overwrites, so an image upgrade propagates instead of a stale\n * copy in a long-lived shared volume pinning the old version.\n *\n * `owner` (e.g. `vscode:vscode`) emits the chowns; omit it when the caller\n * already runs as the box user. By NAME, not uid — the vscode uid differs per\n * provider (docker/hetzner 1000, vercel 1001, e2b 1002).\n */\nexport function buildAgentSeedScript(\n placements: readonly AgentSeedPlacement[],\n opts: { owner?: string } = {},\n): string {\n const groups = placements.map((p) => {\n const steps: string[] = [`[ -f ${shq(p.src)} ]`];\n for (const dir of p.ancestors) steps.push(`mkdir -p ${shq(dir)}`);\n steps.push(`cp -a ${shq(p.src)} ${shq(p.dest)}`);\n if (opts.owner) {\n for (const dir of p.ancestors) steps.push(`chown ${opts.owner} ${shq(dir)}`);\n steps.push(`chown ${opts.owner} ${shq(p.dest)}`);\n }\n steps.push(`echo ${shq(`${AGENT_SEED_MARKER} ${p.destRel}`)}`);\n return `{ ${steps.join(' && ')}; } || true`;\n });\n return groups.join('; ');\n}\n\n/** Which `destRel`s the script reported as copied. */\nexport function parseSeedMarkers(stdout: string): string[] {\n const out: string[] = [];\n for (const line of stdout.split('\\n')) {\n const t = line.trim();\n if (t.startsWith(`${AGENT_SEED_MARKER} `)) out.push(t.slice(AGENT_SEED_MARKER.length + 1));\n }\n return out;\n}\n","/**\n * `SyncContext` — the runtime values a concern needs that aren't the transport\n * or its per-call plan. Assembled once by the provider (docker/cloud) at create\n * or session-start and threaded through every concern, so concern signatures\n * stay `(ctx, transport, plan?)`.\n *\n * The interface itself is a Tier-1 contract that lives in `@agentbox/core` (so\n * the `ProviderSync` facade there can also name it); it's re-exported here so\n * existing `@agentbox/sandbox-core` importers are unchanged. The builder\n * `makeSyncContext` stays here — it defaults `hostHome` to the OS home dir.\n */\n\nimport { homedir } from 'node:os';\nimport type { SyncContext } from '@agentbox/core';\n\nexport type { SyncContext } from '@agentbox/core';\n\nexport interface SyncContextInit {\n boxName: string;\n boxId: string;\n provider: 'docker' | 'cloud';\n hostWorkspace: string;\n projectRoot?: string;\n boxWorkspace?: string;\n hostHome?: string;\n onLog?: (line: string) => void;\n}\n\n/** Build a `SyncContext` with the conventional defaults filled in. */\nexport function makeSyncContext(init: SyncContextInit): SyncContext {\n return {\n boxName: init.boxName,\n boxId: init.boxId,\n provider: init.provider,\n hostWorkspace: init.hostWorkspace,\n projectRoot: init.projectRoot ?? init.hostWorkspace,\n boxWorkspace: init.boxWorkspace ?? '/workspace',\n hostHome: init.hostHome ?? homedir(),\n onLog: init.onLog ?? (() => {}),\n };\n}\n","/**\n * Put an agent's binary into a live box.\n *\n * Replaces the hand-written `ensureCodexInstalled` / `ensureOpencodeInstalled`\n * twins (which differed only in four data points) with one implementation\n * driven by `AgentSyncSpec.install`. Two things fall out of that:\n *\n * - **Cloud boxes gain the capability at all.** The old twins shelled\n * `docker exec` directly, so a hetzner/e2b/vercel box booted from a snapshot\n * that predates an agent had no way to get it. Running over `SyncTransport`\n * covers every provider.\n * - **A box can carry only the agent it was launched for** and still gain\n * another on demand, which is what makes one-agent-per-box viable.\n */\n\nimport type { SyncTransport } from '@agentbox/core';\nimport { resolveAgentSpec } from '../registry.js';\nimport { resolveAgentInstall } from '@agentbox/core';\nimport { pushCredentialToBox, resolveHostCredential } from './credentials.js';\nimport type { AgentInstallRecipe, AgentSettings } from '@agentbox/core';\n\n/**\n * This agent's declared settings, or {} when the config can't be read.\n *\n * Lazy import so `@agentbox/config` stays off this module's static graph, and\n * `agentSettingsFor` already swallows: an install must not fail because a\n * config layer is unreadable, and every consumer treats an absent setting as\n * \"the declared default\".\n */\nasync function resolveConfiguredSettings(agent: string): Promise<AgentSettings | undefined> {\n try {\n const { agentSettingsFor } = await import('@agentbox/config');\n return await agentSettingsFor(agent);\n } catch {\n return undefined;\n }\n}\n\n/** Install failed. Callers rewrap into their own agent-specific error type. */\nexport class AgentInstallError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AgentInstallError';\n }\n}\n\nexport interface EnsureAgentInstalledResult {\n /** True when the binary was absent and we installed it just now. */\n installed: boolean;\n}\n\n/**\n * Run `script` as root, whichever seam we're on.\n *\n * Docker honours `exec --user root`, so `id -u` is already 0 and we run\n * directly. Cloud backends run as the box user by name and generally ignore a\n * `user` option, so the same command re-enters through passwordless sudo. One\n * string, both transports — and no capability sniffing, which would just be a\n * proxy for this test.\n *\n * `sudo -n` (never prompt) so a box without a sudo grant fails fast with a\n * usable message instead of blocking on a password read that nothing answers.\n *\n * THE SCRIPT RIDES AS A POSITIONAL PARAMETER, never interpolated into a quoted\n * string. It used to be embedded as `sudo -n sh -c \"<script with \\\" escaped>\"`,\n * which made the two branches expand at DIFFERENT times: everything `$`-shaped\n * in the sudo branch — `$(command -v claude)`, and any variable the script sets\n * for itself — was substituted by the OUTER shell, as the box user, before sudo\n * ran. So a `postInstall` reading a variable its own prefix exported saw it\n * empty on every cloud provider and correct on docker. Passing it as `$1` means\n * the inner shell does the expansion in both branches, and no escaping is\n * involved at all.\n */\nfunction asRootScript(script: string): string[] {\n return [\n 'sh',\n '-c',\n 'if [ \"$(id -u)\" = 0 ]; then sh -c \"$1\"; else sudo -n sh -c \"$1\"; fi',\n 'agentbox-install',\n script,\n ];\n}\n\n/**\n * `KEY=value` exports for an agent's resolved settings, as one shell prefix.\n *\n * The generic escape hatch. `alternatesFrom` and `tuiEnvFrom` cover the two\n * things AgentBox itself knows how to do with a setting; this covers everything\n * else, because an agent that arrives as an npm package can put arbitrary logic\n * in its own `postInstall` and needs its settings there. Nothing in this repo\n * has to learn what the setting means.\n *\n * Prefixed to the recipe AND the post-install so both see them — they are two\n * `exec` calls, not one shell. Values are single-quoted with the standard\n * `'\\''` escape: a setting's value is user-supplied config.\n */\nexport function renderAgentSettingEnv(settings?: AgentSettings): string {\n const entries = Object.entries(settings ?? {}).sort(([a], [b]) => (a < b ? -1 : 1));\n if (entries.length === 0) return '';\n const assignments = entries.map(([key, value]) => `${settingEnvName(key)}=${shQuote(value)}`);\n // `export`, not a bare assignment: the recipe spawns processes (npm, an\n // installer script) and a shell variable would not reach them.\n return `export ${assignments.join(' ')}; `;\n}\n\n/** `install` -> `AGENTBOX_AGENT_SETTING_INSTALL`. */\nexport function settingEnvName(key: string): string {\n return `AGENTBOX_AGENT_SETTING_${key.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`;\n}\n\n/** Single-quote for sh. A setting's value is user-supplied config. */\nfunction shQuote(value: string | boolean): string {\n return `'${String(value).replaceAll(\"'\", `'\\\\''`)}'`;\n}\n\n/** Render one recipe to a shell snippet. Shared with the docker derived-layer builder. */\nexport function renderInstallRecipe(recipe: AgentInstallRecipe): string {\n switch (recipe.kind) {\n case 'npm': {\n // `--allow-scripts` is only meaningful on npm >= 11.16 and is required\n // for packages whose lifecycle scripts do real setup work; older npm\n // rejects the unknown flag, so only emit it when the spec asks.\n const flags = recipe.allowScripts ? ` --allow-scripts=${recipe.package}` : '';\n return `npm install -g ${recipe.package}${flags} 2>&1`;\n }\n case 'script':\n // Fetch to a file rather than `curl | bash`: piping hides a blocked\n // download behind bash's exit 0. Retry because the Claude CDN\n // intermittently 403s cloud egress IPs under load.\n //\n // Run the fetched installer with `bash`, not `sh`: /bin/sh is dash on\n // Debian/Ubuntu and these installers are bash scripts (the Dockerfile\n // does the same). Running one under dash dies on the first `[[` or\n // process substitution.\n return [\n 'i=1; while :; do',\n ` curl -fsSL ${recipe.url} -o /tmp/agentbox-agent-install.sh`,\n ' && bash /tmp/agentbox-agent-install.sh stable && break;',\n ` [ \"$i\" -ge ${String(recipe.retries ?? 1)} ] && { rm -f /tmp/agentbox-agent-install.sh; exit 71; };`,\n ' i=$((i+1)); sleep 5;',\n 'done; rm -f /tmp/agentbox-agent-install.sh',\n ].join(' ');\n case 'exec':\n return recipe.script;\n }\n}\n\n/**\n * Install an agent's OS prerequisites, whichever package manager the box has.\n *\n * Dispatches at RUN time rather than bake time because the same recipe is\n * rendered for every provider and there is nothing in an `AgentSyncSpec` that\n * knows the target distro: Debian/Ubuntu everywhere except Vercel, whose\n * sandboxes are Amazon Linux 2023 (dnf). Emitting `apt-get` unconditionally\n * exits 127 there, which used to abort a whole box create.\n *\n * Exit 66 (`EX_NOINPUT`) distinguishes \"no package manager I recognise\" from a\n * real install failure, so the caller can treat the two differently.\n */\nexport function renderPackageInstall(pkgs: readonly string[]): string {\n const list = pkgs.join(' ');\n return [\n 'if command -v apt-get >/dev/null 2>&1; then',\n ` apt-get update && apt-get install -y --no-install-recommends ${list} && rm -rf /var/lib/apt/lists/*;`,\n 'elif command -v dnf >/dev/null 2>&1; then',\n ` dnf install -y ${list};`,\n 'elif command -v microdnf >/dev/null 2>&1; then',\n ` microdnf install -y ${list};`,\n 'else',\n ` echo \"no supported package manager (apt-get/dnf) for: ${list}\" >&2; exit 66;`,\n 'fi',\n ].join(' ');\n}\n\n/** OS prerequisites, if any. Always root. */\nasync function installPackages(\n transport: SyncTransport,\n pkgs: readonly string[],\n): Promise<{ ok: boolean; detail: string }> {\n const r = await transport.exec(asRootScript(renderPackageInstall(pkgs)), { user: 'root' });\n return { ok: r.exitCode === 0, detail: `${r.stdout}\\n${r.stderr}`.trim() };\n}\n\n/**\n * Ensure `agent`'s binary is on PATH in the box, installing it if absent.\n *\n * The probe runs as the transport's default user (the box user) because that\n * is whose PATH matters — Claude installs into `~/.local/bin`, so a root probe\n * would miss it.\n */\nexport async function ensureAgentInstalled(\n transport: SyncTransport,\n agent: string,\n opts: { onProgress?: (line: string) => void; settings?: AgentSettings } = {},\n): Promise<EnsureAgentInstalledResult> {\n const spec = resolveAgentSpec(agent);\n const probe = await transport.exec(['sh', '-c', `command -v ${spec.binary}`]);\n if (probe.exitCode === 0) return { installed: false };\n\n opts.onProgress?.(`installing ${spec.id} (absent from this box image)`);\n // The agent's own settings pick an alternate recipe when it declared one\n // (`claude.install: npm`); an agent that declared none falls through to its\n // default recipe.\n //\n // Default them from config rather than requiring every caller to pass them:\n // the bake path threads settings explicitly, but the runtime callers (claude\n // start, the dashboard's agent switch, the cloud attach paths) do not — and a\n // host that set npm BECAUSE the native CDN 403s would otherwise hit that same\n // CDN when adding claude to an existing box.\n const settings = opts.settings ?? (await resolveConfiguredSettings(spec.id));\n const install = resolveAgentInstall(spec.install, settings);\n\n if (install.packages && install.packages.length > 0) {\n const pkgs = await installPackages(transport, install.packages);\n if (!pkgs.ok) {\n const names = install.packages.join(', ');\n if (install.packagesOptional) {\n // A soft dependency must never cost the user a box. Codex's bubblewrap\n // is the case that matters: without it Codex falls back to a bundled\n // sandbox and warns, so aborting create over it trades a warning for a\n // total failure -- and on Amazon Linux the package may not exist at all.\n opts.onProgress?.(\n `${spec.id}: optional prerequisites (${names}) could not be installed; continuing without them`,\n );\n } else {\n throw new AgentInstallError(\n `${spec.id}: installing its prerequisites (${names}) failed.\\n${pkgs.detail.slice(-600)}`,\n );\n }\n }\n }\n\n const settingEnv = renderAgentSettingEnv(settings);\n const script = settingEnv + renderInstallRecipe(install.recipe);\n // `box-user` recipes must NOT be escalated: Claude's native installer writes\n // to the invoking user's ~/.local/bin, so running it as root would install\n // into /root and leave the box user with no `claude` on PATH.\n const cmd = install.runAs === 'root' ? asRootScript(script) : ['sh', '-lc', script];\n const run = await transport.exec(cmd, install.runAs === 'root' ? { user: 'root' } : undefined);\n if (run.exitCode !== 0) {\n throw new AgentInstallError(\n `${spec.id} is not in this box's image and installing it failed (exit ${String(run.exitCode)}). ` +\n `This box was likely created from a checkpoint or base image captured before ` +\n `${spec.id} support — recapture the project checkpoint from a fresh box. ` +\n `Install output:\\n${`${run.stdout}\\n${run.stderr}`.trim().slice(-600)}`,\n );\n }\n\n if (install.postInstall) {\n const post = await transport.exec(asRootScript(settingEnv + install.postInstall), {\n user: 'root',\n });\n if (post.exitCode !== 0) {\n throw new AgentInstallError(\n `${spec.id}: post-install step failed (exit ${String(post.exitCode)}).\\n${`${post.stdout}\\n${post.stderr}`.trim().slice(-600)}`,\n );\n }\n }\n\n // Confirm the binary actually landed on the box user's PATH. An installer\n // that exits 0 without producing a usable binary is a real failure mode\n // (a 403 masked by a wrapper, a wrong install prefix), and finding out here\n // beats a confusing \"session exited immediately\" at attach time.\n const verify = await transport.exec(['sh', '-lc', `command -v ${spec.binary}`]);\n if (verify.exitCode !== 0) {\n throw new AgentInstallError(\n `${spec.id}: the installer reported success but \\`${spec.binary}\\` is still not on PATH in the box.`,\n );\n }\n\n // Seed the login, as FILES rather than a mount.\n //\n // Reaching here means the box was not built for this agent, so its config\n // volume is not mounted — and docker fixes mounts at `docker run`, so we\n // cannot add one to a running container. Syncing the host-side volume would\n // write somewhere this box can't see and leave the agent unauthenticated\n // with no visible error. Pushing the credential file is what the cloud\n // providers already do on every create (`TransportCaps.ephemeralFs`), so\n // this is the established path, not a workaround. The credential watcher and\n // `extractAgentCredentials` still carry any resulting login back to the host.\n //\n // Best-effort: a box whose agent simply isn't logged in on the host is a\n // normal state, and the agent's own login flow handles it.\n try {\n const credential = await resolveHostCredential(spec.id);\n if (credential !== null) {\n await pushCredentialToBox(transport, spec.id, credential);\n opts.onProgress?.(`seeded ${spec.id} credentials into the box`);\n }\n } catch (err) {\n opts.onProgress?.(\n `could not seed ${spec.id} credentials (${err instanceof Error ? err.message : String(err)}); sign in inside the box`,\n );\n }\n\n return { installed: true };\n}\n","/**\n * Concern: env/config files (`.env`, `secrets.toml`, `agentbox.yaml`, …) copied\n * host→box into `/workspace` at create, gitignore-bypassing.\n *\n * Unifies docker `copyHostEnvFilesToBox` (`sandbox-docker/host-export.ts`) and\n * cloud `uploadEnvFiles` (`sandbox-cloud/env-files.ts`): the host-side `find` +\n * `tar --null -T -` pack is identical across providers and lives here; the only\n * difference — how the tarball is extracted into the box — is the transport's\n * `applyTarball`. Both providers now delegate here, injecting their transport.\n *\n * Best-effort: a scan/pack failure or empty match set logs and returns the count\n * rather than throwing — a missing optional secret must not abort a healthy box.\n */\n\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { SyncTransport } from '@agentbox/core';\nimport type { SyncContext } from '../context.js';\n\n/**\n * Default env/config file basename globs. These are almost always gitignored,\n * so a normal gitignore-aware pull skips them; this list opts them back in.\n * `agentbox.yaml` is included so an in-box `/agentbox-setup`-generated file\n * lands on the host even before it's committed.\n */\nexport const DEFAULT_ENV_PATTERNS = [\n '.env',\n '.env.*',\n '.envrc',\n '.dev.vars',\n 'secrets.toml',\n 'local.settings.json',\n 'appsettings.*.json',\n 'agentbox.yaml',\n];\n\n/** Directories the env-file `find` prunes — heavy or never-relevant. */\nexport const ENV_PRUNE_DIRS = [\n 'node_modules',\n '.git',\n '.venv',\n 'venv',\n '__pycache__',\n 'dist',\n '.next',\n 'build',\n];\n\nfunction nameGroup(names: string[]): string[] {\n const out: string[] = [];\n names.forEach((n, i) => {\n if (i > 0) out.push('-o');\n out.push('-name', n);\n });\n return out;\n}\n\n/**\n * Host-side `find` argv enumerating env/config files by basename glob, pruning\n * `ENV_PRUNE_DIRS`. Rooted at `.` (run with cwd = the host workspace) with\n * `-print0` (BSD `find` on macOS has no `-printf`); `./relpath` entries feed\n * `tar -C <workspace> --null -T -` directly.\n */\nexport function buildHostEnvFindArgs(patterns: string[]): string[] {\n return [\n 'find',\n '.',\n '(',\n '-type',\n 'd',\n '(',\n ...nameGroup(ENV_PRUNE_DIRS),\n ')',\n '-prune',\n ')',\n '-o',\n '(',\n '-type',\n 'f',\n '(',\n ...nameGroup(patterns),\n ')',\n '-print0',\n ')',\n ];\n}\n\n/**\n * Raw `find` output relative to `workspaceDir` — `./relpath` entries, NUL-split,\n * NO `./` stripping. This is what feeds `tar -C <workspaceDir> --null -T -`\n * (which handles `./relpath` directly), so `pushEnvFiles` uses it verbatim to\n * stay byte-identical to the pre-refactor copy. Empty on a scan failure or empty\n * pattern set (best-effort).\n */\nasync function findEnvFilesForTar(workspaceDir: string, patterns: string[]): Promise<string[]> {\n if (patterns.length === 0) return [];\n const found = await execa('find', buildHostEnvFindArgs(patterns).slice(1), {\n cwd: workspaceDir,\n reject: false,\n });\n if (found.exitCode !== 0) return [];\n return String(found.stdout)\n .split('\\0')\n .filter((p) => p.length > 0);\n}\n\n/**\n * Run `buildHostEnvFindArgs` against `workspaceDir` and return the matched\n * relative paths with the leading `./` stripped — the display/preview form used\n * by the setup wizard's multiselect. Pure host-side helper (no box mutation).\n * Empty on a scan failure or empty pattern set (best-effort).\n */\nexport async function scanHostEnvFiles(\n workspaceDir: string,\n patterns: string[],\n): Promise<string[]> {\n const raw = await findEnvFilesForTar(workspaceDir, patterns);\n return raw.map((p) => p.replace(/^\\.\\//, '')).filter((p) => p.length > 0);\n}\n\nexport interface PushEnvFilesResult {\n /** Number of files written into the box. 0 when nothing matched. */\n copied: number;\n}\n\n/**\n * Copy the host's env/config files (selected by `patterns`) into the box's\n * `/workspace`, gitignore-bypassing. Files land owned by uid 1000 (`vscode`).\n */\nexport async function pushEnvFiles(\n ctx: SyncContext,\n transport: SyncTransport,\n patterns: string[],\n): Promise<PushEnvFilesResult> {\n const list = await findEnvFilesForTar(ctx.hostWorkspace, patterns);\n if (list.length === 0) return { copied: 0 };\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-envfiles-'));\n const localTar = join(stage, 'envfiles.tar');\n try {\n const packed = await execa(\n 'tar',\n ['-C', ctx.hostWorkspace, '--null', '-T', '-', '-cf', localTar],\n {\n input: list.join('\\0'),\n reject: false,\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs.\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n },\n );\n if (packed.exitCode !== 0) {\n ctx.onLog(`warning: env-file tar pack failed: ${String(packed.stderr).slice(0, 300)}`);\n return { copied: 0 };\n }\n try {\n await transport.applyTarball(localTar, ctx.boxWorkspace, { uid: 1000 });\n } catch (err) {\n ctx.onLog(\n `warning: env-file copy into box failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return { copied: 0 };\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n return { copied: list.length };\n}\n","/**\n * Concern: files (`carry:` block from `agentbox.yaml`) copied host→box to\n * declared destinations that may live anywhere in the box (not constrained to\n * /workspace).\n *\n * carry is the most provider-divergent concern, so this module deliberately\n * unifies only the *decision* logic — the pure `planCarryEntry` below — and\n * leaves each provider's *apply* mechanism byte-identical:\n * - docker `copyOneEntry` (`sandbox-docker/host-export.ts`): `streamTarPipe`\n * (stdin, no temp file) + separate `docker exec --user 0:0` calls.\n * - cloud `uploadOneEntry` (`sandbox-cloud/carry.ts`): a staged temp tar +\n * `uploadFile` + ONE combined bash command (splitting/nesting it reintroduces\n * a Vercel `$(...)`/`while` hang — see the note in that file).\n *\n * Both apply paths share the same up-front decisions (`~/`→`/home/vscode`\n * expansion, file-vs-dir, exclude, owner/mode defaults, rename-needed,\n * parent-chain-needed). Those live here so the two providers can't drift.\n */\n\nimport type { ResolvedCarryEntry } from '@agentbox/core';\n\n/**\n * Hardcoded in-box home — every box runs as a user named `vscode` whose home is\n * this path. Its *uid* is NOT fixed: docker/hetzner/digitalocean/daytona land on\n * 1000, but vercel and e2b `useradd` without `-u` (their base images already\n * hold 1000), so the number is whatever was free when the base was baked. Nothing\n * here may depend on it — see {@link CarryPlan.chownArgs}.\n */\nexport const BOX_HOME = '/home/vscode';\n\n/** dirname() that always uses '/' regardless of host OS (the box is linux). */\nexport function dirnameUnix(p: string): string {\n const i = p.lastIndexOf('/');\n if (i <= 0) return '/';\n return p.slice(0, i);\n}\n\n/** basename() that always uses '/' regardless of host OS (the box is linux). */\nexport function basenameUnix(p: string): string {\n const i = p.lastIndexOf('/');\n return i < 0 ? p : p.slice(i + 1);\n}\n\n/**\n * The shared, byte-for-byte carry decisions both providers apply. Everything\n * here is a pure function of the entry; nothing touches the host FS or the box.\n */\nexport interface CarryPlan {\n /** `absDest` with `~/` expanded to `/home/vscode` (host-side, never in-box). */\n boxDest: string;\n /** True for a `dir` entry, false for a `file` entry. */\n isDir: boolean;\n /**\n * Dir to `mkdir -p` before extracting: the dest itself for a dir, the dest's\n * parent for a file. Trailing slashes on the dest are stripped first.\n */\n parentDir: string;\n /** tar `--exclude` patterns (dir entries only; empty for files). */\n exclude: string[];\n /**\n * argv tokens naming the `chown` target. Default `['--reference=/home/vscode']`\n * — the box user, whatever uid the provider assigned it (see {@link BOX_HOME}).\n * An explicit `user:` gives `['0:0']` / `['33:33']`.\n *\n * `--reference` rather than a name: hetzner/digitalocean may rename an existing\n * uid-1000 account into `vscode` and leave its primary group named `ubuntu`, and\n * a `useradd` without `-u` does not guarantee gid == uid — so the home dir is\n * the only thing that reliably carries both halves of the answer.\n *\n * Contains no shell metacharacters: splice into an argv, or `.join(' ')` into a\n * command string, unquoted.\n */\n chownArgs: string[];\n /** Zero-padded octal `chmod -R` arg, or undefined when no mode is set. */\n mode?: string;\n /** Source basename inside the packed tar (file entries only; '' for dirs). */\n fileBase: string;\n /** Dest basename (file entries only; '' for dirs). */\n destBase: string;\n /** File dest basename differs from the source → `mv` after extract. */\n renameNeeded: boolean;\n /**\n * Dest is under `$HOME` with a non-`$HOME` immediate parent, so the\n * root-created parent chain must be chowned back with {@link chownArgs}.\n * System paths (`/etc/*`, …) are left untouched.\n */\n parentChainNeeded: boolean;\n}\n\n/**\n * Compute the shared carry decisions for one entry. Returns `null` for a\n * `missing` (optional + absent-on-host) entry, which both providers skip.\n */\nexport function planCarryEntry(entry: ResolvedCarryEntry): CarryPlan | null {\n if (entry.kind === 'missing') return null;\n\n // ~/ expands to /home/vscode at this layer (host-side), NOT inside the box's\n // shell — so we never depend on the executing user's $HOME (which is /root\n // when the docker path runs `--user 0:0`).\n const boxDest = entry.absDest.startsWith('~/')\n ? `${BOX_HOME}/${entry.absDest.slice(2)}`\n : entry.absDest;\n const boxDestNoSlash = boxDest.endsWith('/') ? boxDest.slice(0, -1) : boxDest;\n\n const isDir = entry.kind === 'dir';\n const parentDir = isDir ? boxDestNoSlash : dirnameUnix(boxDestNoSlash);\n const exclude = isDir ? (entry.exclude ?? []) : [];\n // Default: whoever owns the box user's home, resolved in-box at chown time.\n // An explicit `user:` stays numeric — `user: 0` lands root:root.\n const chownArgs =\n entry.user === undefined\n ? [`--reference=${BOX_HOME}`]\n : [`${String(entry.user)}:${String(entry.user)}`];\n const mode = entry.mode !== undefined ? entry.mode.toString(8).padStart(4, '0') : undefined;\n\n const fileBase = isDir ? '' : basenameUnix(entry.absSrc);\n const destBase = isDir ? '' : basenameUnix(boxDest);\n const renameNeeded = !isDir && fileBase !== destBase;\n\n // `mkdir -p` runs as root, so any new dirs between $HOME and dirname(dest) are\n // root-owned. Only walk when the dest is under $HOME — system paths keep their\n // existing ownership.\n const parentChainNeeded = boxDest.startsWith(`${BOX_HOME}/`) && dirnameUnix(boxDest) !== BOX_HOME;\n\n return {\n boxDest,\n isDir,\n parentDir,\n exclude,\n chownArgs,\n mode,\n fileBase,\n destBase,\n renameNeeded,\n parentChainNeeded,\n };\n}\n","/**\n * Claude-specific host/box path helpers, shared by every provider's sync layer.\n *\n * Moved here (from `@agentbox/sandbox-docker`'s `host-stage.ts`) so the cloud\n * dynamic-sync path can reuse them without importing the docker package — the\n * dependency leak the sync refactor closes. `host-stage.ts` re-exports these for\n * its existing importers, so nothing else moves.\n */\n\nimport { readdir, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Claude Code keys per-project state (memory, sessions, history) under\n * `~/.claude/projects/<encoded>/`, where `<encoded>` is the project's absolute\n * path with every non-alphanumeric char replaced by `-`. Inside every box the\n * workspace is `/workspace`, so its key is always `-workspace`. We duplicate\n * the rule here (rather than importing apps/cli's `encodeClaudeProjectsDir`)\n * because the sync layer must not depend on the CLI package.\n */\nexport function encodeClaudeProjectsKey(absPath: string): string {\n return absPath.replace(/[^a-zA-Z0-9]/g, '-');\n}\n\n/** In-box Claude project dir for `/workspace` (fixed for every box). */\nexport const BOX_CLAUDE_PROJECT_DIR = '/home/vscode/.claude/projects/-workspace';\n\n/**\n * Resolve the host's `~/.claude/projects/<encode(hostWorkspace)>/memory` dir,\n * or `null` when it's absent or empty (so callers no-op rather than seed an\n * empty tree). `hostHome` is overridable for tests.\n */\nexport async function resolveClaudeMemoryDir(\n hostWorkspace: string,\n hostHome: string = homedir(),\n): Promise<string | null> {\n if (hostWorkspace.length === 0) return null;\n const memDir = join(\n hostHome,\n '.claude',\n 'projects',\n encodeClaudeProjectsKey(hostWorkspace),\n 'memory',\n );\n if (!(await pathExists(memDir))) return null;\n try {\n const entries = await readdir(memDir);\n if (entries.length === 0) return null;\n } catch {\n return null;\n }\n return memDir;\n}\n","/**\n * Host-side symlink pre-scan shared by the skills/agents-volume seed and the\n * claude static stage. Pure filesystem inspection (no docker, no box), so it\n * lives in the sync layer and both providers reuse it. Moved here from\n * `@agentbox/sandbox-docker`'s `claude.ts`, which re-exports it for its existing\n * importers.\n */\n\nimport { readdir, realpath, stat } from 'node:fs/promises';\nimport { isAbsolute, join, relative } from 'node:path';\n\nfunction isUnder(parent: string, child: string): boolean {\n const rel = relative(parent, child);\n return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));\n}\n\n/**\n * Walk `root` and return rsync-style relative paths of every symlink the\n * in-container sync can't dereference, so we can `--exclude` them. Two cases\n * abort the whole sync under `--copy-unsafe-links` if left in:\n *\n * - Broken on the host (e.g. claude's `debug/latest` once an older debug file\n * is reaped).\n * - Valid on the host but pointing OUTSIDE the trees the helper container\n * mounts (`reachableRoots`: `~/.claude` itself and, when present, `~/.agents`\n * at `/.agents`). The referent then has \"no referent\" inside the box — e.g. a\n * dev's `~/.claude/skills/*` symlinked into an agentbox source checkout.\n *\n * A symlinked directory whose target IS reachable can still hide an unsyncable\n * link one level down: `~/.claude/skills/<name>` -> `~/.agents/skills/<name>`\n * (reachable) whose `SKILL.md` is an ABSOLUTE link into a repo checkout (not\n * mounted). rsync's `--copy-unsafe-links` dereferences the reachable dir link\n * and descends into it, then aborts on the nested absolute link. So when a\n * symlink resolves into a reachable tree we recurse into the resolved target,\n * reporting nested findings under the symlink's path as rsync transfers it\n * (the link name in `root`, not the resolved `~/.agents` path). An ancestry\n * guard (`onPath`) blocks symlink cycles without suppressing the same resolved\n * dir reached under a *different* virtual prefix — e.g. two skills symlinked to\n * one shared target must each report their nested unsyncable link, or rsync\n * still aborts on the prefix we skipped.\n */\nexport async function findUnsyncableSymlinks(\n root: string,\n reachableRoots: string[],\n): Promise<string[]> {\n // realpath the reachable roots so a symlinked ancestor (e.g. macOS\n // /var -> /private/var) doesn't make a containment check spuriously fail.\n const reachable = await Promise.all(\n reachableRoots.map(async (r) => {\n try {\n return await realpath(r);\n } catch {\n return r;\n }\n }),\n );\n const unsyncable: string[] = [];\n // Resolved dirs currently on the recursion path. Guards against symlink\n // cycles (a link pointing at an ancestor) while still allowing the same dir\n // to be re-walked under a different virtual prefix once this branch unwinds.\n const onPath = new Set<string>();\n // `realDir` is the filesystem directory to read; `virtualDir` is its path as\n // rsync sees it under `root` (they diverge once we follow a symlinked dir).\n async function walk(realDir: string, virtualDir: string): Promise<void> {\n if (onPath.has(realDir)) return;\n onPath.add(realDir);\n try {\n let entries;\n try {\n entries = await readdir(realDir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const ent of entries) {\n const realFull = join(realDir, ent.name);\n const virtualFull = virtualDir ? join(virtualDir, ent.name) : ent.name;\n if (ent.isSymbolicLink()) {\n let real: string;\n try {\n real = await realpath(realFull);\n } catch {\n unsyncable.push(virtualFull); // broken on the host\n continue;\n }\n if (!reachable.some((r) => isUnder(r, real))) {\n unsyncable.push(virtualFull); // target not mounted in the box\n continue;\n }\n // Reachable target: rsync will dereference + descend, so check inside\n // it too for nested unsyncable links, keyed to the symlink's path.\n const st = await stat(real).catch(() => null);\n if (st?.isDirectory()) await walk(real, virtualFull);\n } else if (ent.isDirectory()) {\n await walk(realFull, virtualFull);\n }\n }\n } finally {\n onPath.delete(realDir);\n }\n }\n await walk(root, '');\n return unsyncable;\n}\n","/**\n * Concern: skills — the shared `~/.agents` tree (`~/.agents/skills/<name>`, the\n * cross-agent Agent Skills location) seeded host→box so the in-box agents see\n * the same skill set the host does.\n *\n * On docker this is a persistent shared volume seeded from the host via the\n * transport's `seedVolumeFromHost` (a throwaway rsync helper container). Cloud\n * has no helper container (`caps.helperContainer === false`) — its static config\n * is baked into the prepare-time snapshot via `stageAgentsStaticForUpload` — so\n * cloud never calls this.\n *\n * The host is authoritative and the sync is additive (no `--delete`). Skills\n * routinely symlink files into checkouts, so the seed dereferences reachable\n * links (`copyUnsafeLinks`) and excludes the ones the box can't resolve (broken\n * on the host or pointing outside the mounted tree — see `findUnsyncableSymlinks`),\n * or rsync aborts with \"symlink has no referent\".\n */\n\nimport { stat } from 'node:fs/promises';\nimport type { SyncTransport } from '@agentbox/core';\nimport { findUnsyncableSymlinks } from '../host-links.js';\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface SeedAgentsVolumeArgs {\n /** Transport bound to the box's provider. Must expose `seedVolumeFromHost`. */\n transport: SyncTransport;\n /** The shared agents-config volume name (already ensured to exist). */\n volume: string;\n /** Host `~/.agents` dir. */\n hostAgents: string;\n /**\n * Sync host → volume when true AND the host `~/.agents` exists. When false or\n * absent, the volume is only made writable by the in-box `vscode` user.\n */\n syncFromHost: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface SeedAgentsVolumeResult {\n /** True when the rsync helper ran (syncFromHost was true AND host had `~/.agents`). */\n synced: boolean;\n}\n\n/**\n * Seed (or make writable) the shared `~/.agents` volume via the transport's\n * persistent-volume seam. The caller owns volume creation + `created`\n * detection; this owns the host→volume sync decision so both providers (only\n * docker today) share it.\n */\nexport async function seedAgentsVolume(\n args: SeedAgentsVolumeArgs,\n): Promise<SeedAgentsVolumeResult> {\n const seed = args.transport.seedVolumeFromHost;\n if (!seed) throw new Error('seedAgentsVolume requires a transport with seedVolumeFromHost');\n\n const willSync = args.syncFromHost && (await pathExists(args.hostAgents));\n if (!willSync) {\n // No host ~/.agents to sync — an empty source set still makes the (possibly\n // freshly created, root-owned) volume root writable by the in-box vscode\n // user. Best-effort: a failed chown must not abort box creation (the sync\n // path below, by contrast, propagates — a botched skills sync is worth\n // surfacing).\n try {\n await seed.call(args.transport, args.volume, []);\n } catch (err) {\n args.onLog?.(\n `skills: volume writable-chown failed (ignored): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n return { synced: false };\n }\n\n // `--copy-unsafe-links` dereferences a skill's symlinks pointing outside\n // ~/.agents into real files; the ones it can't resolve (broken / out-of-tree)\n // are excluded so the sync doesn't abort with \"symlink has no referent\".\n const excludes = (await findUnsyncableSymlinks(args.hostAgents, [args.hostAgents])).map(\n (rel) => `/${rel}`,\n );\n await seed.call(args.transport, args.volume, [\n { hostDir: args.hostAgents, destSubpath: '', exclude: excludes, copyUnsafeLinks: true },\n ]);\n if (excludes.length > 0) {\n args.onLog?.(\n `skills: excluded ${String(excludes.length)} unsyncable symlink(s) from ~/.agents`,\n );\n }\n return { synced: true };\n}\n","/**\n * Concern: git / workspace — seed the box's per-box worktree(s) from the host at\n * create, and resync them with the host's current state on session restart\n * (box-wins on every conflict). This is the concrete `box-wins-content-hash`\n * conflict policy the reconciler contract (`@agentbox/core` `sync/reconciler.ts`)\n * anticipates as its first consumer.\n *\n * This file holds the provider-neutral *resync* half: the pure untracked-overlay\n * classifier + the `resyncWorkspace` orchestration, driven entirely through the\n * `WorkspaceResyncPorts` seam so it's a pure function of its I/O (golden-tested\n * against a scripted fake). The docker/cloud providers supply the ports. Docker\n * is the only implementation today; a cloud one closes the \"Phase 2\" gap (a\n * cloud box gets no workspace resync yet). Workspace *seed* (worktree add +\n * bind-mount replay) stays docker-specific — it has no cloud analog (cloud\n * clones) — and is not moved.\n */\n\nimport { createHash } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { RepoResyncResult, ResyncWorktree, WorkspaceResyncPorts } from '@agentbox/core';\n\n/**\n * Sentinel token the box-side probe emits for a path that exists but is NOT a\n * plain file (a dir or symlink) — always a conflict so we never clobber it.\n */\nexport const NON_REGULAR_TOKEN = '-';\n\n/**\n * Classify a host untracked file against what the box already has at that path.\n * `boxToken` is the box-side probe result: `undefined` when the path is absent\n * in the box (safe to copy), {@link NON_REGULAR_TOKEN} when it exists but isn't\n * a plain file, otherwise the sha256 of the box file's contents. `hostHash` is\n * the sha256 of the host file. A byte-identical file is a no-op (neither copied\n * nor reported); anything else that already exists is a conflict the box keeps\n * (box wins — the host change is shadowed, no marker left).\n */\nexport function classifyUntrackedOverlay(\n boxToken: string | undefined,\n hostHash: string,\n): 'copy' | 'identical' | 'conflict' {\n if (boxToken === undefined) return 'copy';\n if (boxToken === NON_REGULAR_TOKEN) return 'conflict';\n return boxToken === hostHash ? 'identical' : 'conflict';\n}\n\n/** Split a `-z` (NUL-delimited) git output into non-empty entries. */\nfunction splitNul(s: string): string[] {\n return s.split('\\0').filter((p) => p.length > 0);\n}\n\n/** Conflicted (unmerged) paths in the box worktree, if any. */\nasync function unmergedPaths(ports: WorkspaceResyncPorts, ct: string): Promise<string[]> {\n const r = await ports.boxGit(ct, ['diff', '--name-only', '--diff-filter=U', '-z']);\n return r.exitCode === 0 ? splitNul(r.stdout) : [];\n}\n\n/**\n * Resync each box worktree with the host's current state: merge the host's\n * checked-out branch into the box's per-box branch, then overlay the host's\n * uncommitted (stash) + untracked changes. The box wins every conflict — the\n * host change is skipped (no markers left) and the affected paths are returned\n * so the caller can warn the agent.\n *\n * Provider-neutral: all I/O goes through {@link WorkspaceResyncPorts}. On docker\n * the host `.git/` is bind-mounted so the host branch ref is already present in\n * the box and the merge needs no fetch (the same property create-time carry-over\n * relies on). Best-effort throughout — a step that fails is logged and skipped\n * rather than aborting the box start.\n */\nexport async function resyncWorkspace(\n worktrees: ResyncWorktree[],\n ports: WorkspaceResyncPorts,\n onLog?: (line: string) => void,\n): Promise<RepoResyncResult[]> {\n const log = onLog ?? (() => {});\n const results: RepoResyncResult[] = [];\n\n for (const w of worktrees) {\n const ct = w.containerPath;\n const hostMain = w.hostMainRepo;\n const boxBranch = w.branch;\n const res: RepoResyncResult = { containerPath: ct, mergeConflicts: [], overlaySkipped: [] };\n\n // --- host state (host-side git; no side effects on the worktree) ---\n const hostRef = await ports.resolveHostRef(hostMain);\n if (!hostRef) {\n log(`resync: ${ct}: could not resolve host ref; skipping`);\n results.push(res);\n continue;\n }\n const hostStashSha = await ports.createHostStash(hostMain);\n const hostUntracked = await ports.listHostUntracked(hostMain);\n\n // --- merge host commits into the box branch (skip when merging self) ---\n if (hostRef !== boxBranch) {\n // Stash the box's own uncommitted tracked changes so the merge can run;\n // restored on top afterward (box keeps them). Untracked box files stay.\n const status = await ports.boxGit(ct, ['status', '--porcelain']);\n const boxDirty = status.stdout\n .split('\\n')\n .some((line) => line.length > 0 && !line.startsWith('??'));\n let boxStashed = false;\n if (boxDirty) {\n const push = await ports.boxGit(ct, ['stash', 'push', '-m', 'agentbox-resync']);\n boxStashed = push.exitCode === 0;\n }\n\n const newCommits = await ports.boxGit(ct, [\n 'rev-list',\n '--count',\n `${boxBranch}..${hostRef}`,\n ]);\n const n = newCommits.exitCode === 0 ? newCommits.stdout.trim() : '?';\n const merge = await ports.boxGit(ct, ['merge', '--no-commit', hostRef]);\n const mergeInProgress =\n (await ports.boxGit(ct, ['rev-parse', '-q', '--verify', 'MERGE_HEAD'])).exitCode === 0;\n const conflicts = await unmergedPaths(ports, ct);\n if (conflicts.length > 0) {\n await ports.boxGit(ct, ['checkout', '--ours', '--', ...conflicts]);\n await ports.boxGit(ct, ['add', '--', ...conflicts]);\n res.mergeConflicts.push(...conflicts);\n }\n if (mergeInProgress) {\n await ports.boxGit(ct, [\n '-c',\n 'user.name=agentbox',\n '-c',\n 'user.email=agentbox@users.noreply.github.com',\n 'commit',\n '--no-edit',\n ]);\n log(\n `resync: ${ct}: merged ${n} new host commit(s) from ${hostRef}` +\n (conflicts.length > 0\n ? ` (${String(conflicts.length)} conflict(s) kept box version)`\n : ''),\n );\n } else if (merge.exitCode === 0) {\n log(`resync: ${ct}: ${n === '0' ? 'already up to date' : `fast-forwarded to ${hostRef}`}`);\n } else {\n // Hard failure (e.g. an untracked box file would be overwritten). Leave\n // the box untouched.\n await ports.boxGit(ct, ['merge', '--abort']);\n log(\n `resync: ${ct}: merge skipped (${(merge.stderr || merge.stdout).trim().split('\\n')[0]})`,\n );\n }\n\n if (boxStashed) {\n const pop = await ports.boxGit(ct, ['stash', 'pop']);\n if (pop.exitCode !== 0) {\n // Box's uncommitted edits clash with the merged host change. Keep the\n // box's version (stash side = --theirs), drop the dangling stash.\n const popConflicts = await unmergedPaths(ports, ct);\n for (const p of popConflicts) {\n await ports.boxGit(ct, ['checkout', '--theirs', '--', p]);\n await ports.boxGit(ct, ['reset', '-q', '--', p]);\n }\n await ports.boxGit(ct, ['stash', 'drop']);\n }\n }\n }\n\n // --- overlay host uncommitted (stash) on top, box wins on conflict ---\n if (hostStashSha) {\n const apply = await ports.boxGit(ct, ['stash', 'apply', hostStashSha]);\n if (apply.exitCode !== 0) {\n const conflicts = await unmergedPaths(ports, ct);\n for (const p of conflicts) {\n // ours = box working tree, theirs = host stash → keep box, unstage.\n await ports.boxGit(ct, ['checkout', '--ours', '--', p]);\n await ports.boxGit(ct, ['reset', '-q', '--', p]);\n }\n if (conflicts.length > 0) res.overlaySkipped.push(...conflicts);\n }\n }\n\n // --- overlay host untracked files; box wins only when it actually differs ---\n if (hostUntracked.length > 0) {\n // Probe the box for each host path. A path absent in the box is copied; a\n // path present and byte-identical is a no-op (NOT a conflict — this is the\n // common case right after create-time seeding copied these same untracked\n // files in); a path present but differing (or a non-regular file we won't\n // clobber) is the box's version we keep and report.\n const boxTokens = await ports.probeUntrackedTokens(ct, hostUntracked);\n const toCopy: string[] = [];\n let identical = 0;\n for (const p of hostUntracked) {\n const boxToken = boxTokens.get(p);\n let hostHash = '';\n if (boxToken !== undefined && boxToken !== NON_REGULAR_TOKEN) {\n try {\n hostHash = await ports.hashHostFile(hostMain, p);\n } catch {\n // Host file vanished/unreadable since `ls-files` — can't copy it and\n // the box already has its own version; keep the box's, don't report.\n identical++;\n continue;\n }\n }\n const verdict = classifyUntrackedOverlay(boxToken, hostHash);\n if (verdict === 'copy') toCopy.push(p);\n else if (verdict === 'conflict') res.overlaySkipped.push(p);\n else identical++;\n }\n if (identical > 0) {\n log(\n `resync: ${ct}: ${String(identical)} untracked host file(s) already identical in box (no-op)`,\n );\n }\n if (toCopy.length > 0) {\n const tar = await ports.packHostFiles(hostMain, toCopy);\n if (tar) {\n await ports.applyTarToBox(ct, tar);\n log(`resync: ${ct}: copied ${String(toCopy.length)} untracked host file(s)`);\n }\n }\n }\n\n results.push(res);\n }\n\n return results;\n}\n\n/**\n * The host-side half of {@link WorkspaceResyncPorts} — read-only git probes on\n * the host's own repo (checked-out ref, an uncommitted-changes stash sha, the\n * gitignore-respecting untracked list, a file content hash, and a tar pack of\n * chosen files). Host git is provider-neutral: it's the host's real repo whether\n * the box is docker or cloud, so both providers reuse these verbatim while\n * supplying their own box-side ports (`boxGit`/`probeUntrackedTokens`/\n * `applyTarToBox`). Each method reproduces the pre-refactor docker\n * `resyncWorkspaceFromHost` command byte-for-byte.\n *\n * The cloud live-box resync (Phase 7.5) reuses `listHostUntracked`/`hashHostFile`/\n * `packHostFiles` unchanged and overrides `resolveHostRef`/`createHostStash`\n * (its host ref/stash are pre-fetched into the box, not merged from a bind mount).\n */\nexport function makeHostGitPorts(): Pick<\n WorkspaceResyncPorts,\n 'resolveHostRef' | 'createHostStash' | 'listHostUntracked' | 'hashHostFile' | 'packHostFiles'\n> {\n return {\n async resolveHostRef(hostMain) {\n const hostBranchProbe = await execa(\n 'git',\n ['-C', hostMain, 'symbolic-ref', '--short', '-q', 'HEAD'],\n { reject: false },\n );\n const hostRef =\n hostBranchProbe.exitCode === 0 && hostBranchProbe.stdout.trim()\n ? hostBranchProbe.stdout.trim()\n : (\n await execa('git', ['-C', hostMain, 'rev-parse', 'HEAD'], { reject: false })\n ).stdout.trim();\n return hostRef || null;\n },\n async createHostStash(hostMain) {\n const stash = await execa('git', ['-C', hostMain, 'stash', 'create'], { reject: false });\n return stash.exitCode === 0 ? stash.stdout.trim() || null : null;\n },\n async listHostUntracked(hostMain) {\n const untracked = await execa(\n 'git',\n ['-C', hostMain, 'ls-files', '--others', '--exclude-standard', '-z'],\n { reject: false },\n );\n return untracked.exitCode === 0 ? splitNul(untracked.stdout) : [];\n },\n async hashHostFile(hostMain, relPath) {\n return createHash('sha256')\n .update(await readFile(join(hostMain, relPath)))\n .digest('hex');\n },\n async packHostFiles(hostMain, relPaths) {\n const tarOut = await execa('tar', ['-C', hostMain, '--null', '-T', '-', '-cf', '-'], {\n input: relPaths.join('\\0'),\n encoding: 'buffer',\n reject: false,\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs;\n // without it the untracked overlay seeds AppleDouble junk into the box\n // on every session-start resync. Same guard as `host-export.ts`.\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n return tarOut.exitCode === 0 ? (tarOut.stdout as Buffer) : null;\n },\n };\n}\n","/**\n * Concern: bot backups — capturing a running box as a set of files that can\n * recreate it, on any provider.\n *\n * A service bot (openclaw today) is a **workspace plus an agent state dir**.\n * Provider checkpoints cannot express that: they are provider-native snapshots\n * and do not cross from e2b to hetzner. A file-shaped bundle does.\n *\n * The bundle lives INSIDE the project, at\n * `<project>/.agentbox/bots/<bot>/<stamp>/`, because `~/.agentbox/` holds copies\n * AgentBox keeps for its own use, not a user's source of truth. That placement\n * is only safe because of the other half of this change: the workspace SEED now\n * drops `.agentbox/` too (`seedExcludeTarArgs`), so a backup is never copied\n * into the next box. The gitignore entry this module writes is the second guard,\n * not the only one.\n *\n * WHAT THIS DELIBERATELY DOES NOT REUSE: `staticPaths[].exclude`. That list is\n * push-direction hygiene and for openclaw it is exactly the identity —\n * `openclaw.json`, the config-journal key, the live `state/`. A backup that\n * dropped them would restore a DIFFERENT bot, which is not a restore. The agent\n * says what a capture must leave behind through `stateBackup.exclude` instead.\n */\n\nimport { execa } from 'execa';\nimport {\n chmod,\n cp,\n lstat,\n mkdir,\n readdir,\n readFile,\n readlink,\n rm,\n symlink,\n writeFile,\n} from 'node:fs/promises';\nimport { join, sep } from 'node:path';\nimport type { Dirent } from 'node:fs';\nimport type { AgentId, BoxRecord, SyncTransport } from '@agentbox/core';\nimport { LIVE_DATABASE_EXCLUDES } from '@agentbox/core';\nimport { findAgentSpec, resolveAgentSpec } from '../registry.js';\nimport { agentPullBoxDir, pullSqliteSnapshot } from '../agent-pull-module.js';\n\n/** Directory under a project that holds every bot's backups. */\nexport const BOTS_DIR_REL = join('.agentbox', 'bots');\n\n/** The single `.gitignore` entry that keeps all of it out of the project repo. */\nexport const BACKUP_GITIGNORE_ENTRY = '.agentbox/';\n\n/**\n * A backup's timestamp, and its directory name.\n *\n * Chosen so a lexicographic sort is a chronological one — `readdir` order is\n * not defined, and every consumer here (prune, `latest`, \"which is newest\")\n * needs an order. `:` is out because it is not a portable path character.\n */\nexport function backupStamp(at: Date = new Date()): string {\n return at\n .toISOString()\n .replace(/\\.\\d+Z$/, 'Z')\n .replace(/:/g, '-');\n}\n\n/**\n * What {@link backupStamp} produces, and the only directory name under a bot\n * that IS a backup.\n *\n * Matched rather than assumed, because the bot dir is not backups-only: a\n * restore writes its live `workspace/` tree there as a sibling of the stamps.\n * Treating \"any dir that is not `latest`\" as a backup would let that tree take a\n * slot in the prune's ordering and, since `workspace` sorts after every stamp,\n * silently make it the newest \"backup\" nothing may delete.\n */\nconst STAMP_RE = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}Z$/;\n\n/** `<project>/.agentbox/bots/<bot>`. */\nexport function botDir(projectRoot: string, bot: string): string {\n return join(projectRoot, BOTS_DIR_REL, bot);\n}\n\n/**\n * Where a bot spawned from this box should live: a sibling of the source bot\n * under the SAME project, `<project>/.agentbox/bots/<name>/workspace`.\n *\n * Decision 7 of the bot plan — the project is the template and its bots are\n * instances of it, so they share one tree and one `.gitignore` entry instead of\n * scattering under `~/.agentbox/clones/`. A box with no project root (one\n * created from a bare directory) keeps the old home-dir default, which is the\n * only answer available.\n *\n * The trailing-segment strip is what stops bots nesting: a box created BY a\n * restore or a clone already runs on `.../.agentbox/bots/<x>/workspace`, and\n * cloning that one must produce a sibling of `<x>`, not\n * `.../bots/<x>/workspace/.agentbox/bots/<y>/workspace`.\n */\nexport function botWorkspaceRoot(projectRoot: string): string {\n const parts = projectRoot.split(sep);\n const n = parts.length;\n if (\n n >= 4 &&\n parts[n - 1] === 'workspace' &&\n parts[n - 3] === 'bots' &&\n parts[n - 4] === '.agentbox'\n ) {\n return parts.slice(0, n - 4).join(sep);\n }\n return projectRoot;\n}\n\n/** `<project>/.agentbox/bots/<bot>/<stamp>`. */\nexport function botBackupDir(projectRoot: string, bot: string, stamp: string): string {\n return join(botDir(projectRoot, bot), stamp);\n}\n\n/** How many backups a bot keeps before the oldest are pruned. */\nexport const DEFAULT_BACKUP_KEEP = 3;\n\n/** Where one backup goes, and what it will capture. */\nexport interface BackupTarget {\n /** The project the bundle is written under. */\n projectRoot: string;\n bot: string;\n stamp: string;\n /** `<project>/.agentbox/bots/<bot>/<stamp>`. */\n dir: string;\n /** Where the workspace half lands. */\n workspaceDir: string;\n keep: number;\n /** The agent whose state to capture; absent when the box has no known one. */\n agent?: AgentId;\n}\n\n/** What a caller may say about a backup. `keep` is a string so a CLI flag and a\n * JSON body reach the same validator. */\nexport interface BackupTargetOptions {\n name?: string;\n keep?: string | number;\n agent?: string;\n}\n\n/**\n * Resolve where this backup goes and what it will capture.\n *\n * `projectRoot ?? workspacePath` is the fallback the hub already uses: the field\n * is absent on records made before it existed, and a backup must not silently\n * pick a different directory for an old box.\n *\n * Shared with the hub deliberately — a route that resolved the bundle path its\n * own way would be a second definition of \"where a bot's backups live\", and the\n * CLI's `--restore` reads back what either of them wrote.\n */\nexport function resolveBackupTarget(box: BoxRecord, opts: BackupTargetOptions): BackupTarget {\n // `botWorkspaceRoot`, not the raw root. A box created BY a restore (or a clone)\n // already runs on `<proj>/.agentbox/bots/<x>/workspace`, so filing its backups\n // under its own project root would nest a second bundle tree inside the live\n // workspace — with its own `latest` and its own prune, invisible from the\n // project the bot actually belongs to. `prepareClone` has always normalized\n // here; backup could not reach the case until the hub exposed both halves.\n const projectRoot = botWorkspaceRoot(box.projectRoot ?? box.workspacePath);\n const bot = (opts.name ?? box.name).trim();\n // Messages here reach an HTTP client as well as a CLI one, so they name the\n // FIELD rather than a flag of a program the caller may not be running.\n if (bot.length === 0 || bot.includes('/') || bot === '.' || bot === '..') {\n throw new Error(`name \"${opts.name ?? ''}\": a bot name must be a single path segment`);\n }\n\n const keep =\n opts.keep === undefined\n ? DEFAULT_BACKUP_KEEP\n : typeof opts.keep === 'number'\n ? opts.keep\n : Number.parseInt(opts.keep, 10);\n if (!Number.isInteger(keep) || keep < 1) {\n throw new Error(`keep \"${String(opts.keep ?? '')}\": expected a positive integer`);\n }\n\n // An explicit `--agent` is checked; a guess off the record is not, because a\n // box whose recorded agent has since been removed from the registry should\n // still get its workspace backed up.\n let agent: AgentId | undefined;\n if (opts.agent) {\n const spec = findAgentSpec(opts.agent);\n if (!spec) throw new Error(`agent \"${opts.agent}\": no such agent`);\n agent = spec.id;\n } else {\n const guess = box.lastAgent ?? box.agents?.[0];\n agent = guess ? findAgentSpec(guess)?.id : undefined;\n }\n\n const stamp = backupStamp();\n const dir = botBackupDir(projectRoot, bot, stamp);\n return { projectRoot, bot, stamp, dir, workspaceDir: join(dir, 'workspace'), keep, agent };\n}\n\n/**\n * Create the bundle's directories before anything writes into them.\n *\n * rsync creates the LAST component of its destination and no more, so a fresh\n * `<project>/.agentbox/bots/<bot>/<stamp>/workspace` is several levels too deep\n * for it and the transfer dies with \"No such file or directory\". The CLI's\n * dry-run pass hits it too, so this cannot wait until the write.\n */\nexport async function prepareBackupDir(target: BackupTarget): Promise<void> {\n await mkdir(target.workspaceDir, { recursive: true });\n}\n\n/** What a backup records about itself, for a later `--restore`. */\nexport interface BackupManifest {\n version: 1;\n stamp: string;\n bot: string;\n boxId: string;\n boxName: string;\n provider: string;\n /** The agent whose state was captured; absent when the box has none. */\n agent?: AgentId;\n /** False when only the workspace was captured. */\n state: boolean;\n /** Relative paths captured through the SQLite online-backup API. */\n databases?: string[];\n /** Whether `node_modules` was kept in the workspace half. */\n includeNodeModules?: boolean;\n createdBy?: string;\n}\n\nexport async function writeBackupManifest(dir: string, m: BackupManifest): Promise<void> {\n await mkdir(dir, { recursive: true });\n await writeFile(join(dir, 'manifest.json'), `${JSON.stringify(m, null, 2)}\\n`, 'utf8');\n}\n\n/**\n * Point `<bot>/latest` at `stamp`.\n *\n * A RELATIVE link, so moving or copying the whole project keeps it valid — an\n * absolute one would silently dangle the moment the bundle is shared, which is\n * one of the things a backup is for.\n */\nexport async function linkLatest(projectRoot: string, bot: string, stamp: string): Promise<void> {\n const link = join(botDir(projectRoot, bot), 'latest');\n await rm(link, { force: true });\n await symlink(stamp, link);\n}\n\n/**\n * The backup directory names under `<bot>`, newest first.\n *\n * Stamp-shaped names only ({@link STAMP_RE}) — `latest` and a restore's live\n * `workspace/` are siblings, not backups.\n */\nexport async function listBackups(projectRoot: string, bot: string): Promise<string[]> {\n let entries: string[];\n try {\n entries = await readdir(botDir(projectRoot, bot));\n } catch {\n return [];\n }\n const dirs: string[] = [];\n for (const name of entries) {\n if (!STAMP_RE.test(name)) continue;\n const st = await lstat(join(botDir(projectRoot, bot), name)).catch(() => null);\n if (st?.isDirectory()) dirs.push(name);\n }\n return dirs.sort().reverse();\n}\n\n/** One bot's backups, newest first, as a project page or a restore picker needs them. */\nexport interface BotListing {\n bot: string;\n /** The stamp `latest` resolves to, when the link is there and intact. */\n latest?: string;\n /** Every backup this bot has, newest first, with its manifest folded in. */\n backups: Array<{\n stamp: string;\n /** Absent when the bundle predates the field or its manifest is unreadable. */\n agent?: AgentId;\n /** False when the bundle carries only a workspace — no identity to restore. */\n state: boolean;\n boxName?: string;\n provider?: string;\n }>;\n}\n\n/**\n * Every bot this project holds a backup of, alphabetically, each with its own\n * backups newest first.\n *\n * The manifest is folded in here rather than left to the caller because the one\n * fact a restore picker must show — does this bundle carry an identity, or only\n * a workspace? — lives in it, and a UI that offered a `state: false` bundle as\n * \"restore this bot\" would be lying about what it is about to do.\n *\n * A bot directory whose manifests are all unreadable still lists: the stamps are\n * real directories, and hiding them would make a half-written backup invisible\n * rather than visibly suspect.\n */\nexport async function listBots(projectRoot: string): Promise<BotListing[]> {\n let names: Dirent[];\n try {\n names = await readdir(join(projectRoot, BOTS_DIR_REL), { withFileTypes: true });\n } catch {\n return []; // no bots dir is the normal case, not an error\n }\n const out: BotListing[] = [];\n for (const e of names.sort((a, b) => a.name.localeCompare(b.name))) {\n if (!e.isDirectory()) continue;\n const stamps = await listBackups(projectRoot, e.name);\n if (stamps.length === 0) continue;\n const backups: BotListing['backups'] = [];\n for (const stamp of stamps) {\n const m = await readBackupManifest(botBackupDir(projectRoot, e.name, stamp)).catch(\n () => null,\n );\n backups.push({\n stamp,\n ...(m?.agent ? { agent: m.agent } : {}),\n state: m?.state === true,\n ...(m?.boxName ? { boxName: m.boxName } : {}),\n ...(m?.provider ? { provider: m.provider } : {}),\n });\n }\n const latest = await readlink(join(botDir(projectRoot, e.name), 'latest')).catch(() => null);\n out.push({\n bot: e.name,\n ...(latest && stamps.includes(latest) ? { latest } : {}),\n backups,\n });\n }\n return out;\n}\n\n/**\n * Keep the `keep` newest backups, remove the rest. Returns what was removed.\n *\n * Never removes what `latest` points at, even if the count says it should: a\n * dangling `latest` is a worse outcome than one extra directory, and the only\n * way the two disagree is a `latest` written by hand.\n */\nexport async function pruneBackups(\n projectRoot: string,\n bot: string,\n keep: number,\n): Promise<string[]> {\n if (keep < 1) return [];\n const all = await listBackups(projectRoot, bot);\n const current = await readlink(join(botDir(projectRoot, bot), 'latest')).catch(() => null);\n const removed: string[] = [];\n for (const name of all.slice(keep)) {\n if (name === current) continue;\n await rm(join(botDir(projectRoot, bot), name), { recursive: true, force: true });\n removed.push(name);\n }\n return removed;\n}\n\n/**\n * Make sure `.agentbox/` is gitignored in `projectRoot`, and say whether the\n * entry had to be written.\n *\n * Asks `git check-ignore` rather than grepping `.gitignore`: the entry may\n * already come from the user's global excludes file, a parent repo, or a\n * differently-spelled rule, and appending a duplicate to someone's file is\n * rude. A non-repo is a no-op, not an error — a bot's project need not be a\n * git repo at all, and that path has no way to leak a backup into a box anyway\n * (the untracked carry-over only exists for a repo).\n *\n * The probe is a path INSIDE the dir, not the dir itself. MEASURED: against a\n * `.agentbox/` rule, `git check-ignore .agentbox` exits 1 — a trailing-slash\n * pattern matches directories only, and git cannot tell that a path which does\n * not exist yet is one. A file under it matches whichever way the rule is\n * spelled, and \"would the file I am about to write be ignored\" is the question\n * that actually matters.\n */\nexport async function ensureBackupGitignored(projectRoot: string): Promise<boolean> {\n const inRepo = await execa('git', ['-C', projectRoot, 'rev-parse', '--git-dir'], {\n reject: false,\n });\n if (inRepo.exitCode !== 0) return false;\n\n const probe = join(BOTS_DIR_REL, '.probe');\n const ignored = await execa('git', ['-C', projectRoot, 'check-ignore', '-q', probe], {\n reject: false,\n });\n if (ignored.exitCode === 0) return false;\n\n const path = join(projectRoot, '.gitignore');\n const existing = await readFile(path, 'utf8').catch(() => '');\n const prefix = existing.length === 0 || existing.endsWith('\\n') ? '' : '\\n';\n await writeFile(\n path,\n `${existing}${prefix}\\n# AgentBox bot backups (workspace + agent identity). Never commit these.\\n${BACKUP_GITIGNORE_ENTRY}\\n`,\n 'utf8',\n );\n return true;\n}\n\nexport interface AgentStateBackupResult {\n /** Relative paths captured through the SQLite online-backup API. */\n databases: string[];\n /** Patterns the agent asked to leave behind. */\n excluded: string[];\n}\n\n/**\n * Copy an agent's whole state dir out of a box, IDENTITY INCLUDED.\n *\n * Two passes, and the split is not an optimization:\n *\n * 1. `pullTree` for the file tree, minus what the agent declared box-specific\n * and minus every live database.\n * 2. each database through {@link pullSqliteSnapshot}, which uses SQLite's own\n * online-backup API.\n *\n * Pass 2 exists because a byte copy of a live database is a torn read — the\n * agent-pull module records the measurement that produced a 4 KB `state_5.sqlite`\n * against a 1.79 MB `-wal`. openclaw's gateway state IS such a database, so a\n * one-pass tar would produce a backup that restores into a broken gateway, and\n * would do it silently.\n */\nexport async function backupAgentState(args: {\n agent: AgentId;\n transport: SyncTransport;\n destDir: string;\n}): Promise<AgentStateBackupResult> {\n const spec = resolveAgentSpec(args.agent);\n const boxDir = agentPullBoxDir(args.agent);\n const excluded = [...(spec.stateBackup?.exclude ?? [])];\n\n await mkdir(args.destDir, { recursive: true });\n await args.transport.pullTree(boxDir, args.destDir, {\n exclude: [...excluded, ...LIVE_DATABASE_EXCLUDES],\n });\n\n const databases = await backupStateDatabases(args, boxDir, excluded);\n\n // The capture holds a live gateway token. `~/.agentbox` has always kept\n // extracted credentials at 0600; this is the same secret in a new place.\n await chmod(args.destDir, 0o700).catch(() => {});\n\n return { databases, excluded };\n}\n\n/** Find and snapshot every live database under the agent's state dir. */\nasync function backupStateDatabases(\n args: { agent: AgentId; transport: SyncTransport; destDir: string },\n boxDir: string,\n excluded: readonly string[],\n): Promise<string[]> {\n const prune = excluded.map((e) => `-path ${quote(`./${e}`)} -prune -o`).join(' ');\n // `-name` rather than the exclude globs: those are tar patterns, and this is\n // find. The two lists are the same shapes, spelled for their own tool.\n const found = await args.transport.exec([\n 'sh',\n '-c',\n `cd ${quote(boxDir)} 2>/dev/null || exit 0; ` +\n `find . ${prune} \\\\( -name '*.sqlite' -o -name '*.db' \\\\) -type f -print 2>/dev/null`,\n ]);\n if (found.exitCode !== 0) return [];\n\n const rels = found.stdout\n .split('\\n')\n .map((l) => l.trim().replace(/^\\.\\//, ''))\n .filter((l) => l.length > 0);\n\n const captured: string[] = [];\n for (const rel of rels) {\n const dest = join(args.destDir, rel);\n await mkdir(join(dest, '..'), { recursive: true });\n const ok = await pullSqliteSnapshot(args.transport, `${boxDir}/${rel}`, dest);\n if (ok) {\n captured.push(rel);\n await chmod(dest, 0o600).catch(() => {});\n }\n }\n return captured;\n}\n\nfunction quote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Why `--restore` cannot also take a box ref, or null when there is no ref.\n *\n * A ref means \"use THIS box\", and the service command is create-or-resume — so\n * the two together resume a named box and then write a backup's identity over\n * it. No reading of `agentbox <agent> foo --restore bar` is safe, so it is\n * refused before anything is resolved rather than reinterpreted.\n */\nexport function boxRefWithRestoreRefusal(boxRef: string | undefined): string | null {\n if (boxRef === undefined) return null;\n return (\n `--restore always creates a new box, so it cannot also take the box ref \"${boxRef}\" — ` +\n 'drop the ref, or name the new box with -n <name>'\n );\n}\n\n/**\n * Why a restore cannot proceed into a directory a box already runs on.\n *\n * `escape` is the caller's own spelling of the way out — a CLI flag, a checkbox\n * label — because the rule is shared but the escape hatch is not, and a web UI\n * that tells the user to \"pass --into <dir>\" is telling them to use a different\n * program.\n */\nexport function existingBoxRefusal(\n existing: { name: string } | null | undefined,\n dir: string,\n escape = 'restore it somewhere else',\n): string | null {\n if (!existing) return null;\n return `box ${existing.name} already runs on ${dir} — ${escape} to restore alongside it`;\n}\n\n/**\n * Why a restore cannot proceed while the box this bundle came from is still\n * running, or null when it may.\n *\n * Two live gateways holding one identity is the multi-tenancy failure a per-box\n * state dir exists to prevent, and a restore is the one operation that can\n * produce it. The box being GONE is the normal case — that is what a restore is\n * for — so an unknown or unprobeable record proceeds silently; only a record we\n * can still see running stops it.\n *\n * Takes the live state rather than probing, so the CLI and the hub can each ask\n * their own provider and share this one rule about the answer — and `escape` for\n * the same reason as {@link existingBoxRefusal}: the rule is shared, the way out\n * is spelled differently in a CLI flag and a web UI checkbox.\n */\nexport function sourceBoxRunningRefusal(\n source: { name: string } | null | undefined,\n liveState: string | null,\n bot: string,\n escape = 'force the restore',\n): string | null {\n if (!source || liveState !== 'running') return null;\n return (\n `box ${source.name} is still running and holds ${bot}'s identity — ` +\n `two live gateways cannot share one. Stop or destroy it, or ${escape}.`\n );\n}\n\n/**\n * Where a restored box's LIVE workspace goes: `<project>/.agentbox/bots/<bot>/workspace`.\n *\n * Deliberately not the bundle's own `workspace/`. That copy is immutable and\n * `keep` may prune it, so a box writing into it would lose its workspace to a\n * later backup.\n */\nexport function restoreWorkspaceDir(projectRoot: string, bot: string): string {\n return join(botDir(projectRoot, bot), 'workspace');\n}\n\n/**\n * Copy a bundle's workspace half to the live directory the restored box runs on.\n *\n * Refuses a non-empty destination unless `force`: the usual reason it is\n * non-empty is an earlier restore of the same bot that is still in use, and\n * overwriting it in place would take the running box's files out from under it.\n */\nexport async function stageRestoreWorkspace(args: {\n bundle: BotBundle;\n workspaceDir: string;\n force?: boolean;\n}): Promise<{ files: number }> {\n await mkdir(args.workspaceDir, { recursive: true });\n const existing = await readdir(args.workspaceDir);\n if (existing.length > 0 && !args.force) {\n throw new Error(\n `${args.workspaceDir} is not empty — pass a different destination, or force to overwrite it`,\n );\n }\n await cp(args.bundle.workspaceDir, args.workspaceDir, { recursive: true, force: true });\n return { files: (await readdir(args.workspaceDir)).length };\n}\n\n/**\n * What a bundle can put back: both halves, or the workspace alone.\n *\n * A backup of a box with no agent — or one whose state capture failed — carries\n * a `workspace/` and nothing else. Restoring it is still worth doing; claiming\n * it brought an identity is not, and *failing* over it would throw away a\n * perfectly good box the caller had already created.\n */\nexport function restoreScope(bundle: BotBundle): 'workspace' | 'workspace+state' {\n return bundle.stateDir ? 'workspace+state' : 'workspace';\n}\n\n/** A bundle resolved on disk, ready to restore from. */\nexport interface BotBundle {\n /** `<project>/.agentbox/bots/<bot>/<stamp>`. */\n dir: string;\n bot: string;\n stamp: string;\n manifest: BackupManifest;\n /** The workspace half. */\n workspaceDir: string;\n /** The state half; absent when the backup captured only the workspace. */\n stateDir?: string;\n}\n\n/** Read and shape-check a bundle's manifest. */\nexport async function readBackupManifest(dir: string): Promise<BackupManifest> {\n const path = join(dir, 'manifest.json');\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new Error(\n `${path}: not a readable backup manifest (${err instanceof Error ? err.message : String(err)})`,\n );\n }\n const m = parsed as Partial<BackupManifest>;\n // Version first: a bundle from a newer AgentBox may hold a layout this code\n // would half-restore, and half a bot is worse than a refusal.\n if (m.version !== 1) {\n throw new Error(\n `${path}: manifest version ${String(m.version)} is not one this build restores`,\n );\n }\n if (typeof m.bot !== 'string' || typeof m.stamp !== 'string') {\n throw new Error(`${path}: manifest is missing 'bot' or 'stamp'`);\n }\n return m as BackupManifest;\n}\n\n/**\n * Resolve which backup of `bot` to restore.\n *\n * `stamp` absent follows the `latest` symlink, and falls back to the newest\n * stamped dir when the link is missing — a bundle copied with a tool that drops\n * symlinks is still restorable, which is the whole point of a relative link.\n */\nexport async function resolveBotBundle(\n projectRoot: string,\n bot: string,\n stamp?: string,\n): Promise<BotBundle> {\n const base = botDir(projectRoot, bot);\n let chosen = stamp;\n if (!chosen) {\n chosen = (await readlink(join(base, 'latest')).catch(() => null)) ?? undefined;\n if (chosen === undefined) chosen = (await listBackups(projectRoot, bot))[0];\n }\n if (!chosen) {\n throw new Error(\n `no backup of '${bot}' under ${base} — run \\`agentbox download --backup\\` first`,\n );\n }\n const dir = join(base, chosen);\n const manifest = await readBackupManifest(dir);\n const workspaceDir = join(dir, 'workspace');\n if (!(await lstat(workspaceDir).catch(() => null))?.isDirectory()) {\n throw new Error(`${dir}: the backup has no workspace/ directory`);\n }\n const stateDir = join(dir, 'state');\n const hasState = (await lstat(stateDir).catch(() => null))?.isDirectory() === true;\n return {\n dir,\n bot: manifest.bot,\n stamp: chosen,\n manifest,\n workspaceDir,\n ...(hasState ? { stateDir } : {}),\n };\n}\n\nexport interface AgentStateRestoreResult {\n /** Box paths whose stale write-ahead log / shared-memory file was removed. */\n clearedSidecars: string[];\n}\n\n/**\n * Push a captured state dir back into a box, IDENTITY INCLUDED — the inverse of\n * {@link backupAgentState}.\n *\n * The caller must have stopped the agent first. Two things this does that a\n * plain \"copy the directory in\" does not, both of them load-bearing:\n *\n * 1. **The stale write-ahead logs go first.** MEASURED, and it is not a corner\n * case: a fresh openclaw box has already onboarded, so its `state/` holds a\n * live `openclaw.sqlite` with its own `-wal`/`-shm`. Copying the backup's\n * main file over it leaves that WAL in place, pointing at a database it no\n * longer describes, and the gateway then refuses to start —\n * `SQLite integrity_check failed … row 1 missing from index` — in a restart\n * loop. Only the sidecars of a database the bundle actually replaces are\n * removed: one belonging to a database we are not overwriting may hold the\n * only copy of committed rows.\n * 2. **Modes are preserved** (`noSamePerms` left off), because the gateway token\n * file is 0600 and a restore that widened it would be a downgrade the user\n * never asked for.\n *\n * NOT routed through `agentPushExcludes`: that helper adds\n * `LIVE_DATABASE_EXCLUDES` unconditionally, which matches `*.sqlite*` — exactly\n * the gateway state a restore exists to put back. The bundle was already\n * filtered when it was captured.\n */\nexport async function restoreAgentState(args: {\n agent: AgentId;\n transport: SyncTransport;\n srcDir: string;\n}): Promise<AgentStateRestoreResult> {\n const boxDir = agentPullBoxDir(args.agent);\n const clearedSidecars = await clearStaleSidecars(args, boxDir);\n await args.transport.pushTree(args.srcDir, boxDir);\n return { clearedSidecars };\n}\n\n/** Remove the box's `-wal`/`-shm` for every database this bundle replaces. */\nasync function clearStaleSidecars(\n args: { transport: SyncTransport; srcDir: string },\n boxDir: string,\n): Promise<string[]> {\n const rels = await findLocalDatabases(args.srcDir);\n if (rels.length === 0) return [];\n const paths = rels.flatMap((rel) => [`${boxDir}/${rel}-wal`, `${boxDir}/${rel}-shm`]);\n const r = await args.transport.exec(['sh', '-c', `rm -f ${paths.map(quote).join(' ')}`]);\n // FAIL, do not continue. `rm -f` is silent about a file that was not there, so\n // a non-zero exit means the removal itself did not happen — and pushing the\n // databases anyway lands them on the leftover logs, which is precisely the\n // integrity-check restart loop this step exists to prevent. A restore that\n // stops here leaves a box with its own working identity; one that continues\n // leaves a box that never boots.\n if (r.exitCode !== 0) {\n throw new Error(\n `could not clear stale write-ahead logs under ${boxDir}: ` +\n `${r.stderr.trim() || `exit ${String(r.exitCode)}`}`,\n );\n }\n return paths;\n}\n\n/** Host-side twin of the backup's `find`: the databases the bundle carries. */\nasync function findLocalDatabases(root: string, prefix = ''): Promise<string[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(join(root, prefix), { withFileTypes: true });\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const e of entries) {\n const rel = prefix ? join(prefix, e.name) : e.name;\n if (e.isDirectory()) out.push(...(await findLocalDatabases(root, rel)));\n else if (e.isFile() && (e.name.endsWith('.sqlite') || e.name.endsWith('.db'))) out.push(rel);\n }\n return out;\n}\n","/**\n * The per-agent box->host pull, as a registered hook with a data-driven default.\n *\n * WHY A HOOK AND NOT ONE SHARED FUNCTION. An agent's config is not always a file\n * tree. Codex keeps five SQLite databases under `~/.codex` and opencode keeps\n * one, and a database is not copyable: a running agent's data lives in the\n * write-ahead log, so the main file alone is stale and the triple copied\n * together is a torn read (measured: codex's `state_5.sqlite` was 4 KB against a\n * 1.79 MB `-wal`). Collapsing the three pulls into one generic file-copy would\n * have locked that in. Instead: a default that covers the flat case from\n * `AgentPullSpec`, and a hook for an agent whose state needs handling —\n * `pullSqliteSnapshot` is the supported way to do it.\n *\n * Registered the way the docker and cloud module registries are, and for the\n * same reason: `sandbox-core` receives an agent's behavior, it never imports an\n * agent package.\n */\n\nimport type { AgentId, SyncTransport } from '@agentbox/core';\nimport { resolveAgentSpec } from './registry.js';\nimport { pullFlatConfigViaTransport } from './agent-pull.js';\n\nexport interface AgentPullOptions {\n /** Report what WOULD be pulled and write nothing. */\n dryRun?: boolean;\n /** Host home to pull into. Overridable for tests. */\n hostHome?: string;\n}\n\nexport interface AgentPullResult {\n /** Host-relative names newly brought over (empty = nothing to do). */\n newItems: string[];\n}\n\nexport interface AgentPullModule {\n readonly id: AgentId;\n /**\n * Pull this agent's box-side config back to the host, ADDITIVELY — the host\n * copy always wins, so this only ever adds what the host does not have.\n */\n pull(t: SyncTransport, opts: AgentPullOptions): Promise<AgentPullResult>;\n}\n\nconst MODULES = new Map<AgentId, AgentPullModule>();\n\nexport function registerAgentPullModule(mod: AgentPullModule): void {\n MODULES.set(mod.id, mod);\n}\n\nexport function registeredAgentPullModules(): AgentPullModule[] {\n return [...MODULES.values()];\n}\n\n/**\n * The pull for `agent` — its registered module, or the spec-driven default.\n *\n * The default is not a fallback for a broken registration: an agent whose\n * config is a flat set of files (which is most of them) declares\n * `pull.items` and needs no code at all. That is the same \"an agent is a row of\n * data\" rule the install recipe follows.\n */\nexport function agentPull(\n agent: AgentId,\n t: SyncTransport,\n opts: AgentPullOptions = {},\n): Promise<AgentPullResult> {\n const mod = MODULES.get(agent);\n if (mod) return mod.pull(t, opts);\n return pullFlatConfigViaTransport(agent, t, opts);\n}\n\n/**\n * Copy a SQLite database out of a box CONSISTENTLY, for an agent whose state is\n * a database rather than a file tree.\n *\n * Uses SQLite's own online-backup API through the box's Python (or Node 24's\n * `node:sqlite`), which checkpoints the WAL into a single self-contained file —\n * so the result is readable, unlike a byte-copy of a live `.sqlite` (+`-wal`\n * +`-shm`) triple. Neither runtime needs installing: both are already in the box\n * image, which is why this needs no re-bake.\n *\n * Returns false when the box has neither runtime or the database is absent; the\n * caller decides whether that is fatal.\n */\nexport async function pullSqliteSnapshot(\n t: SyncTransport,\n boxDbPath: string,\n hostDestPath: string,\n): Promise<boolean> {\n const tmp = `${boxDbPath}.agentbox-snapshot`;\n const py =\n `import sqlite3,sys\\n` +\n `src=sqlite3.connect('file:${boxDbPath}?mode=ro',uri=True)\\n` +\n `dst=sqlite3.connect('${tmp}')\\n` +\n `src.backup(dst); dst.close(); src.close()\\n`;\n const snap = await t.exec([\n 'sh',\n '-c',\n `[ -f '${boxDbPath}' ] || exit 3; ` +\n `if command -v python3 >/dev/null 2>&1; then python3 - <<'PY'\\n${py}PY\\n` +\n `elif command -v node >/dev/null 2>&1; then ` +\n `node -e \"const{DatabaseSync}=require('node:sqlite');const d=new DatabaseSync('${boxDbPath}');d.exec(\\\\\"VACUUM INTO '${tmp}'\\\\\");d.close()\"; ` +\n `else exit 4; fi`,\n ]);\n if (snap.exitCode !== 0) return false;\n try {\n await t.pullFile(tmp, hostDestPath);\n return true;\n } finally {\n await t.exec(['rm', '-f', tmp]);\n }\n}\n\n/** The box dir an agent's pull reads from, per the registry. */\nexport function agentPullBoxDir(agent: AgentId): string {\n const spec = resolveAgentSpec(agent);\n const dir = spec.staticPaths[0]?.boxDir;\n if (!dir) throw new Error(`agent '${agent}' declares no staticPaths to pull from`);\n return dir;\n}\n","/**\n * Concern: the URL that opens a service agent's own UI, already signed in.\n *\n * A service agent (openclaw) generates its auth token INSIDE the box, and its\n * UI takes that token from the URL fragment. So the box's plain web URL is not\n * enough to reach the dashboard: it lands on a token prompt, and the value it\n * wants is in a file only the box can read.\n *\n * The value is read through the daemon's OWN command where it has one\n * (`openclaw dashboard --json --no-open`) rather than out of its config file:\n * that is the interface it supports, so it survives a config-layout change, and\n * it means AgentBox never has to know how a third-party daemon stores its\n * secrets.\n *\n * Lives here, in `sandbox-core`, rather than in the CLI because three surfaces\n * need the same answer -- `agentbox <agent> url`, the hub's REST API (and so\n * the web UI and the macOS tray through it), and any future client. Two\n * implementations of \"where does the token go in the URL\" would drift, and the\n * one that drifts silently produces a link that opens to a login prompt.\n *\n * The token is read AT CLICK TIME, never carried on the box list: reading it is\n * an exec into the box, and it is a live credential that has no business in\n * every poll of every box.\n */\n\nimport type { AgentServiceUrlField, AgentSyncSpec, BoxRecord, Provider } from '@agentbox/core';\nimport { findAgentSpec } from '../registry.js';\n\n/**\n * The SERVICE agent a box hosts, if any — the daemon whose UI has a token.\n *\n * Scans every agent the box knows about rather than trusting `lastAgent`, which\n * is \"whichever agent ran most recently\" and is overwritten by a later\n * `agentbox claude` in the same box. The gateway is still running there; reading\n * only `lastAgent` would decide the box has no UI to sign in to and hand the\n * user a token prompt.\n */\nexport function serviceAgentForBox(\n box: Pick<BoxRecord, 'lastAgent' | 'agents'>,\n): AgentSyncSpec | undefined {\n const ids = [box.lastAgent, ...(box.agents ?? [])].filter((v): v is string => !!v);\n for (const id of ids) {\n const spec = findAgentSpec(id);\n if (spec?.caps.surface === 'service') return spec;\n }\n return undefined;\n}\n\n/** One resolved url field: what it is called, its value, and where it belongs. */\nexport interface ServiceUrlFieldValue {\n label: string;\n value: string;\n /** Set when the value belongs in the URL fragment under this key. */\n fragmentKey?: string;\n}\n\n/** Walk a dotted path (`gateway.auth.token`) into a parsed JSON document. */\nfunction atJsonPath(doc: unknown, path: string): unknown {\n let cur: unknown = doc;\n for (const key of path.split('.')) {\n if (cur === null || typeof cur !== 'object') return undefined;\n cur = (cur as Record<string, unknown>)[key];\n }\n return cur;\n}\n\n/** The argv that produces one field's JSON, and a cache key for it. */\nfunction sourceArgv(field: AgentServiceUrlField): string[] | null {\n if (field.command && field.command.length > 0) return [...field.command];\n if (field.file) return ['cat', field.file];\n return null;\n}\n\n/** Lift `token` out of `http://127.0.0.1:18789/#token=abc&x=y`. */\nfunction fragmentParam(raw: string, key: string): string | undefined {\n const hash = raw.indexOf('#');\n if (hash < 0) return undefined;\n const params = new URLSearchParams(raw.slice(hash + 1));\n return params.get(key) ?? undefined;\n}\n\n/**\n * How long one source gets before it counts as \"no value\".\n *\n * The read goes through the daemon's own CLI, which needs the daemon running:\n * a gateway that is starting, wedged, or waiting on something can leave that\n * command hanging, and the caller here is a user waiting on a click (the tray's\n * Open Web, the hub's, `agentbox <agent> url`). A healthy read of openclaw's\n * token over an SSH provider measured ~5s, so this is generous, not tight -- it\n * exists to bound the pathological case, not to race the normal one.\n */\nconst SOURCE_READ_TIMEOUT_MS = 20_000;\n\n/** `promise`, or undefined once `ms` has passed. The work is left running: a\n * provider exec has no cancel, and the value is discarded either way. */\nasync function withinTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), ms);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * Read an agent's declared url fields out of the running box.\n *\n * One read per distinct SOURCE, not per field: two fields out of one config (or\n * one command) would otherwise be two round-trips into the box. A source that\n * fails is not an error — a box whose daemon has not finished onboarding simply\n * has no token yet, and the caller falls back to the bare URL rather than\n * refusing to open anything.\n */\nexport async function readServiceUrlFields(\n provider: Provider,\n box: BoxRecord,\n fields: readonly AgentServiceUrlField[],\n): Promise<ServiceUrlFieldValue[]> {\n if (fields.length === 0) return [];\n const out: ServiceUrlFieldValue[] = [];\n const docs = new Map<string, unknown>();\n for (const field of fields) {\n const argv = sourceArgv(field);\n if (!argv) continue;\n const key = argv.join('\\u0000');\n if (!docs.has(key)) {\n let parsed: unknown;\n try {\n const r = await withinTimeout(\n provider.exec(box, argv, { user: 'vscode' }),\n SOURCE_READ_TIMEOUT_MS,\n );\n // A daemon's CLI may print a banner before its JSON, so parse from the\n // first `{` rather than requiring the whole of stdout to be the payload.\n const body = r?.stdout.slice(r.stdout.indexOf('{'));\n parsed = r?.exitCode === 0 && body?.startsWith('{') ? JSON.parse(body) : undefined;\n } catch {\n parsed = undefined;\n }\n docs.set(key, parsed);\n }\n const raw = atJsonPath(docs.get(key), field.jsonPath);\n if (typeof raw !== 'string' || raw.length === 0) continue;\n const value = field.fromUrlFragment ? fragmentParam(raw, field.fromUrlFragment) : raw;\n if (value === undefined || value.length === 0) continue;\n out.push({\n label: field.label,\n value,\n ...(field.fragmentKey ? { fragmentKey: field.fragmentKey } : {}),\n });\n }\n return out;\n}\n\n/**\n * The URL that opens the daemon's UI already signed in, or null when the agent\n * declares nothing that belongs in the URL.\n *\n * Null rather than the bare URL so a caller can tell \"there is nothing to add\"\n * from \"here is a better link\", and print or offer the second one only when it\n * actually says something the plain URL does not.\n */\nexport function serviceSignInUrl(\n url: string,\n fields: readonly ServiceUrlFieldValue[],\n): string | null {\n const parts = fields\n .filter((f) => f.fragmentKey)\n .map((f) => `${encodeURIComponent(f.fragmentKey as string)}=${encodeURIComponent(f.value)}`);\n if (parts.length === 0) return null;\n // The UI is served from the root, and a fragment hung off a bare authority\n // (no path at all) is not something a browser opens predictably.\n const base = url.endsWith('/') ? url : `${url}/`;\n return `${base}#${parts.join('&')}`;\n}\n\n/**\n * `baseUrl` carrying the box's service agent's sign-in fields, or `baseUrl`\n * unchanged when the box hosts no service agent and when the daemon has no\n * token to give yet.\n *\n * The browser INSIDE the box needs this for exactly the reason the host's does:\n * point it at the bare web URL and openclaw's Control UI opens on its token\n * prompt, so the VNC desktop shows a login screen instead of the dashboard. The\n * VNC path resolves its own target (it must — the host's `127.0.0.1:<forward>`\n * is nothing inside the box), which is what left it as the one surface still\n * handing out an unsigned URL.\n *\n * Best-effort by contract, like every other producer here: a daemon mid-onboard\n * has no token, and the plain URL plus its own prompt beats opening nothing.\n */\nexport async function withServiceSignIn(\n provider: Provider,\n box: BoxRecord,\n baseUrl: string,\n): Promise<string> {\n try {\n const fields = serviceAgentForBox(box)?.service?.urlFields ?? [];\n if (fields.length === 0) return baseUrl;\n return serviceSignInUrl(baseUrl, await readServiceUrlFields(provider, box, fields)) ?? baseUrl;\n } catch {\n return baseUrl;\n }\n}\n","/**\n * Concern: workspace files — the provider-neutral half of moving a box's\n * `/workspace` back to the host (`agentbox download`, `agentbox clone`) and of\n * pushing the host's files into a live NON-GIT box (`agentbox sync`).\n *\n * Two things live here because they must not drift between providers:\n *\n * - **The pull's second stage.** Docker materializes `/workspace` into a\n * per-box host scratch dir over a bind mount; the clouds tar it out over the\n * SDK. From that point on both are the same operation — a host-side `rsync -a\n * --checksum` from the scratch dir into the user's working dir, driven by a\n * NUL file list, reported as an itemized change list. That is\n * {@link rsyncPullToHost}, and sharing it is what gives cloud `download` its\n * `--dry-run` and its change list.\n * - **The selection rules.** {@link buildWorkspaceListScript} is the one\n * in-box enumerator: `git ls-files` when `/workspace` is a repo, else a\n * `find` honouring {@link workspaceExcludes}. Exclude-list mode is not a\n * fallback — for a service box whose workspace was never a git repo it is\n * the ONLY mode, which is why its defaults have to be good enough to run\n * unattended (no live databases, no media blobs, no agent state dir).\n *\n * The host→box direction for a non-git workspace is {@link overlayHostDirIntoBox}:\n * the same box-wins-content-hash policy the git resync uses\n * (`classifyUntrackedOverlay`), applied to a plain file list instead of git's\n * untracked set. Never deletes, never overwrites a box file that differs.\n */\n\nimport { createHash } from 'node:crypto';\nimport { lstat, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport { LIVE_DATABASE_EXCLUDES } from '@agentbox/core';\nimport { classifyUntrackedOverlay } from './git.js';\nimport { AGENT_SYNC_SPECS } from '../registry.js';\n\n/**\n * Directories excluded from an exclude-list-mode workspace pull, by basename,\n * at any depth. `.git` and `node_modules` are the historical pair; `media` is\n * new — a service agent (an AI gateway, a chat backend) accumulates uploaded\n * attachments under `media/` and they are not source.\n *\n * `.agentbox` is ours, not the user's: a box-local dir AgentBox regenerates\n * every boot (openclaw's derived box facts live there, because openclaw will\n * only read a system prompt from inside its own workspace). Pulling it back\n * would put a generated file describing THIS box into the user's project.\n *\n * This list covers exclude-list mode and `clone` only, since `download` on a\n * git workspace deliberately does not apply it (see `dropExcludedInGitMode`).\n * `.agentbox` is dropped in git mode too, by {@link GIT_MODE_EXCLUDE_DIRS}.\n */\nexport const WORKSPACE_EXCLUDE_DIR_NAMES: readonly string[] = [\n '.git',\n 'node_modules',\n 'media',\n '.agentbox',\n];\n\n/**\n * Directories dropped from the GIT-mode selection as well, by pathspec.\n *\n * Git mode otherwise carries everything `git ls-files --cached --others\n * --exclude-standard` reports, on purpose: a tracked `.claude/` there is the\n * user's own content and dropping it would be a regression. `.agentbox` is the\n * one thing that is never the user's content — AgentBox generates it in the box\n * every boot (openclaw's derived box facts, which have to live inside the\n * workspace because openclaw will not read a system prompt from outside it), so\n * pulling it back would write a file describing THIS box into the project.\n *\n * A pathspec rather than the box's `.git/info/exclude`, which cannot do the job:\n * in a docker box `/workspace/.git` is a linked-worktree FILE whose per-worktree\n * `info/exclude` git does not read, and the common dir it does read is the\n * user's bind-mounted host repo.\n */\nexport const GIT_MODE_EXCLUDE_DIRS: readonly string[] = ['.agentbox'];\n\n/**\n * The same dirs, as `tar --exclude` arguments for a host -> box workspace SEED.\n *\n * The invariant this closes: **`.agentbox/` never crosses the box boundary, in\n * either direction.** The pull half was already true ({@link\n * GIT_MODE_EXCLUDE_DIRS} and {@link WORKSPACE_EXCLUDE_DIR_NAMES}); the seed half\n * was not, and `<project>/.agentbox/bots/` — where `download --backup` writes a\n * bot's workspace AND its gateway identity — would otherwise be copied into\n * every new box created from that project, growing with each backup.\n *\n * Derived from the pull-side list rather than repeated, so the two cannot drift.\n *\n * ANY-DEPTH, not root-anchored, and that is forced as well as wanted. Forced:\n * neither tar anchors an exclude — MEASURED on bsdtar 3.5.3 (macOS) and true of\n * GNU tar, which defaults to `--no-anchored`, so `--exclude=./.agentbox` drops a\n * nested `sub/.agentbox` just the same and only a `--anchored` GNU tar could\n * tell them apart. Wanted: a nested one is ours too — `download --backup` run\n * from a monorepo sub-project writes `packages/foo/.agentbox/`, which has no\n * more business in a box than the root one. This matches\n * {@link WORKSPACE_EXCLUDE_DIR_NAMES}, whose bare names already match at any\n * depth; the git-mode PULL pathspec stays root-anchored, so the seed refuses\n * slightly more than the pull brings back, which is the safe direction.\n */\nexport function seedExcludeTarArgs(): string[] {\n return GIT_MODE_EXCLUDE_DIRS.map((d) => `--exclude=${d}`);\n}\n\n/**\n * Drop the same dirs from a NUL-joined `git ls-files --others` list — the\n * untracked carry-over leg of a git-backed seed, which tars a vetted file list\n * rather than a whole directory.\n *\n * Belt-and-braces, and deliberately so: `--exclude-standard` already skips a\n * gitignored `.agentbox/`, and `download --backup` writes that gitignore entry.\n * The invariant must not depend on that write having succeeded — in a project\n * whose `.gitignore` the user has since edited, this is what still holds.\n *\n * Matched at any depth, through {@link isExcludedPath}'s bare-name rule, so this\n * agrees with {@link seedExcludeTarArgs} — the two halves of one seed must not\n * disagree about what a path list means.\n *\n * Tolerates an unterminated tail: `git ls-files -z` NUL-TERMINATES rather than\n * NUL-separates, and treating the two the same is how the last path in a list\n * has been dropped here before.\n */\nexport function dropHostOnlyPaths(nulList: string): string {\n const kept = nulList\n .split('\\0')\n .filter((p) => p.length > 0 && !isExcludedPath(p, GIT_MODE_EXCLUDE_DIRS));\n return kept.length > 0 ? `${kept.join('\\0')}\\0` : '';\n}\n\n/**\n * The git-mode pathspecs, as `git ls-files -- . <these>` arguments.\n *\n * `node_modules` joins `.agentbox` here unless the caller asked to keep it, and\n * the two are anchored DIFFERENTLY on purpose:\n *\n * - `.agentbox` is one dir at the workspace root, so one root-anchored pathspec\n * says exactly what is meant.\n * - `node_modules` is whatever rsync's `--exclude=node_modules` means in the\n * docker mirror, and that matches the basename at ANY depth. A single\n * root-anchored `:(exclude)node_modules` would leave a monorepo's\n * `packages/x/node_modules` selected but unmirrored — which is the exact\n * listed-but-absent failure this whole change exists to remove. Measured\n * against git 2.39 in this repo: the root-anchored form alone still lists\n * 3310 nested paths; all three forms list none.\n *\n * Excluding it in git mode at all is a deliberate behaviour choice, not a\n * mechanical one: a repo that does not gitignore `node_modules` used to have it\n * pulled back, and `--include-node-modules` is now the single switch in both\n * modes. Pulling a box-built (Linux) `node_modules` onto the host was never\n * something to do by accident.\n */\nexport function gitModeExcludePathspecs(opts: WorkspaceExcludeOptions = {}): string[] {\n const specs = GIT_MODE_EXCLUDE_DIRS.map((d) => `:(exclude)${d}`);\n if (!opts.includeNodeModules) {\n specs.push(':(exclude)node_modules', ':(exclude)*/node_modules', ':(exclude)*/node_modules/*');\n }\n return specs;\n}\n\n/**\n * Agent state directories, derived from every registered agent's declared\n * `staticPaths` rather than listed. These normally live under the box HOME, but\n * an agent pointed at `/workspace` as its working dir (openclaw's\n * `OPENCLAW_WORKSPACE_DIR`) drops the same tree inside the workspace — and a\n * gateway's state dir landing in the user's project folder is the failure this\n * guards. Home-relative paths are used verbatim as rsync/find patterns, so\n * `.config/opencode` excludes only that subtree, not all of `.config`.\n */\nexport function agentStateExcludePaths(): string[] {\n const out = new Set<string>();\n for (const spec of AGENT_SYNC_SPECS) {\n for (const p of spec.staticPaths) {\n if (p.hostHomeRel.length > 0) out.add(p.hostHomeRel.join('/'));\n }\n }\n return [...out].sort();\n}\n\nexport interface WorkspaceExcludeOptions {\n /** Default false. When true, keep `node_modules` in the selection. */\n includeNodeModules?: boolean;\n}\n\n/**\n * Every exclude pattern an exclude-list-mode pull applies, as rsync/tar\n * patterns. Consumed both by {@link buildWorkspaceListScript} (which compiles\n * them into a `find` expression) and by {@link rsyncPullToHost} when there is\n * no file list at all.\n */\nexport function workspaceExcludes(opts: WorkspaceExcludeOptions = {}): string[] {\n const dirs = WORKSPACE_EXCLUDE_DIR_NAMES.filter(\n (d) => d !== 'node_modules' || !opts.includeNodeModules,\n );\n return [...dirs, ...agentStateExcludePaths(), ...LIVE_DATABASE_EXCLUDES];\n}\n\n/** Split an exclude pattern list into the three shapes `find` needs. */\nfunction partitionExcludes(patterns: readonly string[]): {\n dirNames: string[];\n dirPaths: string[];\n fileGlobs: string[];\n} {\n const dirNames: string[] = [];\n const dirPaths: string[] = [];\n const fileGlobs: string[] = [];\n for (const raw of patterns) {\n const p = raw.replace(/\\/+$/, '');\n if (p.length === 0) continue;\n if (p.includes('*')) fileGlobs.push(p);\n else if (p.includes('/')) dirPaths.push(p);\n else dirNames.push(p);\n }\n return { dirNames, dirPaths, fileGlobs };\n}\n\n/** Single-quote a value for the POSIX shell. */\nfunction sq(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/** Mode marker the list script prints on its first line. */\nexport type WorkspaceListMode = 'git' | 'exclude';\n\nexport interface WorkspaceListScriptOptions {\n /** In-box workspace dir (default `/workspace`). */\n workspaceDir?: string;\n /** Default true. When false, skip the git probe and always use the exclude list. */\n respectGitignore?: boolean;\n /** Exclude patterns for the non-git branch (see {@link workspaceExcludes}). */\n excludes: readonly string[];\n /**\n * Default false. Keep `node_modules` in the GIT-mode selection too — the\n * non-git branch reads the same choice out of `excludes`. Both halves must be\n * told, or the two modes disagree about the one flag the user set.\n */\n includeNodeModules?: boolean;\n}\n\n/**\n * Build the in-box shell script that enumerates the workspace files a pull\n * should carry. Prints `MODE=git` or `MODE=exclude` followed by a newline, then\n * the NUL-delimited paths RELATIVE to the workspace dir — the exact shape rsync\n * `--files-from=- --from0` and `tar --null -T -` both consume.\n *\n * One script for both providers: docker runs it through `docker exec`, the\n * clouds through `backend.exec`. The mode marker is what lets the caller report\n * `(exclude-list mode)` truthfully instead of guessing from the workspace path.\n */\nexport function buildWorkspaceListScript(opts: WorkspaceListScriptOptions): string {\n const dir = opts.workspaceDir ?? '/workspace';\n const { dirNames, dirPaths, fileGlobs } = partitionExcludes(opts.excludes);\n const pruneTerms = [\n ...dirNames.map((n) => `-name ${sq(n)}`),\n ...dirPaths.map((p) => `-path ${sq(`./${p}`)}`),\n ];\n const prune =\n pruneTerms.length > 0 ? `\\\\( -type d \\\\( ${pruneTerms.join(' -o ')} \\\\) -prune \\\\) -o ` : '';\n // The excludes apply to FILES as well, not just to pruned directories: in a\n // linked git worktree `.git` is a regular file, and a `find` that only pruned\n // `-type d -name .git` let it through — rsync then failed outright trying to\n // replace the destination's `.git` DIRECTORY with it.\n const fileFilter = [\n ...dirNames.map((n) => `! -name ${sq(n)}`),\n ...dirPaths.flatMap((p) => [`! -path ${sq(`./${p}`)}`, `! -path ${sq(`./${p}/*`)}`]),\n ...fileGlobs.map((g) => `! -name ${sq(g)}`),\n ].join(' ');\n // `-print0` (not GNU's `-printf '%P\\\\0'`): this script also runs on the HOST,\n // where find may be BSD's. The leading `./` is stripped when parsing.\n // Symlinks ride along: rsync `-a` recreates them and a workspace that pins a\n // path with one would otherwise silently lose it in exclude-list mode.\n const findCmd = `find . ${prune}\\\\( \\\\( -type f -o -type l \\\\) ${fileFilter} -print0 \\\\)`;\n const gitProbe =\n opts.respectGitignore === false ? 'false' : 'git rev-parse --is-inside-work-tree';\n const gitExcludePathspecs = gitModeExcludePathspecs(opts).map(sq).join(' ');\n // Everything the git branch prints is passed through an existence test, so the\n // list can only ever name a path that is really there.\n //\n // That invariant is the whole point. `git ls-files --cached` happily prints an\n // index entry whose worktree file was DELETED, and a listed-but-absent path is\n // fatal on both transports: rsync exits 23 (`link_stat ... No such file`) and\n // the shared `rsyncPullToHost` throws on its dry run, while the cloud tar dies\n // with `Cannot stat` under `set -e`. Same bug, two transports.\n //\n // `-f`/`-L` mirrors the find branch's `-type f -o -type l`, which also drops a\n // gitlink (a submodule, which `--cached` prints as a DIRECTORY): tar would\n // recurse into it and pull its `.git`, while `rsync --files-from` would not\n // recurse at all, so the two staging paths disagreed in both directions.\n //\n // `xargs -0` rather than a `while read -d ''` loop: bash reads a pipe a byte at\n // a time, measured at 8.6s vs 2.65s over 138k paths. No `-r` (BSD xargs has\n // none) — with empty input `sh` runs once with no positional args and the loop\n // prints nothing. No temp file and no process substitution, because a Vercel\n // box has no `/dev/fd`.\n const existingOnly = `xargs -0 sh -c 'for f do if [ -f \"$f\" ] || [ -L \"$f\" ]; then printf \"%s\\\\0\" \"$f\"; fi; done' _`;\n return [\n `set -u`,\n // Without pipefail a failing `git ls-files` is invisible: the pipeline exits\n // 0 and the short list reads as \"this workspace has fewer files\".\n `set -o pipefail`,\n `cd ${sq(dir)} 2>/dev/null || exit 3`,\n `if ${gitProbe} >/dev/null 2>&1; then`,\n ` printf 'MODE=git\\\\n'`,\n ` git ls-files -z --cached --others --exclude-standard -- . ${gitExcludePathspecs} |`,\n ` ${existingOnly}`,\n `else`,\n ` printf 'MODE=exclude\\\\n'`,\n ` ${findCmd}`,\n `fi`,\n ].join('\\n');\n}\n\nexport interface ParsedWorkspaceList {\n mode: WorkspaceListMode;\n /** NUL-joined relative paths; empty string when the workspace has no files. */\n fileList: string;\n /** The same paths, split. */\n paths: string[];\n}\n\n/** Parse {@link buildWorkspaceListScript}'s stdout. Throws on an unknown marker. */\nexport function parseWorkspaceList(stdout: string): ParsedWorkspaceList {\n const nl = stdout.indexOf('\\n');\n const marker = nl >= 0 ? stdout.slice(0, nl) : stdout;\n const rest = nl >= 0 ? stdout.slice(nl + 1) : '';\n if (marker !== 'MODE=git' && marker !== 'MODE=exclude') {\n throw new Error(`workspace file list: unexpected mode marker ${JSON.stringify(marker)}`);\n }\n // `find -print0` emits `./a/b`; `git ls-files -z` emits `a/b`. Normalize so\n // both feed `rsync --files-from` / `tar -T` identically.\n const paths = rest\n .split('\\0')\n .filter((p) => p.length > 0)\n .map((p) => (p.startsWith('./') ? p.slice(2) : p));\n return {\n mode: marker === 'MODE=git' ? 'git' : 'exclude',\n fileList: paths.join('\\0'),\n paths,\n };\n}\n\n/**\n * Does `relPath` match one of the exclude patterns, using the same reading\n * `find`/rsync give them?\n *\n * - a pattern with `/` matches that path prefix (`.config/opencode` hides that\n * subtree, and nothing else under `.config`);\n * - a pattern with `*` is a basename glob (`*.sqlite*`), matched at any depth;\n * - a bare name matches any path SEGMENT (`node_modules`, `.git`).\n *\n * Used where the selection did not come from `find` — the git-mode list, which\n * `agentbox clone` still has to strip an agent state dir out of.\n */\nexport function isExcludedPath(relPath: string, patterns: readonly string[]): boolean {\n const segments = relPath.split('/');\n const base = segments[segments.length - 1] ?? '';\n for (const raw of patterns) {\n const p = raw.replace(/^\\.\\//, '').replace(/\\/+$/, '');\n if (p.length === 0) continue;\n if (p.includes('*')) {\n const re = new RegExp(`^${p.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\*/g, '.*')}$`);\n if (re.test(base)) return true;\n continue;\n }\n if (p.includes('/')) {\n if (relPath === p || relPath.startsWith(`${p}/`)) return true;\n continue;\n }\n if (segments.includes(p)) return true;\n }\n return false;\n}\n\n/** One itemized rsync line, split into the parts a caller can act on. */\nexport interface ItemizedChange {\n /** The line as rsync printed it — what `parseItemizedChanges` returns. */\n raw: string;\n /** The leading flag word (`>f+++++++`, `*deleting`, ...). */\n code: string;\n /** Path relative to the destination, with any ` -> target` suffix removed. */\n path: string;\n /** True when this file does not exist at the destination yet. */\n created: boolean;\n}\n\n/**\n * Parse the itemized lines that represent an actual file transfer or delete.\n * rsync `-i` emits a leading code: char 0 is the update type (`>`/`<`/`c`/`*` =\n * transfer/change/delete; `.` = attr-only, skipped) and char 1 is the entry type\n * (`f` file, `d` dir, ...). Directory lines (`d`) are pruned: rsync creates\n * parent dirs as a side effect of transferring files, so counting them would\n * overstate \"files changed\".\n *\n * `created` is \"every attribute slot is `+`\", NOT a fixed `+++++++` literal: the\n * flag word is 9 characters on the rsync macOS still ships (2.6.9, `YXcstpogz`)\n * and 11 on rsync 3.x (`YXcstpoguax`). Matching a literal would silently report\n * \"nothing is new\" on one of the two.\n */\nexport function parseItemizedEntries(stdout: string): ItemizedChange[] {\n const out: ItemizedChange[] = [];\n for (const line of stdout.split('\\n')) {\n const raw = line.trimEnd();\n if (raw.length === 0) continue;\n const code = raw.slice(0, raw.indexOf(' ') === -1 ? raw.length : raw.indexOf(' '));\n const kind = raw[1];\n const type = raw[0];\n if (!(type === '>' || type === '<' || type === 'c' || type === '*') || kind === 'd') continue;\n const rest = raw.slice(code.length).trimStart();\n // `%i %n%L`: a symlink line carries ` -> target`, which is not part of the name.\n const arrow = rest.indexOf(' -> ');\n const path = arrow === -1 ? rest : rest.slice(0, arrow);\n const attrs = code.slice(2);\n const created =\n (type === '>' || type === '<' || type === 'c') &&\n kind === 'f' &&\n attrs.length > 0 &&\n [...attrs].every((c) => c === '+');\n out.push({ raw, code, path, created });\n }\n return out;\n}\n\n/** The itemized lines that count as a change, as rsync printed them. */\nexport function parseItemizedChanges(stdout: string): string[] {\n return parseItemizedEntries(stdout).map((e) => e.raw);\n}\n\n/**\n * Workspace-relative paths the registered agents CREATE inside `/workspace` —\n * their own scaffolding rather than the user's content.\n *\n * Derived from the registry (every agent's `clone.drop` and `clone.render`)\n * rather than listed, for the same reason `agentStateExcludePaths` is: an\n * agent's files are the agent's to declare. Unlike that one these are NOT\n * excluded — `download` asks about them when they would be new to the project,\n * and it asks about BOTH halves because both are the agent's scaffolding; only\n * a clone treats them differently.\n */\nexport function agentWorkspaceArtifactPaths(): string[] {\n const out = new Set<string>();\n for (const spec of AGENT_SYNC_SPECS) {\n for (const rel of spec.clone?.drop ?? []) out.add(rel);\n for (const rel of spec.clone?.render ?? []) out.add(rel);\n }\n return [...out].sort();\n}\n\n/**\n * The subset a CLONE drops outright, because the agent regenerates it for the\n * new box. `clone.render` files are deliberately absent: they carry the user's\n * own words and are rewritten for the new bot, not thrown away.\n *\n * Scoped to one agent, and EMPTY when the caller cannot say which: the two\n * mistakes are not symmetric. Keeping a file the agent would regenerate costs\n * nothing -- it regenerates. Dropping one it would not is silent data loss, and\n * the names at stake (`AGENTS.md`, `USER.md`) are exactly what a user writes for\n * themselves. So an unidentified agent drops nothing rather than everything.\n */\nexport function agentCloneDropPaths(agentId?: string): string[] {\n if (!agentId) return [];\n const specs = AGENT_SYNC_SPECS.filter((s) => s.id === agentId);\n const out = new Set<string>();\n for (const spec of specs) {\n for (const rel of spec.clone?.drop ?? []) out.add(rel);\n }\n return [...out].sort();\n}\n\n/**\n * Exact, root-anchored match — deliberately NOT {@link isExcludedPath}, whose\n * bare-name rule matches a basename at any depth and would sweep up a\n * `docs/AGENTS.md` the user wrote themselves.\n */\nexport function isAgentWorkspaceArtifact(relPath: string, artifacts: readonly string[]): boolean {\n return artifacts.includes(relPath);\n}\n\nexport interface RsyncPullArgs {\n /** Host dir holding the box's materialized `/workspace`. */\n scratchDir: string;\n /** The user's working dir the files land in (`box.workspacePath`). */\n destDir: string;\n /**\n * NUL-joined relative paths to copy, or null to fall back to an\n * `--exclude`-driven whole-tree copy.\n */\n fileList: string | null;\n /** `--exclude` patterns; only consulted when `fileList` is null. */\n excludes?: readonly string[];\n /** When true, run the dry-run pass only and return the change list. */\n dryRun?: boolean;\n /**\n * Paths to drop from `fileList` before copying — the user declined them.\n * Exact, root-anchored matches.\n */\n skipPaths?: readonly string[];\n}\n\n/**\n * Which of `paths` actually exist under `scratchDir`.\n *\n * `lstat`, so a symlink counts as present without following it, and the cost is\n * nothing next to `--checksum`, which already reads every byte of every file.\n */\nexport async function existingPathsIn(\n scratchDir: string,\n paths: readonly string[],\n): Promise<string[]> {\n const out: string[] = [];\n const LIMIT = 64;\n for (let i = 0; i < paths.length; i += LIMIT) {\n const batch = paths.slice(i, i + LIMIT);\n const found = await Promise.all(\n batch.map(async (rel) => {\n try {\n await lstat(join(scratchDir, rel));\n return rel;\n } catch {\n return null;\n }\n }),\n );\n for (const rel of found) if (rel !== null) out.push(rel);\n }\n return out;\n}\n\n/**\n * Stage 2 of a workspace pull, shared by every provider: copy the staged\n * `/workspace` view into the user's working dir and report what changed.\n *\n * `--checksum`, not the default size+mtime quick-check: a box runs on a fresh\n * git worktree (or a fresh extract), so every file's mtime differs from the\n * user's working tree even when the content is byte-identical. Without `-c`\n * rsync would \"update\" the entire tree.\n *\n * Never passes `--delete`: files that exist on the host but not in the box are\n * preserved. Removals are the user's call.\n */\nexport async function rsyncPullToHost(\n args: RsyncPullArgs,\n): Promise<{ changes: string[]; applied: boolean; missing: string[] }> {\n const baseArgs = ['-a', '--checksum'];\n if (args.fileList === null) {\n for (const e of args.excludes ?? []) baseArgs.push(`--exclude=${e}`);\n } else {\n baseArgs.push('--files-from=-', '--from0');\n }\n const src = `${args.scratchDir}/`;\n const dst = `${args.destDir}/`;\n\n // A path in `--files-from` that is not in the scratch dir makes rsync exit 23\n // and takes the whole pull down with it, and the rsync macOS ships (2.6.9)\n // does not have `--ignore-missing-args` to soften that. So the list is\n // reconciled with the staged copy here instead.\n //\n // A pull is additive — never `--delete` — so a file that vanished between the\n // listing and the staging is reported and skipped, not fatal. Failing on it\n // would let one racing temp file from a live agent kill a 5000-file download,\n // which is the bug this change removes, wearing a different hat.\n let missing: string[] = [];\n let input = args.fileList !== null ? args.fileList : undefined;\n if (args.fileList !== null) {\n const requested = args.fileList.split('\\0').filter((p) => p.length > 0);\n const skip = new Set(args.skipPaths ?? []);\n const wanted = requested.filter((p) => !skip.has(p));\n const present = await existingPathsIn(args.scratchDir, wanted);\n missing = wanted.filter((p) => !present.includes(p));\n // Nothing at all surviving is not a race, it is broken staging — a stale\n // `--no-refresh` scratch dir, or one wiped underneath us. Say so.\n if (present.length === 0 && wanted.length > 0) {\n throw new Error(\n `none of the ${String(wanted.length)} selected file(s) are in the staged copy at ` +\n `${args.scratchDir} — the staging is stale or empty; re-run without --no-refresh`,\n );\n }\n input = present.join('\\0');\n }\n\n const dry = await execa('rsync', [...baseArgs, '--dry-run', '-i', src, dst], {\n reject: false,\n input,\n });\n if (dry.exitCode !== 0) {\n throw new Error(`rsync dry-run failed: ${dry.stderr || dry.stdout}`);\n }\n const changes = parseItemizedChanges(dry.stdout);\n if (args.dryRun) return { changes, applied: false, missing };\n\n const real = await execa('rsync', [...baseArgs, src, dst], { reject: false, input });\n if (real.exitCode !== 0) {\n throw new Error(`rsync into ${args.destDir} failed: ${real.stderr || real.stdout}`);\n }\n return { changes, applied: true, missing };\n}\n\n// ── host → live box (the non-git leg of `agentbox sync`) ──────────────────────\n\n/** What a non-git overlay needs from the box, whatever provider it is on. */\nexport interface WorkspaceOverlayPorts {\n /**\n * For each relative path, the box's token: absent when the path does not\n * exist, `NON_REGULAR_TOKEN` for a dir/symlink, else the sha256 of the file.\n * Mirrors `WorkspaceResyncPorts.probeUntrackedTokens`.\n *\n * MUST THROW rather than return a partial map. A key missing from the result\n * means \"the box does not have this path\", and {@link overlayHostDirIntoBox}\n * acts on that by copying the host's file over — so an implementation that\n * degraded to an empty map on failure would overwrite the whole box.\n */\n probeBoxTokens(relPaths: string[]): Promise<Map<string, string>>;\n /** Extract a tar (rooted at the workspace dir) into the box. */\n applyTarToBox(tar: Buffer): Promise<void>;\n}\n\nexport interface WorkspaceOverlayResult {\n /** Paths copied into the box (absent there, or the box had no differing copy). */\n copied: string[];\n /** Paths the box already had with different content — the box's version kept. */\n skipped: string[];\n /** Paths that were byte-identical on both sides. */\n identical: number;\n /** True when the host dir had nothing to offer (empty or all excluded). */\n empty: boolean;\n}\n\nexport interface OverlayHostDirArgs {\n /** Host dir to push (the user's workspace). */\n hostDir: string;\n /** Exclude patterns (see {@link workspaceExcludes}). */\n excludes: readonly string[];\n ports: WorkspaceOverlayPorts;\n onLog?: (line: string) => void;\n}\n\n/**\n * Push a host workspace into a live box that has no git repo to merge through.\n *\n * Same conflict policy as the git resync — **the box wins**. A host file is\n * copied only when the box does not have it; when the box has a different\n * version the host change is skipped (no marker, nothing clobbered) and\n * reported so the caller can tell the user. There is no base revision to\n * three-way against here, so \"differs\" is the whole conflict test.\n */\nexport async function overlayHostDirIntoBox(\n args: OverlayHostDirArgs,\n): Promise<WorkspaceOverlayResult> {\n const log = args.onLog ?? ((): void => {});\n const rel = await listHostFiles(args.hostDir, args.excludes);\n if (rel.length === 0) {\n log('sync: nothing to push (host workspace is empty or fully excluded)');\n return { copied: [], skipped: [], identical: 0, empty: true };\n }\n\n const boxTokens = await args.ports.probeBoxTokens(rel);\n const copy: string[] = [];\n const skipped: string[] = [];\n let identical = 0;\n for (const p of rel) {\n let hostHash: string;\n try {\n hostHash = createHash('sha256')\n .update(await readFile(join(args.hostDir, p)))\n .digest('hex');\n } catch {\n // Raced away between the listing and the hash — nothing to push.\n continue;\n }\n const verdict = classifyUntrackedOverlay(boxTokens.get(p), hostHash);\n if (verdict === 'copy') copy.push(p);\n else if (verdict === 'conflict') skipped.push(p);\n else identical += 1;\n }\n\n if (copy.length > 0) {\n const tarOut = await execa('tar', ['-C', args.hostDir, '--null', '-T', '-', '-cf', '-'], {\n input: copy.join('\\0'),\n encoding: 'buffer',\n reject: false,\n // COPYFILE_DISABLE silences macOS BSD tar's `._*` resource-fork stubs;\n // without it a mac host seeds AppleDouble junk into the box's workspace,\n // which `download` then pulls back. Same guard as `host-export.ts`.\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n if (tarOut.exitCode !== 0) {\n throw new Error(`tar of ${args.hostDir} failed`);\n }\n await args.ports.applyTarToBox(tarOut.stdout as Buffer);\n }\n log(\n `sync: ${String(copy.length)} copied, ${String(identical)} unchanged, ${String(skipped.length)} kept by the box`,\n );\n return { copied: copy, skipped, identical, empty: false };\n}\n\n/**\n * Enumerate a HOST dir with the same rules the in-box list script applies, so\n * the push and the pull select the same files. Runs the same `find` expression\n * through the local shell.\n */\nexport async function listHostFiles(\n hostDir: string,\n excludes: readonly string[],\n): Promise<string[]> {\n const script = buildWorkspaceListScript({\n workspaceDir: hostDir,\n respectGitignore: false,\n excludes,\n });\n const r = await execa('bash', ['-c', script], { reject: false });\n if (r.exitCode !== 0) {\n throw new Error(`listing ${hostDir} failed: ${r.stderr || r.stdout}`);\n }\n return parseWorkspaceList(r.stdout).paths;\n}\n","/**\n * Concern: box files — the two primitives every workspace file operation needs\n * from a box (run a shell script, move one tar in or out), expressed over the\n * `Provider` surface rather than over a provider-native transport.\n *\n * `agentbox sync` / `download` / `clone` all move whole trees, and every\n * provider already implements `exec` + `uploadPath` + `downloadPath`. Driving\n * them through those three keeps the non-git sync leg and the cloud pull as ONE\n * implementation instead of a docker copy and a cloud copy — which is exactly\n * the drift `docs/sync-architecture.md` exists to prevent.\n */\n\nimport { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport type { BoxRecord, ExecResult, Provider } from '@agentbox/core';\nimport { NON_REGULAR_TOKEN } from './git.js';\nimport type { WorkspaceOverlayPorts } from './workspace-files.js';\n\n/** Remote staging path for one tar hop. Reused per call; removed in-box after. */\nconst REMOTE_TAR = '/tmp/agentbox-workspace-xfer.tar';\n\nexport interface BoxFilePorts {\n /** Run a shell script in the box. `asRoot` for read-only probes (see below). */\n run(script: string, opts?: { asRoot?: boolean }): Promise<ExecResult>;\n /** Extract a tar buffer into `boxDir` inside the box. */\n pushTar(boxDir: string, tar: Buffer): Promise<void>;\n /** Pack `relPaths` (relative to `boxDir`) in the box and return the tar. */\n pullTar(boxDir: string, relPaths: string[]): Promise<Buffer>;\n}\n\n/** NUL-SEPARATED and NUL-TERMINATED — the shape `read -d ''` / `tar --null` want. */\nfunction nulTerminated(paths: string[]): string {\n return paths.length === 0 ? '' : `${paths.join('\\0')}\\0`;\n}\n\n/**\n * Raw bytes of path list allowed in ONE exec. The list rides in as a single\n * base64 `printf` argument, and Linux caps a single argv entry at\n * `MAX_ARG_STRLEN` = 128 KiB — the whole script, not just the payload. base64\n * costs 4/3, so 48 KiB raw is a 64 KiB argument and leaves the rest of the\n * script (plus the `sudo -u vscode -H bash -lc '…'` wrapper Vercel and E2B add)\n * a wide margin. Without chunking, `clone` / cloud `download` / non-git `sync`\n * simply fail on any workspace with a few thousand files — i.e. a normal repo.\n */\nconst MAX_PAYLOAD_BYTES = 48 * 1024;\n\n/**\n * Split `paths` into groups whose NUL-terminated encoding fits one exec.\n * A single path longer than the budget still gets its own chunk — one\n * oversized argument is the kernel's problem to report, not something to\n * silently drop.\n */\nexport function chunkPathsForExec(\n paths: readonly string[],\n maxBytes: number = MAX_PAYLOAD_BYTES,\n): string[][] {\n const chunks: string[][] = [];\n let current: string[] = [];\n let size = 0;\n for (const p of paths) {\n const cost = Buffer.byteLength(p, 'utf8') + 1; // + the NUL terminator\n if (current.length > 0 && size + cost > maxBytes) {\n chunks.push(current);\n current = [];\n size = 0;\n }\n current.push(p);\n size += cost;\n }\n if (current.length > 0) chunks.push(current);\n return chunks;\n}\n\n/** Single-quote a value for the POSIX shell. */\nfunction sq(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Build the ports for one box over its provider.\n *\n * `asRoot` matters on Vercel and E2B: those backends wrap a non-root exec in\n * `sudo -u vscode -H bash -lc`, and the extra re-parse mangles a script's\n * `$(...)` / `while` (the resync probe hangs on it — see\n * `sandbox-cloud/src/sync/workspace-resync.ts`). Read-only probes therefore run\n * as root, which is a single `bash -lc` with no re-parse. Writes stay as the box\n * user so the extracted files are owned by the agent.\n */\nexport function providerBoxFilePorts(provider: Provider, box: BoxRecord): BoxFilePorts {\n const run = async (script: string, opts?: { asRoot?: boolean }): Promise<ExecResult> =>\n provider.exec(box, ['bash', '-c', script], opts?.asRoot ? { user: 'root' } : undefined);\n\n return {\n run,\n async pushTar(boxDir: string, tar: Buffer): Promise<void> {\n if (!provider.uploadPath) {\n throw new Error(`provider '${provider.name}' cannot upload files into a box`);\n }\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-xfer-'));\n const local = join(stage, 'payload.tar');\n try {\n await writeFile(local, tar);\n await provider.uploadPath(box, [local], REMOTE_TAR);\n const r = await run(\n `set -e\\ntar -C ${sq(boxDir)} -xf ${sq(REMOTE_TAR)}\\nrm -f ${sq(REMOTE_TAR)}`,\n );\n if (r.exitCode !== 0) {\n throw new Error(`extract into ${boxDir} failed: ${r.stderr || r.stdout}`);\n }\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n },\n async pullTar(boxDir: string, relPaths: string[]): Promise<Buffer> {\n if (!provider.downloadPath) {\n throw new Error(`provider '${provider.name}' cannot download files from a box`);\n }\n // The path list goes in base64-encoded: `backend.exec` has no stdin, and a\n // Vercel box has no `/dev/fd` for process substitution (see\n // `docs/cloud-providers.md`). `tar --null -T -` then reads it from a pipe.\n // TERMINATED, not joined: an unterminated final record is not a record,\n // and the reader silently drops it.\n //\n // Chunked because that payload is ONE argv entry (see MAX_PAYLOAD_BYTES).\n // The first chunk creates the archive, the rest APPEND to it — `tar -r`\n // works precisely because REMOTE_TAR is uncompressed.\n const chunks = chunkPathsForExec(relPaths);\n const first = await run(`rm -f ${sq(REMOTE_TAR)}`);\n if (first.exitCode !== 0) {\n throw new Error(`clearing ${REMOTE_TAR} failed: ${first.stderr || first.stdout}`);\n }\n let created = false;\n for (const chunk of chunks) {\n const payload = Buffer.from(nulTerminated(chunk)).toString('base64');\n const packed = await run(\n [\n `set -e`,\n `printf %s ${sq(payload)} | base64 -d | ` +\n `tar -C ${sq(boxDir)} --null -T - ${created ? '-rf' : '-cf'} ${sq(REMOTE_TAR)}`,\n ].join('\\n'),\n );\n if (packed.exitCode !== 0) {\n throw new Error(`packing ${boxDir} failed: ${packed.stderr || packed.stdout}`);\n }\n created = true;\n }\n if (!created) {\n // Nothing selected: still hand back a well-formed (empty) archive rather\n // than downloading a file the box never wrote.\n const empty = await run(`tar -C ${sq(boxDir)} --null -T /dev/null -cf ${sq(REMOTE_TAR)}`);\n if (empty.exitCode !== 0) {\n throw new Error(`packing ${boxDir} failed: ${empty.stderr || empty.stdout}`);\n }\n }\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-xfer-'));\n const local = join(stage, 'payload.tar');\n try {\n await provider.downloadPath(box, [REMOTE_TAR], local);\n const buf = await readFile(local);\n await run(`rm -f ${sq(REMOTE_TAR)}`).catch(() => undefined);\n return buf;\n } finally {\n await rm(stage, { recursive: true, force: true });\n }\n },\n };\n}\n\n/** A probe that could not answer. Callers must abort, never assume an answer. */\nexport class BoxProbeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BoxProbeError';\n }\n}\n\n/**\n * The box half of a non-git workspace overlay, over {@link BoxFilePorts}.\n *\n * The probe emits `<token>\\0<path>\\0` pairs: the sha256 for a regular file, the\n * non-regular sentinel for anything else that exists, and nothing at all when\n * the path is absent — exactly what `classifyUntrackedOverlay` consumes. Paths\n * ride in base64-encoded for the same reason `pullTar`'s do, and are chunked for\n * the same reason too.\n *\n * **Fail-closed.** A non-zero probe THROWS instead of returning what it managed\n * to collect. The overlay reads a missing key as \"the box does not have this\n * path\" and copies the host's file over it, so a degraded probe is\n * indistinguishable from an empty box — and would silently overwrite in-box\n * work, the exact inverse of the box-wins contract. An unreadable answer is not\n * an empty answer.\n */\nexport function boxOverlayPorts(ports: BoxFilePorts, boxDir: string): WorkspaceOverlayPorts {\n return {\n async probeBoxTokens(relPaths: string[]): Promise<Map<string, string>> {\n const tokens = new Map<string, string>();\n if (relPaths.length === 0) return tokens;\n for (const chunk of chunkPathsForExec(relPaths)) {\n // Trailing NUL is load-bearing: `read -d ''` treats an unterminated tail\n // as EOF, so `join` alone silently drops the last path — which the\n // overlay would then read as \"absent in the box\" and overwrite.\n const payload = Buffer.from(nulTerminated(chunk)).toString('base64');\n const script =\n `printf %s ${sq(payload)} | base64 -d | ( cd ${sq(boxDir)} && ` +\n `while IFS= read -r -d '' f; do ` +\n `if [ -f \"$f\" ] && [ ! -L \"$f\" ]; then printf '%s\\\\0%s\\\\0' \"$(sha256sum < \"$f\" | cut -d' ' -f1)\" \"$f\"; ` +\n `elif [ -e \"$f\" ] || [ -L \"$f\" ]; then printf '%s\\\\0%s\\\\0' ${sq(NON_REGULAR_TOKEN)} \"$f\"; fi; done )`;\n const r = await ports.run(script, { asRoot: true });\n if (r.exitCode !== 0) {\n throw new BoxProbeError(\n `could not read ${boxDir} in the box (exit ${String(r.exitCode)}): ` +\n `${r.stderr || r.stdout || 'no output'}\\n` +\n `Refusing to sync: without the box's file list every host file would ` +\n `look new and overwrite the box's version.`,\n );\n }\n const flat = r.stdout.split('\\0').filter((s) => s.length > 0);\n for (let i = 0; i + 1 < flat.length; i += 2) {\n const token = flat[i];\n const path = flat[i + 1];\n if (token !== undefined && path !== undefined) tokens.set(path, token);\n }\n }\n return tokens;\n },\n applyTarToBox: (tar: Buffer) => ports.pushTar(boxDir, tar),\n };\n}\n","/**\n * Concern: workspace pull — the provider-neutral `box → host scratch dir → the\n * user's working dir` pipeline behind `agentbox download` and the export half of\n * `agentbox clone`.\n *\n * Stage 1 (materialize `/workspace` on the host) is the only part that differs\n * per provider. Docker has a bind mount and rsyncs over it (`refreshExport`);\n * everyone else has one tar hop, which is {@link stageBoxWorkspace} here.\n * Stage 2 — the `rsync -a --checksum` into the working dir, and the itemized\n * change list `--dry-run` prints — is `rsyncPullToHost`, shared by both. That\n * split is what makes `--dry-run`, the gitignore selection and\n * `--include-node-modules` work on a cloud box: they all live in the half both\n * providers run.\n *\n * The staged file list is written next to the scratch dir so a second call with\n * `noRefresh` (the CLI previews, then applies) copies exactly the set it\n * previewed, instead of re-deriving one from a box that may have moved on.\n */\n\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport type { BoxRecord, Provider } from '@agentbox/core';\nimport { providerBoxFilePorts } from './box-files.js';\nimport { buildHostEnvFindArgs } from './env.js';\nimport {\n buildWorkspaceListScript,\n agentCloneDropPaths,\n isAgentWorkspaceArtifact,\n isExcludedPath,\n parseWorkspaceList,\n rsyncPullToHost,\n workspaceExcludes,\n type WorkspaceListMode,\n} from './workspace-files.js';\n\n/** Sidecar holding the last staged selection, so `noRefresh` can replay it. */\nconst FILELIST_NAME = 'pull-filelist.json';\n\n/** Single-quote a value for the POSIX shell. */\nfunction sq(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\nexport interface StageWorkspaceArgs {\n provider: Provider;\n box: BoxRecord;\n /** In-box workspace dir (default `/workspace`). */\n boxWorkspaceDir?: string;\n /** Host dir the box's workspace is materialized into. Wiped and refilled. */\n scratchDir: string;\n /** Default true. When false, always use the exclude list. */\n respectGitignore?: boolean;\n /** Default false. Keep `node_modules` — in BOTH git and exclude-list mode. */\n includeNodeModules?: boolean;\n /**\n * Extra env/config basename globs pulled regardless of gitignore (the\n * `--with-env` set). Composes WITH the primary selection.\n */\n envPatterns?: string[];\n /**\n * Apply the exclude patterns to the GIT-mode selection too. Off for\n * `download` — a tracked `.claude/` is the user's own content there and\n * dropping it would be a regression. On for `clone`, whose whole contract is\n * that the new box onboards with a fresh identity, so a state dir must not\n * ride along even when the source box happened to commit it.\n */\n dropExcludedInGitMode?: boolean;\n /**\n * Default true. Write the `pull-filelist.json` sidecar next to the scratch\n * dir so a later `noRefresh` pass replays the same selection. `clone` stages\n * into a user-facing directory and turns it off — the sidecar is scratch-dir\n * bookkeeping, not something to leave beside someone's new project folder.\n */\n writeSidecar?: boolean;\n /**\n * The agent the source box runs, when the caller knows it. Scopes the clone\n * drop (`dropExcludedInGitMode`) to THAT agent's `clone.drop` rather than\n * every registered agent's — an openclaw box's clone should not be shaped by\n * a rule claude declared.\n */\n agent?: string;\n}\n\nexport interface StagedWorkspace {\n scratchDir: string;\n /** NUL-joined relative paths staged, or null when nothing matched. */\n fileList: string | null;\n mode: WorkspaceListMode;\n}\n\n/** Where the sidecar for a scratch dir lives (a sibling, never inside it). */\nfunction fileListPath(scratchDir: string): string {\n return join(dirname(scratchDir), FILELIST_NAME);\n}\n\n/**\n * Stage 1 for every non-docker provider: enumerate the workspace in the box,\n * tar exactly those paths out, and extract them into `scratchDir`.\n *\n * The scratch dir is emptied first — a stale file from a previous pull would\n * otherwise be copied to the host as if the box still had it.\n */\nexport async function stageBoxWorkspace(args: StageWorkspaceArgs): Promise<StagedWorkspace> {\n const boxDir = args.boxWorkspaceDir ?? '/workspace';\n const ports = providerBoxFilePorts(args.provider, args.box);\n const excludes = workspaceExcludes({ includeNodeModules: args.includeNodeModules });\n\n const listed = await ports.run(\n buildWorkspaceListScript({\n workspaceDir: boxDir,\n respectGitignore: args.respectGitignore,\n excludes,\n includeNodeModules: args.includeNodeModules,\n }),\n { asRoot: true },\n );\n if (listed.exitCode !== 0) {\n throw new Error(`listing ${boxDir} in the box failed: ${listed.stderr || listed.stdout}`);\n }\n const primary = parseWorkspaceList(listed.stdout);\n // `clone` also drops the scaffolding the agent regenerates for the new box.\n // Only `clone.drop` — the `clone.render` half (SOUL.md, IDENTITY.md) is the\n // user's own writing and is rewritten for the new bot by the clone instead.\n const artifacts = args.dropExcludedInGitMode ? agentCloneDropPaths(args.agent) : [];\n const selected =\n primary.mode === 'git' && args.dropExcludedInGitMode\n ? primary.paths.filter((p) => !isExcludedPath(p, excludes))\n : primary.paths;\n const kept =\n artifacts.length > 0\n ? selected.filter((p) => !isAgentWorkspaceArtifact(p, artifacts))\n : selected;\n const paths = new Set(kept);\n\n if (args.envPatterns && args.envPatterns.length > 0) {\n const envArgv = buildHostEnvFindArgs(args.envPatterns).map(sq).join(' ');\n const env = await ports.run(`cd ${sq(boxDir)} 2>/dev/null || exit 0\\n${envArgv}`, {\n asRoot: true,\n });\n if (env.exitCode === 0) {\n for (const p of env.stdout.split('\\0')) {\n if (p.length === 0) continue;\n paths.add(p.startsWith('./') ? p.slice(2) : p);\n }\n }\n }\n\n await rm(args.scratchDir, { recursive: true, force: true });\n await mkdir(args.scratchDir, { recursive: true });\n const list = [...paths];\n if (list.length > 0) {\n const tar = await ports.pullTar(boxDir, list);\n const extract = await execa('tar', ['-xf', '-', '-C', args.scratchDir], {\n input: tar,\n reject: false,\n });\n if (extract.exitCode !== 0) {\n throw new Error(`extracting the box workspace failed: ${extract.stderr}`);\n }\n }\n\n const staged: StagedWorkspace = {\n scratchDir: args.scratchDir,\n fileList: list.length > 0 ? list.join('\\0') : null,\n mode: primary.mode,\n };\n if (args.writeSidecar !== false) {\n await writeFile(\n fileListPath(args.scratchDir),\n JSON.stringify({ mode: staged.mode, paths: list }),\n 'utf8',\n );\n }\n return staged;\n}\n\n/** Read back the sidecar a previous {@link stageBoxWorkspace} wrote. */\nexport async function readStagedWorkspace(scratchDir: string): Promise<StagedWorkspace | null> {\n try {\n const raw = JSON.parse(await readFile(fileListPath(scratchDir), 'utf8')) as {\n mode?: string;\n paths?: string[];\n };\n const paths = raw.paths ?? [];\n return {\n scratchDir,\n fileList: paths.length > 0 ? paths.join('\\0') : null,\n mode: raw.mode === 'git' ? 'git' : 'exclude',\n };\n } catch {\n return null;\n }\n}\n\nexport interface PullWorkspaceArgs extends StageWorkspaceArgs {\n /** The user's working dir the files land in (`box.workspacePath`). */\n destDir: string;\n /** Paths the user declined; dropped before copying. */\n skipPaths?: readonly string[];\n /** Default false. Preview only — return the change list without writing. */\n dryRun?: boolean;\n /** Default false. Reuse whatever is already in `scratchDir` (and its sidecar). */\n noRefresh?: boolean;\n}\n\nexport interface PullWorkspaceResult {\n hostPath: string;\n changes: string[];\n applied: boolean;\n /** True when git decided the selection; false means exclude-list mode. */\n usedGitignore: boolean;\n /** Selected paths that were not in the staged copy — reported, not fatal. */\n missing: string[];\n}\n\n/**\n * The whole pull for a provider with no host-visible workspace: stage, then run\n * the shared stage 2. Docker does not use this — it stages over its bind mount —\n * but both end in `rsyncPullToHost`, so the reported change list is the same\n * artifact on every provider.\n */\nexport async function pullWorkspaceToHost(args: PullWorkspaceArgs): Promise<PullWorkspaceResult> {\n const staged = args.noRefresh\n ? ((await readStagedWorkspace(args.scratchDir)) ?? (await stageBoxWorkspace(args)))\n : await stageBoxWorkspace(args);\n\n const { changes, applied, missing } = await rsyncPullToHost({\n scratchDir: staged.scratchDir,\n destDir: args.destDir,\n fileList: staged.fileList,\n excludes: workspaceExcludes({ includeNodeModules: args.includeNodeModules }),\n dryRun: args.dryRun,\n skipPaths: args.skipPaths,\n });\n return {\n hostPath: args.destDir,\n changes,\n applied,\n usedGitignore: staged.mode === 'git',\n missing,\n };\n}\n","/**\n * Concern: workspace clone — export a live box's `/workspace` into a fresh host\n * directory that a NEW box can then be created from.\n *\n * `agentbox clone` stands up a second box from the same workspace files and the\n * same `agentbox.yaml`, with a **fresh agent identity**. The identity half needs\n * no code: an agent's state lives in its config volume / box HOME, and clone\n * simply does not copy it, so the new box runs its onboarding from scratch and\n * generates its own token. (Verified in Phase 0 of the service-boxes plan: two\n * onboards under different HOMEs produce different gateway tokens.) There is\n * deliberately no `--with-state` — two live daemons sharing one identity is the\n * failure mode this design exists to prevent, and box→box migration is the\n * checkpoint path's job.\n *\n * So the gateway identity needs no code. What DOES need code is everything\n * downstream of it: a bot's workspace files still name the source bot, and its\n * channel tokens are per-bot secrets a second instance must not share. Both are\n * declared by the agent (`AgentSyncSpec.clone`) and applied by the hub's clone\n * path -- see `clone.drop` / `clone.render` / `clone.perBoxCarry`.\n *\n * The export itself is the Phase-4b staging pass with one extra rule: exclude\n * patterns apply in git mode too, so an agent state dir cannot ride along even\n * if the source box committed one.\n */\n\nimport { lstat, readdir } from 'node:fs/promises';\nimport type { BoxRecord, Provider } from '@agentbox/core';\nimport { stageBoxWorkspace } from './workspace-pull.js';\n\nexport interface ExportWorkspaceArgs {\n provider: Provider;\n box: BoxRecord;\n /** Host dir to fill. Created if missing; must be empty when it exists. */\n destDir: string;\n /** In-box workspace dir (default `/workspace`). */\n boxWorkspaceDir?: string;\n /** Default false. Carry `node_modules` into the clone as well. */\n includeNodeModules?: boolean;\n /** The agent the source box runs, so the drop is scoped to its `clone.drop`. */\n agent?: string;\n /**\n * Drop the scaffolding the agent regenerates for a new box (`clone.drop` —\n * openclaw's `AGENTS.md` / `USER.md`). Default true, which is the CLONE rule:\n * the new bot writes its own.\n *\n * A BACKUP passes false. A restore is meant to reproduce the bot it captured,\n * so a bundle missing files the user may well have edited is not a backup of\n * that bot — it is a template of it, which is what clone already produces.\n */\n dropAgentScaffolding?: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface ExportWorkspaceResult {\n destDir: string;\n /** Number of files written. */\n files: number;\n /** True when git decided the selection; false means exclude-list mode. */\n usedGitignore: boolean;\n}\n\n/**\n * Throw unless `dir` is absent, or is a real and empty directory.\n *\n * The export `rm -rf`s this path before refilling it, so it has to be\n * POSITIVELY identified first. Reading any stat failure as \"absent\" is what\n * made `--into ~/notes.md` delete `notes.md`: `readdir` on a file fails with\n * `ENOTDIR`, the old code took that for \"nothing there\", and the staging step\n * removed the file and put a directory in its place. Only `ENOENT` means absent;\n * everything else that exists but is not a directory is refused by name.\n */\nexport async function assertEmptyDir(dir: string): Promise<void> {\n let stats;\n try {\n stats = await lstat(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return; // the export creates it\n throw new Error(`cannot use ${dir} as a destination: ${(err as Error).message}`);\n }\n if (stats.isSymbolicLink()) {\n throw new Error(\n `${dir} is a symlink; pick a real directory (the export would replace the link, not its target)`,\n );\n }\n if (!stats.isDirectory()) {\n throw new Error(`${dir} exists and is not a directory; pick another destination`);\n }\n const entries = await readdir(dir);\n if (entries.length > 0) {\n throw new Error(`${dir} is not empty; pick another destination or empty it first`);\n }\n}\n\n/**\n * Copy the source box's workspace files into `destDir`.\n *\n * `.git` is never part of the export: the git selection lists tracked +\n * untracked-not-ignored files, and the exclude list drops the directory itself.\n * The clone is therefore a template — files and `agentbox.yaml`, no history and\n * no branch. That is the intended shape (a new tenant, not a second checkout);\n * a git-backed clone is `agentbox create` on the same project.\n */\nexport async function exportBoxWorkspace(\n args: ExportWorkspaceArgs,\n): Promise<ExportWorkspaceResult> {\n const log = args.onLog ?? ((): void => {});\n await assertEmptyDir(args.destDir);\n log(`exporting ${args.box.name}:/workspace to ${args.destDir}`);\n const staged = await stageBoxWorkspace({\n provider: args.provider,\n box: args.box,\n boxWorkspaceDir: args.boxWorkspaceDir,\n scratchDir: args.destDir,\n includeNodeModules: args.includeNodeModules,\n dropExcludedInGitMode: true,\n writeSidecar: false,\n ...(args.dropAgentScaffolding === false ? {} : { agent: args.agent }),\n });\n const files = staged.fileList === null ? 0 : staged.fileList.split('\\0').length;\n log(`exported ${String(files)} file(s)${staged.mode === 'git' ? '' : ' (exclude-list mode)'}`);\n return { destDir: args.destDir, files, usedGitignore: staged.mode === 'git' };\n}\n","/**\n * `agentbox upload` — host → live box, both legs.\n *\n * A box's workspace is either a git worktree or a plain directory, and the two\n * need different machinery:\n *\n * - **git leg** — `provider.resyncWorkspace`, which has existed and been\n * golden-tested since the sync refactor but was reachable only from an\n * agent-session start after a down→up transition. It merges the host branch\n * into the box branch and overlays the host's uncommitted + untracked\n * changes. Nothing here re-implements it.\n * - **non-git leg** — new. Enumerate the host dir with the shared workspace\n * excludes, hash each file, ask the box what it has, and copy only what the\n * box is missing.\n *\n * Both legs keep the same promise: **the box wins.** Nothing in the box is ever\n * overwritten or reset, only added to; a host file the box has changed is\n * skipped and reported. This runs against a live box, so a destructive default\n * would be a data-loss default.\n *\n * Shared by the CLI command and the hub's `POST /api/v1/boxes/:id/sync`, so the\n * web UI and the tray get the same operation.\n */\n\nimport type { BoxRecord, Provider } from '@agentbox/core';\nimport { detectGitRepos } from '../../git-detect.js';\nimport { boxOverlayPorts, providerBoxFilePorts } from './box-files.js';\nimport { overlayHostDirIntoBox, workspaceExcludes } from './workspace-files.js';\n\nexport interface UploadWorkspaceArgs {\n provider: Provider;\n box: BoxRecord;\n /** In-box workspace dir (default `/workspace`). */\n boxWorkspaceDir?: string;\n /** Default false. Keep `node_modules` in the non-git push. */\n includeNodeModules?: boolean;\n onLog?: (line: string) => void;\n}\n\nexport interface UploadWorkspaceResult {\n /** Which leg ran. `git` merges; `files` overlays a plain directory. */\n mode: 'git' | 'files';\n /** Paths the box kept its own version of (the host change was skipped). */\n conflicts: string[];\n /** Files copied into the box. Always 0 on the git leg (git reports merges). */\n copied: number;\n /** Per-repo merge/overlay detail, git leg only. */\n repos?: { containerPath: string; mergeConflicts: string[]; overlaySkipped: string[] }[];\n}\n\n/**\n * Push the host workspace into a live box. Picks the leg from what the HOST\n * workspace is: a git repo there means the box was seeded as a worktree/clone\n * and the git path applies; anything else is a plain file overlay.\n */\nexport async function uploadWorkspaceToBox(\n args: UploadWorkspaceArgs,\n): Promise<UploadWorkspaceResult> {\n const log = args.onLog ?? ((): void => {});\n const boxDir = args.boxWorkspaceDir ?? '/workspace';\n const repos = await detectGitRepos(args.box.workspacePath);\n\n if (repos.length > 0) {\n if (!args.provider.resyncWorkspace) {\n throw new Error(\n `provider '${args.provider.name}' cannot resync a git workspace into a live box`,\n );\n }\n log('syncing git workspace (merge host branch + overlay uncommitted/untracked)');\n const result = await args.provider.resyncWorkspace(args.box, log);\n const conflicts = result.repos.flatMap((r) => [...r.mergeConflicts, ...r.overlaySkipped]);\n return { mode: 'git', conflicts, copied: 0, repos: result.repos };\n }\n\n log('syncing non-git workspace (file overlay; the box wins on conflict)');\n const ports = providerBoxFilePorts(args.provider, args.box);\n const overlay = await overlayHostDirIntoBox({\n hostDir: args.box.workspacePath,\n excludes: workspaceExcludes({ includeNodeModules: args.includeNodeModules }),\n ports: boxOverlayPorts(ports, boxDir),\n onLog: log,\n });\n return { mode: 'files', conflicts: overlay.skipped, copied: overlay.copied.length };\n}\n","/**\n * Concern: dynamic Claude config — the global `~/.claude/workflows/` scripts and\n * the current project's `memory/` tree. Unlike the static config\n * (plugins/skills/settings) that the cloud path bakes into the prepare-time\n * snapshot, these change between runs and must be refreshed per-box at create —\n * like credentials.\n *\n * These pieces are provider-neutral and pure where possible, so both the docker\n * volume sync and the cloud `seedDynamicConfig` reuse them:\n *\n * - `buildHostSyncManifest` hashes every file in each set on the host.\n * - `computeSyncDelta` diffs that against the manifest the box already\n * carries (captured by any checkpoint/snapshot), yielding the minimal set\n * of files to upload + delete and the manifest to write back.\n * - `stageDynamicSyncTarball` packs only the changed files into one tarball\n * whose members are laid out by set name, so the box `cp -a`s each set into\n * place without tar touching shared parent-dir perms.\n *\n * The box stores its manifest at {@link BOX_DYNAMIC_SYNC_MANIFEST}. Because it\n * lives on the box filesystem it rides along in every checkpoint, so a\n * checkpoint boot naturally syncs only what changed on the host since.\n *\n * Moved here (from `@agentbox/sandbox-docker`'s `dynamic-sync.ts`) so the cloud\n * path reuses it without importing the docker package. `sandbox-docker`\n * re-exports these for its existing importers.\n */\n\nimport { createHash } from 'node:crypto';\nimport { copyFile, mkdir, mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { execa } from 'execa';\nimport { BOX_CLAUDE_PROJECT_DIR, resolveClaudeMemoryDir } from '../agents/claude/paths.js';\n\n/** In-box destination for the global workflow scripts. */\nexport const BOX_WORKFLOWS_DIR = '/home/vscode/.claude/workflows';\n\n/** In-box path of the per-box dynamic-sync manifest (rides along in checkpoints). */\nexport const BOX_DYNAMIC_SYNC_MANIFEST = '/home/vscode/.agentbox/dynamic-sync.json';\n\n/** In-box destination for the current project's rekeyed memory. */\nexport const BOX_MEMORY_DIR = `${BOX_CLAUDE_PROJECT_DIR}/memory`;\n\nexport type DynamicSyncSetName = 'workflows' | 'memory';\n\n/** A set's box destination dir + per-file content hashes (relpath -> sha256 hex). */\nexport interface DynamicSyncSet {\n dst: string;\n files: Record<string, string>;\n}\n\n/** Persisted shape written to {@link BOX_DYNAMIC_SYNC_MANIFEST}. */\nexport interface DynamicSyncManifest {\n version: 1;\n syncedAt?: string;\n sets: Record<DynamicSyncSetName, DynamicSyncSet>;\n}\n\n/** Host-side set: like {@link DynamicSyncSet} plus the source dir to read bytes from. */\ninterface HostSyncSet extends DynamicSyncSet {\n /** Absolute host source dir, or null when this set has nothing on the host. */\n hostDir: string | null;\n}\n\nexport interface HostSyncManifest {\n sets: Record<DynamicSyncSetName, HostSyncSet>;\n}\n\nexport interface DynamicSyncUpload {\n set: DynamicSyncSetName;\n /** Path relative to the set's dir. */\n rel: string;\n /** Absolute host source file. */\n absSrc: string;\n /** Absolute box destination file (`dst/rel`). */\n dst: string;\n}\n\nexport interface DynamicSyncDeletion {\n set: DynamicSyncSetName;\n rel: string;\n /** Absolute box file to remove. */\n dst: string;\n}\n\nexport interface DynamicSyncDelta {\n uploads: DynamicSyncUpload[];\n deletions: DynamicSyncDeletion[];\n /** Manifest to persist into the box after applying the delta (host state). */\n nextManifest: DynamicSyncManifest;\n}\n\nasync function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Recursively collect regular-file relpaths under `root` (posix-separated). */\nasync function walkFiles(root: string, prefix = ''): Promise<string[]> {\n let entries;\n try {\n entries = await readdir(root, { withFileTypes: true });\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const ent of entries) {\n const rel = prefix ? `${prefix}/${ent.name}` : ent.name;\n const full = join(root, ent.name);\n if (ent.isDirectory()) {\n out.push(...(await walkFiles(full, rel)));\n } else if (ent.isFile()) {\n out.push(rel);\n } else if (ent.isSymbolicLink()) {\n // Follow only symlinks that resolve to a regular file (e.g. a workflow\n // symlinked from a checkout); ignore dangling/dir links.\n try {\n const s = await stat(full);\n if (s.isFile()) out.push(rel);\n } catch {\n /* skip dangling */\n }\n }\n }\n return out;\n}\n\nasync function hashFile(absPath: string): Promise<string> {\n const buf = await readFile(absPath);\n return createHash('sha256').update(buf).digest('hex');\n}\n\nasync function buildHostSet(\n name: DynamicSyncSetName,\n hostDir: string | null,\n boxDst: string,\n): Promise<HostSyncSet> {\n if (hostDir === null) return { dst: boxDst, files: {}, hostDir: null };\n const rels = await walkFiles(hostDir);\n const files: Record<string, string> = {};\n for (const rel of rels) {\n files[rel] = await hashFile(join(hostDir, rel));\n }\n return { dst: boxDst, files, hostDir };\n}\n\n/**\n * Hash the host's workflow + memory sets. `workspacePath` is the host-absolute\n * project path (used to locate the project's memory dir); `hostHome` is\n * overridable for tests. Sets with nothing on the host get an empty `files` map\n * and `hostDir: null` so the diff can still emit deletions for them.\n */\nexport async function buildHostSyncManifest(\n workspacePath: string,\n hostHome: string = homedir(),\n): Promise<HostSyncManifest> {\n const workflowsDir = join(hostHome, '.claude', 'workflows');\n const workflowsHost = (await pathExists(workflowsDir)) ? workflowsDir : null;\n const memoryHost = await resolveClaudeMemoryDir(workspacePath, hostHome);\n const [workflows, memory] = await Promise.all([\n buildHostSet('workflows', workflowsHost, BOX_WORKFLOWS_DIR),\n buildHostSet('memory', memoryHost, BOX_MEMORY_DIR),\n ]);\n return { sets: { workflows, memory } };\n}\n\nconst SET_NAMES: DynamicSyncSetName[] = ['workflows', 'memory'];\n\n/**\n * Diff the host manifest against the manifest the box already carries. A file\n * is uploaded when its hash differs (new or changed); a file in the box\n * manifest absent on the host is deleted. Pure — no IO, no clock.\n */\nexport function computeSyncDelta(\n host: HostSyncManifest,\n box: DynamicSyncManifest | null,\n): DynamicSyncDelta {\n const uploads: DynamicSyncUpload[] = [];\n const deletions: DynamicSyncDeletion[] = [];\n const nextSets = {} as Record<DynamicSyncSetName, DynamicSyncSet>;\n\n for (const name of SET_NAMES) {\n const hostSet = host.sets[name];\n const boxFiles = box?.sets?.[name]?.files ?? {};\n for (const [rel, hash] of Object.entries(hostSet.files)) {\n if (boxFiles[rel] !== hash) {\n uploads.push({\n set: name,\n rel,\n absSrc: join(hostSet.hostDir as string, rel),\n dst: `${hostSet.dst}/${rel}`,\n });\n }\n }\n for (const rel of Object.keys(boxFiles)) {\n if (!(rel in hostSet.files)) {\n deletions.push({ set: name, rel, dst: `${hostSet.dst}/${rel}` });\n }\n }\n nextSets[name] = { dst: hostSet.dst, files: hostSet.files };\n }\n\n return { uploads, deletions, nextManifest: { version: 1, sets: nextSets } };\n}\n\nexport interface StagedTarball {\n /** Absolute path to the .tar.gz, or null when there was nothing to upload. */\n tarballPath: string | null;\n /** Remove the staging dir + tarball. Idempotent. */\n cleanup(): Promise<void>;\n}\n\n/**\n * Pack the upload files into one gzip tarball laid out by set name\n * (`workflows/<rel>`, `memory/<rel>`). The box extracts into a staging dir and\n * `cp -a`s each set into its destination, so tar never touches the perms of\n * shared parent dirs (`/`, `/home`). Returns `{ tarballPath: null }` when\n * `uploads` is empty.\n */\nexport async function stageDynamicSyncTarball(\n uploads: DynamicSyncUpload[],\n): Promise<StagedTarball> {\n if (uploads.length === 0) {\n return { tarballPath: null, cleanup: async () => {} };\n }\n const stageDir = await mkdtemp(join(tmpdir(), 'agentbox-dynsync-stage-'));\n let tarballPath: string | null = null;\n try {\n for (const up of uploads) {\n const target = join(stageDir, up.set, up.rel);\n await mkdir(dirname(target), { recursive: true });\n await copyFile(up.absSrc, target);\n }\n tarballPath = join(tmpdir(), `agentbox-dynsync-${basename(stageDir)}.tar.gz`);\n // COPYFILE_DISABLE=1: stop macOS bsdtar from emitting AppleDouble sidecars.\n await execa('tar', ['-czf', tarballPath, '-C', stageDir, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n const tp = tarballPath;\n return {\n tarballPath: tp,\n cleanup: async () => {\n await rm(stageDir, { recursive: true, force: true });\n await rm(tp, { force: true });\n },\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n","/**\n * Stage the host's agent-config trees (`~/.claude`, `~/.codex`,\n * `~/.config/opencode` + `~/.local/share/opencode`) into filtered tarballs any\n * provider can ship into a remote sandbox.\n *\n * Per agent we produce **two** tarballs:\n *\n * - **static**: plugins, skills, settings, marketplaces, prompts, config —\n * stuff that's stable across re-auths. The cloud path bakes this into the\n * published Daytona snapshot once (`agentbox daytona publish-snapshot`),\n * so it ships into the sandbox FS at snapshot capture time, never the\n * S3-backed FUSE volume.\n *\n * - **credentials**: the renewable OAuth/auth files only (a handful of KB).\n * The cloud path uploads these into a per-org `agentbox-credentials`\n * volume on every create (cheap) and `agentbox daytona resync` refreshes\n * them after a re-auth — without touching the snapshot.\n *\n * Each `stage*ForUpload(opts)` returns a `StageResult`:\n * - `tarballPath`: absolute path to a `.tar.gz`, or `null` when the host has\n * nothing relevant to stage (no `~/.claude` etc., or no credentials file).\n * - `cleanup()`: removes the staging dir + the tarball; ALWAYS call after\n * the upload completes, even on error.\n * - `warnings`: non-fatal user-facing messages (the codex Keychain landmine\n * surfaces here).\n *\n * Requires `rsync` and `tar` on the host. macOS + every common Linux distro\n * ship both.\n */\n\nimport { copyFile, mkdtemp, readdir, rm, stat } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { basename, join, relative } from 'node:path';\nimport { execa } from 'execa';\nimport { resolveAgentSpec } from './registry.js';\nimport type { AgentId, AgentPathMap } from '@agentbox/core';\nimport { agentPushExcludes } from '@agentbox/core';\n\n/**\n * Portable host backup of the claude OAuth creds — the single source of truth is\n * the registry (`credential.hostBackup`), which resolves to\n * `~/.agentbox/claude-credentials.json`. The docker provider's\n * `syncClaudeCredentials` mirrors the macOS Keychain into this same path.\n */\n\nexport interface StageResult {\n /** Absolute path to the .tar.gz, or null when there was nothing to stage. */\n tarballPath: string | null;\n /** Remove the staging dir + tarball. Idempotent. */\n cleanup(): Promise<void>;\n /** Non-fatal messages (e.g. codex Keychain landmine). */\n warnings: string[];\n}\n\nexport async function pathExists(p: string): Promise<boolean> {\n try {\n await stat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function findBrokenSymlinks(root: string): Promise<string[]> {\n const broken: string[] = [];\n async function walk(dir: string): Promise<void> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const ent of entries) {\n const full = join(dir, ent.name);\n if (ent.isSymbolicLink()) {\n try {\n await stat(full);\n } catch {\n broken.push(relative(root, full));\n }\n } else if (ent.isDirectory()) {\n await walk(full);\n }\n }\n }\n await walk(root);\n return broken;\n}\n\nexport async function mkStageDir(prefix: string): Promise<string> {\n return mkdtemp(join(tmpdir(), `agentbox-${prefix}-stage-`));\n}\n\n// A stage dir is a throwaway scratch copy that we rewrite in place (filter\n// settings.json, sanitize config.toml, rewrite plugin paths) and then `rm`.\n// `rsync -a` implies `-p`, so it preserves the *source's* modes — and when the\n// source is read-only (skill/plugin symlinks into the Nix store, or any\n// root-owned / 0444 dotfiles), the copy comes out read-only too. That breaks us\n// two ways: the in-place `writeFile` rewrites fail with EACCES, and `rm` can't\n// unlink children of a 0555 dir (`EACCES unlink .../skills/*/SKILL.md`). Force\n// the copy user-writable — a scratch dir has no business inheriting the store's\n// perms. Only GNU rsync honors this; macOS's openrsync ignores it (and doesn't\n// hit the read-only-source case in practice), so it's a safe no-op there.\nexport const STAGE_WRITABLE_CHMOD = '--chmod=Du+rwx,Fu+rw';\n\n// `rsync -a` implies `-D` (devices + specials), so a unix socket in the source\n// tree — codex's `~/.codex/ipc/ipc.sock`, live whenever the desktop app has run\n// — makes rsync try to recreate it in the stage dir. On macOS that bind() fails\n// with EINVAL once the destination path exceeds sockaddr_un's 104-byte limit\n// (`/var/folders/.../agentbox-<agent>-static-stage-XXXXXX/ipc/.ipc.sock.XXXXXX`\n// clears it easily), aborting the whole stage with exit 23. A socket is dead\n// weight in a snapshot anyway — nothing in the box can connect to the host's\n// end — so skip specials and devices outright.\nexport const STAGE_NO_SPECIALS = '--no-D';\n\nexport function emptyResult(warnings: string[] = []): StageResult {\n return { tarballPath: null, cleanup: async () => {}, warnings };\n}\n\nexport async function tarballFromDir(stageDir: string, agent: string): Promise<string> {\n const tarballPath = join(tmpdir(), `agentbox-${agent}-${basename(stageDir)}.tar.gz`);\n // COPYFILE_DISABLE=1: macOS's bsdtar (the system `tar`) walks extended attrs\n // and emits AppleDouble `._<name>` sidecars for any file with xattrs, which\n // then pollute the volume inside the cloud sandbox (claude reads ~/.claude\n // top-level and chokes on those bogus entries). The env knob makes Apple's\n // copyfile() helpers a no-op, so tar produces a clean POSIX archive.\n await execa('tar', ['-czf', tarballPath, '-C', stageDir, '.'], {\n env: { ...process.env, COPYFILE_DISABLE: '1' },\n });\n return tarballPath;\n}\n\nexport function makeCleanup(paths: string[]): () => Promise<void> {\n return async () => {\n for (const p of paths) {\n await rm(p, { recursive: true, force: true });\n }\n };\n}\n\n/**\n * Stage one file into a tarball whose only entry is that file at the tarball\n * root. Used for the credentials-only variants.\n */\nexport async function stageSingleFileTarball(\n agent: string,\n sourcePath: string,\n tarballEntryName: string,\n): Promise<StageResult> {\n const stageDir = await mkStageDir(agent);\n let tarballPath: string | null = null;\n try {\n await copyFile(sourcePath, join(stageDir, tarballEntryName));\n tarballPath = await tarballFromDir(stageDir, agent);\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n// ---------- the generic stager ----------\n\n/**\n * Stage one agent's static config from its registry row alone.\n *\n * Every `staticPaths` entry carries what an rsync needs — host source, box\n * destination, sub-path to land at, includes and excludes — so an agent that\n * needs no post-processing needs no code here at all: it declares its paths and\n * this stages them. That is what makes a newly added agent reach every cloud\n * provider's snapshot without an edit to this file.\n *\n * `stagedAs: 'state'` entries are skipped. They are two-way per-box state, and\n * a snapshot is shared by every box made from it.\n *\n * Agents whose staging needs more than a copy (claude filters host hooks, codex\n * sanitizes `config.toml` and purges orphan marketplaces) keep a dedicated\n * stager, listed in `DEDICATED_STATIC_STAGERS` below.\n */\nexport async function stageAgentStaticForUpload(\n agent: string,\n opts: { hostHome?: string } = {},\n): Promise<StageResult> {\n const spec = resolveAgentSpec(agent);\n const hostHome = opts.hostHome ?? homedir();\n const sources = spec.staticPaths.filter((sp) => (sp.stagedAs ?? 'static') === 'static');\n\n const present: Array<{ path: AgentPathMap; hostPath: string }> = [];\n for (const path of sources) {\n const hostPath = join(hostHome, ...path.hostHomeRel);\n if (await pathExists(hostPath)) present.push({ path, hostPath });\n }\n if (present.length === 0) return emptyResult();\n\n const stageDir = await mkStageDir(`${spec.id}-static`);\n let tarballPath: string | null = null;\n try {\n for (const { path, hostPath } of present) {\n const dest = path.relocToSubpath ? join(stageDir, path.relocToSubpath) : stageDir;\n // `-L` dereferences symlinks (Daytona's FUSE volumes reject creating\n // them); a broken one would abort the whole rsync, so pre-scan and\n // exclude. Rule order is first-match-wins: the anchored broken-symlink\n // excludes come first, then the includes that carve out of the excludes.\n const broken = await findBrokenSymlinks(hostPath);\n await execa('rsync', [\n '-a',\n STAGE_WRITABLE_CHMOD,\n STAGE_NO_SPECIALS,\n '-L',\n ...broken.map((r) => `--exclude=/${r}`),\n ...(path.include ?? []).map((pat) => `--include=${pat}`),\n // One list for both transports. `agentPushExcludes` adds the\n // live-database deny and, for a SHARED snapshot, the credential file.\n ...agentPushExcludes(spec, path, 'snapshot').map((pat) => `--exclude=${pat}`),\n `${hostPath}/`,\n `${dest}/`,\n ]);\n }\n tarballPath = await tarballFromDir(stageDir, `${spec.id}-static`);\n return { tarballPath, cleanup: makeCleanup([stageDir, tarballPath]), warnings: [] };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n/**\n * Filtered tarball of `~/.agents/` (the cross-agent \"Agent Skills\" dir).\n * Extracts into `/home/vscode/.agents/` on the sandbox FS at snapshot-bake time\n * so the in-box agents (codex reads `~/.agents/skills` directly) see the same\n * skill set the host does. `-L` dereferences each skill's symlinks into real\n * files; broken ones are excluded so the sync can't abort.\n */\nexport async function stageAgentsStaticForUpload(\n opts: { hostHome?: string } = {},\n): Promise<StageResult> {\n const hostHome = opts.hostHome ?? homedir();\n const hostAgents = join(hostHome, '.agents');\n if (!(await pathExists(hostAgents))) return emptyResult();\n\n const stageDir = await mkStageDir('agents-static');\n let tarballPath: string | null = null;\n try {\n const broken = await findBrokenSymlinks(hostAgents);\n await execa('rsync', [\n '-a',\n STAGE_WRITABLE_CHMOD,\n STAGE_NO_SPECIALS,\n '-L',\n ...broken.map((r) => `--exclude=/${r}`),\n `${hostAgents}/`,\n `${stageDir}/`,\n ]);\n tarballPath = await tarballFromDir(stageDir, 'agents-static');\n return {\n tarballPath,\n cleanup: makeCleanup([stageDir, tarballPath]),\n warnings: [],\n };\n } catch (err) {\n await rm(stageDir, { recursive: true, force: true });\n if (tarballPath) await rm(tarballPath, { force: true });\n throw err;\n }\n}\n\n// ---------- all-agent static bake (shared across cloud prepare paths) ----------\n\n/** Box-side dir each tool's static tarball extracts into. Provider-neutral —\n * the same target on every backend (docker model). */\n/** Extract root for the shared `~/.agents` skills tree. */\nexport const AGENTS_STATIC_BOX_DIR = '/home/vscode/.agents';\n\nexport interface AgentStaticStage {\n kind: AgentId | 'agents';\n /** Absolute box path the static tarball extracts into. */\n extractDir: string;\n staged: StageResult;\n}\n\n/**\n * Stage all four host static-config trees in parallel, each paired with the\n * box-side dir it extracts into. This is the single source of truth for the\n * cloud prepare paths (vercel / hetzner / daytona / e2b): every provider walks\n * this list and supplies only its own upload + extract transport, never its own\n * copy of the producer→dir mapping. The caller must `staged.cleanup()` each\n * result after the build has picked the tarball up.\n */\n","/**\n * Cross-provider versioning primitives for `~/.agentbox/<provider>-prepared.json`.\n *\n * Each provider records what it has baked (docker image / hetzner snapshot /\n * daytona snapshot) under a per-provider JSON file with a shared `base.*`\n * substructure so the CLI can detect when the on-disk artifact is stale\n * relative to the current CLI's build context.\n *\n * The invalidation key is `base.contextSha256`: a deterministic SHA-256\n * over every file in the build context (Dockerfile + scripts + baked\n * config), keyed by the file's relative path. Two CLIs with the same\n * staged runtime tree produce the same hash; an edit to any baked asset\n * — even a one-byte tweak to `custom-system-CLAUDE.md` — flips it.\n *\n * Checkpoints embed the captured `contextSha256` so restoring an older\n * checkpoint can warn the user that the baked layers predate the current\n * base image.\n */\n\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, resolve as pathResolve } from 'node:path';\n\nimport type { ProviderKind } from '@agentbox/config';\nimport type { AgentSettings } from '@agentbox/core';\nimport { findAgentSpec } from './sync/registry.js';\n\n/**\n * Providers that bake a `~/.agentbox/<provider>-prepared.json` artifact. The\n * built-in set is the config `ProviderKind`; the `(string & {})` arm keeps\n * autocomplete for those while also admitting an external plugin's open-string\n * provider name (a plugin manages its own prepared-state — see docs/provider-plugins.md).\n */\nexport type PreparedProviderKind = ProviderKind | (string & {});\n\n/**\n * The cross-provider record. `TImage` is the provider's opaque image\n * identifier: a string tag for docker/daytona, a numeric image id for\n * hetzner. The `TExtra` slot lets a provider attach provider-specific\n * fields (e.g. hetzner's `description` and `projects[]`) without forking\n * the whole shape.\n */\nexport interface PreparedBaseSnapshot<TImage = string, TExtra = unknown> {\n /** Schema version. Bumped when the on-disk shape changes incompatibly. */\n schema: number;\n base?: {\n /** Provider-opaque image identifier (docker tag | hetzner imageId | daytona snapshot name). */\n imageRef: TImage;\n /** Deterministic SHA-256 of the build context — the invalidation key. */\n contextSha256: string;\n /** Informational: CLI version that produced this artifact. */\n cliVersion: string;\n /** Informational: git short SHA injected at CLI build time (or 'dev'). */\n cliCommit?: string;\n /** ISO timestamp of bake completion. */\n createdAt: string;\n /**\n * Per-file digests of the context this base was baked from (relpath →\n * sha256), so a later `stale` verdict can name the files that changed\n * rather than only reporting that the aggregate hash moved.\n *\n * Optional: records stamped before manifests existed simply lack it, and\n * consumers must degrade to \"no manifest recorded, re-bake to enable the\n * diff\" rather than inventing one.\n */\n files?: FileManifest;\n };\n /** Provider-specific extras (e.g. hetzner's per-project snapshot tier). */\n extras?: TExtra;\n}\n\nexport function preparedStatePathFor(provider: PreparedProviderKind): string {\n // The name lands in a filename; a plugin's open-string name could otherwise\n // carry a path separator. Provider names are `[a-z0-9-]` by convention — reject\n // anything else rather than resolve outside ~/.agentbox.\n if (!/^[A-Za-z0-9._-]+$/.test(provider)) {\n throw new Error(`invalid provider name for prepared-state: ${JSON.stringify(provider)}`);\n }\n return pathResolve(homedir(), '.agentbox', `${provider}-prepared.json`);\n}\n\n/**\n * Read the prepared-state file for `provider`. Returns `null` when the file\n * is missing, malformed, or carries a schema this code doesn't recognise —\n * callers treat all three as \"rebuild needed\". Sync so it can run from\n * non-async setup paths (mirrors the hetzner helper it generalises).\n */\nexport function readPreparedStateRaw(provider: PreparedProviderKind): unknown {\n const path = preparedStatePathFor(provider);\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, 'utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * Atomic write: write to `<path>.tmp` then rename. `mode: 0o600` because\n * the file is informational but lives alongside `secrets.env` — same dir,\n * same permissions hygiene.\n */\nexport function writePreparedStateRaw(provider: PreparedProviderKind, state: unknown): void {\n const path = preparedStatePathFor(provider);\n mkdirSync(dirname(path), { recursive: true });\n const body = JSON.stringify(state, null, 2) + '\\n';\n const tmp = `${path}.tmp`;\n writeFileSync(tmp, body, { mode: 0o600 });\n renameSync(tmp, path);\n}\n\nexport async function sha256OfFile(path: string): Promise<string> {\n const buf = await readFile(path);\n return createHash('sha256').update(buf).digest('hex');\n}\n\nexport interface ContextFile {\n /**\n * Logical relative path. Used as the canonical key for hash determinism\n * — two stagings with identical contents but different absolute paths\n * must hash the same.\n */\n rel: string;\n /** Absolute path the file is read from. */\n abs: string;\n}\n\n/**\n * Deterministic hash over a set of context files. Entries are sorted by\n * `rel` then hashed as `<rel>\\0<sha256(file)>\\n` lines into a final SHA-256.\n *\n * - Sort order = determinism (the caller can pass files in any order).\n * - NUL separator = no collision between a `rel` ending in hex and the\n * following digest.\n * - Trailing newline per record = stable framing.\n *\n * Missing files raise — silently skipping would let a partial dev rebuild\n * stamp a hash that doesn't represent what's actually in the image.\n */\nexport async function computeContextSha256(files: ContextFile[]): Promise<string> {\n return (await computeContextManifest(files)).contextSha256;\n}\n\n/** Per-file digests keyed by the canonical `rel` path. */\nexport type FileManifest = Record<string, string>;\n\nexport interface ContextManifest {\n /** The same aggregate hash `computeContextSha256` returns. */\n contextSha256: string;\n /** Every file that fed it, so a later mismatch can name the culprit. */\n files: FileManifest;\n}\n\n/**\n * {@link computeContextSha256}, but keeping the per-file digests it folds.\n *\n * The aggregate hash alone can only ever say \"the build context changed\" — it\n * cannot say *which* file changed, which is the one thing anyone actually wants\n * when a provider reports `stale`. Recording the per-file map at bake time is\n * what makes that diff possible later (see {@link diffFileManifests}); the\n * digests were already being computed here and thrown away.\n *\n * Same shape as `DynamicSyncSet.files` in sync/concerns/dynamic.ts — one\n * relpath→sha256 convention across the codebase.\n */\nexport async function computeContextManifest(files: ContextFile[]): Promise<ContextManifest> {\n const sorted = [...files].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));\n const outer = createHash('sha256');\n const manifest: FileManifest = {};\n for (const f of sorted) {\n const inner = await sha256OfFile(f.abs);\n manifest[f.rel] = inner;\n outer.update(`${f.rel}\\0${inner}\\n`);\n }\n return { contextSha256: outer.digest('hex'), files: manifest };\n}\n\nexport interface FileManifestDiff {\n /** Present in both, different contents — the usual cause of a stale base. */\n changed: { rel: string; from: string; to: string }[];\n /** Only in the current context (a file added since the bake). */\n added: string[];\n /** Only in the baked manifest (a file removed since). */\n removed: string[];\n}\n\n/** Pure compare of a baked manifest against the current one. */\nexport function diffFileManifests(stored: FileManifest, current: FileManifest): FileManifestDiff {\n const changed: FileManifestDiff['changed'] = [];\n const added: string[] = [];\n const removed: string[] = [];\n for (const [rel, to] of Object.entries(current)) {\n const from = stored[rel];\n if (from === undefined) added.push(rel);\n else if (from !== to) changed.push({ rel, from, to });\n }\n for (const rel of Object.keys(stored)) {\n if (current[rel] === undefined) removed.push(rel);\n }\n changed.sort((a, b) => (a.rel < b.rel ? -1 : 1));\n added.sort();\n removed.sort();\n return { changed, added, removed };\n}\n\n/** Short form for log lines — first 12 hex chars of a sha256. */\nexport function shortFingerprint(sha: string): string {\n return sha.slice(0, 12);\n}\n\n/** Normalize an agent set so ordering and duplicates can't change the hash. */\nexport function normalizeAgentSet(agents: readonly string[] | undefined): string[] {\n return [...new Set((agents ?? []).map((a) => a.trim()).filter((a) => a.length > 0))].sort();\n}\n\n/** The `AGENTBOX_AGENTS` build-arg / env value for a set (empty string = no agents). */\nexport function agentSetArg(agents: readonly string[] | undefined): string {\n return normalizeAgentSet(agents).join(',');\n}\n\n/** Every agent's declared settings, keyed by agent id. */\nexport type AgentSettingsMap = Readonly<Record<string, AgentSettings>>;\n\n/**\n * The settings entries that change what a BAKE produces, canonicalised as\n * sorted `<agent>.<key>=<value>` strings.\n *\n * Two filters, both load-bearing. Only settings the agent declared\n * `affectsBake` count — claude's `tui` rides the launch env, and folding it\n * would re-bake a whole image for a renderer flip. And a value equal to its\n * declared default is dropped, so **a default-configured bake keeps the raw\n * context hash**: without that, adding a setting to any agent would invalidate\n * every existing artifact on every provider.\n *\n * An agent the registry doesn't know (a plugin removed after its box was baked)\n * contributes nothing rather than throwing — a fingerprint must not be able to\n * fail a create.\n */\nexport function bakeSettingsFingerprintInput(settings?: AgentSettingsMap): string[] {\n if (!settings) return [];\n const out: string[] = [];\n for (const [agentId, values] of Object.entries(settings)) {\n const spec = findAgentSpec(agentId);\n for (const declared of spec?.settings ?? []) {\n if (!declared.affectsBake) continue;\n const value = values[declared.key];\n if (value === undefined || value === declared.default) continue;\n out.push(`${agentId}.${declared.key}=${String(value)}`);\n }\n }\n return out.sort();\n}\n\n/**\n * Fold a base image's build variant into its context fingerprint, so two images\n * built from the same context but carrying different agents (or a different\n * value for a bake-affecting agent setting) are distinct cache identities.\n *\n * The empty variant — no agents, every setting at its default — is the identity\n * fold, so the plain base keeps the raw context hash and a provider that never\n * passes a variant is unaffected.\n */\nexport function variantFingerprint(\n baseSha: string,\n variant: { agents?: readonly string[]; agentSettings?: AgentSettingsMap } = {},\n): string {\n const agents = agentSetArg(variant.agents);\n const settings = bakeSettingsFingerprintInput(variant.agentSettings);\n if (settings.length === 0 && agents === '') return baseSha;\n const parts: string[] = [...settings];\n if (agents !== '') parts.push(`agents=${agents}`);\n return createHash('sha256')\n .update(`${baseSha}\\0${parts.join('\\0')}`)\n .digest('hex');\n}\n\n/**\n * CLI version stamps set by `apps/cli/src/index.ts` at startup via env vars\n * (the values themselves come from tsup's build-time `define`). Providers\n * record them onto prepared-state files and checkpoint manifests so a stale\n * artifact carries a human-readable hint about which CLI built it.\n *\n * Fallbacks cover the unit-test and unbundled-dev paths (the CLI never\n * loaded, env unset). `unknown` is a sentinel — never a real version.\n */\nexport interface CliStamp {\n cliVersion: string;\n cliCommit: string;\n}\n\nexport function readCliStamp(): CliStamp {\n return {\n cliVersion: process.env.AGENTBOX_CLI_VERSION ?? 'unknown',\n cliCommit: process.env.AGENTBOX_CLI_COMMIT ?? 'unknown',\n };\n}\n\n/**\n * Canonical map of files that go into the Docker base image build context\n * — every file `Dockerfile.box` COPYs, plus the Dockerfile itself. Two\n * layouts resolve the same logical entries:\n *\n * - staged: `<contextDir>/<staged>` (production CLI runtime + dev with `apps/cli/runtime/docker`)\n * - dev: `<sandboxDockerRoot>/<dev>` (workspace dev, no staged tree)\n *\n * Shared across providers because:\n * - sandbox-docker uses it to fingerprint its locally-built image.\n * - sandbox-daytona uses it to fingerprint the snapshot it bakes from the\n * same Dockerfile.box + the daytona-specific CLAUDE.md overlay.\n *\n * If you add a COPY line to `Dockerfile.box`, add the file here AND in\n * `apps/cli/scripts/stage-runtime.mjs` — failure to do so means the image\n * won't get re-built when that file changes.\n */\nexport const DOCKER_CONTEXT_FILE_MAP: Record<string, { staged: string; dev: string }> = {\n 'Dockerfile.box': { staged: 'Dockerfile.box', dev: 'Dockerfile.box' },\n 'ctl/bin.cjs': {\n staged: 'packages/ctl/dist/bin.cjs',\n dev: '../ctl/dist/bin.cjs',\n },\n 'share/agentbox-setup/SKILL.md': {\n staged: 'apps/cli/share/agentbox-setup/SKILL.md',\n dev: '../../apps/cli/share/agentbox-setup/SKILL.md',\n },\n 'share/agentbox-identity/SKILL.md': {\n staged: 'apps/cli/share/agentbox-identity/SKILL.md',\n dev: '../../apps/cli/share/agentbox-identity/SKILL.md',\n },\n 'scripts/agentbox-vnc-start': {\n staged: 'packages/sandbox-docker/scripts/agentbox-vnc-start',\n dev: 'scripts/agentbox-vnc-start',\n },\n 'scripts/agentbox-dockerd-start': {\n staged: 'packages/sandbox-docker/scripts/agentbox-dockerd-start',\n dev: 'scripts/agentbox-dockerd-start',\n },\n 'scripts/agentbox-checkpoint-cleanup': {\n staged: 'packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup',\n dev: 'scripts/agentbox-checkpoint-cleanup',\n },\n 'scripts/agentbox-open': {\n staged: 'packages/sandbox-docker/scripts/agentbox-open',\n dev: 'scripts/agentbox-open',\n },\n 'scripts/custom-system-CLAUDE.md': {\n staged: 'packages/sandbox-docker/scripts/custom-system-CLAUDE.md',\n dev: 'scripts/custom-system-CLAUDE.md',\n },\n 'scripts/claude-managed-settings.json': {\n staged: 'packages/sandbox-docker/scripts/claude-managed-settings.json',\n dev: 'scripts/claude-managed-settings.json',\n },\n 'scripts/agentbox-codex-hooks.json': {\n staged: 'packages/sandbox-docker/scripts/agentbox-codex-hooks.json',\n dev: 'scripts/agentbox-codex-hooks.json',\n },\n // These eight were COPY'd by Dockerfile.box and staged by stage-runtime.mjs\n // but missing here, so editing any of them did NOT change the fingerprint and\n // the stale image was reused (or a stale published tag pulled) indefinitely.\n // The guard test now derives the expected set from Dockerfile.box's COPY\n // lines so this cannot drift again.\n 'scripts/gh-shim': {\n staged: 'packages/sandbox-docker/scripts/gh-shim',\n dev: 'scripts/gh-shim',\n },\n 'scripts/git-shim': {\n staged: 'packages/sandbox-docker/scripts/git-shim',\n dev: 'scripts/git-shim',\n },\n 'scripts/agentbox-tool-shim': {\n staged: 'packages/sandbox-docker/scripts/agentbox-tool-shim',\n dev: 'scripts/agentbox-tool-shim',\n },\n 'scripts/chromium-resolver': {\n staged: 'packages/sandbox-docker/scripts/chromium-resolver',\n dev: 'scripts/chromium-resolver',\n },\n 'scripts/agentbox-sshd-start': {\n staged: 'packages/sandbox-docker/scripts/agentbox-sshd-start',\n dev: 'scripts/agentbox-sshd-start',\n },\n 'scripts/agentbox-portless-trust': {\n staged: 'packages/sandbox-docker/scripts/agentbox-portless-trust',\n dev: 'scripts/agentbox-portless-trust',\n },\n 'scripts/opencode-agentbox-plugin.js': {\n staged: 'packages/sandbox-docker/scripts/opencode-agentbox-plugin.js',\n dev: 'scripts/opencode-agentbox-plugin.js',\n },\n 'scripts/pi-agentbox-extension.js': {\n staged: 'packages/sandbox-docker/scripts/pi-agentbox-extension.js',\n dev: 'scripts/pi-agentbox-extension.js',\n },\n};\n\n/**\n * Resolve every entry in `fileMap` to an absolute path. Tries `<contextDir>/<staged>`\n * first; falls back to `<devRoot>/<dev>`. Returns `null` if any required file\n * is missing — callers treat that as \"can't fingerprint\" and skip the\n * cache-hit shortcut. Pure (no I/O beyond `existsSync`), so safe for use\n * from the provider's prepare path.\n */\nexport function resolveContextFilesFrom(\n fileMap: Record<string, { staged: string; dev: string }>,\n opts: { contextDir: string; devRoot: string },\n): ContextFile[] | null {\n const out: ContextFile[] = [];\n for (const [rel, paths] of Object.entries(fileMap)) {\n const candidates = [\n pathResolve(opts.contextDir, paths.staged),\n pathResolve(opts.devRoot, paths.dev),\n ];\n const hit = candidates.find((p) => existsSync(p));\n if (!hit) return null;\n out.push({ rel, abs: hit });\n }\n return out;\n}\n","/**\n * The public registry the box image is published to, and how a build-context\n * fingerprint names an image in it.\n *\n * These are pure string helpers, but they live here rather than in\n * `@agentbox/sandbox-docker` (which owns the pull/build machinery) because two\n * unrelated providers need the *ref* without wanting the machinery:\n *\n * - docker pulls this ref instead of building locally when the fingerprint\n * matches a published build (`pullOrBuild`).\n * - daytona's linux-vm bake *must* have it: Daytona can only build a VM\n * snapshot from a prebuilt registry image, never from a Dockerfile.\n *\n * `sandbox-docker/src/image.ts` imports `execa` at module scope, so importing\n * the ref from there would drag a process-spawning dependency into the daytona\n * import graph for two lines of string concatenation.\n */\n\n/**\n * Public registry repo the box image is published to (see\n * `.github/workflows/box-image.yml`). An empty registry (config override)\n * disables pulling and always builds.\n */\nexport const BOX_IMAGE_REGISTRY = 'ghcr.io/madarco/agentbox/box';\n\n/**\n * The pull target for a given build-context fingerprint. The tag *is* the\n * content identity: a local staged context that matches a published build has\n * the same sha, so a pull hit can be retagged to `agentbox/box:dev` without\n * risk of a stale image (a locally edited context has a different sha, its tag\n * 404s, and we build instead).\n */\nexport function registryRefForSha(sha: string, registry: string = BOX_IMAGE_REGISTRY): string {\n return `${registry}:sha-${sha.slice(0, 16)}`;\n}\n","/**\n * Custody project-slug derivation, shared by every producer/consumer of the\n * `projects/<slug>/…` custody scope (secrets push, seed push, plane\n * registration, hub worker). All of them MUST agree on the slug for the same\n * repo, so the parsing lives here rather than in each caller.\n *\n * The slug is `owner__repo` (double underscore — `/` is not a valid custody\n * path segment character), derived from the repo's origin URL in any of the\n * usual git shapes:\n * https://github.com/owner/repo(.git)\n * git@github.com:owner/repo(.git)\n * ssh://git@github.com/owner/repo(.git)\n */\nimport { basename } from 'node:path';\n\n/** Parse `owner`/`repo` out of any common git remote URL shape, or null. */\nexport function ownerRepoFromOriginUrl(originUrl: string): { owner: string; repo: string } | null {\n const url = originUrl.trim();\n if (url.length === 0) return null;\n let path: string | null = null;\n // scp-like: git@host:owner/repo(.git)\n const scp = /^[^@/\\s]+@[^:/\\s]+:(.+)$/.exec(url);\n if (scp) {\n path = scp[1]!;\n } else {\n try {\n // Decode: `new URL` percent-encodes the path, while the scp-like branch\n // above doesn't. Without this, the same repo spelled two ways yields two\n // different slugs (`re%20po` -> `re-20po` vs `re po` -> `re-po`) — which\n // is exactly the drift this shared helper exists to prevent.\n path = safeDecode(new URL(url).pathname);\n } catch {\n return null;\n }\n }\n const segments = path\n .replace(/\\.git\\/?$/, '')\n .split('/')\n .filter((s) => s.length > 0);\n if (segments.length < 2) return null;\n const owner = segments[segments.length - 2]!;\n const repo = segments[segments.length - 1]!;\n if (owner.length === 0 || repo.length === 0) return null;\n return { owner, repo };\n}\n\n/** `decodeURIComponent`, falling back to the raw value on a malformed escape. */\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\n/** Custody `projects/<slug>` key for an origin URL: `owner__repo`, or null. */\nexport function projectSlugFromOriginUrl(originUrl: string): string | null {\n const parsed = ownerRepoFromOriginUrl(originUrl);\n if (!parsed) return null;\n const clean = (s: string) => s.replace(/[^A-Za-z0-9._-]/g, '-');\n return `${clean(parsed.owner)}__${clean(parsed.repo)}`;\n}\n\n/**\n * Prefix of the per-job clone a control box builds every box from\n * (`$TMPDIR/agentbox-hub-worker-<jobId>`), deleted the moment the create\n * returns. Exported so the producer (`hub-worker.ts`'s `tmpDir`) and every\n * consumer can't drift — a rename on one side silently resurrects the ghost\n * project cards this is used to filter out.\n *\n * Lives here, in a package both `apps/hub` and `apps/cli` depend on, because\n * both sides have to recognize the path: the hub to key a project by its repo\n * instead of a directory that no longer exists, the CLI to avoid printing that\n * directory in `agentbox ls`.\n */\nexport const HUB_WORKER_CLONE_PREFIX = 'agentbox-hub-worker-';\n\n/**\n * True for a control box's throwaway per-job checkout.\n *\n * Deliberately a NAME test, not an existence test: during the minute a create is\n * running the directory is still there, and a PC-created box's `hostMainRepo`\n * legitimately doesn't exist on the control box while still being a real,\n * durable folder on the PC that we do want to group by.\n */\nexport function isHubWorkerClone(dir: string): boolean {\n return basename(dir).startsWith(HUB_WORKER_CLONE_PREFIX);\n}\n\n/** `owner/repo` from a clone URL, else the URL unchanged. */\nexport function deriveRepoLabel(originUrl: string): string {\n const parsed = ownerRepoFromOriginUrl(originUrl);\n return parsed ? `${parsed.owner}/${parsed.repo}` : originUrl;\n}\n\n/**\n * What to derive a box's default name from when its workspace path is a control\n * box's per-job clone — the repo name, so a hub-created box reads `optima-<id>`\n * instead of `agentbox-hub-worker-<uuid>-<id>`. Null when the URL isn't\n * parseable, leaving the caller on its existing workspace-basename default.\n */\nexport function boxNameBasisFromOriginUrl(originUrl: string): string | null {\n return ownerRepoFromOriginUrl(originUrl)?.repo ?? null;\n}\n","/**\n * The host-boundary gate for a project's `carry:` block: resolve every declared\n * entry, safety-check it, and ask a human before any of it reaches a box.\n *\n * The gate does not know how the question is asked. It builds one\n * {@link PromptRequest} and hands it to a {@link PromptAsker} — clack in the\n * CLI, an HTTP preflight in the hub, a recorded answer map when a client posts\n * its answers back. That is what lets a box created from the tray or the web UI\n * carry the same files a `agentbox create` box does.\n *\n * Parsing stays with the caller (`loadCarrySpec` in `@agentbox/ctl`): this\n * package cannot import ctl, since ctl -> relay -> sandbox-core would cycle.\n */\n\nimport {\n promptId,\n type CarryItem,\n type PromptAsker,\n type PromptFileRow,\n type PromptRequest,\n type ReplaceRule,\n type ResolvedCarryEntry,\n} from '@agentbox/core';\nimport { resolveCarry } from './carry-resolve.js';\n\nexport const CARRY_TOPIC = 'carry';\n\n/**\n * Topic for the standing GRANT, deliberately not `CARRY_TOPIC`: a grant id and a\n * prompt id are different things over different payloads, and a shared topic\n * would let one be mistaken for the other by `promptTopicOf` or an answer map.\n */\nexport const CARRY_GRANT_TOPIC = 'carry-grant';\n\n/** The three things a user can say about a carry block. */\nexport type CarryDecision = 'approve' | 'skip-this-run' | 'cancel';\n\n/**\n * The sentence printed when there is no way to ask. Owned here because only the\n * gate knows its own escape hatches.\n */\nexport const CARRY_NON_INTERACTIVE_HINT =\n 'Set AGENTBOX_CARRY_YES=1 to allow the copy, or AGENTBOX_CARRY=skip to skip it.';\n\nexport interface CarryGateArgs {\n /**\n * The `approvedId` of this project's stored carry grant, when it has one.\n * Matching it approves without asking — see {@link carryGrantId}.\n *\n * Passed IN rather than read here on purpose: this package must not touch\n * `~/.agentbox`, or its tests (which have no HOME isolation) would write to\n * the real home. The caller owns the store; the gate owns the decision.\n */\n approvedGrantId?: string;\n /** `--carry ask` — ignore any grant and ask again, even for an unchanged list. */\n carryAsk?: boolean;\n /** Absolute project root (the dir holding `agentbox.yaml`). */\n projectRoot: string;\n /** Parsed `carry:` entries — see `loadCarrySpec` in `@agentbox/ctl`. */\n items: CarryItem[];\n /** Parsed top-level `replacements:` rule-sets, for expanding `rules:` refs. */\n replacements?: Record<string, ReplaceRule[]>;\n /** Per-entry size cap; callers pass the effective `box.cpMaxBytes`. */\n maxBytes?: number;\n /** How to ask. */\n ask: PromptAsker;\n /** `--carry-yes` / `AGENTBOX_CARRY_YES=1` — approves without asking. */\n carryYes?: boolean;\n /** `--carry skip` / `AGENTBOX_CARRY=skip` — proceeds with carry disabled. */\n carrySkip?: boolean;\n onLog?: (line: string) => void;\n}\n\nexport type CarryGateResult =\n | {\n decision: 'approve';\n entries: ResolvedCarryEntry[];\n /**\n * Identity of the list that was approved — what a caller stores so the\n * next create can skip the question. Absent only when there was nothing\n * to carry.\n */\n grantId?: string;\n /**\n * True when the approval came from a stored grant rather than a human\n * just now. A caller must not re-record one of these (nothing changed),\n * and it is what keeps `--carry-yes` from minting a standing grant.\n */\n fromGrant?: boolean;\n /**\n * A human was actually shown the table. Distinguishes a decision from a\n * short-circuit (`--carry-yes`, `--carry skip`, a matching grant), which\n * is what lets a caller WITHDRAW a standing grant when someone re-reviews\n * the list and says no — without a per-run `--carry skip` doing the same.\n */\n asked?: boolean;\n }\n | { decision: 'skip'; entries: []; asked?: boolean }\n | { decision: 'cancel'; asked?: boolean };\n\n/**\n * Build the question for an already-resolved carry table.\n *\n * Exported so a caller can show the same prompt without re-running the gate —\n * and so the id is derived in exactly one place. The id is content-addressed\n * over what is being asked (src/dest/size/flags per row), so an answer collected\n * in a preflight cannot be replayed onto a `carry:` block that changed in\n * between: the id no longer matches and the create refuses.\n */\nexport function buildCarryPrompt(entries: ResolvedCarryEntry[]): PromptRequest {\n const rows = entries.map(toFileRow);\n const totalBytes = rows.reduce((n, r) => n + (r.bytes ?? 0), 0);\n return {\n id: promptId(CARRY_TOPIC, rows),\n topic: CARRY_TOPIC,\n kind: 'select',\n heading: 'Copy files',\n title: 'Copy these files into the box?',\n choices: [\n { value: 'approve', label: 'Copy' },\n { value: 'skip-this-run', label: 'Skip' },\n { value: 'cancel', label: 'Cancel', danger: true },\n ],\n defaultValue: 'approve',\n detail: {\n type: 'file-table',\n summary: renderCarryTable(rows),\n rows,\n totalBytes,\n },\n // Silently answering this moves host secrets, so there is no safe default.\n required: true,\n fallback: { value: 'cancel', reason: 'nobody was there to approve the copy' },\n nonInteractiveHint: CARRY_NON_INTERACTIVE_HINT,\n };\n}\n\n/**\n * Identity of a carry LIST, for the standing grant: `carry-grant:<12 hex>`.\n *\n * The same rows the prompt is built from, minus `bytes` — and that omission is\n * the whole point. `buildCarryPrompt`'s id includes each row's size so a\n * preflight answer cannot be replayed onto a table that moved underneath it,\n * which is right for a single create but wrong for a standing approval: editing\n * an already-approved `secrets.env` would rotate the id and re-ask forever.\n *\n * Everything else stays in: `src`, `dest`, `kind`, `mode`, `user`, `flags` and\n * `warn` describe the SHAPE and the SAFETY of the copy, not its contents, so a\n * file that becomes a folder, changes mode, or starts resolving through a\n * symlink out of $HOME correctly invalidates the grant.\n */\nexport function carryGrantId(entries: ResolvedCarryEntry[]): string {\n const rows = entries.map((e) => {\n // Rebuilt without `bytes` rather than deleted from the row, so the key ORDER\n // is stable and explicit — `promptId` hashes JSON.stringify output, which is\n // order-sensitive.\n const row = toFileRow(e);\n return {\n src: row.src,\n dest: row.dest,\n kind: row.kind,\n ...(row.mode !== undefined ? { mode: row.mode } : {}),\n ...(row.user !== undefined ? { user: row.user } : {}),\n flags: row.flags,\n ...(row.warn ? { warn: row.warn } : {}),\n // WHAT a directory entry copies, which the prompt's row does not show:\n // dropping an `exclude:` from a committed agentbox.yaml widens the copy\n // (`~/.config` minus `gh` becomes `~/.config` WITH the token in it) while\n // leaving src/dest/kind identical. Only `bytes` would have moved, and that\n // is the one field this digest omits — so these have to be in it or the\n // grant would approve a copy nobody agreed to.\n ...(e.exclude?.length ? { exclude: e.exclude } : {}),\n // Same for the content rewrites: `rules:` is expanded into `replace` by\n // the resolver, so hashing these two covers replaceEnvs/replace/rules.\n ...(e.replaceEnvs ? { replaceEnvs: true } : {}),\n ...(e.replace?.length ? { replace: e.replace } : {}),\n };\n });\n return promptId(CARRY_GRANT_TOPIC, rows);\n}\n\n/**\n * Run the gate: resolve, safety-check, ask, and return the approved entries.\n *\n * Throws on a hard resolver error (a missing non-optional src, a denylisted\n * dest, an over-cap entry) so the caller aborts *before* a box exists.\n */\nexport async function runCarryGate(args: CarryGateArgs): Promise<CarryGateResult> {\n const emit = args.onLog ?? (() => {});\n if (args.items.length === 0) return { decision: 'approve', entries: [] };\n\n const resolved = await resolveCarry(args.items, {\n projectRoot: args.projectRoot,\n ...(args.maxBytes !== undefined ? { maxBytes: args.maxBytes } : {}),\n ...(args.replacements ? { replacements: args.replacements } : {}),\n });\n if (resolved.errors.length > 0) {\n throw new Error(\n [\"carry: these files can't be copied:\", ...resolved.errors.map((e) => ` - ${e}`)].join('\\n'),\n );\n }\n\n // Flags decide the question before anyone is asked, so a scripted create never\n // surfaces a prompt it has already been told the answer to.\n if (args.carrySkip) return skip(resolved.entries.length, emit);\n const grantId = carryGrantId(resolved.entries);\n // A one-shot bypass, not a human reading the table: it approves this run and\n // reports `fromGrant: false` WITHOUT being a grant a caller should store.\n // `clone`/`restore` pass it, and a scripted flag must not leave a standing\n // approval behind.\n if (args.carryYes) return { decision: 'approve', entries: resolved.entries, grantId };\n\n // The list this project already approved, unchanged since. `--carry ask`\n // re-opens the decision even then.\n if (!args.carryAsk && args.approvedGrantId === grantId) {\n const n = resolved.entries.length;\n emit(\n `carry: approved earlier for this project (${String(n)} ${n === 1 ? 'file' : 'files'}, list unchanged)`,\n );\n return { decision: 'approve', entries: resolved.entries, grantId, fromGrant: true };\n }\n\n const req = buildCarryPrompt(resolved.entries);\n const answer = await args.ask(req);\n const decision: CarryDecision = answer.cancelled\n ? 'cancel'\n : isCarryDecision(answer.value)\n ? answer.value\n : 'cancel';\n\n if (decision === 'cancel') return { decision: 'cancel', asked: true };\n if (decision === 'skip-this-run') return skip(resolved.entries.length, emit, true);\n return { decision: 'approve', entries: resolved.entries, grantId, asked: true };\n}\n\nfunction skip(\n count: number,\n emit: (line: string) => void,\n asked = false,\n): { decision: 'skip'; entries: []; asked?: boolean } {\n emit(`carry: skipped (${String(count)} ${count === 1 ? 'file' : 'files'} not copied)`);\n return { decision: 'skip', entries: [], ...(asked ? { asked: true } : {}) };\n}\n\nfunction isCarryDecision(v: string): v is CarryDecision {\n return v === 'approve' || v === 'skip-this-run' || v === 'cancel';\n}\n\n/** Project one resolved entry into the wire row every client renders. */\nexport function toFileRow(e: ResolvedCarryEntry): PromptFileRow {\n const flags: string[] = [];\n // Plain words, not the resolver's vocabulary — these are read by whoever is\n // deciding, not by whoever wrote the `carry:` block.\n if (e.kind === 'missing') flags.push('not on this machine');\n else if (e.optional) flags.push('optional');\n if (e.kind === 'dir') flags.push('folder');\n if (e.symlinkInfo === 'outside-home') flags.push('shortcut to somewhere else');\n return {\n src: e.rawSrc,\n dest: e.rawDest,\n ...(e.kind === 'missing' ? {} : { bytes: e.bytes ?? 0 }),\n kind: e.kind,\n ...(e.mode !== undefined ? { mode: e.mode.toString(8).padStart(4, '0') } : {}),\n // Unset means \"the box user\", the calm common case. Any explicit `user:` is\n // an override worth seeing at the gate — including a literal 1000.\n ...(e.user !== undefined ? { user: e.user } : {}),\n flags,\n // The only flag that says \"this may not be what you think it is\".\n ...(e.symlinkInfo === 'outside-home' ? { warn: true } : {}),\n };\n}\n\n/**\n * The plain-text table, for a client that renders no typed detail (and for the\n * CLI, which renders exactly this).\n *\n * Unlike the GUI tables, this one DOES show `mode` and `user`. A permission bit\n * is noise on a card someone is glancing at, but this is the terminal gate — the\n * one surface where an entry landing 0644 or root-owned is worth seeing before\n * you approve it.\n */\nexport function renderCarryTable(rows: PromptFileRow[]): string {\n if (rows.length === 0) return '';\n const srcW = Math.max(3, ...rows.map((r) => r.src.length));\n const destW = Math.max(4, ...rows.map((r) => r.dest.length));\n const out = [`${pad('from', srcW)} -> ${pad('to', destW)} size notes`];\n for (const r of rows) {\n const flags = [...r.flags];\n if (r.mode !== undefined) flags.push(`mode ${r.mode}`);\n if (r.user !== undefined) flags.push(`user ${String(r.user)}`);\n const size = r.kind === 'missing' ? '-' : formatBytes(r.bytes ?? 0);\n out.push(\n `${pad(r.src, srcW)} -> ${pad(r.dest, destW)} ${pad(size, 9)} ${flags.join(', ')}`,\n );\n }\n return out.join('\\n');\n}\n\nfunction pad(s: string, w: number): string {\n return s.length >= w ? s : s + ' '.repeat(w - s.length);\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${String(n)} B`;\n const units = ['KB', 'MB', 'GB', 'TB'];\n let v = n / 1024;\n let i = 0;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i += 1;\n }\n return `${v < 10 ? v.toFixed(1) : String(Math.round(v))} ${units[i]!}`;\n}\n","import { realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join, normalize, relative, resolve } from 'node:path';\nimport { BUILT_IN_DEFAULTS } from '@agentbox/config';\nimport {\n isInside,\n realpathSafe,\n resolveRuleRefs,\n type CarryItem,\n type ReplaceRule,\n type ResolvedCarryEntry,\n} from '@agentbox/core';\n\nimport { effectiveExcludes, isPathExcluded, toTarExcludes } from './dir-breakdown.js';\n\n// `ResolvedCarryEntry` is @agentbox/core's — this module used to declare a\n// structurally identical copy, which was one drift away from a silent bug.\n\nexport interface ResolveOptions {\n /** Absolute path to the dir holding `agentbox.yaml`. `./` srcs anchor here. */\n projectRoot: string;\n /** Resolved $HOME for the user. Injected so tests can stub it. */\n homeDir?: string;\n /**\n * Per-entry size cap in bytes (after excludes). Callers pass the effective\n * `box.cpMaxBytes` so carry and `agentbox cp` share one limit; defaults to the\n * built-in `box.cpMaxBytes` when omitted.\n */\n maxBytes?: number;\n /** Top-level `replacements:` rule-sets, for expanding carry `rules:` refs. */\n replacements?: Record<string, ReplaceRule[]>;\n}\n\nexport interface ResolveResult {\n entries: ResolvedCarryEntry[];\n errors: string[];\n}\n\nconst DENYLIST_DEST_PREFIXES = ['/proc', '/sys', '/dev'];\nconst DENYLIST_DEST_EXACT = new Set(['/etc/passwd', '/etc/shadow']);\n\nexport async function resolveCarry(\n items: CarryItem[],\n opts: ResolveOptions,\n): Promise<ResolveResult> {\n const home = opts.homeDir ?? homedir();\n const cap = opts.maxBytes ?? BUILT_IN_DEFAULTS.box.cpMaxBytes;\n const projectRoot = opts.projectRoot;\n const replacements = opts.replacements ?? {};\n\n const entries: ResolvedCarryEntry[] = [];\n const errors: string[] = [];\n\n for (const [i, item] of items.entries()) {\n const where = `carry[${String(i)}]`;\n try {\n const entry = await resolveOne(item, { projectRoot, home, cap, where, replacements });\n entries.push(entry);\n } catch (err) {\n errors.push(err instanceof Error ? err.message : String(err));\n }\n }\n\n return { entries, errors };\n}\n\ninterface OneCtx {\n projectRoot: string;\n home: string;\n cap: number;\n where: string;\n replacements: Record<string, ReplaceRule[]>;\n}\n\nasync function resolveOne(item: CarryItem, ctx: OneCtx): Promise<ResolvedCarryEntry> {\n const absSrc = expandHostPath(item.src, ctx);\n if (containsDotDot(absSrc)) {\n throw new Error(`${ctx.where}: resolved src \"${absSrc}\" contains .. — refused`);\n }\n\n validateBoxDest(item.dest, ctx);\n\n const optional = item.optional;\n const rawSrc = item.src;\n const rawDest = item.dest;\n const absDest = item.dest;\n\n // Expand named rule-set refs + inline rules into a single ordered list.\n const hasReplaceOpts = !!(item.replaceEnvs || item.replace || item.rules);\n const replaceRules: ReplaceRule[] = [\n ...resolveRuleRefs(item.rules ?? [], ctx.replacements, `${ctx.where}.rules`),\n ...(item.replace ?? []),\n ];\n const replaceFields = {\n ...(item.replaceEnvs ? { replaceEnvs: true } : {}),\n ...(replaceRules.length > 0 ? { replace: replaceRules } : {}),\n };\n\n let st: Awaited<ReturnType<typeof stat>>;\n try {\n st = await stat(absSrc);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n if (optional) {\n // A missing optional entry is skipped at transfer time, so replace\n // options are moot — don't carry them onto the tombstone.\n return {\n rawSrc,\n rawDest,\n absSrc,\n absDest,\n kind: 'missing',\n ...(item.mode !== undefined ? { mode: item.mode } : {}),\n ...(item.user !== undefined ? { user: item.user } : {}),\n optional: true,\n };\n }\n throw new Error(\n `${ctx.where}: host src \"${absSrc}\" does not exist (use optional: true to skip)`,\n );\n }\n throw err;\n }\n\n // Symlink containment: a symlink whose target leaves both $HOME and\n // projectRoot is suspicious. Mark, don't reject — the prompt makes it loud.\n // Containment is computed in canonicalized space because macOS's /var\n // symlink to /private/var would otherwise make every tmpdir-rooted symlink\n // look \"outside\" its own project root.\n let symlinkInfo: 'safe' | 'outside-home' | undefined;\n try {\n const real = await realpath(absSrc);\n if (real !== absSrc) {\n const homeReal = await realpathSafe(ctx.home);\n const rootReal = await realpathSafe(ctx.projectRoot);\n if (!isInside(real, homeReal) && !isInside(real, rootReal)) {\n symlinkInfo = 'outside-home';\n } else {\n symlinkInfo = 'safe';\n }\n }\n } catch {\n /* best-effort; missing realpath shouldn't block carry */\n }\n\n if (st.isDirectory()) {\n if (hasReplaceOpts) {\n throw new Error(\n `${ctx.where}: replaceEnvs/replace/rules are file-only (src \"${absSrc}\" is a directory)`,\n );\n }\n // Default heavy-dir excludes + the entry's own patterns, applied to both\n // the size accounting and the copy step so the cap weighs only what lands.\n const tokens = effectiveExcludes(item.exclude ?? [], true);\n const tarPatterns = toTarExcludes(tokens);\n const bytes = await dirSizeCapped(absSrc, ctx.cap, tokens);\n if (bytes > ctx.cap) {\n throw new Error(\n `${ctx.where}: dir \"${absSrc}\" exceeds ${String(ctx.cap)} bytes after excludes (add carry exclude: patterns, raise box.cpMaxBytes, or narrow the path)`,\n );\n }\n return {\n rawSrc,\n rawDest,\n absSrc,\n absDest,\n kind: 'dir',\n bytes,\n ...(item.mode !== undefined ? { mode: item.mode } : {}),\n ...(item.user !== undefined ? { user: item.user } : {}),\n ...(tarPatterns.length > 0 ? { exclude: tarPatterns } : {}),\n optional,\n ...(symlinkInfo ? { symlinkInfo } : {}),\n };\n }\n\n if (st.isFile()) {\n if (st.size > ctx.cap) {\n throw new Error(\n `${ctx.where}: file \"${absSrc}\" is ${String(st.size)} bytes, exceeds cap ${String(ctx.cap)} (raise box.cpMaxBytes)`,\n );\n }\n return {\n rawSrc,\n rawDest,\n absSrc,\n absDest,\n kind: 'file',\n bytes: st.size,\n ...(item.mode !== undefined ? { mode: item.mode } : {}),\n ...(item.user !== undefined ? { user: item.user } : {}),\n optional,\n ...(symlinkInfo ? { symlinkInfo } : {}),\n ...replaceFields,\n };\n }\n\n throw new Error(`${ctx.where}: src \"${absSrc}\" is neither a regular file nor a directory`);\n}\n\nfunction expandHostPath(src: string, ctx: OneCtx): string {\n if (src.startsWith('~/')) {\n return resolve(ctx.home, src.slice(2));\n }\n if (src.startsWith('./')) {\n return resolve(ctx.projectRoot, src.slice(2));\n }\n if (isAbsolute(src)) return resolve(src);\n // Schema rejects this shape, but defensive anyway.\n throw new Error(`${ctx.where}: src \"${src}\" must start with /, ~/, or ./`);\n}\n\nfunction containsDotDot(p: string): boolean {\n // After normalize, any `..` segment that survived is suspicious.\n const segs = normalize(p).split('/');\n return segs.some((s) => s === '..');\n}\n\nfunction validateBoxDest(dest: string, ctx: OneCtx): void {\n if (dest.length === 0) {\n throw new Error(`${ctx.where}.dest must not be empty`);\n }\n if (!dest.startsWith('/') && !dest.startsWith('~/')) {\n throw new Error(`${ctx.where}.dest \"${dest}\" must start with / or ~/`);\n }\n // Check the RAW path for `..` segments — must not normalize first because\n // normalize() collapses `a/../b` to `b`, hiding the traversal attempt.\n const rawTail = dest.startsWith('~/') ? dest.slice(2) : dest.slice(1);\n if (rawTail.split('/').some((s) => s === '..')) {\n throw new Error(`${ctx.where}.dest \"${dest}\" contains .. — refused`);\n }\n if (DENYLIST_DEST_EXACT.has(dest)) {\n throw new Error(`${ctx.where}.dest \"${dest}\" is on the denylist`);\n }\n for (const p of DENYLIST_DEST_PREFIXES) {\n if (dest === p || dest.startsWith(`${p}/`)) {\n throw new Error(`${ctx.where}.dest \"${dest}\" is on the denylist (prefix ${p})`);\n }\n }\n}\n\nasync function dirSizeCapped(dir: string, cap: number, exclude: string[] = []): Promise<number> {\n let total = 0;\n const seen = new Set<string>();\n async function walk(d: string): Promise<void> {\n if (total > cap) return;\n const { readdir } = await import('node:fs/promises');\n let names: string[];\n try {\n names = await readdir(d);\n } catch {\n return;\n }\n for (const name of names) {\n if (total > cap) return;\n const full = join(d, name);\n // Skip excluded paths so the cap weighs only what actually copies. The\n // relpath is computed against the carry root with posix separators.\n const rel = relative(dir, full).split(/[\\\\/]/).join('/');\n if (exclude.length > 0 && isPathExcluded(rel, exclude)) continue;\n let st: Awaited<ReturnType<typeof stat>>;\n try {\n st = await stat(full);\n } catch {\n continue;\n }\n // Loop guard for symlink cycles via the symlink-resolved inode pair.\n const key = `${String(st.dev)}:${String(st.ino)}`;\n if (seen.has(key)) continue;\n seen.add(key);\n if (st.isDirectory()) {\n await walk(full);\n } else if (st.isFile()) {\n total += st.size;\n if (total > cap) return;\n }\n }\n }\n await walk(dir);\n return total;\n}\n","/**\n * Host-side size accounting for `agentbox cp`: an exclude-aware recursive\n * `du`-style walk that powers the over-threshold guard. When a copy would\n * exceed `box.cpMaxBytes`, the command prints the heaviest folders/subfolders\n * so the caller (often an in-box agent) can decide what to drop or split.\n *\n * The walk's exclusion semantics are kept in lockstep with the tar patterns\n * `toTarExcludes` emits, so the size we report matches what actually copies.\n */\n\nimport { readdir, stat } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Heavy build/VCS dirs dropped by default (override with `--no-default-excludes`).\n * These are regenerable in the box (`git`/`npm`/`dotnet restore`/rebuild) and are\n * the usual reason a workspace folder balloons past the per-copy size limit.\n */\nexport const DEFAULT_CP_EXCLUDES = [\n '.git',\n 'node_modules',\n 'bin',\n 'obj',\n 'packages',\n 'dist',\n '.next',\n 'target',\n];\n\n/** A token with no glob metachar and no `/` matches a path component by name. */\nfunction isBareName(token: string): boolean {\n return !token.includes('/') && !token.includes('*') && !token.includes('?');\n}\n\n/**\n * Expand exclude tokens to `tar --exclude` patterns. A bare name (e.g.\n * `node_modules`) becomes `*​/node_modules` + `node_modules` so it matches at any\n * depth in the tarball (members carry the source basename prefix). Glob/path\n * tokens pass through verbatim.\n */\nexport function toTarExcludes(tokens: string[]): string[] {\n const out: string[] = [];\n for (const t of tokens) {\n if (isBareName(t)) {\n out.push(`*/${t}`, t);\n } else {\n out.push(t);\n }\n }\n return out;\n}\n\n/** Combine the default exclude set (unless opted out) with user tokens. */\nexport function effectiveExcludes(userTokens: string[], useDefaults: boolean): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n const add = (t: string) => {\n if (t && !seen.has(t)) {\n seen.add(t);\n out.push(t);\n }\n };\n if (useDefaults) DEFAULT_CP_EXCLUDES.forEach(add);\n userTokens.forEach(add);\n return out;\n}\n\nfunction globToRegExp(glob: string): RegExp {\n // tar's exclude wildcards match `/` by default, so `*` -> `.*`.\n const escaped = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/\\?/g, '.');\n return new RegExp(`^${escaped}$`);\n}\n\n/** True if `relPath` (posix, relative to the copy root) is excluded. */\nexport function isPathExcluded(relPath: string, tokens: string[]): boolean {\n const segs = relPath.split('/');\n for (const t of tokens) {\n if (isBareName(t)) {\n if (segs.includes(t)) return true;\n } else if (globToRegExp(t).test(relPath)) {\n return true;\n }\n }\n return false;\n}\n\nexport interface TreeNode {\n /** Path relative to the copy root (`'.'` for the root itself). */\n path: string;\n bytes: number;\n children: TreeNode[];\n}\n\nasync function buildNode(\n abs: string,\n rel: string,\n tokens: string[],\n seen: Set<string>,\n): Promise<TreeNode> {\n let bytes = 0;\n const children: TreeNode[] = [];\n let entries: string[];\n try {\n entries = await readdir(abs);\n } catch {\n return { path: rel || '.', bytes: 0, children };\n }\n for (const name of entries) {\n const childRel = rel ? `${rel}/${name}` : name;\n if (isPathExcluded(childRel, tokens)) continue;\n const full = join(abs, name);\n let st: Awaited<ReturnType<typeof stat>>;\n try {\n st = await stat(full);\n } catch {\n continue;\n }\n // Guard against symlink cycles inflating the total.\n const key = `${String(st.dev)}:${String(st.ino)}`;\n if (seen.has(key)) continue;\n seen.add(key);\n if (st.isDirectory()) {\n const child = await buildNode(full, childRel, tokens, seen);\n bytes += child.bytes;\n children.push(child);\n } else if (st.isFile()) {\n bytes += st.size;\n }\n }\n return { path: rel || '.', bytes, children };\n}\n\nexport interface MeasureResult {\n totalBytes: number;\n isDir: boolean;\n /** Rendered breakdown lines (biggest first, depth-limited). Empty for files. */\n treeLines: string[];\n /** Immediate subdirectories, biggest first (for split-copy suggestions). */\n topChildren: Array<{ path: string; bytes: number }>;\n}\n\nexport interface MeasureOptions {\n /** Max directory depth to render (root is depth 0). Default 3. */\n maxDepth?: number;\n /** Hide folders smaller than this in the rendered tree. Default 10 MiB. */\n floorBytes?: number;\n /** Max children shown per level. Default 8. */\n perLevel?: number;\n}\n\n/**\n * Measure a copy source (file or dir) after applying exclude tokens, and render\n * a `du`-style tree of the heaviest remaining folders/subfolders.\n */\nexport async function measureCopy(\n absSrc: string,\n tokens: string[],\n opts: MeasureOptions = {},\n): Promise<MeasureResult> {\n const st = await stat(absSrc);\n if (!st.isDirectory()) {\n return { totalBytes: st.size, isDir: false, treeLines: [], topChildren: [] };\n }\n const root = await buildNode(absSrc, '', tokens, new Set<string>());\n const maxDepth = opts.maxDepth ?? 3;\n const floor = opts.floorBytes ?? 10 * 1024 * 1024;\n const perLevel = opts.perLevel ?? 8;\n const lines: string[] = [];\n const render = (node: TreeNode, depth: number, label: string): void => {\n const pad = ' '.repeat(depth);\n lines.push(` ${fmtBytes(node.bytes).padStart(8)} ${pad}${label}`);\n if (depth >= maxDepth) return;\n const kids = [...node.children]\n .sort((a, b) => b.bytes - a.bytes)\n .filter((c) => c.bytes >= floor)\n .slice(0, perLevel);\n for (const kid of kids) {\n render(kid, depth + 1, `./${kid.path}`);\n }\n };\n render(root, 0, './');\n const topChildren = [...root.children]\n .sort((a, b) => b.bytes - a.bytes)\n .map((c) => ({ path: c.path, bytes: c.bytes }));\n return { totalBytes: root.bytes, isDir: true, treeLines: lines, topChildren };\n}\n\nexport function fmtBytes(n: number): string {\n if (n < 1024) return `${String(n)} B`;\n const units = ['KB', 'MB', 'GB', 'TB'];\n let v = n / 1024;\n let i = 0;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i += 1;\n }\n return `${v >= 10 || Number.isInteger(v) ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`;\n}\n","/**\n * The create-time decision \"which of the host's model-provider logins does this\n * box get?\" — the host-boundary gate for `AgentSyncSpec.modelAuth`.\n *\n * Precedence: `--model-auth` > the agent's `<agent>.modelAuth` config key > a\n * prompt. The prompt only offers what the host can actually satisfy right now,\n * so a scripted create never hands out a login by surprise.\n *\n * Two kinds of source share one picker: an `agent` source is another agent's\n * login FILE, an `env` source a provider API key from the host environment.\n *\n * The offered login is pre-selected, because reaching this question at all means\n * the host holds one the box can use. Nothing is copied without a human seeing\n * it: with no one to ask, the fallback declines.\n *\n * Like the carry gate, it asks through a {@link PromptAsker} rather than a\n * prompt library, so the hub can ask the same question of a tray or web client.\n */\n\nimport {\n decodeMultiAnswer,\n modelAuthSourceId,\n promptId,\n type AgentModelAuthSource,\n type AgentSettings,\n type AgentSyncSpec,\n type PromptAsker,\n type PromptChoice,\n type PromptCredentialRow,\n type PromptRequest,\n} from '@agentbox/core';\nimport { resolveModelAuthSources } from '../borrowed-credentials.js';\nimport { resolveHostCredentialFile } from '../sync/concerns/credentials.js';\n\nexport const MODEL_AUTH_TOPIC = 'model-auth';\nexport const MODEL_AUTH_SETTING = 'modelAuth';\nexport const MODEL_AUTH_NONE = 'none';\n\n/** A declared source the host can actually satisfy, with what to show the user. */\nexport interface AvailableSource {\n /** The stable source id — `codex`, `env:XAI_API_KEY`. */\n id: string;\n kind: 'agent' | 'env';\n label: string;\n provider?: string;\n caveat?: string;\n /** `agent` sources only: where the login is, and where it lands. */\n hostPath?: string;\n boxPath?: string;\n bytes?: number;\n /** `env` sources only: the variable name. Never its value. */\n envVar?: string;\n}\n\nexport interface ModelAuthGateArgs {\n spec: Pick<AgentSyncSpec, 'id' | 'modelAuth'>;\n /** `--model-auth <source...>` as typed, if passed. */\n flags?: readonly string[];\n /** The agent's settings block, defaults applied. */\n settings: AgentSettings;\n /** True when `<agent>.modelAuth` was set by the user rather than defaulted. */\n configuredExplicitly: boolean;\n ask: PromptAsker;\n /** Injectable for tests: which sources this host can satisfy. */\n listAvailable?: (spec: ModelAuthGateArgs['spec']) => Promise<AvailableSource[]>;\n}\n\nfunction detailRow(s: AvailableSource): PromptCredentialRow {\n return {\n value: s.id,\n source: s.kind === 'agent' ? 'file' : 'env',\n label: s.label,\n ...(s.provider ? { provider: s.provider } : {}),\n ...(s.caveat ? { caveat: s.caveat } : {}),\n ...(s.hostPath ? { hostPath: s.hostPath } : {}),\n ...(s.boxPath ? { boxPath: s.boxPath } : {}),\n ...(s.bytes !== undefined ? { bytes: s.bytes } : {}),\n ...(s.envVar ? { envVar: s.envVar } : {}),\n };\n}\n\n/** The plain-text rendering a client that does not know `credential-list` shows. */\nfunction listSummary(available: readonly AvailableSource[]): string {\n return available\n .map((s) =>\n s.kind === 'agent'\n ? `${s.label}\\n ${s.hostPath ?? ''} -> ${s.boxPath ?? ''}`\n : `${s.label}\\n ${s.envVar ?? ''}${s.provider ? ` (${s.provider})` : ''}`,\n )\n .join('\\n');\n}\n\n/**\n * Build the question for a set of satisfiable sources.\n *\n * One shape: a LIST of the logins the host can actually lend, plus \"None\", and\n * exactly one pick. Not a yes/no, because that only reads correctly while there\n * is one source to say yes TO — and not a multi-select, because a box runs on\n * one model provider. `multiple` stays in the schema for a prompt that genuinely\n * wants several; this one does not.\n *\n * The first offered login is the DEFAULT — someone who reached this question\n * has a login the box can use, and making them pick it every time is friction\n * for the common case.\n *\n * `fallback` still declines, and that difference is deliberate: a default is\n * what you get by pressing enter with the question in front of you, while the\n * fallback is what happens when NOBODY is there to read it. A scripted or\n * non-TTY create must not gain a subscription token silently; it says so up\n * front with `--model-auth`, or once with the config key.\n */\nexport function buildModelAuthPrompt(agentId: string, available: AvailableSource[]): PromptRequest {\n const id = promptId(MODEL_AUTH_TOPIC, {\n agent: agentId,\n sources: available.map((s) => ({ id: s.id, hostPath: s.hostPath, envVar: s.envVar })),\n });\n const choices: PromptChoice[] = [\n ...available.map((s) => ({\n value: s.id,\n label: s.label,\n ...((s.caveat ?? s.provider) ? { hint: s.caveat ?? s.provider } : {}),\n })),\n { value: MODEL_AUTH_NONE, label: 'None' },\n ];\n const first = available[0];\n return {\n id,\n topic: MODEL_AUTH_TOPIC,\n kind: 'select',\n heading: 'Model provider',\n title: 'Which login should this box use as its model provider?',\n choices,\n defaultValue: first ? first.id : MODEL_AUTH_NONE,\n // One `agent` source still gets the richer single-credential card, which\n // every shipped client already draws properly. Several get the list, whose\n // `summary` is what an older client falls back to.\n detail:\n available.length === 1 && first?.kind === 'agent'\n ? {\n type: 'credential' as const,\n summary: `${first.hostPath ?? ''} -> ${first.boxPath ?? ''}`,\n agent: first.id,\n label: first.label,\n ...(first.caveat ? { caveat: first.caveat } : {}),\n hostPath: first.hostPath ?? '',\n boxPath: first.boxPath ?? '',\n ...(first.bytes !== undefined ? { bytes: first.bytes } : {}),\n }\n : {\n type: 'credential-list' as const,\n summary: listSummary(available),\n rows: available.map(detailRow),\n },\n fallback: { value: MODEL_AUTH_NONE, reason: 'not asked - the box starts without it' },\n nonInteractiveHint:\n `Use --model-auth <source|none>, or \\`agentbox config set ${agentId}.${MODEL_AUTH_SETTING} <source>\\` ` +\n 'to decide this once.',\n };\n}\n\n/** Parse a flag / config value into source ids. `none` is only legal alone. */\nexport function parseModelAuthValue(raw: readonly string[] | string): string[] {\n const parts = (typeof raw === 'string' ? [raw] : raw).flatMap((v) => decodeMultiAnswer(v));\n if (parts.length === 0) return [];\n if (parts.includes(MODEL_AUTH_NONE)) {\n if (parts.length > 1) {\n throw new Error(\n `--model-auth ${MODEL_AUTH_NONE} cannot be combined with ${parts\n .filter((p) => p !== MODEL_AUTH_NONE)\n .join(', ')}`,\n );\n }\n return [];\n }\n return parts;\n}\n\n/** The model-auth sources this create should seed, in declaration order. */\nexport async function resolveModelAuth(args: ModelAuthGateArgs): Promise<string[]> {\n const { spec } = args;\n const sources = spec.modelAuth?.sources ?? [];\n if (sources.length === 0) {\n if (args.flags !== undefined && parseModelAuthValue(args.flags).length > 0) {\n throw new Error(`${spec.id} uses no host login — --model-auth does not apply to it`);\n }\n return [];\n }\n\n if (args.flags !== undefined) {\n return resolveModelAuthSources(spec, parseModelAuthValue(args.flags));\n }\n\n const configured = args.settings[MODEL_AUTH_SETTING];\n const configuredIds = typeof configured === 'string' ? parseModelAuthValue(configured) : [];\n if (args.configuredExplicitly || configuredIds.length > 0) {\n return resolveModelAuthSources(spec, configuredIds);\n }\n\n // Asking is opt-in per row. A coding agent has its own sign-in and usually\n // its own login, so a question on every create would be noise; it is still\n // fully drivable by `--model-auth` and the config key above.\n if (!spec.modelAuth?.promptOnCreate) return [];\n\n const available = await (args.listAvailable ?? listAvailableSources)(spec);\n // Nothing to offer: the host holds none of the declared logins.\n if (available.length === 0) return [];\n\n const answer = await args.ask(buildModelAuthPrompt(spec.id, available));\n if (answer.cancelled) return [];\n const chosen = parseModelAuthValue(answer.value);\n if (chosen.length === 0) return [];\n // An answer naming a source this host cannot satisfy is a stale answer, not a\n // silent \"none\" — resolveModelAuthSources throws with the valid values.\n return resolveModelAuthSources(spec, chosen);\n}\n\n/** Which declared sources this host can actually satisfy right now. */\nexport async function listAvailableSources(\n spec: Pick<AgentSyncSpec, 'id' | 'modelAuth'>,\n /** Injectable so a test never reads the ambient environment. */\n env: Readonly<Record<string, string | undefined>> = process.env,\n): Promise<AvailableSource[]> {\n const { findAgentSpec } = await import('@agentbox/agent-registry');\n const out: AvailableSource[] = [];\n for (const s of spec.modelAuth?.sources ?? []) {\n if (s.kind === 'env') {\n const v = env[s.envKey];\n if (typeof v !== 'string' || v.length === 0) continue;\n out.push({\n id: modelAuthSourceId(s),\n kind: 'env',\n label: s.label,\n ...(s.provider ? { provider: s.provider } : {}),\n ...(s.caveat ? { caveat: s.caveat } : {}),\n envVar: s.envKey,\n });\n continue;\n }\n const hit = await resolveHostCredentialFile(s.agent);\n if (!hit) continue;\n out.push({\n id: modelAuthSourceId(s),\n kind: 'agent',\n label: s.label,\n ...(s.caveat ? { caveat: s.caveat } : {}),\n hostPath: hit.path,\n boxPath: findAgentSpec(s.agent)?.credential?.boxAbsPath ?? '',\n bytes: Buffer.byteLength(hit.text, 'utf8'),\n });\n }\n return out;\n}\n\nexport type { AgentModelAuthSource };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,MAAM,UAAU,QAAQ,IAAI,MAAM,iBAAiB;AACnE,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAC9B,SAAS,cAAc,aAAa;ACHpC,SAAS,aAAa;AACtB,SAAS,SAAS,QAAAA,aAAY;AAC9B,SAAS,QAAAC,aAAY;ACFrB,SAAS,aAAa;ACAtB,SAAS,YAAY,UAAU;AAC/B,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,QAAAF,aAAY;ACW9B,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,QAAAF,aAAY;AGC9B,SAAS,cAAAG,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,SAAAC,QAAO,QAAAC,OAAM,YAAAC,WAAU,UAAAC,SAAQ,MAAAC,KAAI,QAAAC,OAAM,aAAAC,kBAAiB;AACnE,SAAS,WAAAC,gBAAe;AACxB,SAAS,WAAAC,UAAS,QAAAC,aAAY;AAC9B,SAAS,cAAcC,cAAa;AEZpC,SAAS,SAAAV,QAAO,YAAAE,iBAAgB;AAChC,SAAS,QAAAO,OAAM,eAAe;AAC9B,SAAS,SAAAE,cAAa;ACGtB,SAAS,QAAAN,aAAY;AACrB,SAAS,WAAAE,gBAAe;AACxB,SAAS,S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AAK;AAC/C,MAAI,OAAO,WAAW,EAAG,QAAO,CAAC;AAGjC,SAAO,wBAAwB,MAAM,MAAM;AAC7C;AAGA,eAAsB,qBACpB,MAEA,MAAoD,QAAQ,KAChC;AAC5B,QAAM,EAAE,eAAAC,eAAc,IAAI,MAAM,OAAO,oBAA0B;AACjE,QAAM,MAAyB,CAAC;AAChC,aAAW,KAAK,KAAK,WAAW,WAAW,CAAC,GAAG;AAC7C,QAAI,EAAE,SAAS,OAAO;AACpB,YAAM,IAAI,IAAI,EAAE,MAAM;AACtB,UAAI,OAAO,MAAM,YAAY,EAAE,WAAW,EAAG;AAC7C,UAAI,KAAK;QACP,IAAIC,kBAAkB,CAAC;QACvB,MAAM;QACN,OAAO,EAAE;QACT,GAAI,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,IAAI,CAAC;QAC7C,GAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,IAAI,CAAC;QACvC,QAAQ,EAAE;MACZ,CAAC;AACD;IACF;AACA,UAAM,MAAM,MAAM,0BAA0B,EAAE,KAAK;AACnD,QAAI,CAAC,IAAK;AACV,QAAI,KAAK;MACP,IAAIA,kBAAkB,CAAC;MACvB,MAAM;MACN,OAAO,EAAE;MACT,GAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,IAAI,CAAC;MACvC,UAAU,IAAI;MACd,SAASD,eAAc,EAAE,KAAK,GAAG,YAAY,cAAc;MAC3D,OAAO,OAAO,WAAW,IAAI,MAAM,MAAM;IAC3C,CAAC;EACH;AACA,SAAO;AACT;","names":["stat","join","homedir","dirname","existsSync","readFileSync","mkdir","open","readFile","rename","rm","stat","writeFile","homedir","dirname","join","delay","execa","resolve","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","resolve","delay","spawn","mkdir","readFile","stat","writeFile","join","fileURLToPath","stat","homedir","resolve","stat","mkdir","mkdtemp","readFile","rename","rm","stat","writeFile","homedir","tmpdir","dirname","join","chmod","readdir","homedir","mkdtemp","rm","tmpdir","join","execa","readdir","stat","homedir","isAbsolute","createHash","readFile","chmod","mkdir","writeFile","createHash","lstat","readFile","join","execa","mkdtemp","readFile","rm","writeFile","tmpdir","join","mkdir","dirname","execa","lstat","readdir","createHash","stat","homedir","basename","copyFile","relative","createHash","existsSync","mkdirSync","readFileSync","renameSync","writeFileSync","readFile","homedir","dirname","basename","realpath","stat","homedir","isAbsolute","join","normalize","relative","resolve","readdir","stat","join","join","stat","homedir","dirname","EMPTY","LOCK_STALE_MS","LOCK_ACQUIRE_TIMEOUT_MS","LOCK_RETRY_MS","mkdir","open","rm","delay","existsSync","readFileSync","readFile","writeFile","rename","execa","resolve","mkdirSync","writeFileSync","override","basename","fileURLToPath","STATE_DIR","HOST","dockerContext","spawn","mkdtemp","tmpdir","normalize","readdir","chmod","run","pathExists","isAbsolute","createHash","LIVE_DATABASE_EXCLUDES","lstat","skip","sq","relative","copyFile","renameSync","pad","realpath","promptId","findAgentSpec","modelAuthSourceId"]}