@madarco/agentbox 0.27.1 → 0.28.0-nightly.202607251721

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 (364) hide show
  1. package/CHANGELOG.md +87 -4
  2. package/README.md +7 -3
  3. package/dist/_cloud-attach-XZYF324R.js +26 -0
  4. package/dist/admin-client-NOZ5CCAH.js +15 -0
  5. package/dist/chunk-2VW37PW4.js +1694 -0
  6. package/dist/chunk-2VW37PW4.js.map +1 -0
  7. package/dist/{chunk-HR7NHH5J.js → chunk-3UMM4VJH.js} +808 -57
  8. package/dist/chunk-3UMM4VJH.js.map +1 -0
  9. package/dist/chunk-5U5QOFL5.js +20 -0
  10. package/dist/chunk-5U5QOFL5.js.map +1 -0
  11. package/dist/chunk-6P6D77QP.js +285 -0
  12. package/dist/chunk-6P6D77QP.js.map +1 -0
  13. package/dist/chunk-6V366IZC.js +2892 -0
  14. package/dist/chunk-6V366IZC.js.map +1 -0
  15. package/dist/{chunk-KWOEUFVA.js → chunk-7J6G526Q.js} +6 -14
  16. package/dist/{chunk-KWOEUFVA.js.map → chunk-7J6G526Q.js.map} +1 -1
  17. package/dist/{chunk-IDH5A4RR.js → chunk-AYPAYY5R.js} +17 -4
  18. package/dist/chunk-AYPAYY5R.js.map +1 -0
  19. package/dist/{chunk-JGZSA5ZI.js → chunk-BHJCMTHP.js} +58 -15
  20. package/dist/chunk-BHJCMTHP.js.map +1 -0
  21. package/dist/{chunk-26IKZRTT.js → chunk-BLWAWGFX.js} +297 -1217
  22. package/dist/chunk-BLWAWGFX.js.map +1 -0
  23. package/dist/chunk-CGPUFXET.js +95 -0
  24. package/dist/chunk-CGPUFXET.js.map +1 -0
  25. package/dist/{chunk-SJ75AIA2.js → chunk-D6AODRNA.js} +12 -9
  26. package/dist/{chunk-SJ75AIA2.js.map → chunk-D6AODRNA.js.map} +1 -1
  27. package/dist/chunk-DPJMEG7U.js +11 -0
  28. package/dist/chunk-DPJMEG7U.js.map +1 -0
  29. package/dist/chunk-E2ITEZAQ.js +148 -0
  30. package/dist/chunk-E2ITEZAQ.js.map +1 -0
  31. package/dist/{chunk-JE6UI5YR.js → chunk-NKVCIH6N.js} +89 -223
  32. package/dist/chunk-NKVCIH6N.js.map +1 -0
  33. package/dist/chunk-OEYAVBA6.js +120 -0
  34. package/dist/chunk-OEYAVBA6.js.map +1 -0
  35. package/dist/{chunk-UJEH2NJT.js → chunk-PXYPQ5BO.js} +64 -264
  36. package/dist/chunk-PXYPQ5BO.js.map +1 -0
  37. package/dist/chunk-QESXSSO6.js +670 -0
  38. package/dist/chunk-QESXSSO6.js.map +1 -0
  39. package/dist/{chunk-NEF6MDJO.js → chunk-QJCK2AFX.js} +128 -26
  40. package/dist/chunk-QJCK2AFX.js.map +1 -0
  41. package/dist/chunk-RUJJY23M.js +84 -0
  42. package/dist/chunk-RUJJY23M.js.map +1 -0
  43. package/dist/{chunk-LL7NCMUU.js → chunk-SKNJRYM5.js} +7 -13
  44. package/dist/chunk-SKNJRYM5.js.map +1 -0
  45. package/dist/chunk-WFGAMJ5Q.js +689 -0
  46. package/dist/chunk-WFGAMJ5Q.js.map +1 -0
  47. package/dist/chunk-ZJL56TJD.js +1444 -0
  48. package/dist/chunk-ZJL56TJD.js.map +1 -0
  49. package/dist/{chunk-V5XXJH63.js → chunk-ZXOP4LBG.js} +5 -8
  50. package/dist/chunk-ZXOP4LBG.js.map +1 -0
  51. package/dist/control-plane-2VEM2KCL.js +31 -0
  52. package/dist/custody-client-P6XIXHRG.js +16 -0
  53. package/dist/{dist-TSFVB7AI.js → dist-2SYQI5S2.js} +11 -7
  54. package/dist/dist-2SYQI5S2.js.map +1 -0
  55. package/dist/{dist-KQTMCVME.js → dist-6QZMZEL7.js} +18 -11
  56. package/dist/dist-6QZMZEL7.js.map +1 -0
  57. package/dist/{dist-FTKS2GI4.js → dist-JHMILJUT.js} +10 -6
  58. package/dist/{dist-OO52HARR.js → dist-JOFZOZCY.js} +41 -25
  59. package/dist/{dist-O3LKOIE7.js → dist-KZ2GEEEX.js} +11 -7
  60. package/dist/dist-KZ2GEEEX.js.map +1 -0
  61. package/dist/{dist-Z6L5MM5D.js → dist-Q5NY4CF6.js} +10 -6
  62. package/dist/{dist-U2SVLJUQ.js → dist-SKMNEDVW.js} +8 -2
  63. package/dist/dist-SKMNEDVW.js.map +1 -0
  64. package/dist/dist-SRCKO7ZV.js +197 -0
  65. package/dist/dist-SRCKO7ZV.js.map +1 -0
  66. package/dist/{dist-WVYAURMF.js → dist-UXZQWKY6.js} +10 -6
  67. package/dist/dist-UXZQWKY6.js.map +1 -0
  68. package/dist/env-file-UDUDQMP4.js +11 -0
  69. package/dist/env-file-UDUDQMP4.js.map +1 -0
  70. package/dist/hub-adopt-ZS5CREYF.js +21 -0
  71. package/dist/hub-adopt-ZS5CREYF.js.map +1 -0
  72. package/dist/index.js +2461 -1905
  73. package/dist/index.js.map +1 -1
  74. package/dist/node-postgres-6JUOVUN5.js +3584 -0
  75. package/dist/node-postgres-6JUOVUN5.js.map +1 -0
  76. package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js → prepared-state-75DIZ55S-P6LE4N64.js} +3 -2
  77. package/dist/prepared-state-75DIZ55S-P6LE4N64.js.map +1 -0
  78. package/dist/remote-hub-SJ4XWBA5.js +9 -0
  79. package/dist/remote-hub-SJ4XWBA5.js.map +1 -0
  80. package/dist/sqlite-proxy-53E5D2VM.js +2882 -0
  81. package/dist/sqlite-proxy-53E5D2VM.js.map +1 -0
  82. package/package.json +1 -1
  83. package/runtime/_shared/ctl.cjs +29199 -16813
  84. package/runtime/digitalocean/ctl.cjs +29199 -16813
  85. package/runtime/docker/packages/ctl/dist/bin.cjs +29199 -16813
  86. package/runtime/e2b/ctl.cjs +29199 -16813
  87. package/runtime/hetzner/ctl.cjs +29199 -16813
  88. package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
  89. package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
  90. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +5 -5
  91. package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -1
  92. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
  93. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
  94. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js +2 -2
  95. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
  96. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +2 -2
  97. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
  98. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js +2 -2
  99. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
  100. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +2 -2
  101. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
  102. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js +2 -2
  103. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
  104. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
  105. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
  106. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
  107. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
  108. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js +2 -2
  109. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
  110. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
  111. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
  112. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js +4 -4
  113. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
  114. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +2 -2
  115. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
  116. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js +2 -2
  117. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.nft.json +1 -1
  118. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +2 -2
  119. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
  120. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +2 -2
  121. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
  122. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
  123. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
  124. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
  125. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
  126. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js +2 -2
  127. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
  128. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js +2 -2
  129. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
  130. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js +2 -2
  131. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
  132. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js +2 -2
  133. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
  134. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js +2 -2
  135. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
  136. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
  137. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
  138. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
  139. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
  140. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
  141. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
  142. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js +2 -2
  143. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
  144. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js +2 -2
  145. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
  146. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
  147. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js +2 -2
  148. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
  149. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
  150. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js +2 -2
  151. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
  152. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
  153. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js +2 -2
  154. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
  155. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
  156. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js +2 -2
  157. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
  158. package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  159. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +4 -2
  160. package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
  161. package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
  162. package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
  163. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  164. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  165. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  166. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  167. package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  168. package/runtime/hub/apps/hub/.next/server/chunks/0-fj_better-auth_dist_adapters_kysely-adapter_index_mjs_0btft52._.js +3 -0
  169. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0gvv4ct._.js +4 -0
  170. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0pn9b49._.js +4 -0
  171. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_145bz8z._.js +9 -0
  172. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_14y990b._.js +3 -0
  173. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_1nl4l3q._.js +3 -0
  174. package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_sqlite-proxy_index_05v_j5r.js +15 -0
  175. package/runtime/hub/apps/hub/.next/server/chunks/{[externals]__12m3qoa._.js → [externals]__0f3aqcx._.js} +2 -2
  176. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-9g1s8._.js +3 -0
  177. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-pvfxg._.js +3 -0
  178. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01amzh6._.js +3 -0
  179. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02q799_._.js +3 -0
  180. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__03k22rl._.js +3 -0
  181. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04tqk-j._.js +3 -0
  182. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05ovf1y._.js +3 -0
  183. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05s-_x7._.js +3 -0
  184. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07dnyfi._.js +3 -0
  185. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07zk6qo._.js +3 -0
  186. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_59yi6._.js +3 -0
  187. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ajlo3d._.js +3 -0
  188. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0b5s54n._.js +3 -0
  189. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c4fiez._.js +3 -0
  190. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c9iff1._.js +3 -0
  191. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +5 -5
  192. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dh6lzr._.js +3 -0
  193. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ey83ai._.js +3 -0
  194. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0h6vdvr._.js +3 -0
  195. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lup7p4._.js +3 -0
  196. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0luxuu4._.js +3 -0
  197. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nl2u6u._.js +3 -0
  198. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nonp-6._.js +3 -0
  199. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0oplozy._.js +3 -0
  200. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0p-6wgd._.js +3 -0
  201. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0rcnwbw._.js +3 -0
  202. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0tuz1am._.js +3 -0
  203. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-9g0ae._.js +1 -1
  204. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10ry4ss._.js +3 -0
  205. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11hv164._.js +3 -0
  206. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__154_i13._.js +3 -0
  207. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17676rc._.js +3 -0
  208. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bg1alc._.js +3 -0
  209. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1cvqb1d._.js +3 -0
  210. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d60gbz._.js +3 -0
  211. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dm0jmw._.js +6 -0
  212. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dv_b1t._.js +3 -0
  213. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1fzxip4._.js +3 -0
  214. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4oj-e._.js +3 -0
  215. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i4gq_2._.js +3 -0
  216. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v1p7in._.js +3 -0
  217. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9_her._.js +4 -0
  218. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1x1jkpb._.js +3 -0
  219. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1yd8n5l._.js +3 -0
  220. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20t_rs8._.js +3 -0
  221. package/runtime/hub/apps/hub/.next/server/chunks/_033w048._.js +1 -1
  222. package/runtime/hub/apps/hub/.next/server/chunks/_06f2faq._.js +1 -1
  223. package/runtime/hub/apps/hub/.next/server/chunks/{_0760z6y._.js → _0907rw0._.js} +15 -15
  224. package/runtime/hub/apps/hub/.next/server/chunks/_0f3molr._.js +1 -1
  225. package/runtime/hub/apps/hub/.next/server/chunks/_0lgs9kd._.js +1 -1
  226. package/runtime/hub/apps/hub/.next/server/chunks/_0pyhcqe._.js +1 -1
  227. package/runtime/hub/apps/hub/.next/server/chunks/_1-42ili._.js +1 -1
  228. package/runtime/hub/apps/hub/.next/server/chunks/_11__3wi._.js +1 -1
  229. package/runtime/hub/apps/hub/.next/server/chunks/_12flzuh._.js +1 -1
  230. package/runtime/hub/apps/hub/.next/server/chunks/_1bng7w9._.js +1 -1
  231. package/runtime/hub/apps/hub/.next/server/chunks/_1rpkqst._.js +1 -1
  232. package/runtime/hub/apps/hub/.next/server/chunks/_1wt72m1._.js +1 -1
  233. package/runtime/hub/apps/hub/.next/server/chunks/_1x3l5t8._.js +1 -1
  234. package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +62 -31
  235. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_0xy-j7z._.js +1 -1
  236. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_1uccfbf._.js +1 -1
  237. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_010858m.js +1 -1
  238. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_04zwxnx.js +1 -1
  239. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_06exuc7.js +1 -1
  240. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2ldrt.js +1 -1
  241. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2tzep.js +1 -1
  242. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_116nh32.js +1 -1
  243. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_11dyjcb.js +1 -1
  244. package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_1_4knli.js +1 -1
  245. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0ebuy19._.js +3 -0
  246. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0wxhi0-._.js +3 -0
  247. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0xe4ick._.js +9 -0
  248. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_14oaveu._.js +4 -0
  249. package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_sqlite-proxy_index_1a6wfdg.js +15 -0
  250. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0-pm2yl._.js +3 -0
  251. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__08-1wwu._.js +1 -1
  252. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0c9mbcn._.js +1 -1
  253. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0gdfxj4._.js +1 -1
  254. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0kc-hwp._.js +1 -1
  255. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0lu73p6._.js +1 -1
  256. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0m1yf2b._.js +4 -0
  257. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0wv-3zo._.js +3 -0
  258. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__10bfmwi._.js +1 -1
  259. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__18qvdzb._.js +2 -2
  260. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1l2urlw._.js +1 -1
  261. package/runtime/hub/apps/hub/.next/server/chunks/ssr/{_0ro6vh6._.js → _0r2xlss._.js} +3 -3
  262. package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_components_1z1p98f._.js +1 -1
  263. package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +2 -25
  264. package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
  265. package/runtime/hub/apps/hub/.next/server/middleware.js +1 -1
  266. package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
  267. package/runtime/hub/apps/hub/.next/static/chunks/{2xc1sm79a6tsb.js → 2gsrna76i1d80.js} +1 -1
  268. package/runtime/hub/apps/hub/attach-helper.cjs +191 -0
  269. package/runtime/hub/apps/hub/{auth-DC44GQZY.js → auth-IRNNO3IK.js} +2 -2
  270. package/runtime/hub/apps/hub/{auth-config-LALRDYDO.js → auth-config-WJHIMGUE.js} +4 -2
  271. package/runtime/hub/apps/hub/{chunk-YJ5MJOXK.js → chunk-4LYVBRBC.js} +2094 -220
  272. package/runtime/hub/apps/hub/chunk-6AVSKCZJ.js +669 -0
  273. package/runtime/hub/apps/hub/{chunk-QSMPSV5Z.js → chunk-A5Y7LJMU.js} +57 -14
  274. package/runtime/hub/apps/hub/chunk-EDRFXO2M.js +35 -0
  275. package/runtime/hub/apps/hub/chunk-F2JI4GMX.js +2891 -0
  276. package/runtime/hub/apps/hub/{chunk-EHBJKZCL.js → chunk-O3K3ZGFF.js} +500 -35
  277. package/runtime/hub/apps/hub/chunk-RII6IKNJ.js +688 -0
  278. package/runtime/hub/apps/hub/{chunk-RXYOWSSN.js → chunk-RMEUA6PA.js} +120 -14
  279. package/runtime/hub/apps/hub/{chunk-3FJNKSNZ.js → chunk-SCHQR5KR.js} +3 -1
  280. package/runtime/hub/apps/hub/{dist-6FPPUSWZ.js → dist-2GEAA7QA.js} +15 -3
  281. package/runtime/hub/apps/hub/{dist-JG45OFT2.js → dist-36O6F6M3.js} +39 -24
  282. package/runtime/hub/apps/hub/{dist-3I7KUI6W.js → dist-IWLEL2TO.js} +21 -24
  283. package/runtime/hub/apps/hub/{dist-G6TXUSPZ.js → dist-NYKIT5W5.js} +10 -11
  284. package/runtime/hub/apps/hub/{dist-EQV4L7KP.js → dist-QB2IJ7OD.js} +7 -1
  285. package/runtime/hub/apps/hub/{dist-LYDHYTP2.js → dist-RBBXXGLI.js} +129 -26
  286. package/runtime/hub/apps/hub/{dist-GTVVXCBP.js → dist-RRJN2U5P.js} +10 -14
  287. package/runtime/hub/apps/hub/{dist-DX6IYMAH.js → dist-UWXGDCK4.js} +14 -11
  288. package/runtime/hub/apps/hub/{hub-token-COBZGSLS.js → hub-token-6USIMBPQ.js} +2 -2
  289. package/runtime/hub/apps/hub/hub-worker-SOFWVTWU.js +215 -0
  290. package/runtime/hub/apps/hub/node-postgres-DIU2H5VP.js +3583 -0
  291. package/runtime/hub/apps/hub/package.json +5 -2
  292. package/runtime/hub/apps/hub/{prepared-state-75DIZ55S-2IFNUHHM.js → prepared-state-75DIZ55S-P5FHEORG.js} +1 -1
  293. package/runtime/hub/apps/hub/server.js +247 -66
  294. package/runtime/hub/apps/hub/sqlite-proxy-VJS3HIOV.js +2881 -0
  295. package/runtime/relay/bin.cjs +694 -13
  296. package/runtime/vercel/ctl.cjs +29199 -16813
  297. package/dist/_cloud-attach-WDGM6FL5.js +0 -19
  298. package/dist/chunk-26IKZRTT.js.map +0 -1
  299. package/dist/chunk-HR7NHH5J.js.map +0 -1
  300. package/dist/chunk-IDH5A4RR.js.map +0 -1
  301. package/dist/chunk-JE6UI5YR.js.map +0 -1
  302. package/dist/chunk-JGZSA5ZI.js.map +0 -1
  303. package/dist/chunk-LL7NCMUU.js.map +0 -1
  304. package/dist/chunk-NEF6MDJO.js.map +0 -1
  305. package/dist/chunk-UJEH2NJT.js.map +0 -1
  306. package/dist/chunk-V5XXJH63.js.map +0 -1
  307. package/dist/dist-KQTMCVME.js.map +0 -1
  308. package/dist/dist-O3LKOIE7.js.map +0 -1
  309. package/dist/dist-TSFVB7AI.js.map +0 -1
  310. package/runtime/hub/apps/hub/.next/server/chunks/0zhp_better-auth_dist_adapters_kysely-adapter_index_mjs_1rl4qnh._.js +0 -3
  311. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04h15ml._.js +0 -3
  312. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04jgk9x._.js +0 -3
  313. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07ednlo._.js +0 -3
  314. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a7djvw._.js +0 -3
  315. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ig1bot._.js +0 -3
  316. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +0 -3
  317. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ql4fjo._.js +0 -3
  318. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0szd4sh._.js +0 -3
  319. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t7o5ed._.js +0 -3
  320. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vs8fma._.js +0 -3
  321. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w9ud8u._.js +0 -3
  322. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xh14bo._.js +0 -3
  323. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yhb0gc._.js +0 -3
  324. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-0flwc._.js +0 -3
  325. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13ioh5z._.js +0 -3
  326. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13jwk_k._.js +0 -3
  327. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16_uteg._.js +0 -3
  328. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16p2m-g._.js +0 -3
  329. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19pc87s._.js +0 -3
  330. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_gu2yk._.js +0 -3
  331. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1a50b07._.js +0 -3
  332. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ai-945._.js +0 -3
  333. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bu2zio._.js +0 -3
  334. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ctczev._.js +0 -3
  335. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d6mtlk._.js +0 -3
  336. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dn_3i1._.js +0 -3
  337. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1e4z_-v._.js +0 -3
  338. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f2sueq._.js +0 -3
  339. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f9zctr._.js +0 -3
  340. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4xycg._.js +0 -3
  341. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hqla7-._.js +0 -3
  342. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1js2jdv._.js +0 -3
  343. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1md9kdw._.js +0 -3
  344. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mttufy._.js +0 -3
  345. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1nepkp-._.js +0 -6
  346. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1pp5oib._.js +0 -3
  347. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q5bqse._.js +0 -3
  348. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qwhzmi._.js +0 -3
  349. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1thipug._.js +0 -3
  350. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9om6g._.js +0 -3
  351. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xeczo7._.js +0 -3
  352. package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20503l7._.js +0 -3
  353. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[externals]_pg_20c820g._.js +0 -3
  354. package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0j0tjwn._.js +0 -3
  355. /package/dist/{_cloud-attach-WDGM6FL5.js.map → _cloud-attach-XZYF324R.js.map} +0 -0
  356. /package/dist/{dist-FTKS2GI4.js.map → admin-client-NOZ5CCAH.js.map} +0 -0
  357. /package/dist/{dist-OO52HARR.js.map → control-plane-2VEM2KCL.js.map} +0 -0
  358. /package/dist/{dist-U2SVLJUQ.js.map → custody-client-P6XIXHRG.js.map} +0 -0
  359. /package/dist/{dist-WVYAURMF.js.map → dist-JHMILJUT.js.map} +0 -0
  360. /package/dist/{dist-Z6L5MM5D.js.map → dist-JOFZOZCY.js.map} +0 -0
  361. /package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js.map → dist-Q5NY4CF6.js.map} +0 -0
  362. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_buildManifest.js +0 -0
  363. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_clientMiddlewareManifest.js +0 -0
  364. /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_ssgManifest.js +0 -0
@@ -0,0 +1,1694 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ providerForCreate
4
+ } from "./chunk-OEYAVBA6.js";
5
+ import {
6
+ deployControlPlaneToHetzner,
7
+ readHetznerCredStatus
8
+ } from "./chunk-QJCK2AFX.js";
9
+ import {
10
+ createGitDeployment,
11
+ createGitProject,
12
+ deleteProject,
13
+ getDeployment,
14
+ getProductionAlias,
15
+ getProject,
16
+ patchProjectSettings,
17
+ projectHasEnv,
18
+ resolveVercelApiAuth,
19
+ upsertProjectEnv
20
+ } from "./chunk-SKNJRYM5.js";
21
+ import {
22
+ loadControlPlaneEnv
23
+ } from "./chunk-5U5QOFL5.js";
24
+ import {
25
+ CustodyClient,
26
+ collectAgentCredentialUploads,
27
+ planPush
28
+ } from "./chunk-CGPUFXET.js";
29
+ import {
30
+ applyProjectSeed,
31
+ deadlineFetch,
32
+ hostReachable,
33
+ pushPreparedToCustody,
34
+ pushProjectSeedToCustody,
35
+ readGitOriginUrl
36
+ } from "./chunk-3UMM4VJH.js";
37
+ import {
38
+ ClaudeSessionError
39
+ } from "./chunk-BLWAWGFX.js";
40
+ import {
41
+ GitHubAppLeaser,
42
+ PostgresStore,
43
+ cloneRepoWithLfs,
44
+ drainCreateJobs,
45
+ loadGitHubAppConfig,
46
+ makeControlPlaneCreateBox,
47
+ parseGitRemote,
48
+ toAuthedHttpsUrl
49
+ } from "./chunk-ZJL56TJD.js";
50
+ import {
51
+ findProjectRoot,
52
+ loadEffectiveConfig,
53
+ setConfigValue,
54
+ unsetConfigValue
55
+ } from "./chunk-BHJCMTHP.js";
56
+ import {
57
+ AGENT_SYNC_SPECS,
58
+ AmbiguousBoxError,
59
+ BoxNotFoundError,
60
+ DEFAULT_ENV_PATTERNS,
61
+ hostOpenCommand,
62
+ projectSlugFromOriginUrl
63
+ } from "./chunk-PXYPQ5BO.js";
64
+
65
+ // src/commands/control-plane.ts
66
+ import { isCancel as isCancel3, log as log2, note as note2, select, spinner } from "@clack/prompts";
67
+ import { Command } from "commander";
68
+ import { spawn as spawn4 } from "child_process";
69
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
70
+ import { chmod, mkdir, readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
71
+ import { hostname, homedir as homedir3, tmpdir as tmpdir2 } from "os";
72
+ import { basename, dirname, join as join4 } from "path";
73
+ import { setTimeout as delay } from "timers/promises";
74
+ import { randomBytes as randomBytes3 } from "crypto";
75
+
76
+ // src/control-plane/github-app-manifest.ts
77
+ import { createServer } from "http";
78
+ import { randomBytes } from "crypto";
79
+ function htmlEscape(s) {
80
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
81
+ }
82
+ async function runGitHubAppManifestFlow(opts) {
83
+ const githubUrl = (opts.githubUrl ?? "https://github.com").replace(/\/$/, "");
84
+ const apiBaseUrl = (opts.apiBaseUrl ?? "https://api.github.com").replace(/\/$/, "");
85
+ const fetchImpl = opts.fetchImpl ?? fetch;
86
+ const log3 = opts.log ?? (() => {
87
+ });
88
+ const state = randomBytes(16).toString("hex");
89
+ return new Promise((resolve, reject) => {
90
+ let listenPort = 0;
91
+ let settled = false;
92
+ const server = createServer((req, res) => {
93
+ if (settled) {
94
+ res.writeHead(204);
95
+ res.end();
96
+ return;
97
+ }
98
+ const url = new URL(req.url ?? "/", `http://127.0.0.1`);
99
+ const redirectUrl = `http://127.0.0.1:${String(listenPort)}/callback`;
100
+ if (url.pathname === "/") {
101
+ const manifest = {
102
+ name: opts.appName,
103
+ url: opts.homepageUrl ?? "https://agent-box.sh",
104
+ redirect_url: redirectUrl,
105
+ public: false,
106
+ default_permissions: { contents: "write", pull_requests: "write" }
107
+ };
108
+ const action = opts.org ? `${githubUrl}/organizations/${encodeURIComponent(opts.org)}/settings/apps/new?state=${state}` : `${githubUrl}/settings/apps/new?state=${state}`;
109
+ const page = `<!doctype html><html><body>
110
+ <p>Creating the GitHub App on GitHub\u2026 if this page doesn't redirect, click Continue.</p>
111
+ <form id="f" method="post" action="${htmlEscape(action)}">
112
+ <input type="hidden" name="manifest" value="${htmlEscape(JSON.stringify(manifest))}">
113
+ <button type="submit">Continue to GitHub</button>
114
+ </form>
115
+ <script>document.getElementById('f').submit()</script>
116
+ </body></html>`;
117
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
118
+ res.end(page);
119
+ return;
120
+ }
121
+ if (url.pathname === "/callback") {
122
+ const code = url.searchParams.get("code") ?? "";
123
+ const gotState = url.searchParams.get("state") ?? "";
124
+ if (gotState !== state) {
125
+ res.writeHead(400, { "content-type": "text/plain" });
126
+ res.end("state mismatch");
127
+ return;
128
+ }
129
+ if (code.length === 0) {
130
+ res.writeHead(400, { "content-type": "text/plain" });
131
+ res.end("missing code");
132
+ return;
133
+ }
134
+ void fetchImpl(`${apiBaseUrl}/app-manifests/${encodeURIComponent(code)}/conversions`, {
135
+ method: "POST",
136
+ headers: {
137
+ Accept: "application/vnd.github+json",
138
+ "X-GitHub-Api-Version": "2022-11-28",
139
+ "User-Agent": "agentbox"
140
+ }
141
+ }).then(async (r) => {
142
+ if (!r.ok) throw new Error(`manifest conversion failed (\u2192 ${String(r.status)})`);
143
+ const body = await r.json();
144
+ if (typeof body.id !== "number" || !body.slug || !body.pem) {
145
+ throw new Error("manifest conversion response missing id/slug/pem");
146
+ }
147
+ const result = {
148
+ appId: String(body.id),
149
+ slug: body.slug,
150
+ pem: body.pem,
151
+ htmlUrl: body.html_url ?? `${githubUrl}/apps/${body.slug}`,
152
+ installUrl: `${githubUrl}/apps/${body.slug}/installations/new`
153
+ };
154
+ settled = true;
155
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
156
+ res.end(
157
+ `<!doctype html><html><head><meta charset="utf-8"></head><body><h2>GitHub App created \u2713</h2><p>App: ${htmlEscape(result.slug)} (id ${result.appId}). You can close this tab and return to the terminal.</p></body></html>`
158
+ );
159
+ server.close();
160
+ resolve(result);
161
+ }).catch((err) => {
162
+ settled = true;
163
+ res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
164
+ res.end("conversion failed");
165
+ server.close();
166
+ reject(err instanceof Error ? err : new Error(String(err)));
167
+ });
168
+ return;
169
+ }
170
+ res.writeHead(404);
171
+ res.end();
172
+ });
173
+ const timer = setTimeout(
174
+ () => {
175
+ server.close();
176
+ reject(new Error("timed out waiting for the GitHub App manifest flow to complete"));
177
+ },
178
+ opts.timeoutMs ?? 5 * 6e4
179
+ );
180
+ if (typeof timer.unref === "function") timer.unref();
181
+ server.on("error", (err) => {
182
+ clearTimeout(timer);
183
+ reject(err);
184
+ });
185
+ server.listen(0, "127.0.0.1", () => {
186
+ listenPort = server.address().port;
187
+ const startUrl = `http://127.0.0.1:${String(listenPort)}/`;
188
+ log3(`opening ${startUrl} to create the GitHub App\u2026`);
189
+ void Promise.resolve(opts.openBrowser(startUrl)).catch((err) => {
190
+ log3(`could not open the browser automatically: ${err instanceof Error ? err.message : String(err)}`);
191
+ log3(`open this URL manually: ${startUrl}`);
192
+ });
193
+ });
194
+ });
195
+ }
196
+
197
+ // src/control-plane/deploy-vercel.ts
198
+ import { spawn as spawn3 } from "child_process";
199
+ import { mkdtempSync, rmSync } from "fs";
200
+ import { tmpdir } from "os";
201
+ import { join as join2 } from "path";
202
+
203
+ // src/control-plane/github-fork.ts
204
+ import { spawn } from "child_process";
205
+ function gh(args) {
206
+ return new Promise((resolve) => {
207
+ let stdout = "";
208
+ let stderr = "";
209
+ let child;
210
+ try {
211
+ child = spawn("gh", args, { stdio: ["ignore", "pipe", "pipe"] });
212
+ } catch {
213
+ resolve({ code: 127, stdout: "", stderr: "gh not found" });
214
+ return;
215
+ }
216
+ child.stdout.on("data", (c) => stdout += c.toString("utf8"));
217
+ child.stderr.on("data", (c) => stderr += c.toString("utf8"));
218
+ child.on("error", () => resolve({ code: 127, stdout, stderr: stderr || "gh not found" }));
219
+ child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
220
+ });
221
+ }
222
+ function ownerOf(repo) {
223
+ return repo.split("/")[0] ?? "";
224
+ }
225
+ function nameOf(repo) {
226
+ return repo.split("/")[1] ?? "";
227
+ }
228
+ async function ghAvailable() {
229
+ return (await gh(["auth", "status"])).code === 0;
230
+ }
231
+ async function ghLogin() {
232
+ const r = await gh(["api", "user", "-q", ".login"]);
233
+ const login = r.stdout.trim();
234
+ return r.code === 0 && login.length > 0 ? login : null;
235
+ }
236
+ async function ensureFork(repo, login, log3) {
237
+ const fork = `${login}/${nameOf(repo)}`;
238
+ log3(`forking ${repo} -> ${fork}\u2026`);
239
+ const f = await gh(["repo", "fork", repo, "--clone=false"]);
240
+ if (f.code !== 0 && !/already exists/i.test(`${f.stderr}${f.stdout}`)) {
241
+ throw new Error(`gh repo fork ${repo} failed: ${(f.stderr || f.stdout).trim()}`);
242
+ }
243
+ const stop = Date.now() + 6e4;
244
+ while (Date.now() < stop) {
245
+ const v = await gh(["api", `repos/${fork}`, "-q", ".full_name"]);
246
+ if (v.code === 0 && v.stdout.trim().toLowerCase() === fork.toLowerCase()) return fork;
247
+ await new Promise((r) => setTimeout(r, 2e3));
248
+ }
249
+ throw new Error(`fork ${fork} did not become available within 60s`);
250
+ }
251
+
252
+ // src/control-plane/ensure-repo-installed.ts
253
+ import { confirm, isCancel, log as clog, note } from "@clack/prompts";
254
+ import { spawn as spawn2 } from "child_process";
255
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
256
+ import { homedir } from "os";
257
+ import { join } from "path";
258
+ import { execa } from "execa";
259
+ var CP_DIR = join(homedir(), ".agentbox", "control-plane");
260
+ var ENV_PATH = join(CP_DIR, "control-plane.env");
261
+ var META_PATH = join(CP_DIR, "control-plane.json");
262
+ var REPOS_STATE = join(CP_DIR, "repos.json");
263
+ function openInBrowser(url) {
264
+ try {
265
+ const child = spawn2(hostOpenCommand(), [url], { detached: true, stdio: "ignore" });
266
+ child.unref();
267
+ } catch {
268
+ }
269
+ }
270
+ function loadControlPlaneMeta() {
271
+ try {
272
+ return JSON.parse(readFileSync(META_PATH, "utf8"));
273
+ } catch {
274
+ return null;
275
+ }
276
+ }
277
+ function loadLocalControlPlaneEnv() {
278
+ if (!existsSync(ENV_PATH)) return;
279
+ for (const line of readFileSync(ENV_PATH, "utf8").split("\n")) {
280
+ const m = /^([A-Z_]+)=(.*)$/.exec(line.trim());
281
+ if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
282
+ }
283
+ }
284
+ async function resolveOwnerRepo(projectRoot) {
285
+ const r = await execa("git", ["-C", projectRoot, "remote", "get-url", "origin"], { reject: false });
286
+ const origin = (r.stdout ?? "").trim();
287
+ if (r.exitCode !== 0 || origin.length === 0) return null;
288
+ try {
289
+ const { path } = parseGitRemote(origin);
290
+ const [owner, repo] = path.replace(/\.git$/, "").split("/");
291
+ if (!owner || !repo) return null;
292
+ return { owner, repo };
293
+ } catch {
294
+ return null;
295
+ }
296
+ }
297
+ async function checkRepoInstalled(owner, repo, controlPlaneUrl) {
298
+ loadLocalControlPlaneEnv();
299
+ const appCfg = loadGitHubAppConfig();
300
+ if (appCfg) {
301
+ try {
302
+ return await new GitHubAppLeaser(appCfg).isRepoInstalled(owner, repo);
303
+ } catch {
304
+ }
305
+ }
306
+ const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN;
307
+ if (controlPlaneUrl && adminToken) {
308
+ try {
309
+ const u = `${controlPlaneUrl.replace(/\/$/, "")}/admin/app/repo-installed?owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`;
310
+ const res = await fetch(u, {
311
+ headers: { Authorization: `Bearer ${adminToken}` },
312
+ signal: AbortSignal.timeout(8e3)
313
+ });
314
+ if (res.ok) return Boolean((await res.json()).installed);
315
+ } catch {
316
+ }
317
+ }
318
+ return "unknown";
319
+ }
320
+ function addRepoUrl(meta) {
321
+ return meta?.installUrl ?? (meta?.slug ? `https://github.com/apps/${meta.slug}/installations/new` : null);
322
+ }
323
+ function readReposState() {
324
+ try {
325
+ return JSON.parse(readFileSync(REPOS_STATE, "utf8"));
326
+ } catch {
327
+ return {};
328
+ }
329
+ }
330
+ function writeReposState(state) {
331
+ try {
332
+ mkdirSync(CP_DIR, { recursive: true });
333
+ writeFileSync(REPOS_STATE, JSON.stringify(state, null, 2) + "\n", { mode: 384 });
334
+ } catch {
335
+ }
336
+ }
337
+ async function ensureProjectRepoOnControlPlane(args) {
338
+ const { controlPlaneUrl, projectRoot } = args;
339
+ if (!controlPlaneUrl) return;
340
+ if (args.gitPushMode === "relay" || args.gitPushMode === "direct") return;
341
+ const ownerRepo = await resolveOwnerRepo(projectRoot);
342
+ if (!ownerRepo) return;
343
+ const { owner, repo } = ownerRepo;
344
+ const key = `${controlPlaneUrl.replace(/\/$/, "")}|${owner}/${repo}`;
345
+ const state = readReposState();
346
+ if (state[key]?.installed) return;
347
+ const installed = await checkRepoInstalled(owner, repo, controlPlaneUrl);
348
+ if (installed === true) {
349
+ state[key] = { installed: true };
350
+ writeReposState(state);
351
+ return;
352
+ }
353
+ if (state[key]?.promptedAt) {
354
+ clog.warn(
355
+ `${owner}/${repo} isn't authorized on the control plane's GitHub App yet \u2014 run \`agentbox hub add\`.`
356
+ );
357
+ return;
358
+ }
359
+ const meta = loadControlPlaneMeta();
360
+ const url = addRepoUrl(meta);
361
+ const nonInteractive = args.yes === true || process.env.AGENTBOX_PROMPT === "off" || !process.stdout.isTTY;
362
+ if (nonInteractive) {
363
+ clog.warn(
364
+ `Repo ${owner}/${repo} may not be authorized on the control plane's GitHub App; pushes/PRs will fail to lease until you run \`agentbox hub add\`.`
365
+ );
366
+ state[key] = { promptedAt: (/* @__PURE__ */ new Date()).toISOString() };
367
+ writeReposState(state);
368
+ return;
369
+ }
370
+ if (!url) {
371
+ clog.warn(
372
+ `Repo ${owner}/${repo} isn't authorized on the GitHub App and no App metadata was found locally. Run \`agentbox hub add\` from a machine that ran \`hub setup\`.`
373
+ );
374
+ state[key] = { promptedAt: (/* @__PURE__ */ new Date()).toISOString() };
375
+ writeReposState(state);
376
+ return;
377
+ }
378
+ const ok = await confirm({
379
+ message: `Authorize ${owner}/${repo} on the GitHub App so this box can push / open PRs?`,
380
+ initialValue: true
381
+ });
382
+ if (!isCancel(ok) && ok) {
383
+ openInBrowser(url);
384
+ note(`Opened ${url}
385
+ Select ${owner}/${repo}, approve, then return here.`, "GitHub App");
386
+ }
387
+ state[key] = { promptedAt: (/* @__PURE__ */ new Date()).toISOString() };
388
+ writeReposState(state);
389
+ }
390
+
391
+ // src/control-plane/deploy-vercel.ts
392
+ var PROJECT_DEFAULT = "agentbox-control-plane";
393
+ var ROOT_DIRECTORY = "apps/hub";
394
+ var GitConnectError = class extends Error {
395
+ };
396
+ function connectedTo(p, repo) {
397
+ return !!p?.link && p.link.type === "github" && `${p.link.org ?? ""}/${p.link.repo ?? ""}`.toLowerCase() === repo.toLowerCase();
398
+ }
399
+ function isConnectError(msg) {
400
+ return /install the GitHub integration|integration first|github integration/i.test(msg);
401
+ }
402
+ function provisionNeon(teamId, projectId, log3) {
403
+ return new Promise((resolve) => {
404
+ const work = mkdtempSync(join2(tmpdir(), "agentbox-neon-"));
405
+ const env = { ...process.env, VERCEL_PROJECT_ID: projectId, ...teamId ? { VERCEL_ORG_ID: teamId } : {} };
406
+ const child = spawn3("vercel", ["integration", "add", "neon", "--non-interactive"], {
407
+ cwd: work,
408
+ env,
409
+ stdio: ["ignore", "pipe", "pipe"]
410
+ });
411
+ const onData = (c) => {
412
+ for (const l of c.toString("utf8").split(/\r?\n/)) if (l.trim()) log3(`neon: ${l.trim()}`);
413
+ };
414
+ child.stdout.on("data", onData);
415
+ child.stderr.on("data", onData);
416
+ const done = () => {
417
+ try {
418
+ rmSync(work, { recursive: true, force: true });
419
+ } catch {
420
+ }
421
+ resolve();
422
+ };
423
+ child.on("error", (e) => {
424
+ log3(`neon: could not run \`vercel integration add neon\` (${e.message}) \u2014 continuing`);
425
+ done();
426
+ });
427
+ child.on("close", (code) => {
428
+ if (code !== 0) log3(`neon: integration add exited ${String(code)} \u2014 continuing (it may already be attached)`);
429
+ done();
430
+ });
431
+ });
432
+ }
433
+ async function pollDeployment(token, teamId, id, log3) {
434
+ const stop = Date.now() + 20 * 6e4;
435
+ let last = "";
436
+ while (Date.now() < stop) {
437
+ const d = await getDeployment(token, teamId, id);
438
+ if (d.readyState !== last) {
439
+ log3(`build: ${d.readyState.toLowerCase()}`);
440
+ last = d.readyState;
441
+ }
442
+ if (d.readyState === "READY") return;
443
+ if (d.readyState === "ERROR" || d.readyState === "CANCELED" || d.readyState === "BLOCKED") {
444
+ throw new Error(
445
+ `Vercel build ${d.readyState.toLowerCase()}${d.errorStep ? ` at ${d.errorStep}` : ""}: ${d.errorMessage ?? "see the Vercel dashboard"}`
446
+ );
447
+ }
448
+ await new Promise((r) => setTimeout(r, 6e3));
449
+ }
450
+ throw new Error("timed out waiting for the Vercel build to finish");
451
+ }
452
+ function envVars(env) {
453
+ return Object.entries(env).map(([key, value]) => ({ key, value }));
454
+ }
455
+ async function apiDeploy(a) {
456
+ const [owner, repoName] = a.repo.split("/");
457
+ a.log(`ensuring Vercel project "${a.projectName}" is connected to ${a.repo}\u2026`);
458
+ let project = await getProject(a.token, a.teamId, a.projectName);
459
+ if (project && !connectedTo(project, a.repo)) {
460
+ a.log(`project exists but is not connected to ${a.repo}; recreating\u2026`);
461
+ await deleteProject(a.token, a.teamId, project.id);
462
+ project = null;
463
+ }
464
+ if (!project) {
465
+ try {
466
+ project = await createGitProject(a.token, a.teamId, {
467
+ name: a.projectName,
468
+ repo: a.repo,
469
+ rootDirectory: ROOT_DIRECTORY
470
+ });
471
+ } catch (e) {
472
+ const msg = e instanceof Error ? e.message : String(e);
473
+ if (isConnectError(msg)) throw new GitConnectError(msg);
474
+ throw e;
475
+ }
476
+ } else {
477
+ await patchProjectSettings(a.token, a.teamId, project.id, {
478
+ framework: "nextjs",
479
+ rootDirectory: ROOT_DIRECTORY
480
+ });
481
+ }
482
+ if (await projectHasEnv(a.token, a.teamId, project.id, "POSTGRES_URL")) {
483
+ a.log("Postgres already attached \u2014 skipping Neon provisioning");
484
+ } else {
485
+ a.log("provisioning Neon Postgres\u2026");
486
+ await provisionNeon(a.teamId, project.id, a.log);
487
+ }
488
+ a.log("setting environment variables\u2026");
489
+ await upsertProjectEnv(a.token, a.teamId, project.id, envVars(a.env));
490
+ a.log(`triggering a production build of ${a.repo}@${a.ref}\u2026`);
491
+ const dep = await createGitDeployment(a.token, a.teamId, {
492
+ name: a.projectName,
493
+ projectId: project.id,
494
+ owner,
495
+ repo: repoName,
496
+ ref: a.ref
497
+ });
498
+ await pollDeployment(a.token, a.teamId, dep.id, a.log);
499
+ const alias = await getProductionAlias(a.token, a.teamId, project.id) ?? dep.url ?? null;
500
+ if (!alias) throw new Error("build is ready but no production URL was found");
501
+ return { url: alias.startsWith("http") ? alias : `https://${alias}` };
502
+ }
503
+ function deployButtonUrl(repo, projectName) {
504
+ const p = new URLSearchParams({
505
+ "repository-url": `https://github.com/${repo}`,
506
+ "root-directory": ROOT_DIRECTORY,
507
+ stores: '[{"type":"postgres"}]',
508
+ "project-name": projectName,
509
+ "repository-name": projectName
510
+ });
511
+ return `https://vercel.com/new/clone?${p.toString()}`;
512
+ }
513
+ async function buttonDeploy(a) {
514
+ const url = deployButtonUrl(a.repo, a.projectName);
515
+ a.log(`opening the Vercel Deploy Button \u2014 complete the clone + Postgres setup in your browser:`);
516
+ a.log(url);
517
+ openInBrowser(url);
518
+ a.log("waiting for the Vercel project to appear (finish the deploy in the browser)\u2026");
519
+ const stop = Date.now() + 10 * 6e4;
520
+ let project = null;
521
+ while (Date.now() < stop) {
522
+ project = await getProject(a.token, a.teamId, a.projectName);
523
+ if (project?.link?.type === "github" && project.link.repo) break;
524
+ project = null;
525
+ await new Promise((r) => setTimeout(r, 5e3));
526
+ }
527
+ if (!project?.link?.repo) {
528
+ throw new Error(
529
+ `timed out waiting for the Vercel project "${a.projectName}". Finish the browser deploy, then re-run, or set the env vars + redeploy in the Vercel dashboard.`
530
+ );
531
+ }
532
+ a.log("setting environment variables + redeploying\u2026");
533
+ await upsertProjectEnv(a.token, a.teamId, project.id, envVars(a.env));
534
+ const dep = await createGitDeployment(a.token, a.teamId, {
535
+ name: a.projectName,
536
+ projectId: project.id,
537
+ owner: project.link.org ?? ownerOf(a.repo),
538
+ repo: project.link.repo,
539
+ ref: a.ref
540
+ });
541
+ await pollDeployment(a.token, a.teamId, dep.id, a.log);
542
+ const alias = await getProductionAlias(a.token, a.teamId, project.id) ?? dep.url ?? null;
543
+ if (!alias) throw new Error("redeploy is ready but no production URL was found");
544
+ return { url: alias.startsWith("http") ? alias : `https://${alias}` };
545
+ }
546
+ async function deployControlPlaneToVercel(opts) {
547
+ const auth = await resolveVercelApiAuth();
548
+ if (!auth) {
549
+ throw new Error("not logged in to Vercel \u2014 run `agentbox vercel login` (or set VERCEL_TOKEN)");
550
+ }
551
+ const { token, teamId } = auth;
552
+ const projectName = opts.project ?? PROJECT_DEFAULT;
553
+ const [owner, repoName] = opts.repo.split("/");
554
+ if (!owner || !repoName) throw new Error(`--repo must be "owner/name" (got "${opts.repo}")`);
555
+ let target = opts.repo;
556
+ if (await ghAvailable()) {
557
+ const login = await ghLogin();
558
+ if (login && login.toLowerCase() !== owner.toLowerCase()) {
559
+ target = await ensureFork(opts.repo, login, opts.log);
560
+ }
561
+ }
562
+ const args = { token, teamId, repo: target, ref: opts.ref, env: opts.env, projectName, log: opts.log };
563
+ try {
564
+ return await apiDeploy(args);
565
+ } catch (e) {
566
+ if (e instanceof GitConnectError) {
567
+ opts.log(`Vercel can't connect ${target} via the API (GitHub App not installed); using the Deploy Button\u2026`);
568
+ return buttonDeploy(args);
569
+ }
570
+ throw e;
571
+ }
572
+ }
573
+
574
+ // src/control-plane/deploy-hetzner.ts
575
+ import { readFile, writeFile } from "fs/promises";
576
+ import { homedir as homedir2 } from "os";
577
+ import { join as join3 } from "path";
578
+ async function runHetznerDeploy(opts) {
579
+ if (readHetznerCredStatus().source === "none") {
580
+ throw new Error("no HCLOUD_TOKEN configured \u2014 run `agentbox hetzner login` first");
581
+ }
582
+ const envContent = await readFile(opts.envPath, "utf8");
583
+ const result = await deployControlPlaneToHetzner({
584
+ envContent,
585
+ repoRef: opts.repoRef,
586
+ repoUrl: opts.repoUrl,
587
+ onLog: opts.log
588
+ });
589
+ const deployPath = join3(homedir2(), ".agentbox", "control-plane", "deploy.json");
590
+ await writeFile(
591
+ deployPath,
592
+ JSON.stringify({ provider: "hetzner", ...result }, null, 2) + "\n",
593
+ { mode: 384 }
594
+ );
595
+ return { url: result.url };
596
+ }
597
+
598
+ // src/control-plane/hub-auth-env.ts
599
+ import { randomBytes as randomBytes2 } from "crypto";
600
+ import { isCancel as isCancel2, password, text } from "@clack/prompts";
601
+ async function resolveHubAuthEnv() {
602
+ let email = process.env.AGENTBOX_HUB_ADMIN_EMAIL;
603
+ let pass = process.env.AGENTBOX_HUB_ADMIN_PASSWORD;
604
+ const secret = process.env.BETTER_AUTH_SECRET || randomBytes2(32).toString("base64");
605
+ if (!email) {
606
+ const v = await text({
607
+ message: "Hub admin email (used to log in to the deployed hub UI)",
608
+ validate: (s) => /^.+@.+\..+$/.test(s.trim()) ? void 0 : "enter a valid email"
609
+ });
610
+ if (isCancel2(v)) return null;
611
+ email = v.trim();
612
+ }
613
+ if (!pass) {
614
+ const v = await password({
615
+ message: "Hub admin password (min 8 characters)",
616
+ validate: (s) => s.length >= 8 ? void 0 : "at least 8 characters"
617
+ });
618
+ if (isCancel2(v)) return null;
619
+ pass = v;
620
+ }
621
+ return {
622
+ AGENTBOX_HUB_AUTH: "on",
623
+ BETTER_AUTH_SECRET: secret,
624
+ AGENTBOX_HUB_ADMIN_EMAIL: email,
625
+ AGENTBOX_HUB_ADMIN_PASSWORD: pass
626
+ };
627
+ }
628
+
629
+ // src/control-plane/hub-api-client.ts
630
+ var HubApiError = class extends Error {
631
+ constructor(message, code, status) {
632
+ super(message);
633
+ this.code = code;
634
+ this.status = status;
635
+ this.name = "HubApiError";
636
+ }
637
+ code;
638
+ status;
639
+ };
640
+ var HubApiClient = class {
641
+ base;
642
+ token;
643
+ fetchImpl;
644
+ constructor(target) {
645
+ this.base = target.url.replace(/\/+$/, "");
646
+ this.token = target.apiKey;
647
+ this.fetchImpl = target.fetchImpl ?? fetch;
648
+ }
649
+ async request(method, path, body) {
650
+ const res = await this.fetchImpl(`${this.base}/api/v1${path}`, {
651
+ method,
652
+ headers: {
653
+ Authorization: `Bearer ${this.token}`,
654
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
655
+ },
656
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
657
+ });
658
+ if (res.status === 204) return void 0;
659
+ const text2 = await res.text();
660
+ let parsed;
661
+ try {
662
+ parsed = text2.length > 0 ? JSON.parse(text2) : {};
663
+ } catch {
664
+ throw new HubApiError(`unexpected non-JSON response (${res.status})`, "internal", res.status);
665
+ }
666
+ if (!res.ok) {
667
+ const err = parsed.error;
668
+ throw new HubApiError(
669
+ err?.message ?? `request failed: ${res.status}`,
670
+ err?.code ?? "internal",
671
+ res.status
672
+ );
673
+ }
674
+ return parsed;
675
+ }
676
+ /** All boxes the hub knows (its own + registered). Topology-agnostic read. */
677
+ async listBoxes() {
678
+ return (await this.request("GET", "/boxes")).boxes;
679
+ }
680
+ /** One box by id (throws HubApiError 'not_found' when absent). */
681
+ getBox(id) {
682
+ return this.request("GET", `/boxes/${encodeURIComponent(id)}`);
683
+ }
684
+ /** Lifecycle action on a box. Reverse-adoption lets the hub drive registered-only boxes. */
685
+ async lifecycle(id, action) {
686
+ await this.request("POST", `/boxes/${encodeURIComponent(id)}/${action}`);
687
+ }
688
+ /** Real destroy: tears down the cloud resource AND reaps the hub's registration/custody. */
689
+ destroy(id) {
690
+ return this.lifecycle(id, "destroy");
691
+ }
692
+ /** A git op against the box's branch. */
693
+ git(id, op, body = {}) {
694
+ return this.request("POST", `/boxes/${encodeURIComponent(id)}/git/${op}`, body);
695
+ }
696
+ /** Create-job status (poll until done/failed). */
697
+ getJob(id) {
698
+ return this.request("GET", `/jobs/${encodeURIComponent(id)}`);
699
+ }
700
+ /** Pending host-action approvals across every box. */
701
+ async listApprovals() {
702
+ return (await this.request("GET", "/approvals")).approvals;
703
+ }
704
+ /** Answer a pending approval by id. */
705
+ async answerApproval(id, answer) {
706
+ await this.request("POST", `/approvals/${encodeURIComponent(id)}/answer`, { answer });
707
+ }
708
+ };
709
+
710
+ // src/control-plane/hub-enqueue.ts
711
+ async function safeText(res) {
712
+ try {
713
+ return (await res.text()).slice(0, 500);
714
+ } catch {
715
+ return "";
716
+ }
717
+ }
718
+ async function enqueueCreateViaHub(target, request) {
719
+ const base = target.url.replace(/\/+$/, "");
720
+ const f = target.fetchImpl ?? fetch;
721
+ const res = await f(`${base}/remote/boxes`, {
722
+ method: "POST",
723
+ headers: { Authorization: `Bearer ${target.adminToken}`, "Content-Type": "application/json" },
724
+ body: JSON.stringify(request)
725
+ });
726
+ if (res.status !== 202) {
727
+ throw new Error(`enqueue failed: ${res.status} ${await safeText(res)}`);
728
+ }
729
+ return (await res.json()).jobId;
730
+ }
731
+ async function getHubJob(target, jobId) {
732
+ const base = target.url.replace(/\/+$/, "");
733
+ const f = target.fetchImpl ?? fetch;
734
+ const res = await f(`${base}/remote/boxes/${encodeURIComponent(jobId)}`, {
735
+ headers: { Authorization: `Bearer ${target.adminToken}` }
736
+ });
737
+ if (res.status === 404) return null;
738
+ if (!res.ok) throw new Error(`job status failed: ${res.status} ${await safeText(res)}`);
739
+ return await res.json();
740
+ }
741
+ async function listHubJobs(target) {
742
+ const base = target.url.replace(/\/+$/, "");
743
+ const f = target.fetchImpl ?? fetch;
744
+ const res = await f(`${base}/remote/boxes`, {
745
+ headers: { Authorization: `Bearer ${target.adminToken}` }
746
+ });
747
+ if (!res.ok) throw new Error(`list jobs failed: ${res.status} ${await safeText(res)}`);
748
+ const body = await res.json();
749
+ return Array.isArray(body.jobs) ? body.jobs : [];
750
+ }
751
+ async function pollHubJob(target, jobId, opts = {}) {
752
+ const intervalMs = opts.intervalMs ?? 3e3;
753
+ const timeoutMs = opts.timeoutMs ?? 30 * 6e4;
754
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
755
+ const now = opts.now ?? Date.now;
756
+ const deadline = now() + timeoutMs;
757
+ let lastStatus = "";
758
+ for (; ; ) {
759
+ const job = await getHubJob(target, jobId);
760
+ if (!job) throw new Error(`job ${jobId} disappeared from the control plane`);
761
+ if (job.status !== lastStatus) {
762
+ lastStatus = job.status;
763
+ opts.onStatus?.(job);
764
+ }
765
+ if (job.status === "done" || job.status === "failed") return job;
766
+ if (now() >= deadline) {
767
+ throw new Error(`timed out waiting for job ${jobId} (last status: ${job.status})`);
768
+ }
769
+ await sleep(intervalMs);
770
+ }
771
+ }
772
+
773
+ // src/commands/_errors.ts
774
+ import { log } from "@clack/prompts";
775
+ function handleLifecycleError(err) {
776
+ if (err instanceof BoxNotFoundError) {
777
+ log.error(err.message);
778
+ log.info("Run `agentbox list` to see available boxes.");
779
+ process.exit(2);
780
+ }
781
+ if (err instanceof AmbiguousBoxError) {
782
+ log.error(err.message);
783
+ log.info("Specify more characters of the id, or use the full name.");
784
+ process.exit(2);
785
+ }
786
+ if (err instanceof ClaudeSessionError) {
787
+ log.error(err.message);
788
+ process.exit(2);
789
+ }
790
+ const msg = err instanceof Error ? err.message : String(err);
791
+ log.error(msg);
792
+ process.exit(1);
793
+ }
794
+
795
+ // src/commands/control-plane.ts
796
+ var SEED_FETCH_MS = 12e4;
797
+ var CP_DIR2 = join4(homedir3(), ".agentbox", "control-plane");
798
+ var PEM_PATH = join4(CP_DIR2, "github-app.pem");
799
+ var ENV_PATH2 = join4(CP_DIR2, "control-plane.env");
800
+ var META_PATH2 = join4(CP_DIR2, "control-plane.json");
801
+ var DEFAULT_DEPLOY_REPO = "madarco/agentbox";
802
+ var DEFAULT_DEPLOY_REF = "main";
803
+ async function applyControlPlaneUrl(url) {
804
+ const trimmed = url.replace(/\/$/, "");
805
+ await setConfigValue("global", "relay.controlPlaneUrl", trimmed, process.cwd());
806
+ return trimmed;
807
+ }
808
+ async function waitForHealthz(url, deadlineMs) {
809
+ const stop = Date.now() + deadlineMs;
810
+ while (Date.now() < stop) {
811
+ try {
812
+ const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8e3) });
813
+ if (res.ok) return true;
814
+ } catch {
815
+ }
816
+ await delay(4e3);
817
+ }
818
+ return false;
819
+ }
820
+ function hetznerAuthBody(hubAuth) {
821
+ return `AGENTBOX_HUB_PROFILE=hetzner
822
+ AGENTBOX_HUB_AUTH=${hubAuth.AGENTBOX_HUB_AUTH}
823
+ BETTER_AUTH_SECRET=${hubAuth.BETTER_AUTH_SECRET}
824
+ AGENTBOX_HUB_ADMIN_EMAIL=${hubAuth.AGENTBOX_HUB_ADMIN_EMAIL}
825
+ AGENTBOX_HUB_ADMIN_PASSWORD=${hubAuth.AGENTBOX_HUB_ADMIN_PASSWORD}
826
+ `;
827
+ }
828
+ async function ensureHetznerHubAuth() {
829
+ const body = existsSync2(ENV_PATH2) ? readFileSync2(ENV_PATH2, "utf8") : "";
830
+ if (/^BETTER_AUTH_SECRET=/m.test(body)) return true;
831
+ const hubAuth = await resolveHubAuthEnv();
832
+ if (!hubAuth) return false;
833
+ await writeFile2(ENV_PATH2, body + hetznerAuthBody(hubAuth), { mode: 384 });
834
+ await chmod(ENV_PATH2, 384);
835
+ return true;
836
+ }
837
+ var setupSub = new Command("setup").description(
838
+ "Create the GitHub App the control plane leases push tokens with, and write its deploy config (env + admin token)"
839
+ ).option("--name <name>", "GitHub App name (default: autogenerated agentbox-<rand>, must be globally unique)").option("--org <org>", "create the App under an organization instead of your user account").option("--deploy <target>", "deploy the plane after creating the App: vercel | hetzner | none").option("--repo <owner/name>", "GitHub repo to deploy the plane from (default madarco/agentbox; fork + pass this if you don't own it)").option("--ref <ref>", "git ref of the repo to deploy (branch/tag/sha; default main) \u2014 used by Vercel + Hetzner").action(async (opts) => {
840
+ try {
841
+ const name = opts.name ?? `agentbox-${randomBytes3(4).toString("hex")}`;
842
+ note2(
843
+ 'Your browser will open to GitHub to create the App. Review the\npermissions (Contents + Pull requests: write) and click "Create".',
844
+ "GitHub App"
845
+ );
846
+ const s = spinner();
847
+ s.start("waiting for the GitHub App to be created in your browser");
848
+ const app = await runGitHubAppManifestFlow({
849
+ appName: String(name),
850
+ org: opts.org,
851
+ // Honor GHES overrides (and make the flow scriptable in tests).
852
+ githubUrl: process.env.GITHUB_URL,
853
+ apiBaseUrl: process.env.GITHUB_API_URL,
854
+ openBrowser: openInBrowser,
855
+ log: (line) => s.message(line)
856
+ });
857
+ s.stop(`GitHub App created: ${app.slug} (id ${app.appId})`);
858
+ const adminToken = randomBytes3(32).toString("hex");
859
+ const hubApiKey = randomBytes3(32).toString("hex");
860
+ await mkdir(CP_DIR2, { recursive: true });
861
+ await writeFile2(PEM_PATH, app.pem, { mode: 384 });
862
+ await chmod(PEM_PATH, 384);
863
+ const pemB64 = Buffer.from(app.pem, "utf8").toString("base64");
864
+ const envBody = `# AgentBox control plane deploy env (generated by 'agentbox hub setup').
865
+ # Feed to docker compose (--env-file) or 'vercel env add'. Keep secret.
866
+ GITHUB_APP_ID=${app.appId}
867
+ GITHUB_APP_PRIVATE_KEY=${pemB64}
868
+ AGENTBOX_RELAY_ADMIN_TOKEN=${adminToken}
869
+ AGENTBOX_HUB_API_KEY=${hubApiKey}
870
+ `;
871
+ await writeFile2(ENV_PATH2, envBody, { mode: 384 });
872
+ await chmod(ENV_PATH2, 384);
873
+ await writeFile2(
874
+ META_PATH2,
875
+ JSON.stringify({ appId: app.appId, slug: app.slug, htmlUrl: app.htmlUrl, installUrl: app.installUrl }, null, 2) + "\n",
876
+ { mode: 384 }
877
+ );
878
+ log2.success(`GitHub App ready. Deploy config written to ${ENV_PATH2} (0600).`);
879
+ const target = await resolveDeployTarget(opts.deploy);
880
+ let deployedUrl = null;
881
+ if (target !== "none") {
882
+ const hubAuth = await resolveHubAuthEnv();
883
+ if (target === "hetzner" && hubAuth) {
884
+ await writeFile2(ENV_PATH2, envBody + hetznerAuthBody(hubAuth), { mode: 384 });
885
+ await chmod(ENV_PATH2, 384);
886
+ }
887
+ const ds = spinner();
888
+ ds.start(`deploying the control plane to ${target}`);
889
+ try {
890
+ const onLog = (line) => ds.message(line);
891
+ const repo = opts.repo ?? DEFAULT_DEPLOY_REPO;
892
+ const ref = opts.ref ?? DEFAULT_DEPLOY_REF;
893
+ if (target === "vercel") {
894
+ const env = {
895
+ GITHUB_APP_ID: app.appId,
896
+ GITHUB_APP_PRIVATE_KEY: pemB64,
897
+ AGENTBOX_RELAY_ADMIN_TOKEN: adminToken,
898
+ AGENTBOX_HUB_API_KEY: hubApiKey,
899
+ ...hubAuth ?? {}
900
+ };
901
+ deployedUrl = (await deployControlPlaneToVercel({ env, repo, ref, log: onLog })).url;
902
+ } else {
903
+ deployedUrl = (await runHetznerDeploy({ envPath: ENV_PATH2, repoRef: ref, log: onLog })).url;
904
+ }
905
+ ds.stop(`deployed: ${deployedUrl}`);
906
+ } catch (e) {
907
+ ds.stop(`deploy to ${target} failed`, 1);
908
+ log2.warn(`deploy to ${target} failed: ${e instanceof Error ? e.message : String(e)}`);
909
+ printManualDeploy();
910
+ }
911
+ } else {
912
+ printManualDeploy();
913
+ }
914
+ if (deployedUrl) {
915
+ const url = await applyControlPlaneUrl(deployedUrl);
916
+ log2.success(`Pointed the CLI at ${url} (relay.controlPlaneUrl).`);
917
+ const ok = await waitForHealthz(url, 6e4);
918
+ log2[ok ? "success" : "warn"](
919
+ ok ? `Control plane is healthy (${url}/healthz).` : `Could not confirm ${url}/healthz yet \u2014 check the deployment.`
920
+ );
921
+ }
922
+ log2.info(`Install the App on your repos: ${app.installUrl}`);
923
+ openInBrowser(app.installUrl);
924
+ } catch (err) {
925
+ handleLifecycleError(err);
926
+ }
927
+ });
928
+ async function resolveDeployTarget(flag) {
929
+ if (flag === "vercel" || flag === "hetzner" || flag === "none") return flag;
930
+ if (flag) {
931
+ log2.warn(`unknown --deploy "${flag}"; choose interactively`);
932
+ }
933
+ const choice = await select({
934
+ message: "Deploy the control plane now?",
935
+ options: [
936
+ { value: "vercel", label: "Vercel \u2014 managed (auto-provisions Neon Postgres)" },
937
+ { value: "hetzner", label: "Hetzner VPS \u2014 HTTPS via <ip>.sslip.io + Caddy/Let\u2019s Encrypt" },
938
+ { value: "none", label: "Skip \u2014 I\u2019ll deploy later (print manual steps)" }
939
+ ],
940
+ initialValue: "vercel"
941
+ });
942
+ if (isCancel3(choice)) return "none";
943
+ return choice;
944
+ }
945
+ function printManualDeploy() {
946
+ log2.info(
947
+ [
948
+ "Deploy later with the written env:",
949
+ ` Self-host: cd apps/hub && docker compose --env-file ${ENV_PATH2} up --build`,
950
+ ` Vercel: agentbox hub setup --deploy vercel (or 'vercel env add' the vars + 'vercel deploy --prod')`,
951
+ ` Then: agentbox hub set-url https://<your-plane-url>`
952
+ ].join("\n")
953
+ );
954
+ }
955
+ var setUrlSub = new Command("set-url").description("Point boxes + the CLI at a deployed control plane (sets relay.controlPlaneUrl)").argument("<url>", "base URL of the deployed control plane, e.g. https://plane.example.com").action(async (url) => {
956
+ try {
957
+ const trimmed = await applyControlPlaneUrl(url);
958
+ log2.success(`Set relay.controlPlaneUrl = ${trimmed}`);
959
+ } catch (err) {
960
+ handleLifecycleError(err);
961
+ }
962
+ });
963
+ var unsetUrlSub = new Command("unset-url").description("Stop using a control plane on this machine (removes relay.controlPlaneUrl)").option("--purge", "also delete this machine's local App metadata + admin token (~/.agentbox/control-plane)").action(async (opts) => {
964
+ try {
965
+ const g = await unsetConfigValue("global", "relay.controlPlaneUrl", process.cwd());
966
+ const p = await unsetConfigValue("project", "relay.controlPlaneUrl", process.cwd());
967
+ if (!g.existed && !p.existed) {
968
+ log2.info("No control plane was configured (relay.controlPlaneUrl not set).");
969
+ } else {
970
+ const where = [g.existed ? "global" : null, p.existed ? "project" : null].filter(Boolean).join(" + ");
971
+ log2.success(
972
+ `Removed relay.controlPlaneUrl (${where}). New cloud boxes now push through the host relay (your laptop must be on), and the GitHub-App repo-authorization prompt no longer fires.`
973
+ );
974
+ }
975
+ if (existsSync2(CP_DIR2)) {
976
+ if (opts.purge) {
977
+ await rm(CP_DIR2, { recursive: true, force: true });
978
+ log2.success(`Purged this machine's control-plane credentials (${CP_DIR2}).`);
979
+ } else {
980
+ log2.info(`This machine's App metadata + admin token remain in ${CP_DIR2} (use --purge to delete).`);
981
+ }
982
+ }
983
+ } catch (err) {
984
+ handleLifecycleError(err);
985
+ }
986
+ });
987
+ async function probeControlPlaneStatus(url) {
988
+ let healthy = false;
989
+ let boxes = 0;
990
+ let events = 0;
991
+ let detail = "";
992
+ try {
993
+ const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8e3) });
994
+ healthy = res.ok;
995
+ const body = await res.json().catch(() => ({}));
996
+ boxes = body.boxes ?? 0;
997
+ events = body.events ?? 0;
998
+ detail = `${String(boxes)} box(es), ${String(events)} event(s)`;
999
+ } catch (e) {
1000
+ detail = e instanceof Error ? e.name : String(e);
1001
+ }
1002
+ return { url, healthy, boxes, events, detail };
1003
+ }
1004
+ var addSub = new Command("add").description("Authorize the current project's git repo on the control plane's GitHub App").action(async () => {
1005
+ try {
1006
+ const cfg = await loadEffectiveConfig(process.cwd());
1007
+ const controlPlaneUrl = cfg.effective.relay.controlPlaneUrl;
1008
+ if (!controlPlaneUrl) {
1009
+ log2.error("No control plane configured. Run `agentbox hub set-url <url>` first.");
1010
+ process.exitCode = 1;
1011
+ return;
1012
+ }
1013
+ const ownerRepo = await resolveOwnerRepo(process.cwd());
1014
+ if (!ownerRepo) {
1015
+ log2.error("No git origin found here \u2014 `cd` into a project with a GitHub remote.");
1016
+ process.exitCode = 1;
1017
+ return;
1018
+ }
1019
+ const { owner, repo } = ownerRepo;
1020
+ const installed = await checkRepoInstalled(owner, repo, controlPlaneUrl);
1021
+ if (installed === true) {
1022
+ log2.success(`${owner}/${repo} is already authorized on the GitHub App.`);
1023
+ return;
1024
+ }
1025
+ const url = addRepoUrl(loadControlPlaneMeta());
1026
+ if (!url) {
1027
+ log2.error(
1028
+ "No GitHub App metadata found locally. Run this from a machine that ran `hub setup`,\nor open your App settings on GitHub and add the repo manually."
1029
+ );
1030
+ process.exitCode = 1;
1031
+ return;
1032
+ }
1033
+ log2.info(`Opening ${url} \u2014 select ${owner}/${repo}, then approve.`);
1034
+ openInBrowser(url);
1035
+ } catch (err) {
1036
+ handleLifecycleError(err);
1037
+ }
1038
+ });
1039
+ function runGit(args, env, timeoutMs) {
1040
+ return new Promise((resolve, reject) => {
1041
+ const child = spawn4("git", args, {
1042
+ stdio: ["ignore", "ignore", "pipe"],
1043
+ env: env ? { ...process.env, ...env } : process.env
1044
+ });
1045
+ const timer = timeoutMs ? setTimeout(() => child.kill("SIGKILL"), timeoutMs) : void 0;
1046
+ let err = "";
1047
+ child.stderr.on("data", (c) => err += c.toString("utf8"));
1048
+ child.on("error", (e) => {
1049
+ if (timer) clearTimeout(timer);
1050
+ reject(e);
1051
+ });
1052
+ child.on("close", (code) => {
1053
+ if (timer) clearTimeout(timer);
1054
+ if (code === 0) resolve();
1055
+ else reject(new Error(`git ${args[0]} failed (${String(code)}): ${err.trim()}`));
1056
+ });
1057
+ });
1058
+ }
1059
+ var workerSub = new Command("worker").description(
1060
+ "Drain the control plane box-creation queue and provision real boxes (long-running; needs provider creds + the App key)"
1061
+ ).requiredOption("--store <url>", "Postgres URL of the control plane (same store the plane uses)").option("--once", "drain the queue once and exit (default: loop)").option("--poll-interval <ms>", "poll interval when looping", "5000").action(async (opts) => {
1062
+ try {
1063
+ loadControlPlaneEnv();
1064
+ const appCfg = loadGitHubAppConfig();
1065
+ if (!appCfg) {
1066
+ log2.error("No GitHub App configured. Run `agentbox hub setup` first.");
1067
+ process.exitCode = 1;
1068
+ return;
1069
+ }
1070
+ const store = new PostgresStore({ connectionString: opts.store });
1071
+ await store.migrate();
1072
+ const leaser = new GitHubAppLeaser(appCfg);
1073
+ const cfg = await loadEffectiveConfig(process.cwd());
1074
+ const createBox = makeControlPlaneCreateBox({
1075
+ leaseRemoteUrl: async (repoUrl) => {
1076
+ const { path } = parseGitRemote(repoUrl);
1077
+ const [owner, repo] = path.replace(/\.git$/, "").split("/");
1078
+ if (!owner || !repo) throw new Error(`cannot derive owner/repo from ${repoUrl}`);
1079
+ const { token } = await leaser.leaseRepoToken(owner, repo);
1080
+ return toAuthedHttpsUrl(repoUrl, token);
1081
+ },
1082
+ cloneRepo: (authedUrl, repoUrl, dest, branch) => cloneRepoWithLfs(runGit, authedUrl, repoUrl, dest, branch, (line) => log2.info(line)),
1083
+ createBox: async ({ workspacePath, name, provider, agent, onLog }) => {
1084
+ const p = await providerForCreate({ flag: provider, config: cfg.effective });
1085
+ const created = await p.create({
1086
+ workspacePath,
1087
+ name,
1088
+ projectRoot: workspacePath,
1089
+ // Registered on the plane so an adopting PC relaunches the right agent.
1090
+ agent: agent === "claude" || agent === "codex" || agent === "opencode" ? agent : void 0,
1091
+ onLog
1092
+ });
1093
+ return { id: created.record.id };
1094
+ },
1095
+ // Overlay the project's custody seed onto the clone, exactly as the
1096
+ // resident hub worker does — without this, boxes drained by THIS worker
1097
+ // come up missing the untracked files + env material the seed exists to
1098
+ // provide. Unlike the hub, this worker is not the custody host, so it
1099
+ // reads the blobs over HTTP.
1100
+ fetchSeedMaterial: async (repoUrl, dest) => {
1101
+ const target = await resolveCustodyTarget(void 0, { quiet: true });
1102
+ if (!target) return null;
1103
+ const slug = projectSlugFromOriginUrl(repoUrl);
1104
+ if (!slug) return null;
1105
+ if (!await hostReachable(target.url)) {
1106
+ process.stdout.write("agentbox-cp-worker: control box unreachable \u2014 bare clone, no seed\n");
1107
+ return null;
1108
+ }
1109
+ const client = new CustodyClient({
1110
+ ...target,
1111
+ fetchImpl: deadlineFetch(AbortSignal.timeout(SEED_FETCH_MS))
1112
+ });
1113
+ return applyProjectSeed({
1114
+ source: { get: (rel) => client.get(`projects/${slug}/seed/${rel}`) },
1115
+ dest,
1116
+ log: (line) => process.stdout.write(`agentbox-cp-worker: ${line}
1117
+ `)
1118
+ });
1119
+ },
1120
+ tmpDir: (jobId) => join4(tmpdir2(), `agentbox-cp-worker-${jobId}`),
1121
+ cleanup: (dir) => rm(dir, { recursive: true, force: true }),
1122
+ log: (line) => process.stdout.write(`agentbox-cp-worker: ${line}
1123
+ `)
1124
+ });
1125
+ const workerId = `worker-${hostname()}-${String(process.pid)}`;
1126
+ const interval = Number.parseInt(opts.pollInterval, 10) || 5e3;
1127
+ let running = true;
1128
+ const stop = () => {
1129
+ running = false;
1130
+ };
1131
+ process.on("SIGINT", stop);
1132
+ process.on("SIGTERM", stop);
1133
+ process.stdout.write(`agentbox-cp-worker: draining create jobs as ${workerId}
1134
+ `);
1135
+ do {
1136
+ const n = await drainCreateJobs(store, createBox, workerId);
1137
+ if (n > 0) process.stdout.write(`agentbox-cp-worker: processed ${String(n)} job(s)
1138
+ `);
1139
+ if (opts.once) break;
1140
+ await delay(interval);
1141
+ } while (running);
1142
+ await store.close();
1143
+ } catch (err) {
1144
+ handleLifecycleError(err);
1145
+ }
1146
+ });
1147
+ async function resolveCustodyTarget(urlFlag, opts = {}) {
1148
+ const cfg = await loadEffectiveConfig(process.cwd());
1149
+ const url = (urlFlag ?? cfg.effective.relay.controlPlaneUrl ?? "").replace(/\/$/, "");
1150
+ if (!url) {
1151
+ if (!opts.quiet)
1152
+ log2.error("No control plane configured. Run `agentbox hub set-url <url>` (or pass --url).");
1153
+ return null;
1154
+ }
1155
+ loadControlPlaneEnv();
1156
+ const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN ?? "";
1157
+ if (!adminToken) {
1158
+ if (!opts.quiet)
1159
+ log2.error(
1160
+ "No admin token available. Set AGENTBOX_RELAY_ADMIN_TOKEN, or run this from the machine that\nran `agentbox hub setup` (it writes the token to ~/.agentbox/control-plane)."
1161
+ );
1162
+ return null;
1163
+ }
1164
+ return { url, adminToken };
1165
+ }
1166
+ async function resolveHubApiTarget(urlFlag, opts = {}) {
1167
+ const cfg = await loadEffectiveConfig(process.cwd());
1168
+ const url = (urlFlag ?? cfg.effective.relay.controlPlaneUrl ?? "").replace(/\/$/, "");
1169
+ if (!url) {
1170
+ if (!opts.quiet)
1171
+ log2.error("No control plane configured. Run `agentbox hub set-url <url>` (or pass --url).");
1172
+ return null;
1173
+ }
1174
+ loadControlPlaneEnv();
1175
+ const apiKey = process.env.AGENTBOX_HUB_API_KEY ?? "";
1176
+ if (!apiKey) {
1177
+ if (!opts.quiet)
1178
+ log2.error(
1179
+ "No hub API key available. Set AGENTBOX_HUB_API_KEY, or run this from the machine that\nran `agentbox hub setup` (it writes the key to ~/.agentbox/control-plane)."
1180
+ );
1181
+ return null;
1182
+ }
1183
+ return { url, apiKey };
1184
+ }
1185
+ async function resolveHubApiClient(urlFlag, opts = {}) {
1186
+ const target = await resolveHubApiTarget(urlFlag, opts);
1187
+ return target ? new HubApiClient(target) : null;
1188
+ }
1189
+ async function projectSlug(explicit, projectRoot) {
1190
+ if (explicit) return explicit.replace(/[^A-Za-z0-9._-]/g, "-");
1191
+ const origin = await readGitOriginUrl(projectRoot).catch(() => void 0);
1192
+ const slug = origin ? projectSlugFromOriginUrl(origin) : null;
1193
+ if (slug) return slug;
1194
+ return basename(projectRoot).replace(/[^A-Za-z0-9._-]/g, "-") || "project";
1195
+ }
1196
+ async function pushItems(client, items, prefix, force) {
1197
+ if (items.length === 0) {
1198
+ log2.info("Nothing to push.");
1199
+ return;
1200
+ }
1201
+ const manifest = await client.list(prefix);
1202
+ const plan = planPush(items, manifest, { force });
1203
+ let uploaded = 0;
1204
+ let skipped = 0;
1205
+ for (const item of items) {
1206
+ const decision = plan.find((d) => d.path === item.path);
1207
+ if (decision.action === "skip") {
1208
+ skipped++;
1209
+ continue;
1210
+ }
1211
+ const res = await client.put(item.path, item.data);
1212
+ if (res.changed) uploaded++;
1213
+ else skipped++;
1214
+ }
1215
+ log2.success(`Pushed ${String(uploaded)} item(s), skipped ${String(skipped)} unchanged.`);
1216
+ }
1217
+ var credentialsPushSub = new Command("push").description("Push host agent-credential backups (claude/codex/opencode) to the control box custody store").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--agent <id>", "push only one agent: claude | codex | opencode").option("--force", "upload even when the stored hash matches").action(async (opts) => {
1218
+ try {
1219
+ const target = await resolveCustodyTarget(opts.url);
1220
+ if (!target) {
1221
+ process.exitCode = 1;
1222
+ return;
1223
+ }
1224
+ const only = opts.agent;
1225
+ if (opts.agent && !["claude", "codex", "opencode"].includes(opts.agent)) {
1226
+ log2.error(`unknown --agent "${opts.agent}" (expected claude | codex | opencode)`);
1227
+ process.exitCode = 1;
1228
+ return;
1229
+ }
1230
+ const items = await collectAgentCredentialUploads(only);
1231
+ const client = new CustodyClient(target);
1232
+ await pushItems(client, items, "agents", opts.force === true);
1233
+ } catch (err) {
1234
+ handleLifecycleError(err);
1235
+ }
1236
+ });
1237
+ var credentialsPullSub = new Command("pull").description("Pull agent-credential backups from the control box custody store into ~/.agentbox").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--agent <id>", "pull only one agent: claude | codex | opencode").action(async (opts) => {
1238
+ try {
1239
+ const target = await resolveCustodyTarget(opts.url);
1240
+ if (!target) {
1241
+ process.exitCode = 1;
1242
+ return;
1243
+ }
1244
+ if (opts.agent && !["claude", "codex", "opencode"].includes(opts.agent)) {
1245
+ log2.error(`unknown --agent "${opts.agent}" (expected claude | codex | opencode)`);
1246
+ process.exitCode = 1;
1247
+ return;
1248
+ }
1249
+ const client = new CustodyClient(target);
1250
+ let pulled = 0;
1251
+ for (const spec of AGENT_SYNC_SPECS) {
1252
+ if (opts.agent && spec.id !== opts.agent) continue;
1253
+ const data = await client.get(`agents/${spec.id}/${spec.credential.boxRelPath}`);
1254
+ if (data === null) continue;
1255
+ await mkdir(dirname(spec.credential.hostBackup), { recursive: true });
1256
+ await writeFile2(spec.credential.hostBackup, data, { mode: 384 });
1257
+ await chmod(spec.credential.hostBackup, 384);
1258
+ log2.info(`pulled ${spec.id} credentials \u2192 ${spec.credential.hostBackup}`);
1259
+ pulled++;
1260
+ }
1261
+ if (pulled === 0) log2.info("No agent credentials in custody to pull.");
1262
+ else log2.success(`Pulled ${String(pulled)} agent credential set(s).`);
1263
+ } catch (err) {
1264
+ handleLifecycleError(err);
1265
+ }
1266
+ });
1267
+ var credentialsCmd = new Command("credentials").description("Manage agent credentials on the control box custody store").addCommand(credentialsPushSub).addCommand(credentialsPullSub);
1268
+ var secretsPushSub = new Command("push").description("Push project secret/env files to the control box custody store").argument("[files...]", "files to push (default: ./.env if present)").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--project <slug>", "custody project slug (default: owner__repo, else the directory name)").option("--force", "upload even when the stored hash matches").action(async (files, opts) => {
1269
+ try {
1270
+ const target = await resolveCustodyTarget(opts.url);
1271
+ if (!target) {
1272
+ process.exitCode = 1;
1273
+ return;
1274
+ }
1275
+ const root = process.cwd();
1276
+ const slug = await projectSlug(opts.project, root);
1277
+ const chosen = files.length > 0 ? files : existsSync2(join4(root, ".env")) ? [join4(root, ".env")] : [];
1278
+ if (chosen.length === 0) {
1279
+ log2.error("No files to push (no ./.env found; pass files explicitly).");
1280
+ process.exitCode = 1;
1281
+ return;
1282
+ }
1283
+ const items = [];
1284
+ for (const f of chosen) {
1285
+ items.push({ path: `projects/${slug}/${basename(f)}`, data: await readFile2(f) });
1286
+ }
1287
+ const client = new CustodyClient(target);
1288
+ await pushItems(client, items, `projects/${slug}`, opts.force === true);
1289
+ } catch (err) {
1290
+ handleLifecycleError(err);
1291
+ }
1292
+ });
1293
+ var secretsCmd = new Command("secrets").description("Manage per-project secrets/envs on the control box custody store").addCommand(secretsPushSub);
1294
+ var projectPushSub = new Command("push").description(
1295
+ "Push this project's seed material (untracked files + env/secrets) to the control box, so boxes created from its web UI get the files a fresh clone can't provide. A PC create does this automatically; run this to register a project before creating a box from it."
1296
+ ).option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--project <slug>", "custody project slug (default: owner__repo, else the directory name)").option("--force", "upload even when the stored hash matches").action(async (opts) => {
1297
+ try {
1298
+ const target = await resolveCustodyTarget(opts.url);
1299
+ if (!target) {
1300
+ process.exitCode = 1;
1301
+ return;
1302
+ }
1303
+ const root = (await findProjectRoot(process.cwd())).root;
1304
+ const slug = await projectSlug(opts.project, root);
1305
+ const cfg = await loadEffectiveConfig(root).catch(() => null);
1306
+ const res = await pushProjectSeedToCustody({
1307
+ controlPlaneUrl: target.url,
1308
+ adminToken: target.adminToken,
1309
+ slug,
1310
+ projectRoot: root,
1311
+ // The default env set (same one `--with-env` uses). Unlike a create —
1312
+ // which mirrors that box's own wizard picks and must not widen them —
1313
+ // this command has no box and no picks: the user is explicitly asking to
1314
+ // register the project's seed, so the default set is the intent. What
1315
+ // actually gets captured is reported below.
1316
+ envPatterns: DEFAULT_ENV_PATTERNS,
1317
+ // Honour the configured cap, so raising it actually admits a bigger seed.
1318
+ maxBodyBytes: cfg?.effective.relay.custodyMaxBodyBytes,
1319
+ force: opts.force,
1320
+ log: (line) => log2.info(line)
1321
+ });
1322
+ if (res.unreachable) {
1323
+ log2.error(
1324
+ `Control box unreachable at ${target.url} \u2014 nothing was pushed. The project is NOT registered; re-run when it is up.`
1325
+ );
1326
+ process.exitCode = 1;
1327
+ return;
1328
+ }
1329
+ const head = res.manifest.repoHeadSha?.slice(0, 8) ?? "unknown";
1330
+ log2.success(
1331
+ `Pushed ${String(res.uploaded)} item(s), skipped ${String(res.skipped)} unchanged \u2192 projects/${slug}/seed (at ${head}).`
1332
+ );
1333
+ if (res.envFiles.length > 0) {
1334
+ log2.info(`env/secret files captured: ${res.envFiles.join(", ")}`);
1335
+ }
1336
+ if (res.skippedTarBytes !== void 0) {
1337
+ log2.warn(
1338
+ `The untracked-files tar (${String(Math.round(res.skippedTarBytes / 1024 / 1024))}MB) exceeded this machine's custody body cap and was NOT pushed \u2014 hub-created boxes will miss those files. To include it, raise \`relay.custodyMaxBodyBytes\` here AND AGENTBOX_CUSTODY_MAX_BODY_BYTES on the control box (it enforces its own cap).`
1339
+ );
1340
+ }
1341
+ if (res.dropped.length > 0) {
1342
+ log2.warn(
1343
+ `The control box refused ${res.dropped.join(", ")} \u2014 hub-created boxes will miss those files. If it is a size limit, raise AGENTBOX_CUSTODY_MAX_BODY_BYTES on the control box.`
1344
+ );
1345
+ }
1346
+ } catch (err) {
1347
+ handleLifecycleError(err);
1348
+ }
1349
+ });
1350
+ var projectCmd = new Command("project").description("Manage a project on the control box (seed material for hub-created boxes)").addCommand(projectPushSub);
1351
+ var custodyListSub = new Command("list").description("List custody entries (paths + hashes; values are never returned)").argument("[prefix]", "scope to a prefix, e.g. agents or projects/owner__repo").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").action(async (prefix, opts) => {
1352
+ try {
1353
+ const target = await resolveCustodyTarget(opts.url);
1354
+ if (!target) {
1355
+ process.exitCode = 1;
1356
+ return;
1357
+ }
1358
+ const client = new CustodyClient(target);
1359
+ const entries = await client.list(prefix);
1360
+ if (entries.length === 0) {
1361
+ log2.info("No custody entries.");
1362
+ return;
1363
+ }
1364
+ for (const e of entries) {
1365
+ process.stdout.write(`${e.path} ${String(e.size)}B ${e.sha256.slice(0, 12)}
1366
+ `);
1367
+ }
1368
+ } catch (err) {
1369
+ handleLifecycleError(err);
1370
+ }
1371
+ });
1372
+ var custodyPullSub = new Command("pull").description("Download a custody scope to a local directory (0600 files)").argument("<scope>", "custody scope/prefix, e.g. agents, projects/owner__repo, boxes/<id>").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--dest <dir>", "destination directory (default: ./agentbox-custody)").action(async (scope, opts) => {
1373
+ try {
1374
+ const target = await resolveCustodyTarget(opts.url);
1375
+ if (!target) {
1376
+ process.exitCode = 1;
1377
+ return;
1378
+ }
1379
+ const dest = opts.dest ?? join4(process.cwd(), "agentbox-custody");
1380
+ const client = new CustodyClient(target);
1381
+ const entries = await client.list(scope);
1382
+ if (entries.length === 0) {
1383
+ log2.info(`No custody entries under '${scope}'.`);
1384
+ return;
1385
+ }
1386
+ let pulled = 0;
1387
+ for (const e of entries) {
1388
+ const data = await client.get(e.path);
1389
+ if (data === null) continue;
1390
+ const out = join4(dest, e.path);
1391
+ await mkdir(dirname(out), { recursive: true, mode: 448 });
1392
+ await writeFile2(out, data, { mode: 384 });
1393
+ await chmod(out, 384);
1394
+ pulled++;
1395
+ }
1396
+ log2.success(`Pulled ${String(pulled)} entr${pulled === 1 ? "y" : "ies"} under '${scope}' to ${dest}.`);
1397
+ } catch (err) {
1398
+ handleLifecycleError(err);
1399
+ }
1400
+ });
1401
+ var custodyRmSub = new Command("rm").description("Delete a custody entry (one path) from the control box").argument("<path>", "custody path, e.g. boxes/<sandboxId>/ssh/id_ed25519 or agents/claude/.credentials.json").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").action(async (path, opts) => {
1402
+ try {
1403
+ const target = await resolveCustodyTarget(opts.url);
1404
+ if (!target) {
1405
+ process.exitCode = 1;
1406
+ return;
1407
+ }
1408
+ const res = await fetch(`${target.url}/admin/custody/${path.split("/").map(encodeURIComponent).join("/")}`, {
1409
+ method: "DELETE",
1410
+ headers: { Authorization: `Bearer ${target.adminToken}` }
1411
+ });
1412
+ if (res.status === 204) log2.success(`Deleted custody entry '${path}'.`);
1413
+ else if (res.status === 404) log2.info(`No custody entry at '${path}'.`);
1414
+ else {
1415
+ log2.error(`custody rm failed: ${res.status} ${(await res.text().catch(() => "")).slice(0, 200)}`);
1416
+ process.exitCode = 1;
1417
+ }
1418
+ } catch (err) {
1419
+ handleLifecycleError(err);
1420
+ }
1421
+ });
1422
+ var custodyCmd = new Command("custody").description("Inspect + download the control box custody store").addCommand(custodyListSub).addCommand(custodyPullSub).addCommand(custodyRmSub);
1423
+ var boxesListSub = new Command("list").description("List boxes on the control box (via its /api/v1)").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--json", "print raw JSON").action(async (opts) => {
1424
+ try {
1425
+ const client = await resolveHubApiClient(opts.url);
1426
+ if (!client) {
1427
+ process.exitCode = 1;
1428
+ return;
1429
+ }
1430
+ const boxes = await client.listBoxes();
1431
+ if (opts.json) {
1432
+ process.stdout.write(`${JSON.stringify({ boxes }, null, 2)}
1433
+ `);
1434
+ return;
1435
+ }
1436
+ if (boxes.length === 0) {
1437
+ log2.info("No boxes on the control box.");
1438
+ return;
1439
+ }
1440
+ for (const b of boxes) {
1441
+ process.stdout.write(`${b.id} ${b.name ?? b.task} ${b.provider} ${b.state ?? b.status}
1442
+ `);
1443
+ }
1444
+ } catch (err) {
1445
+ handleLifecycleError(err);
1446
+ }
1447
+ });
1448
+ var boxesRmSub = new Command("rm").description("Destroy a box via the control box (tears down the cloud resource AND reaps its registration/custody)").argument("<boxId>", "the box id as shown by `hub boxes list`").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").action(async (boxId, opts) => {
1449
+ try {
1450
+ const client = await resolveHubApiClient(opts.url);
1451
+ if (!client) {
1452
+ process.exitCode = 1;
1453
+ return;
1454
+ }
1455
+ await client.destroy(boxId);
1456
+ log2.success(`Destroyed '${boxId}' (cloud resource + control-box state).`);
1457
+ } catch (err) {
1458
+ if (err instanceof HubApiError && err.code === "not_found") {
1459
+ log2.info(`No box '${boxId}' on the control box.`);
1460
+ return;
1461
+ }
1462
+ handleLifecycleError(err);
1463
+ }
1464
+ });
1465
+ function boxesLifecycleSub(action, verb, past) {
1466
+ return new Command(action).description(`${verb} a box on the control box (via its /api/v1)`).argument("<boxId>", "the box id as shown by `hub boxes list`").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").action(async (boxId, opts) => {
1467
+ try {
1468
+ const client = await resolveHubApiClient(opts.url);
1469
+ if (!client) {
1470
+ process.exitCode = 1;
1471
+ return;
1472
+ }
1473
+ await client.lifecycle(boxId, action);
1474
+ log2.success(`${past} '${boxId}'.`);
1475
+ } catch (err) {
1476
+ if (err instanceof HubApiError && err.code === "not_found") {
1477
+ log2.info(`No box '${boxId}' on the control box.`);
1478
+ process.exitCode = 1;
1479
+ return;
1480
+ }
1481
+ handleLifecycleError(err);
1482
+ }
1483
+ });
1484
+ }
1485
+ var boxesCmd = new Command("boxes").description("List + drive boxes on the control box over its public /api/v1").addCommand(boxesListSub).addCommand(boxesLifecycleSub("start", "Start", "Started")).addCommand(boxesLifecycleSub("stop", "Stop", "Stopped")).addCommand(boxesLifecycleSub("pause", "Pause", "Paused")).addCommand(boxesLifecycleSub("resume", "Resume", "Resumed")).addCommand(boxesRmSub);
1486
+ var promptsListSub = new Command("list").description("List pending host-action approvals across control-box boxes").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--json", "print raw JSON").action(async (opts) => {
1487
+ try {
1488
+ const client = await resolveHubApiClient(opts.url);
1489
+ if (!client) {
1490
+ process.exitCode = 1;
1491
+ return;
1492
+ }
1493
+ const [approvals, boxes] = await Promise.all([client.listApprovals(), client.listBoxes().catch(() => [])]);
1494
+ if (opts.json) {
1495
+ process.stdout.write(`${JSON.stringify(approvals, null, 2)}
1496
+ `);
1497
+ return;
1498
+ }
1499
+ if (approvals.length === 0) {
1500
+ log2.info("No pending approvals.");
1501
+ return;
1502
+ }
1503
+ const nameBy = new Map(boxes.map((b) => [b.id, b.name ?? b.task]));
1504
+ for (const a of approvals) {
1505
+ process.stdout.write(`${a.id} [${nameBy.get(a.boxId) ?? a.boxId}] ${a.message}
1506
+ `);
1507
+ }
1508
+ } catch (err) {
1509
+ handleLifecycleError(err);
1510
+ }
1511
+ });
1512
+ var promptsAnswerSub = new Command("answer").description("Answer a pending approval on the control box").argument("<id>", "the prompt id from `hub prompts list`").argument("[answer]", "y | n (default: y)", "y").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").action(async (id, answer, opts) => {
1513
+ try {
1514
+ if (answer !== "y" && answer !== "n") {
1515
+ log2.error(`answer must be 'y' or 'n' (got '${answer}')`);
1516
+ process.exitCode = 1;
1517
+ return;
1518
+ }
1519
+ const client = await resolveHubApiClient(opts.url);
1520
+ if (!client) {
1521
+ process.exitCode = 1;
1522
+ return;
1523
+ }
1524
+ await client.answerApproval(id, answer);
1525
+ log2.success(`Answered ${id} \u2192 ${answer}.`);
1526
+ } catch (err) {
1527
+ if (err instanceof HubApiError && err.code === "not_found") {
1528
+ log2.info(`No pending approval with id ${id} (already answered or expired?).`);
1529
+ process.exitCode = 1;
1530
+ return;
1531
+ }
1532
+ handleLifecycleError(err);
1533
+ }
1534
+ });
1535
+ var promptsCmd = new Command("prompts").description("List + answer control-box host-action approvals from the PC").addCommand(promptsListSub).addCommand(promptsAnswerSub);
1536
+ function jobLine(job) {
1537
+ const label = job.request.name ?? job.request.repoUrl;
1538
+ const boxOrError = job.result?.error !== void 0 ? ` ${job.result.error.split("\n")[0]?.slice(0, 80) ?? ""}` : job.result?.boxId ? ` box ${job.result.boxId}` : "";
1539
+ return `${job.id.slice(0, 8)} ${job.status.padEnd(7)} ${job.request.provider.padEnd(9)} ${label}${boxOrError}`;
1540
+ }
1541
+ var jobsListSub = new Command("list").description(
1542
+ "List create jobs on the control box. This is the queue that background `-i` cloud runs go to when a control box is configured \u2014 distinct from this PC's local `agentbox queue`."
1543
+ ).option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").option("--json", "print raw JSON").action(async (opts) => {
1544
+ try {
1545
+ const target = await resolveCustodyTarget(opts.url);
1546
+ if (!target) {
1547
+ process.exitCode = 1;
1548
+ return;
1549
+ }
1550
+ const jobs = await listHubJobs(target);
1551
+ if (opts.json) {
1552
+ process.stdout.write(`${JSON.stringify({ jobs }, null, 2)}
1553
+ `);
1554
+ return;
1555
+ }
1556
+ if (jobs.length === 0) {
1557
+ log2.info("No create jobs on the control box.");
1558
+ return;
1559
+ }
1560
+ for (const job of jobs) process.stdout.write(`${jobLine(job)}
1561
+ `);
1562
+ } catch (err) {
1563
+ handleLifecycleError(err);
1564
+ }
1565
+ });
1566
+ var jobsShowSub = new Command("show").description("Dump one control-box create job").argument("<jobId>", "job id (or the short prefix `hub jobs list` prints)").option("--url <url>", "override the control-plane URL (default: relay.controlPlaneUrl)").action(async (jobId, opts) => {
1567
+ try {
1568
+ const target = await resolveCustodyTarget(opts.url);
1569
+ if (!target) {
1570
+ process.exitCode = 1;
1571
+ return;
1572
+ }
1573
+ let job = await getHubJob(target, jobId);
1574
+ if (!job) {
1575
+ const matches = (await listHubJobs(target)).filter((j) => j.id.startsWith(jobId));
1576
+ if (matches.length > 1) {
1577
+ log2.error(
1578
+ `'${jobId}' matches ${String(matches.length)} jobs (${matches.map((m) => m.id.slice(0, 12)).join(", ")}) \u2014 pass more of the id.`
1579
+ );
1580
+ process.exitCode = 1;
1581
+ return;
1582
+ }
1583
+ job = matches[0] ?? null;
1584
+ }
1585
+ if (!job) {
1586
+ log2.info(`No job '${jobId}' on the control box.`);
1587
+ process.exitCode = 1;
1588
+ return;
1589
+ }
1590
+ process.stdout.write(`${JSON.stringify(job, null, 2)}
1591
+ `);
1592
+ } catch (err) {
1593
+ handleLifecycleError(err);
1594
+ }
1595
+ });
1596
+ var jobsCmd = new Command("jobs").description("Inspect the control box's box-create queue").addCommand(jobsListSub).addCommand(jobsShowSub);
1597
+ async function ensureHubApiKeyInEnv() {
1598
+ const body = await readFile2(ENV_PATH2, "utf8");
1599
+ const existing = /^AGENTBOX_HUB_API_KEY=(.+)$/m.exec(body)?.[1]?.trim();
1600
+ if (existing) return existing;
1601
+ const key = randomBytes3(32).toString("hex");
1602
+ const nl = body.length === 0 || body.endsWith("\n") ? "" : "\n";
1603
+ await writeFile2(ENV_PATH2, `${body}${nl}AGENTBOX_HUB_API_KEY=${key}
1604
+ `, { mode: 384 });
1605
+ await chmod(ENV_PATH2, 384);
1606
+ return key;
1607
+ }
1608
+ var deployHetznerSub = new Command("hetzner").description("Deploy the full hub to a new Hetzner VPS, reusing the App creds from `hub setup`").option("--ref <ref>", "branch / tag / sha the VPS clones + builds", DEFAULT_DEPLOY_REF).option("--repo <url>", "git repo the VPS clones", DEFAULT_DEPLOY_REPO).action(async (opts) => {
1609
+ try {
1610
+ if (!existsSync2(ENV_PATH2)) {
1611
+ log2.error("No control-plane env found. Run `agentbox hub setup` first (it creates the GitHub App + admin token).");
1612
+ process.exitCode = 1;
1613
+ return;
1614
+ }
1615
+ if (!await ensureHetznerHubAuth()) {
1616
+ log2.warn("login prompt cancelled \u2014 deploying without web-UI auth.");
1617
+ }
1618
+ await ensureHubApiKeyInEnv();
1619
+ const repoSpec = opts.repo ?? DEFAULT_DEPLOY_REPO;
1620
+ const repoUrl = repoSpec.includes("://") ? repoSpec : `https://github.com/${repoSpec}.git`;
1621
+ const ds = spinner();
1622
+ ds.start("deploying the control box to hetzner");
1623
+ let deployedUrl;
1624
+ try {
1625
+ deployedUrl = (await runHetznerDeploy({
1626
+ envPath: ENV_PATH2,
1627
+ repoRef: opts.ref ?? DEFAULT_DEPLOY_REF,
1628
+ repoUrl,
1629
+ log: (line) => ds.message(line)
1630
+ })).url;
1631
+ ds.stop(`deployed: ${deployedUrl}`);
1632
+ } catch (e) {
1633
+ ds.stop("deploy failed");
1634
+ log2.error(e instanceof Error ? e.message : String(e));
1635
+ process.exitCode = 1;
1636
+ return;
1637
+ }
1638
+ const url = await applyControlPlaneUrl(deployedUrl);
1639
+ log2.success(`Pointed the CLI at ${url} (relay.controlPlaneUrl).`);
1640
+ const ok = await waitForHealthz(url, 6e4);
1641
+ log2[ok ? "success" : "warn"](
1642
+ ok ? `Control box is healthy (${url}/healthz).` : `Could not confirm ${url}/healthz yet \u2014 check the deployment.`
1643
+ );
1644
+ if (ok) await seedPreparedToNewControlBox(url);
1645
+ } catch (err) {
1646
+ handleLifecycleError(err);
1647
+ }
1648
+ });
1649
+ async function seedPreparedToNewControlBox(url) {
1650
+ const target = await resolveCustodyTarget(url, { quiet: true });
1651
+ if (!target) return;
1652
+ const shared = [];
1653
+ for (const provider of SHAREABLE_PREPARED_PROVIDERS) {
1654
+ const ok = await pushPreparedToCustody(provider, {
1655
+ controlPlaneUrl: target.url,
1656
+ adminToken: target.adminToken
1657
+ }).catch(() => false);
1658
+ if (ok) shared.push(provider);
1659
+ }
1660
+ if (shared.length > 0) {
1661
+ log2.success(`Shared your ${shared.join(", ")} base bake(s) with the control box \u2014 it won't re-bake them.`);
1662
+ }
1663
+ }
1664
+ var SHAREABLE_PREPARED_PROVIDERS = ["hetzner", "vercel", "e2b", "daytona", "digitalocean"];
1665
+ var deployCmd = new Command("deploy").description("Deploy the full hub to a VPS, reusing the App creds from `hub setup`").addCommand(deployHetznerSub);
1666
+ var controlPlaneSubcommands = [
1667
+ setupSub,
1668
+ deployCmd,
1669
+ setUrlSub,
1670
+ unsetUrlSub,
1671
+ addSub,
1672
+ workerSub,
1673
+ credentialsCmd,
1674
+ secretsCmd,
1675
+ projectCmd,
1676
+ custodyCmd,
1677
+ boxesCmd,
1678
+ promptsCmd,
1679
+ jobsCmd
1680
+ ];
1681
+
1682
+ export {
1683
+ ensureProjectRepoOnControlPlane,
1684
+ enqueueCreateViaHub,
1685
+ listHubJobs,
1686
+ pollHubJob,
1687
+ handleLifecycleError,
1688
+ probeControlPlaneStatus,
1689
+ resolveCustodyTarget,
1690
+ resolveHubApiTarget,
1691
+ resolveHubApiClient,
1692
+ controlPlaneSubcommands
1693
+ };
1694
+ //# sourceMappingURL=chunk-2VW37PW4.js.map