@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.
- package/CHANGELOG.md +87 -4
- package/README.md +7 -3
- package/dist/_cloud-attach-XZYF324R.js +26 -0
- package/dist/admin-client-NOZ5CCAH.js +15 -0
- package/dist/chunk-2VW37PW4.js +1694 -0
- package/dist/chunk-2VW37PW4.js.map +1 -0
- package/dist/{chunk-HR7NHH5J.js → chunk-3UMM4VJH.js} +808 -57
- package/dist/chunk-3UMM4VJH.js.map +1 -0
- package/dist/chunk-5U5QOFL5.js +20 -0
- package/dist/chunk-5U5QOFL5.js.map +1 -0
- package/dist/chunk-6P6D77QP.js +285 -0
- package/dist/chunk-6P6D77QP.js.map +1 -0
- package/dist/chunk-6V366IZC.js +2892 -0
- package/dist/chunk-6V366IZC.js.map +1 -0
- package/dist/{chunk-KWOEUFVA.js → chunk-7J6G526Q.js} +6 -14
- package/dist/{chunk-KWOEUFVA.js.map → chunk-7J6G526Q.js.map} +1 -1
- package/dist/{chunk-IDH5A4RR.js → chunk-AYPAYY5R.js} +17 -4
- package/dist/chunk-AYPAYY5R.js.map +1 -0
- package/dist/{chunk-JGZSA5ZI.js → chunk-BHJCMTHP.js} +58 -15
- package/dist/chunk-BHJCMTHP.js.map +1 -0
- package/dist/{chunk-26IKZRTT.js → chunk-BLWAWGFX.js} +297 -1217
- package/dist/chunk-BLWAWGFX.js.map +1 -0
- package/dist/chunk-CGPUFXET.js +95 -0
- package/dist/chunk-CGPUFXET.js.map +1 -0
- package/dist/{chunk-SJ75AIA2.js → chunk-D6AODRNA.js} +12 -9
- package/dist/{chunk-SJ75AIA2.js.map → chunk-D6AODRNA.js.map} +1 -1
- package/dist/chunk-DPJMEG7U.js +11 -0
- package/dist/chunk-DPJMEG7U.js.map +1 -0
- package/dist/chunk-E2ITEZAQ.js +148 -0
- package/dist/chunk-E2ITEZAQ.js.map +1 -0
- package/dist/{chunk-JE6UI5YR.js → chunk-NKVCIH6N.js} +89 -223
- package/dist/chunk-NKVCIH6N.js.map +1 -0
- package/dist/chunk-OEYAVBA6.js +120 -0
- package/dist/chunk-OEYAVBA6.js.map +1 -0
- package/dist/{chunk-UJEH2NJT.js → chunk-PXYPQ5BO.js} +64 -264
- package/dist/chunk-PXYPQ5BO.js.map +1 -0
- package/dist/chunk-QESXSSO6.js +670 -0
- package/dist/chunk-QESXSSO6.js.map +1 -0
- package/dist/{chunk-NEF6MDJO.js → chunk-QJCK2AFX.js} +128 -26
- package/dist/chunk-QJCK2AFX.js.map +1 -0
- package/dist/chunk-RUJJY23M.js +84 -0
- package/dist/chunk-RUJJY23M.js.map +1 -0
- package/dist/{chunk-LL7NCMUU.js → chunk-SKNJRYM5.js} +7 -13
- package/dist/chunk-SKNJRYM5.js.map +1 -0
- package/dist/chunk-WFGAMJ5Q.js +689 -0
- package/dist/chunk-WFGAMJ5Q.js.map +1 -0
- package/dist/chunk-ZJL56TJD.js +1444 -0
- package/dist/chunk-ZJL56TJD.js.map +1 -0
- package/dist/{chunk-V5XXJH63.js → chunk-ZXOP4LBG.js} +5 -8
- package/dist/chunk-ZXOP4LBG.js.map +1 -0
- package/dist/control-plane-2VEM2KCL.js +31 -0
- package/dist/custody-client-P6XIXHRG.js +16 -0
- package/dist/{dist-TSFVB7AI.js → dist-2SYQI5S2.js} +11 -7
- package/dist/dist-2SYQI5S2.js.map +1 -0
- package/dist/{dist-KQTMCVME.js → dist-6QZMZEL7.js} +18 -11
- package/dist/dist-6QZMZEL7.js.map +1 -0
- package/dist/{dist-FTKS2GI4.js → dist-JHMILJUT.js} +10 -6
- package/dist/{dist-OO52HARR.js → dist-JOFZOZCY.js} +41 -25
- package/dist/{dist-O3LKOIE7.js → dist-KZ2GEEEX.js} +11 -7
- package/dist/dist-KZ2GEEEX.js.map +1 -0
- package/dist/{dist-Z6L5MM5D.js → dist-Q5NY4CF6.js} +10 -6
- package/dist/{dist-U2SVLJUQ.js → dist-SKMNEDVW.js} +8 -2
- package/dist/dist-SKMNEDVW.js.map +1 -0
- package/dist/dist-SRCKO7ZV.js +197 -0
- package/dist/dist-SRCKO7ZV.js.map +1 -0
- package/dist/{dist-WVYAURMF.js → dist-UXZQWKY6.js} +10 -6
- package/dist/dist-UXZQWKY6.js.map +1 -0
- package/dist/env-file-UDUDQMP4.js +11 -0
- package/dist/env-file-UDUDQMP4.js.map +1 -0
- package/dist/hub-adopt-ZS5CREYF.js +21 -0
- package/dist/hub-adopt-ZS5CREYF.js.map +1 -0
- package/dist/index.js +2461 -1905
- package/dist/index.js.map +1 -1
- package/dist/node-postgres-6JUOVUN5.js +3584 -0
- package/dist/node-postgres-6JUOVUN5.js.map +1 -0
- package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js → prepared-state-75DIZ55S-P6LE4N64.js} +3 -2
- package/dist/prepared-state-75DIZ55S-P6LE4N64.js.map +1 -0
- package/dist/remote-hub-SJ4XWBA5.js +9 -0
- package/dist/remote-hub-SJ4XWBA5.js.map +1 -0
- package/dist/sqlite-proxy-53E5D2VM.js +2882 -0
- package/dist/sqlite-proxy-53E5D2VM.js.map +1 -0
- package/package.json +1 -1
- package/runtime/_shared/ctl.cjs +29199 -16813
- package/runtime/digitalocean/ctl.cjs +29199 -16813
- package/runtime/docker/packages/ctl/dist/bin.cjs +29199 -16813
- package/runtime/e2b/ctl.cjs +29199 -16813
- package/runtime/hetzner/ctl.cjs +29199 -16813
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +5 -5
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js +4 -4
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/settings/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +4 -2
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/0-fj_better-auth_dist_adapters_kysely-adapter_index_mjs_0btft52._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0gvv4ct._.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_0pn9b49._.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_145bz8z._.js +9 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_14y990b._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_1nl4l3q._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1w4z_drizzle-orm_sqlite-proxy_index_05v_j5r.js +15 -0
- package/runtime/hub/apps/hub/.next/server/chunks/{[externals]__12m3qoa._.js → [externals]__0f3aqcx._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-9g1s8._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0-pvfxg._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01amzh6._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02q799_._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__03k22rl._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04tqk-j._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05ovf1y._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__05s-_x7._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07dnyfi._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07zk6qo._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_59yi6._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ajlo3d._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0b5s54n._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c4fiez._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c9iff1._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +5 -5
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dh6lzr._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ey83ai._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0h6vdvr._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lup7p4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0luxuu4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nl2u6u._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0nonp-6._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0oplozy._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0p-6wgd._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0rcnwbw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0tuz1am._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-9g0ae._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__10ry4ss._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11hv164._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__154_i13._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__17676rc._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bg1alc._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1cvqb1d._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d60gbz._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dm0jmw._.js +6 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dv_b1t._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1fzxip4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4oj-e._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1i4gq_2._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v1p7in._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9_her._.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1x1jkpb._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1yd8n5l._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20t_rs8._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_033w048._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_06f2faq._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{_0760z6y._.js → _0907rw0._.js} +15 -15
- package/runtime/hub/apps/hub/.next/server/chunks/_0f3molr._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0lgs9kd._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0pyhcqe._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_1-42ili._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_11__3wi._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_12flzuh._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_1bng7w9._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_1rpkqst._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_1wt72m1._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_1x3l5t8._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/packages_relay_dist_control-plane_03a-9aj.js +62 -31
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_0xy-j7z._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_1uccfbf._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_010858m.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_04zwxnx.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_06exuc7.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2ldrt.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_0f2tzep.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_116nh32.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_11dyjcb.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/09xn_next_dist_esm_build_templates_app-page_1_4knli.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0ebuy19._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0wxhi0-._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_0xe4ick._.js +9 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_14oaveu._.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/1w4z_drizzle-orm_sqlite-proxy_index_1a6wfdg.js +15 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0-pm2yl._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__08-1wwu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0c9mbcn._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0gdfxj4._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0kc-hwp._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0lu73p6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0m1yf2b._.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0wv-3zo._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__10bfmwi._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__18qvdzb._.js +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__1l2urlw._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/{_0ro6vh6._.js → _0r2xlss._.js} +3 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_components_1z1p98f._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/packages_relay_dist_control-plane_0ve-wz4.js +2 -25
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/middleware.js +1 -1
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/{2xc1sm79a6tsb.js → 2gsrna76i1d80.js} +1 -1
- package/runtime/hub/apps/hub/attach-helper.cjs +191 -0
- package/runtime/hub/apps/hub/{auth-DC44GQZY.js → auth-IRNNO3IK.js} +2 -2
- package/runtime/hub/apps/hub/{auth-config-LALRDYDO.js → auth-config-WJHIMGUE.js} +4 -2
- package/runtime/hub/apps/hub/{chunk-YJ5MJOXK.js → chunk-4LYVBRBC.js} +2094 -220
- package/runtime/hub/apps/hub/chunk-6AVSKCZJ.js +669 -0
- package/runtime/hub/apps/hub/{chunk-QSMPSV5Z.js → chunk-A5Y7LJMU.js} +57 -14
- package/runtime/hub/apps/hub/chunk-EDRFXO2M.js +35 -0
- package/runtime/hub/apps/hub/chunk-F2JI4GMX.js +2891 -0
- package/runtime/hub/apps/hub/{chunk-EHBJKZCL.js → chunk-O3K3ZGFF.js} +500 -35
- package/runtime/hub/apps/hub/chunk-RII6IKNJ.js +688 -0
- package/runtime/hub/apps/hub/{chunk-RXYOWSSN.js → chunk-RMEUA6PA.js} +120 -14
- package/runtime/hub/apps/hub/{chunk-3FJNKSNZ.js → chunk-SCHQR5KR.js} +3 -1
- package/runtime/hub/apps/hub/{dist-6FPPUSWZ.js → dist-2GEAA7QA.js} +15 -3
- package/runtime/hub/apps/hub/{dist-JG45OFT2.js → dist-36O6F6M3.js} +39 -24
- package/runtime/hub/apps/hub/{dist-3I7KUI6W.js → dist-IWLEL2TO.js} +21 -24
- package/runtime/hub/apps/hub/{dist-G6TXUSPZ.js → dist-NYKIT5W5.js} +10 -11
- package/runtime/hub/apps/hub/{dist-EQV4L7KP.js → dist-QB2IJ7OD.js} +7 -1
- package/runtime/hub/apps/hub/{dist-LYDHYTP2.js → dist-RBBXXGLI.js} +129 -26
- package/runtime/hub/apps/hub/{dist-GTVVXCBP.js → dist-RRJN2U5P.js} +10 -14
- package/runtime/hub/apps/hub/{dist-DX6IYMAH.js → dist-UWXGDCK4.js} +14 -11
- package/runtime/hub/apps/hub/{hub-token-COBZGSLS.js → hub-token-6USIMBPQ.js} +2 -2
- package/runtime/hub/apps/hub/hub-worker-SOFWVTWU.js +215 -0
- package/runtime/hub/apps/hub/node-postgres-DIU2H5VP.js +3583 -0
- package/runtime/hub/apps/hub/package.json +5 -2
- package/runtime/hub/apps/hub/{prepared-state-75DIZ55S-2IFNUHHM.js → prepared-state-75DIZ55S-P5FHEORG.js} +1 -1
- package/runtime/hub/apps/hub/server.js +247 -66
- package/runtime/hub/apps/hub/sqlite-proxy-VJS3HIOV.js +2881 -0
- package/runtime/relay/bin.cjs +694 -13
- package/runtime/vercel/ctl.cjs +29199 -16813
- package/dist/_cloud-attach-WDGM6FL5.js +0 -19
- package/dist/chunk-26IKZRTT.js.map +0 -1
- package/dist/chunk-HR7NHH5J.js.map +0 -1
- package/dist/chunk-IDH5A4RR.js.map +0 -1
- package/dist/chunk-JE6UI5YR.js.map +0 -1
- package/dist/chunk-JGZSA5ZI.js.map +0 -1
- package/dist/chunk-LL7NCMUU.js.map +0 -1
- package/dist/chunk-NEF6MDJO.js.map +0 -1
- package/dist/chunk-UJEH2NJT.js.map +0 -1
- package/dist/chunk-V5XXJH63.js.map +0 -1
- package/dist/dist-KQTMCVME.js.map +0 -1
- package/dist/dist-O3LKOIE7.js.map +0 -1
- package/dist/dist-TSFVB7AI.js.map +0 -1
- package/runtime/hub/apps/hub/.next/server/chunks/0zhp_better-auth_dist_adapters_kysely-adapter_index_mjs_1rl4qnh._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04h15ml._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__04jgk9x._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07ednlo._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a7djvw._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ig1bot._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0keu6we._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ql4fjo._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0szd4sh._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t7o5ed._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vs8fma._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0w9ud8u._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xh14bo._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0yhb0gc._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-0flwc._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13ioh5z._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__13jwk_k._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16_uteg._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__16p2m-g._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__19pc87s._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1_gu2yk._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1a50b07._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ai-945._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bu2zio._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1ctczev._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1d6mtlk._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1dn_3i1._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1e4z_-v._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f2sueq._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1f9zctr._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4xycg._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hqla7-._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1js2jdv._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1md9kdw._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1mttufy._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1nepkp-._.js +0 -6
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1pp5oib._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1q5bqse._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qwhzmi._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1thipug._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1v9om6g._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1xeczo7._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__20503l7._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[externals]_pg_20c820g._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__0j0tjwn._.js +0 -3
- /package/dist/{_cloud-attach-WDGM6FL5.js.map → _cloud-attach-XZYF324R.js.map} +0 -0
- /package/dist/{dist-FTKS2GI4.js.map → admin-client-NOZ5CCAH.js.map} +0 -0
- /package/dist/{dist-OO52HARR.js.map → control-plane-2VEM2KCL.js.map} +0 -0
- /package/dist/{dist-U2SVLJUQ.js.map → custody-client-P6XIXHRG.js.map} +0 -0
- /package/dist/{dist-WVYAURMF.js.map → dist-JHMILJUT.js.map} +0 -0
- /package/dist/{dist-Z6L5MM5D.js.map → dist-JOFZOZCY.js.map} +0 -0
- /package/dist/{prepared-state-75DIZ55S-TNJXWMXV.js.map → dist-Q5NY4CF6.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{PWF2iHQOg9-rRyfqVDLrh → B4bEtdig9I9joQFHDOjX3}/_ssgManifest.js +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/control-plane.ts","../src/control-plane/github-app-manifest.ts","../src/control-plane/deploy-vercel.ts","../src/control-plane/github-fork.ts","../src/control-plane/ensure-repo-installed.ts","../src/control-plane/deploy-hetzner.ts","../src/control-plane/hub-auth-env.ts","../src/control-plane/hub-api-client.ts","../src/control-plane/hub-enqueue.ts","../src/commands/_errors.ts"],"sourcesContent":["import { isCancel, log, note, select, spinner } from '@clack/prompts';\nimport { Command } from 'commander';\nimport { spawn } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { hostname, homedir, tmpdir } from 'node:os';\nimport { basename, dirname, join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { findProjectRoot, loadEffectiveConfig, setConfigValue, unsetConfigValue } from '@agentbox/config';\nimport { DEFAULT_ENV_PATTERNS, projectSlugFromOriginUrl } from '@agentbox/sandbox-core';\nimport {\n applyProjectSeed,\n deadlineFetch,\n hostReachable,\n pushPreparedToCustody,\n pushProjectSeedToCustody,\n readGitOriginUrl,\n} from '@agentbox/sandbox-cloud';\n\n/** Bound on the worker's seed download once the control box is known to be up. */\nconst SEED_FETCH_MS = 120_000;\nimport {\n drainCreateJobs,\n GitHubAppLeaser,\n loadGitHubAppConfig,\n parseGitRemote,\n PostgresStore,\n toAuthedHttpsUrl,\n} from '@agentbox/relay';\nimport { randomBytes } from 'node:crypto';\nimport { providerForCreate } from '../provider/registry.js';\nimport { makeControlPlaneCreateBox, cloneRepoWithLfs } from '../control-plane/create-box.js';\nimport { runGitHubAppManifestFlow } from '../control-plane/github-app-manifest.js';\nimport { deployControlPlaneToVercel } from '../control-plane/deploy-vercel.js';\nimport { runHetznerDeploy } from '../control-plane/deploy-hetzner.js';\nimport { resolveHubAuthEnv } from '../control-plane/hub-auth-env.js';\nimport {\n addRepoUrl,\n checkRepoInstalled,\n loadControlPlaneMeta,\n openInBrowser,\n resolveOwnerRepo,\n} from '../control-plane/ensure-repo-installed.js';\nimport {\n CustodyClient,\n collectAgentCredentialUploads,\n planPush,\n type UploadItem,\n} from '../control-plane/custody-client.js';\nimport { HubApiClient, HubApiError, type HubLifecycleAction } from '../control-plane/hub-api-client.js';\nimport { loadControlPlaneEnv } from '../control-plane/env-file.js';\nimport { getHubJob, listHubJobs } from '../control-plane/hub-enqueue.js';\nimport type { CreateJobRow } from '@agentbox/relay/control-plane';\nimport { AGENT_SYNC_SPECS } from '@agentbox/sandbox-core';\nimport { handleLifecycleError } from './_errors.js';\n\nconst CP_DIR = join(homedir(), '.agentbox', 'control-plane');\nconst PEM_PATH = join(CP_DIR, 'github-app.pem');\nconst ENV_PATH = join(CP_DIR, 'control-plane.env');\nconst META_PATH = join(CP_DIR, 'control-plane.json');\n\n/** Default GitHub repo the control plane is deployed from (Vercel + Hetzner). */\nconst DEFAULT_DEPLOY_REPO = 'madarco/agentbox';\nconst DEFAULT_DEPLOY_REF = 'main';\n\n/** Persist `relay.controlPlaneUrl` and report it. Shared by set-url + setup. */\nasync function applyControlPlaneUrl(url: string): Promise<string> {\n const trimmed = url.replace(/\\/$/, '');\n await setConfigValue('global', 'relay.controlPlaneUrl', trimmed, process.cwd());\n return trimmed;\n}\n\n/** Poll a deployed plane's /healthz until it answers (or the deadline elapses). */\nasync function waitForHealthz(url: string, deadlineMs: number): Promise<boolean> {\n const stop = Date.now() + deadlineMs;\n while (Date.now() < stop) {\n try {\n const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8000) });\n if (res.ok) return true;\n } catch {\n /* retry */\n }\n await delay(4000);\n }\n return false;\n}\n\n/**\n * The hetzner hub-auth env block appended to `control-plane.env`. The full-hub\n * compose sets the profile literally, but these secrets (`BETTER_AUTH_SECRET`,\n * admin email/password) are read from the `.env` by the compose file, so a\n * network-reachable hub is login-gated.\n */\nfunction hetznerAuthBody(hubAuth: {\n AGENTBOX_HUB_AUTH: string;\n BETTER_AUTH_SECRET: string;\n AGENTBOX_HUB_ADMIN_EMAIL: string;\n AGENTBOX_HUB_ADMIN_PASSWORD: string;\n}): string {\n return (\n `AGENTBOX_HUB_PROFILE=hetzner\\n` +\n `AGENTBOX_HUB_AUTH=${hubAuth.AGENTBOX_HUB_AUTH}\\n` +\n `BETTER_AUTH_SECRET=${hubAuth.BETTER_AUTH_SECRET}\\n` +\n `AGENTBOX_HUB_ADMIN_EMAIL=${hubAuth.AGENTBOX_HUB_ADMIN_EMAIL}\\n` +\n `AGENTBOX_HUB_ADMIN_PASSWORD=${hubAuth.AGENTBOX_HUB_ADMIN_PASSWORD}\\n`\n );\n}\n\n/**\n * Ensure `control-plane.env` carries the hub-auth block (a prior `setup --deploy\n * none` writes only the App creds). Appends it when `BETTER_AUTH_SECRET` is\n * absent; returns false only if the operator cancels the login prompt.\n */\nasync function ensureHetznerHubAuth(): Promise<boolean> {\n const body = existsSync(ENV_PATH) ? readFileSync(ENV_PATH, 'utf8') : '';\n if (/^BETTER_AUTH_SECRET=/m.test(body)) return true;\n const hubAuth = await resolveHubAuthEnv();\n if (!hubAuth) return false;\n await writeFile(ENV_PATH, body + hetznerAuthBody(hubAuth), { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n return true;\n}\n\ntype DeployTarget = 'vercel' | 'hetzner' | 'none';\n\ninterface SetupOpts {\n name?: string;\n org?: string;\n deploy?: string;\n ref?: string;\n repo?: string;\n}\n\nconst setupSub = new Command('setup')\n .description(\n 'Create the GitHub App the control plane leases push tokens with, and write its deploy config (env + admin token)',\n )\n .option('--name <name>', 'GitHub App name (default: autogenerated agentbox-<rand>, must be globally unique)')\n .option('--org <org>', 'create the App under an organization instead of your user account')\n .option('--deploy <target>', 'deploy the plane after creating the App: vercel | hetzner | none')\n .option('--repo <owner/name>', 'GitHub repo to deploy the plane from (default madarco/agentbox; fork + pass this if you don\\'t own it)')\n .option('--ref <ref>', 'git ref of the repo to deploy (branch/tag/sha; default main) — used by Vercel + Hetzner')\n .action(async (opts: SetupOpts) => {\n try {\n // Globally-unique by default — GitHub rejects duplicate App names.\n const name = opts.name ?? `agentbox-${randomBytes(4).toString('hex')}`;\n\n note(\n 'Your browser will open to GitHub to create the App. Review the\\n' +\n 'permissions (Contents + Pull requests: write) and click \"Create\".',\n 'GitHub App',\n );\n\n const s = spinner();\n s.start('waiting for the GitHub App to be created in your browser');\n const app = await runGitHubAppManifestFlow({\n appName: String(name),\n org: opts.org,\n // Honor GHES overrides (and make the flow scriptable in tests).\n githubUrl: process.env.GITHUB_URL,\n apiBaseUrl: process.env.GITHUB_API_URL,\n openBrowser: openInBrowser,\n log: (line) => s.message(line),\n });\n s.stop(`GitHub App created: ${app.slug} (id ${app.appId})`);\n\n // Persist the App key + a generated admin token as the plane's deploy env.\n const adminToken = randomBytes(32).toString('hex');\n // Headless bearer for the hub's public /api/v1 (CLI / tray against a remote\n // control box, which can't carry the browser session cookie). Separate from\n // the admin token, which gates the internal /admin/* wire.\n const hubApiKey = randomBytes(32).toString('hex');\n await mkdir(CP_DIR, { recursive: true });\n await writeFile(PEM_PATH, app.pem, { mode: 0o600 });\n await chmod(PEM_PATH, 0o600);\n const pemB64 = Buffer.from(app.pem, 'utf8').toString('base64');\n const envBody =\n `# AgentBox control plane deploy env (generated by 'agentbox hub setup').\\n` +\n `# Feed to docker compose (--env-file) or 'vercel env add'. Keep secret.\\n` +\n `GITHUB_APP_ID=${app.appId}\\n` +\n `GITHUB_APP_PRIVATE_KEY=${pemB64}\\n` +\n `AGENTBOX_RELAY_ADMIN_TOKEN=${adminToken}\\n` +\n `AGENTBOX_HUB_API_KEY=${hubApiKey}\\n`;\n await writeFile(ENV_PATH, envBody, { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n await writeFile(\n META_PATH,\n JSON.stringify({ appId: app.appId, slug: app.slug, htmlUrl: app.htmlUrl, installUrl: app.installUrl }, null, 2) + '\\n',\n { mode: 0o600 },\n );\n\n log.success(`GitHub App ready. Deploy config written to ${ENV_PATH} (0600).`);\n\n // --- Deploy step (after the App exists) ---\n const target = await resolveDeployTarget(opts.deploy);\n let deployedUrl: string | null = null;\n if (target !== 'none') {\n // Prompt for the hub login admin BEFORE the deploy spinner starts (a\n // spinner and @clack prompts can't share the terminal). Setting these\n // turns login on in the deployed hub so it is never left loginless — both\n // vercel and hetzner (the Caddy-HTTPS docker-compose deploy).\n const hubAuth = await resolveHubAuthEnv();\n // hetzner reads ENV_PATH (written to the VPS .env); append the auth env +\n // the Postgres auth profile so docker-compose enforces login there too.\n if (target === 'hetzner' && hubAuth) {\n await writeFile(ENV_PATH, envBody + hetznerAuthBody(hubAuth), { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n }\n const ds = spinner();\n ds.start(`deploying the control plane to ${target}`);\n try {\n const onLog = (line: string): void => ds.message(line);\n const repo = opts.repo ?? DEFAULT_DEPLOY_REPO;\n const ref = opts.ref ?? DEFAULT_DEPLOY_REF;\n if (target === 'vercel') {\n const env = {\n GITHUB_APP_ID: app.appId,\n GITHUB_APP_PRIVATE_KEY: pemB64,\n AGENTBOX_RELAY_ADMIN_TOKEN: adminToken,\n AGENTBOX_HUB_API_KEY: hubApiKey,\n ...(hubAuth ?? {}),\n };\n deployedUrl = (await deployControlPlaneToVercel({ env, repo, ref, log: onLog })).url;\n } else {\n deployedUrl = (await runHetznerDeploy({ envPath: ENV_PATH, repoRef: ref, log: onLog })).url;\n }\n ds.stop(`deployed: ${deployedUrl}`);\n } catch (e) {\n // Stop the spinner (code 1) before printing — otherwise it keeps\n // animating its last \"creating the firewall…\" frame under the error.\n ds.stop(`deploy to ${target} failed`, 1);\n log.warn(`deploy to ${target} failed: ${e instanceof Error ? e.message : String(e)}`);\n printManualDeploy();\n }\n } else {\n printManualDeploy();\n }\n\n if (deployedUrl) {\n const url = await applyControlPlaneUrl(deployedUrl);\n log.success(`Pointed the CLI at ${url} (relay.controlPlaneUrl).`);\n const ok = await waitForHealthz(url, 60_000);\n log[ok ? 'success' : 'warn'](\n ok ? `Control plane is healthy (${url}/healthz).` : `Could not confirm ${url}/healthz yet — check the deployment.`,\n );\n }\n\n // Open the repo-selection page so the user can authorize repos right away.\n log.info(`Install the App on your repos: ${app.installUrl}`);\n openInBrowser(app.installUrl);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/** Resolve the deploy target from the flag, or ask interactively. */\nasync function resolveDeployTarget(flag: string | undefined): Promise<DeployTarget> {\n if (flag === 'vercel' || flag === 'hetzner' || flag === 'none') return flag;\n if (flag) {\n log.warn(`unknown --deploy \"${flag}\"; choose interactively`);\n }\n const choice = await select({\n message: 'Deploy the control plane now?',\n options: [\n { value: 'vercel', label: 'Vercel — managed (auto-provisions Neon Postgres)' },\n { value: 'hetzner', label: 'Hetzner VPS — HTTPS via <ip>.sslip.io + Caddy/Let’s Encrypt' },\n { value: 'none', label: 'Skip — I’ll deploy later (print manual steps)' },\n ],\n initialValue: 'vercel',\n });\n if (isCancel(choice)) return 'none';\n return choice as DeployTarget;\n}\n\nfunction printManualDeploy(): void {\n log.info(\n [\n 'Deploy later with the written env:',\n ` Self-host: cd apps/hub && docker compose --env-file ${ENV_PATH} up --build`,\n ` Vercel: agentbox hub setup --deploy vercel (or 'vercel env add' the vars + 'vercel deploy --prod')`,\n ` Then: agentbox hub set-url https://<your-plane-url>`,\n ].join('\\n'),\n );\n}\n\nconst setUrlSub = new Command('set-url')\n .description('Point boxes + the CLI at a deployed control plane (sets relay.controlPlaneUrl)')\n .argument('<url>', 'base URL of the deployed control plane, e.g. https://plane.example.com')\n .action(async (url: string) => {\n try {\n const trimmed = await applyControlPlaneUrl(url);\n log.success(`Set relay.controlPlaneUrl = ${trimmed}`);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst unsetUrlSub = new Command('unset-url')\n .description('Stop using a control plane on this machine (removes relay.controlPlaneUrl)')\n .option('--purge', \"also delete this machine's local App metadata + admin token (~/.agentbox/control-plane)\")\n .action(async (opts: { purge?: boolean }) => {\n try {\n // set-url writes the global scope; also clear a per-project override if one\n // exists. A cwd with no project config just yields `existed:false` (the\n // project unset never throws for that) — real I/O/write errors from either\n // scope propagate to handleLifecycleError rather than being masked.\n const g = await unsetConfigValue('global', 'relay.controlPlaneUrl', process.cwd());\n const p = await unsetConfigValue('project', 'relay.controlPlaneUrl', process.cwd());\n if (!g.existed && !p.existed) {\n log.info('No control plane was configured (relay.controlPlaneUrl not set).');\n } else {\n const where = [g.existed ? 'global' : null, p.existed ? 'project' : null].filter(Boolean).join(' + ');\n log.success(\n `Removed relay.controlPlaneUrl (${where}). New cloud boxes now push through the host relay ` +\n '(your laptop must be on), and the GitHub-App repo-authorization prompt no longer fires.',\n );\n }\n if (existsSync(CP_DIR)) {\n if (opts.purge) {\n await rm(CP_DIR, { recursive: true, force: true });\n log.success(`Purged this machine's control-plane credentials (${CP_DIR}).`);\n } else {\n log.info(`This machine's App metadata + admin token remain in ${CP_DIR} (use --purge to delete).`);\n }\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/** Reachability + box/event counts for a configured (remote) hub. */\nexport interface ControlPlaneStatus {\n url: string;\n healthy: boolean;\n boxes: number;\n events: number;\n detail: string;\n}\n\n/**\n * Probe a remote hub's `/healthz` for reachability + box/event counts. Used by\n * the unified `agentbox hub status` when a control box is configured (the local\n * hub renders `getHubStatus()` instead). Never throws — an unreachable hub comes\n * back `healthy:false` with the error name in `detail`.\n */\nexport async function probeControlPlaneStatus(url: string): Promise<ControlPlaneStatus> {\n let healthy = false;\n let boxes = 0;\n let events = 0;\n let detail = '';\n try {\n const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8000) });\n healthy = res.ok;\n const body = (await res.json().catch(() => ({}))) as { boxes?: number; events?: number };\n boxes = body.boxes ?? 0;\n events = body.events ?? 0;\n detail = `${String(boxes)} box(es), ${String(events)} event(s)`;\n } catch (e) {\n detail = e instanceof Error ? e.name : String(e);\n }\n return { url, healthy, boxes, events, detail };\n}\n\nconst addSub = new Command('add')\n .description(\"Authorize the current project's git repo on the control plane's GitHub App\")\n .action(async () => {\n try {\n const cfg = await loadEffectiveConfig(process.cwd());\n const controlPlaneUrl = cfg.effective.relay.controlPlaneUrl;\n if (!controlPlaneUrl) {\n log.error('No control plane configured. Run `agentbox hub set-url <url>` first.');\n process.exitCode = 1;\n return;\n }\n const ownerRepo = await resolveOwnerRepo(process.cwd());\n if (!ownerRepo) {\n log.error('No git origin found here — `cd` into a project with a GitHub remote.');\n process.exitCode = 1;\n return;\n }\n const { owner, repo } = ownerRepo;\n const installed = await checkRepoInstalled(owner, repo, controlPlaneUrl);\n if (installed === true) {\n log.success(`${owner}/${repo} is already authorized on the GitHub App.`);\n return;\n }\n const url = addRepoUrl(loadControlPlaneMeta());\n if (!url) {\n log.error(\n 'No GitHub App metadata found locally. Run this from a machine that ran `hub setup`,\\n' +\n 'or open your App settings on GitHub and add the repo manually.',\n );\n process.exitCode = 1;\n return;\n }\n log.info(`Opening ${url} — select ${owner}/${repo}, then approve.`);\n openInBrowser(url);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/** Run `git <args>`, rejecting on a non-zero exit. */\nfunction runGit(args: string[], env?: Record<string, string>, timeoutMs?: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const child = spawn('git', args, {\n stdio: ['ignore', 'ignore', 'pipe'],\n env: env ? { ...process.env, ...env } : process.env,\n });\n const timer = timeoutMs ? setTimeout(() => child.kill('SIGKILL'), timeoutMs) : undefined;\n let err = '';\n child.stderr.on('data', (c: Buffer) => (err += c.toString('utf8')));\n child.on('error', (e) => {\n if (timer) clearTimeout(timer);\n reject(e);\n });\n child.on('close', (code) => {\n if (timer) clearTimeout(timer);\n if (code === 0) resolve();\n else reject(new Error(`git ${args[0]} failed (${String(code)}): ${err.trim()}`));\n });\n });\n}\n\ninterface WorkerOpts {\n store: string;\n once?: boolean;\n pollInterval: string;\n}\n\nconst workerSub = new Command('worker')\n .description(\n 'Drain the control plane box-creation queue and provision real boxes (long-running; needs provider creds + the App key)',\n )\n .requiredOption('--store <url>', 'Postgres URL of the control plane (same store the plane uses)')\n .option('--once', 'drain the queue once and exit (default: loop)')\n .option('--poll-interval <ms>', 'poll interval when looping', '5000')\n .action(async (opts: WorkerOpts) => {\n try {\n loadControlPlaneEnv();\n const appCfg = loadGitHubAppConfig();\n if (!appCfg) {\n log.error('No GitHub App configured. Run `agentbox hub setup` first.');\n process.exitCode = 1;\n return;\n }\n const store = new PostgresStore({ connectionString: opts.store });\n await store.migrate();\n const leaser = new GitHubAppLeaser(appCfg);\n const cfg = await loadEffectiveConfig(process.cwd());\n\n const createBox = makeControlPlaneCreateBox({\n leaseRemoteUrl: async (repoUrl) => {\n const { path } = parseGitRemote(repoUrl);\n const [owner, repo] = path.replace(/\\.git$/, '').split('/');\n if (!owner || !repo) throw new Error(`cannot derive owner/repo from ${repoUrl}`);\n const { token } = await leaser.leaseRepoToken(owner, repo);\n return toAuthedHttpsUrl(repoUrl, token);\n },\n cloneRepo: (authedUrl, repoUrl, dest, branch) =>\n cloneRepoWithLfs(runGit, authedUrl, repoUrl, dest, branch, (line) => log.info(line)),\n createBox: async ({ workspacePath, name, provider, agent, onLog }) => {\n const p = await providerForCreate({ flag: provider, config: cfg.effective });\n const created = await p.create({\n workspacePath,\n name,\n projectRoot: workspacePath,\n // Registered on the plane so an adopting PC relaunches the right agent.\n agent:\n agent === 'claude' || agent === 'codex' || agent === 'opencode' ? agent : undefined,\n onLog,\n });\n return { id: created.record.id };\n },\n // Overlay the project's custody seed onto the clone, exactly as the\n // resident hub worker does — without this, boxes drained by THIS worker\n // come up missing the untracked files + env material the seed exists to\n // provide. Unlike the hub, this worker is not the custody host, so it\n // reads the blobs over HTTP.\n fetchSeedMaterial: async (repoUrl, dest) => {\n const target = await resolveCustodyTarget(undefined, { quiet: true });\n if (!target) return null;\n const slug = projectSlugFromOriginUrl(repoUrl);\n if (!slug) return null;\n // Probe + bound like every other custody call: a down control box must\n // not park each blob `get` on undici's ~10s connect timeout and stall\n // a create the user is waiting on (see sandbox-cloud/reachability.ts).\n if (!(await hostReachable(target.url))) {\n process.stdout.write('agentbox-cp-worker: control box unreachable — bare clone, no seed\\n');\n return null;\n }\n const client = new CustodyClient({\n ...target,\n fetchImpl: deadlineFetch(AbortSignal.timeout(SEED_FETCH_MS)),\n });\n return applyProjectSeed({\n source: { get: (rel) => client.get(`projects/${slug}/seed/${rel}`) },\n dest,\n log: (line) => process.stdout.write(`agentbox-cp-worker: ${line}\\n`),\n });\n },\n tmpDir: (jobId) => join(tmpdir(), `agentbox-cp-worker-${jobId}`),\n cleanup: (dir) => rm(dir, { recursive: true, force: true }),\n log: (line) => process.stdout.write(`agentbox-cp-worker: ${line}\\n`),\n });\n\n const workerId = `worker-${hostname()}-${String(process.pid)}`;\n const interval = Number.parseInt(opts.pollInterval, 10) || 5000;\n let running = true;\n const stop = (): void => {\n running = false;\n };\n process.on('SIGINT', stop);\n process.on('SIGTERM', stop);\n process.stdout.write(`agentbox-cp-worker: draining create jobs as ${workerId}\\n`);\n do {\n const n = await drainCreateJobs(store, createBox, workerId);\n if (n > 0) process.stdout.write(`agentbox-cp-worker: processed ${String(n)} job(s)\\n`);\n if (opts.once) break;\n await delay(interval);\n } while (running);\n await store.close();\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/**\n * Resolve the control-plane URL (`--url` > `relay.controlPlaneUrl`) and the\n * admin bearer (`AGENTBOX_RELAY_ADMIN_TOKEN` > the setup-written env file).\n * Returns null and prints an actionable error when either is missing.\n *\n * `quiet` suppresses those errors, for callers where a control box is optional\n * and its absence is a normal outcome rather than a user mistake (the recover\n * key fallback, the by-name auto-adopt hook).\n */\nexport async function resolveCustodyTarget(\n urlFlag: string | undefined,\n opts: { quiet?: boolean } = {},\n): Promise<{ url: string; adminToken: string } | null> {\n const cfg = await loadEffectiveConfig(process.cwd());\n const url = (urlFlag ?? cfg.effective.relay.controlPlaneUrl ?? '').replace(/\\/$/, '');\n if (!url) {\n if (!opts.quiet)\n log.error('No control plane configured. Run `agentbox hub set-url <url>` (or pass --url).');\n return null;\n }\n loadControlPlaneEnv();\n const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN ?? '';\n if (!adminToken) {\n if (!opts.quiet)\n log.error(\n 'No admin token available. Set AGENTBOX_RELAY_ADMIN_TOKEN, or run this from the machine that\\n' +\n 'ran `agentbox hub setup` (it writes the token to ~/.agentbox/control-plane).',\n );\n return null;\n }\n return { url, adminToken };\n}\n\n/**\n * Resolve a control box's public REST API target: its URL + the headless\n * `/api/v1` bearer (`AGENTBOX_HUB_API_KEY`). This is the client-facing hub API\n * (boxes/lifecycle/approvals), distinct from {@link resolveCustodyTarget}'s admin\n * token, which is the internal `/admin/*` wire. Seam for the shared hub-API client\n * (URL-swappable local ⇄ remote); not yet wired into commands.\n *\n * Returns null (actionable error unless `quiet`) when no control box is configured\n * or no API key is available — the key is minted + recorded by `control-plane\n * setup`/deploy into `~/.agentbox/control-plane/control-plane.env`.\n */\nexport async function resolveHubApiTarget(\n urlFlag: string | undefined,\n opts: { quiet?: boolean } = {},\n): Promise<{ url: string; apiKey: string } | null> {\n const cfg = await loadEffectiveConfig(process.cwd());\n const url = (urlFlag ?? cfg.effective.relay.controlPlaneUrl ?? '').replace(/\\/$/, '');\n if (!url) {\n if (!opts.quiet)\n log.error('No control plane configured. Run `agentbox hub set-url <url>` (or pass --url).');\n return null;\n }\n loadControlPlaneEnv();\n const apiKey = process.env.AGENTBOX_HUB_API_KEY ?? '';\n if (!apiKey) {\n if (!opts.quiet)\n log.error(\n 'No hub API key available. Set AGENTBOX_HUB_API_KEY, or run this from the machine that\\n' +\n 'ran `agentbox hub setup` (it writes the key to ~/.agentbox/control-plane).',\n );\n return null;\n }\n return { url, apiKey };\n}\n\n/**\n * Build a {@link HubApiClient} for the configured hub from {@link resolveHubApiTarget}\n * (URL + `/api/v1` key), or null (with an actionable error unless `quiet`) when\n * unconfigured. The client-facing counterpart to `new ControlPlaneAdminClient`.\n */\nexport async function resolveHubApiClient(\n urlFlag: string | undefined,\n opts: { quiet?: boolean } = {},\n): Promise<HubApiClient | null> {\n const target = await resolveHubApiTarget(urlFlag, opts);\n return target ? new HubApiClient(target) : null;\n}\n\n/**\n * Slug a project into a custody `projects/<slug>` key: `owner__repo`, else the\n * dir name.\n *\n * Delegates to the shared `projectSlugFromOriginUrl` — every producer and\n * consumer of the `projects/<slug>` scope MUST derive the same key from the same\n * origin, and a second local implementation is exactly how they drift apart. (It\n * did: this used to take the *first* two path segments unsanitized, while the\n * create path and the hub worker take the last two and sanitize — so for a\n * nested remote like `gitlab.com/group/subgroup/repo` a push landed under\n * `group__subgroup` while the worker looked in `subgroup__repo`.)\n */\nasync function projectSlug(explicit: string | undefined, projectRoot: string): Promise<string> {\n if (explicit) return explicit.replace(/[^A-Za-z0-9._-]/g, '-');\n const origin = await readGitOriginUrl(projectRoot).catch(() => undefined);\n const slug = origin ? projectSlugFromOriginUrl(origin) : null;\n if (slug) return slug;\n return basename(projectRoot).replace(/[^A-Za-z0-9._-]/g, '-') || 'project';\n}\n\n/** Upload a set of items with a hash-skip pass; logs one line per decision. */\nasync function pushItems(\n client: CustodyClient,\n items: UploadItem[],\n prefix: string,\n force: boolean,\n): Promise<void> {\n if (items.length === 0) {\n log.info('Nothing to push.');\n return;\n }\n const manifest = await client.list(prefix);\n const plan = planPush(items, manifest, { force });\n let uploaded = 0;\n let skipped = 0;\n for (const item of items) {\n const decision = plan.find((d) => d.path === item.path)!;\n if (decision.action === 'skip') {\n skipped++;\n continue;\n }\n const res = await client.put(item.path, item.data);\n if (res.changed) uploaded++;\n else skipped++;\n }\n log.success(`Pushed ${String(uploaded)} item(s), skipped ${String(skipped)} unchanged.`);\n}\n\nconst credentialsPushSub = new Command('push')\n .description('Push host agent-credential backups (claude/codex/opencode) to the control box custody store')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--agent <id>', 'push only one agent: claude | codex | opencode')\n .option('--force', 'upload even when the stored hash matches')\n .action(async (opts: { url?: string; agent?: string; force?: boolean }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const only = opts.agent as 'claude' | 'codex' | 'opencode' | undefined;\n if (opts.agent && !['claude', 'codex', 'opencode'].includes(opts.agent)) {\n log.error(`unknown --agent \"${opts.agent}\" (expected claude | codex | opencode)`);\n process.exitCode = 1;\n return;\n }\n const items = await collectAgentCredentialUploads(only);\n const client = new CustodyClient(target);\n await pushItems(client, items, 'agents', opts.force === true);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst credentialsPullSub = new Command('pull')\n .description('Pull agent-credential backups from the control box custody store into ~/.agentbox')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--agent <id>', 'pull only one agent: claude | codex | opencode')\n .action(async (opts: { url?: string; agent?: string }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n if (opts.agent && !['claude', 'codex', 'opencode'].includes(opts.agent)) {\n log.error(`unknown --agent \"${opts.agent}\" (expected claude | codex | opencode)`);\n process.exitCode = 1;\n return;\n }\n const client = new CustodyClient(target);\n let pulled = 0;\n for (const spec of AGENT_SYNC_SPECS) {\n if (opts.agent && spec.id !== opts.agent) continue;\n const data = await client.get(`agents/${spec.id}/${spec.credential.boxRelPath}`);\n if (data === null) continue;\n await mkdir(dirname(spec.credential.hostBackup), { recursive: true });\n await writeFile(spec.credential.hostBackup, data, { mode: 0o600 });\n await chmod(spec.credential.hostBackup, 0o600);\n log.info(`pulled ${spec.id} credentials → ${spec.credential.hostBackup}`);\n pulled++;\n }\n if (pulled === 0) log.info('No agent credentials in custody to pull.');\n else log.success(`Pulled ${String(pulled)} agent credential set(s).`);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst credentialsCmd = new Command('credentials')\n .description('Manage agent credentials on the control box custody store')\n .addCommand(credentialsPushSub)\n .addCommand(credentialsPullSub);\n\nconst secretsPushSub = new Command('push')\n .description('Push project secret/env files to the control box custody store')\n .argument('[files...]', 'files to push (default: ./.env if present)')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--project <slug>', 'custody project slug (default: owner__repo, else the directory name)')\n .option('--force', 'upload even when the stored hash matches')\n .action(async (files: string[], opts: { url?: string; project?: string; force?: boolean }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const root = process.cwd();\n const slug = await projectSlug(opts.project, root);\n const chosen = files.length > 0 ? files : existsSync(join(root, '.env')) ? [join(root, '.env')] : [];\n if (chosen.length === 0) {\n log.error('No files to push (no ./.env found; pass files explicitly).');\n process.exitCode = 1;\n return;\n }\n const items: UploadItem[] = [];\n for (const f of chosen) {\n items.push({ path: `projects/${slug}/${basename(f)}`, data: await readFile(f) });\n }\n const client = new CustodyClient(target);\n await pushItems(client, items, `projects/${slug}`, opts.force === true);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst secretsCmd = new Command('secrets')\n .description('Manage per-project secrets/envs on the control box custody store')\n .addCommand(secretsPushSub);\n\nconst projectPushSub = new Command('push')\n .description(\n \"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.\",\n )\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--project <slug>', 'custody project slug (default: owner__repo, else the directory name)')\n .option('--force', 'upload even when the stored hash matches')\n .action(async (opts: { url?: string; project?: string; force?: boolean }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const root = (await findProjectRoot(process.cwd())).root;\n const slug = await projectSlug(opts.project, root);\n const cfg = await loadEffectiveConfig(root).catch(() => null);\n const res = await pushProjectSeedToCustody({\n controlPlaneUrl: target.url,\n adminToken: target.adminToken,\n slug,\n projectRoot: root,\n // The default env set (same one `--with-env` uses). Unlike a create —\n // which mirrors that box's own wizard picks and must not widen them —\n // this command has no box and no picks: the user is explicitly asking to\n // register the project's seed, so the default set is the intent. What\n // actually gets captured is reported below.\n envPatterns: DEFAULT_ENV_PATTERNS,\n // Honour the configured cap, so raising it actually admits a bigger seed.\n maxBodyBytes: cfg?.effective.relay.custodyMaxBodyBytes,\n force: opts.force,\n log: (line) => log.info(line),\n });\n if (res.unreachable) {\n log.error(\n `Control box unreachable at ${target.url} — nothing was pushed. The project is NOT registered; re-run when it is up.`,\n );\n process.exitCode = 1;\n return;\n }\n const head = res.manifest.repoHeadSha?.slice(0, 8) ?? 'unknown';\n log.success(\n `Pushed ${String(res.uploaded)} item(s), skipped ${String(res.skipped)} unchanged → projects/${slug}/seed (at ${head}).`,\n );\n // Name the env files that went up. This command captures the default env\n // set rather than a per-box selection, so the user should never have to\n // guess which secrets now live on the control box.\n if (res.envFiles.length > 0) {\n log.info(`env/secret files captured: ${res.envFiles.join(', ')}`);\n }\n if (res.skippedTarBytes !== undefined) {\n log.warn(\n `The untracked-files tar (${String(Math.round(res.skippedTarBytes / 1024 / 1024))}MB) exceeded this machine's custody body cap and was NOT pushed — ` +\n 'hub-created boxes will miss those files. To include it, raise `relay.custodyMaxBodyBytes` here AND ' +\n 'AGENTBOX_CUSTODY_MAX_BODY_BYTES on the control box (it enforces its own cap).',\n );\n }\n if (res.dropped.length > 0) {\n log.warn(\n `The control box refused ${res.dropped.join(', ')} — hub-created boxes will miss those files. ` +\n 'If it is a size limit, raise AGENTBOX_CUSTODY_MAX_BODY_BYTES on the control box.',\n );\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst projectCmd = new Command('project')\n .description('Manage a project on the control box (seed material for hub-created boxes)')\n .addCommand(projectPushSub);\n\nconst custodyListSub = new Command('list')\n .description('List custody entries (paths + hashes; values are never returned)')\n .argument('[prefix]', 'scope to a prefix, e.g. agents or projects/owner__repo')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (prefix: string | undefined, opts: { url?: string }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const client = new CustodyClient(target);\n const entries = await client.list(prefix);\n if (entries.length === 0) {\n log.info('No custody entries.');\n return;\n }\n for (const e of entries) {\n process.stdout.write(`${e.path} ${String(e.size)}B ${e.sha256.slice(0, 12)}\\n`);\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst custodyPullSub = new Command('pull')\n .description('Download a custody scope to a local directory (0600 files)')\n .argument('<scope>', 'custody scope/prefix, e.g. agents, projects/owner__repo, boxes/<id>')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--dest <dir>', 'destination directory (default: ./agentbox-custody)')\n .action(async (scope: string, opts: { url?: string; dest?: string }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const dest = opts.dest ?? join(process.cwd(), 'agentbox-custody');\n const client = new CustodyClient(target);\n const entries = await client.list(scope);\n if (entries.length === 0) {\n log.info(`No custody entries under '${scope}'.`);\n return;\n }\n let pulled = 0;\n for (const e of entries) {\n const data = await client.get(e.path);\n if (data === null) continue;\n const out = join(dest, e.path);\n await mkdir(dirname(out), { recursive: true, mode: 0o700 });\n await writeFile(out, data, { mode: 0o600 });\n await chmod(out, 0o600);\n pulled++;\n }\n log.success(`Pulled ${String(pulled)} entr${pulled === 1 ? 'y' : 'ies'} under '${scope}' to ${dest}.`);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst custodyRmSub = new Command('rm')\n .description('Delete a custody entry (one path) from the control box')\n .argument('<path>', 'custody path, e.g. boxes/<sandboxId>/ssh/id_ed25519 or agents/claude/.credentials.json')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (path: string, opts: { url?: string }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const res = await fetch(`${target.url}/admin/custody/${path.split('/').map(encodeURIComponent).join('/')}`, {\n method: 'DELETE',\n headers: { Authorization: `Bearer ${target.adminToken}` },\n });\n if (res.status === 204) log.success(`Deleted custody entry '${path}'.`);\n else if (res.status === 404) log.info(`No custody entry at '${path}'.`);\n else {\n log.error(`custody rm failed: ${res.status} ${(await res.text().catch(() => '')).slice(0, 200)}`);\n process.exitCode = 1;\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst custodyCmd = new Command('custody')\n .description('Inspect + download the control box custody store')\n .addCommand(custodyListSub)\n .addCommand(custodyPullSub)\n .addCommand(custodyRmSub);\n\n// --- control-plane box registry (the PC's admin view of the control box) ---\n\nconst boxesListSub = new Command('list')\n .description('List boxes on the control box (via its /api/v1)')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--json', 'print raw JSON')\n .action(async (opts: { url?: string; json?: boolean }) => {\n try {\n const client = await resolveHubApiClient(opts.url);\n if (!client) {\n process.exitCode = 1;\n return;\n }\n const boxes = await client.listBoxes();\n if (opts.json) {\n process.stdout.write(`${JSON.stringify({ boxes }, null, 2)}\\n`);\n return;\n }\n if (boxes.length === 0) {\n log.info('No boxes on the control box.');\n return;\n }\n for (const b of boxes) {\n process.stdout.write(`${b.id} ${b.name ?? b.task} ${b.provider} ${b.state ?? b.status}\\n`);\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst boxesRmSub = new Command('rm')\n .description('Destroy a box via the control box (tears down the cloud resource AND reaps its registration/custody)')\n .argument('<boxId>', 'the box id as shown by `hub boxes list`')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (boxId: string, opts: { url?: string }) => {\n try {\n const client = await resolveHubApiClient(opts.url);\n if (!client) {\n process.exitCode = 1;\n return;\n }\n // Reverse-adoption on the control box means this drives a REAL destroy even\n // for a box created on the PC (registration-only) — not just a state reap.\n await client.destroy(boxId);\n log.success(`Destroyed '${boxId}' (cloud resource + control-box state).`);\n } catch (err) {\n if (err instanceof HubApiError && err.code === 'not_found') {\n log.info(`No box '${boxId}' on the control box.`);\n return;\n }\n handleLifecycleError(err);\n }\n });\n\n/** A `hub boxes <action>` lifecycle subcommand over the hub `/api/v1`. */\nfunction boxesLifecycleSub(action: HubLifecycleAction, verb: string, past: string): Command {\n return new Command(action)\n .description(`${verb} a box on the control box (via its /api/v1)`)\n .argument('<boxId>', 'the box id as shown by `hub boxes list`')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (boxId: string, opts: { url?: string }) => {\n try {\n const client = await resolveHubApiClient(opts.url);\n if (!client) {\n process.exitCode = 1;\n return;\n }\n await client.lifecycle(boxId, action);\n log.success(`${past} '${boxId}'.`);\n } catch (err) {\n if (err instanceof HubApiError && err.code === 'not_found') {\n log.info(`No box '${boxId}' on the control box.`);\n process.exitCode = 1;\n return;\n }\n handleLifecycleError(err);\n }\n });\n}\n\nconst boxesCmd = new Command('boxes')\n .description('List + drive boxes on the control box over its public /api/v1')\n .addCommand(boxesListSub)\n .addCommand(boxesLifecycleSub('start', 'Start', 'Started'))\n .addCommand(boxesLifecycleSub('stop', 'Stop', 'Stopped'))\n .addCommand(boxesLifecycleSub('pause', 'Pause', 'Paused'))\n .addCommand(boxesLifecycleSub('resume', 'Resume', 'Resumed'))\n .addCommand(boxesRmSub);\n\n// --- control-plane approvals (answerable from the PC over /api/v1) ---\n\nconst promptsListSub = new Command('list')\n .description('List pending host-action approvals across control-box boxes')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--json', 'print raw JSON')\n .action(async (opts: { url?: string; json?: boolean }) => {\n try {\n const client = await resolveHubApiClient(opts.url);\n if (!client) {\n process.exitCode = 1;\n return;\n }\n // One call returns every pending approval (vs the admin wire's N per-box\n // fetches); cross-ref the box list once for human-readable names.\n const [approvals, boxes] = await Promise.all([client.listApprovals(), client.listBoxes().catch(() => [])]);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify(approvals, null, 2)}\\n`);\n return;\n }\n if (approvals.length === 0) {\n log.info('No pending approvals.');\n return;\n }\n const nameBy = new Map(boxes.map((b) => [b.id, b.name ?? b.task]));\n for (const a of approvals) {\n process.stdout.write(`${a.id} [${nameBy.get(a.boxId) ?? a.boxId}] ${a.message}\\n`);\n }\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst promptsAnswerSub = new Command('answer')\n .description('Answer a pending approval on the control box')\n .argument('<id>', 'the prompt id from `hub prompts list`')\n .argument('[answer]', 'y | n (default: y)', 'y')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (id: string, answer: string, opts: { url?: string }) => {\n try {\n if (answer !== 'y' && answer !== 'n') {\n log.error(`answer must be 'y' or 'n' (got '${answer}')`);\n process.exitCode = 1;\n return;\n }\n const client = await resolveHubApiClient(opts.url);\n if (!client) {\n process.exitCode = 1;\n return;\n }\n await client.answerApproval(id, answer);\n log.success(`Answered ${id} → ${answer}.`);\n } catch (err) {\n if (err instanceof HubApiError && err.code === 'not_found') {\n log.info(`No pending approval with id ${id} (already answered or expired?).`);\n process.exitCode = 1;\n return;\n }\n handleLifecycleError(err);\n }\n });\n\nconst promptsCmd = new Command('prompts')\n .description('List + answer control-box host-action approvals from the PC')\n .addCommand(promptsListSub)\n .addCommand(promptsAnswerSub);\n\n// --- control-plane create queue (distinct from the PC's local `-i` queue) ---\n\n/** `<age> <status> <provider> <name/repo>` — one job per line. */\nfunction jobLine(job: CreateJobRow): string {\n const label = job.request.name ?? job.request.repoUrl;\n const boxOrError =\n job.result?.error !== undefined\n ? ` ${job.result.error.split('\\n')[0]?.slice(0, 80) ?? ''}`\n : job.result?.boxId\n ? ` box ${job.result.boxId}`\n : '';\n return `${job.id.slice(0, 8)} ${job.status.padEnd(7)} ${job.request.provider.padEnd(9)} ${label}${boxOrError}`;\n}\n\nconst jobsListSub = new Command('list')\n .description(\n 'List create jobs on the control box. This is the queue that background `-i` cloud runs go to ' +\n \"when a control box is configured — distinct from this PC's local `agentbox queue`.\",\n )\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .option('--json', 'print raw JSON')\n .action(async (opts: { url?: string; json?: boolean }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n const jobs = await listHubJobs(target);\n if (opts.json) {\n process.stdout.write(`${JSON.stringify({ jobs }, null, 2)}\\n`);\n return;\n }\n if (jobs.length === 0) {\n log.info('No create jobs on the control box.');\n return;\n }\n for (const job of jobs) process.stdout.write(`${jobLine(job)}\\n`);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst jobsShowSub = new Command('show')\n .description('Dump one control-box create job')\n .argument('<jobId>', 'job id (or the short prefix `hub jobs list` prints)')\n .option('--url <url>', 'override the control-plane URL (default: relay.controlPlaneUrl)')\n .action(async (jobId: string, opts: { url?: string }) => {\n try {\n const target = await resolveCustodyTarget(opts.url);\n if (!target) {\n process.exitCode = 1;\n return;\n }\n // `jobs list` (and the `queue list` block) print an 8-char prefix, so the\n // id you can actually copy is not the full UUID the by-id route wants.\n // Try it verbatim first, then resolve it as a prefix.\n let job = await getHubJob(target, jobId);\n if (!job) {\n const matches = (await listHubJobs(target)).filter((j) => j.id.startsWith(jobId));\n if (matches.length > 1) {\n log.error(\n `'${jobId}' matches ${String(matches.length)} jobs (${matches.map((m) => m.id.slice(0, 12)).join(', ')}) — pass more of the id.`,\n );\n process.exitCode = 1;\n return;\n }\n job = matches[0] ?? null;\n }\n if (!job) {\n log.info(`No job '${jobId}' on the control box.`);\n process.exitCode = 1;\n return;\n }\n process.stdout.write(`${JSON.stringify(job, null, 2)}\\n`);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\nconst jobsCmd = new Command('jobs')\n .description(\"Inspect the control box's box-create queue\")\n .addCommand(jobsListSub)\n .addCommand(jobsShowSub);\n\ninterface DeployOpts {\n ref?: string;\n repo?: string;\n}\n\n/**\n * Ensure `control-plane.env` carries a non-empty `AGENTBOX_HUB_API_KEY` (the\n * headless `/api/v1` bearer), minting + appending one if absent, and return it.\n * `setup` writes the key into a fresh env; this covers **redeploys** of a control\n * box whose env predates the key (or a hand-managed env), so every deploy — fresh\n * or repeat — ships a hub that accepts the headless key. Idempotent.\n */\nasync function ensureHubApiKeyInEnv(): Promise<string> {\n const body = await readFile(ENV_PATH, 'utf8');\n const existing = /^AGENTBOX_HUB_API_KEY=(.+)$/m.exec(body)?.[1]?.trim();\n if (existing) return existing;\n const key = randomBytes(32).toString('hex');\n const nl = body.length === 0 || body.endsWith('\\n') ? '' : '\\n';\n await writeFile(ENV_PATH, `${body}${nl}AGENTBOX_HUB_API_KEY=${key}\\n`, { mode: 0o600 });\n await chmod(ENV_PATH, 0o600);\n return key;\n}\n\n// Re-deploy the FULL hub to a fresh Hetzner VPS, REUSING the existing\n// ~/.agentbox/control-plane App creds + env — no GitHub-App manifest flow. Pins\n// the VPS clone to --ref so a feature branch can be deployed for live verify.\nconst deployHetznerSub = new Command('hetzner')\n .description('Deploy the full hub to a new Hetzner VPS, reusing the App creds from `hub setup`')\n .option('--ref <ref>', 'branch / tag / sha the VPS clones + builds', DEFAULT_DEPLOY_REF)\n .option('--repo <url>', 'git repo the VPS clones', DEFAULT_DEPLOY_REPO)\n .action(async (opts: DeployOpts) => {\n try {\n if (!existsSync(ENV_PATH)) {\n log.error('No control-plane env found. Run `agentbox hub setup` first (it creates the GitHub App + admin token).');\n process.exitCode = 1;\n return;\n }\n if (!(await ensureHetznerHubAuth())) {\n log.warn('login prompt cancelled — deploying without web-UI auth.');\n }\n // Mint the headless /api/v1 bearer into the env if it isn't there yet, so a\n // redeploy of a pre-existing control box also gets it (setup writes it for\n // fresh installs). It rides the same scp'd .env into the container.\n await ensureHubApiKeyInEnv();\n // `--repo` accepts an owner/repo slug or a full git URL; the VPS clones a URL.\n const repoSpec = opts.repo ?? DEFAULT_DEPLOY_REPO;\n const repoUrl = repoSpec.includes('://') ? repoSpec : `https://github.com/${repoSpec}.git`;\n const ds = spinner();\n ds.start('deploying the control box to hetzner');\n let deployedUrl: string;\n try {\n deployedUrl = (\n await runHetznerDeploy({\n envPath: ENV_PATH,\n repoRef: opts.ref ?? DEFAULT_DEPLOY_REF,\n repoUrl,\n log: (line) => ds.message(line),\n })\n ).url;\n ds.stop(`deployed: ${deployedUrl}`);\n } catch (e) {\n ds.stop('deploy failed');\n log.error(e instanceof Error ? e.message : String(e));\n process.exitCode = 1;\n return;\n }\n const url = await applyControlPlaneUrl(deployedUrl);\n log.success(`Pointed the CLI at ${url} (relay.controlPlaneUrl).`);\n const ok = await waitForHealthz(url, 60_000);\n log[ok ? 'success' : 'warn'](\n ok ? `Control box is healthy (${url}/healthz).` : `Could not confirm ${url}/healthz yet — check the deployment.`,\n );\n if (ok) await seedPreparedToNewControlBox(url);\n } catch (err) {\n handleLifecycleError(err);\n }\n });\n\n/**\n * Share this machine's cloud bake records with a freshly-deployed control box,\n * so its first web-UI create boots the base you already baked instead of\n * spending minutes re-baking an identical one. Best-effort: a fresh deploy is\n * still perfectly usable without it (it just bakes on demand).\n */\nasync function seedPreparedToNewControlBox(url: string): Promise<void> {\n const target = await resolveCustodyTarget(url, { quiet: true });\n if (!target) return;\n const shared: string[] = [];\n for (const provider of SHAREABLE_PREPARED_PROVIDERS) {\n const ok = await pushPreparedToCustody(provider, {\n controlPlaneUrl: target.url,\n adminToken: target.adminToken,\n }).catch(() => false);\n if (ok) shared.push(provider);\n }\n if (shared.length > 0) {\n log.success(`Shared your ${shared.join(', ')} base bake(s) with the control box — it won't re-bake them.`);\n }\n}\n\n/**\n * Providers whose base is a provider-side snapshot another machine can boot, so\n * the bake record is worth sharing. Docker is excluded: its base is a local\n * image, rebuilt (or pulled) per machine.\n */\nconst SHAREABLE_PREPARED_PROVIDERS = ['hetzner', 'vercel', 'e2b', 'daytona', 'digitalocean'] as const;\n\nconst deployCmd = new Command('deploy')\n .description('Deploy the full hub to a VPS, reusing the App creds from `hub setup`')\n .addCommand(deployHetznerSub);\n\n/**\n * The remote-hub admin subcommands, folded into the one `hub` command group\n * (`apps/cli/src/commands/hub.ts`). AgentBox is unreleased, so there is no\n * standalone `control-plane` group anymore — `hub setup`/`hub deploy`/`hub boxes`\n * etc. are the single surface. `status` is not here: it merged into `hub status`\n * (local process vs remote reachability, resolved by target).\n */\nexport const controlPlaneSubcommands = [\n setupSub,\n deployCmd,\n setUrlSub,\n unsetUrlSub,\n addSub,\n workerSub,\n credentialsCmd,\n secretsCmd,\n projectCmd,\n custodyCmd,\n boxesCmd,\n promptsCmd,\n jobsCmd,\n] as const;\n","import { createServer } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { randomBytes } from 'node:crypto';\n\n/**\n * GitHub App **manifest flow** — create a GitHub App from a manifest without\n * hand-filling the web form. We serve a one-shot local page that auto-POSTs the\n * manifest to GitHub; the user reviews + clicks \"Create\"; GitHub redirects back\n * to our localhost callback with a `code`; we exchange it for the App's id +\n * private key. See https://docs.github.com/apps/sharing-github-apps/registering-a-github-app-from-a-manifest\n *\n * The GitHub base URLs and the browser-open are injectable so this is e2e\n * testable against a fake GitHub (and so it works against GitHub Enterprise).\n */\nexport interface ManifestFlowOptions {\n /** Desired App name (must be globally unique on GitHub). */\n appName: string;\n /** Create under an org instead of the user account. */\n org?: string;\n /** Public-facing URL recorded on the App. */\n homepageUrl?: string;\n /** github.com base (override for GHES / tests). Default https://github.com. */\n githubUrl?: string;\n /** api.github.com base (override for GHES / tests). Default https://api.github.com. */\n apiBaseUrl?: string;\n /** Opens the URL in the user's browser. Injected in tests. */\n openBrowser: (url: string) => void | Promise<void>;\n /** How long to wait for the user to complete the flow. Default 5 min. */\n timeoutMs?: number;\n log?: (line: string) => void;\n fetchImpl?: typeof fetch;\n}\n\nexport interface ManifestFlowResult {\n appId: string;\n slug: string;\n /** PEM private key (store 0600). */\n pem: string;\n /** The App's html_url, e.g. https://github.com/apps/<slug>. */\n htmlUrl: string;\n /** Where to install it: https://github.com/apps/<slug>/installations/new. */\n installUrl: string;\n}\n\nfunction htmlEscape(s: string): string {\n return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n\nexport async function runGitHubAppManifestFlow(\n opts: ManifestFlowOptions,\n): Promise<ManifestFlowResult> {\n const githubUrl = (opts.githubUrl ?? 'https://github.com').replace(/\\/$/, '');\n const apiBaseUrl = (opts.apiBaseUrl ?? 'https://api.github.com').replace(/\\/$/, '');\n const fetchImpl = opts.fetchImpl ?? fetch;\n const log = opts.log ?? (() => {});\n const state = randomBytes(16).toString('hex');\n\n return new Promise<ManifestFlowResult>((resolve, reject) => {\n // Captured once at listen() time — NEVER read server.address() per request:\n // after the flow settles we close the server, and a stray follow-up request\n // (favicon, a reloaded tab) would otherwise hit a null address and throw.\n let listenPort = 0;\n let settled = false;\n const server = createServer((req, res) => {\n if (settled) {\n res.writeHead(204);\n res.end();\n return;\n }\n const url = new URL(req.url ?? '/', `http://127.0.0.1`);\n const redirectUrl = `http://127.0.0.1:${String(listenPort)}/callback`;\n\n if (url.pathname === '/') {\n // The manifest GitHub will turn into an App. Repo-scoped write perms.\n const manifest = {\n name: opts.appName,\n url: opts.homepageUrl ?? 'https://agent-box.sh',\n redirect_url: redirectUrl,\n public: false,\n default_permissions: { contents: 'write', pull_requests: 'write' },\n };\n const action = opts.org\n ? `${githubUrl}/organizations/${encodeURIComponent(opts.org)}/settings/apps/new?state=${state}`\n : `${githubUrl}/settings/apps/new?state=${state}`;\n const page = `<!doctype html><html><body>\n<p>Creating the GitHub App on GitHub… if this page doesn't redirect, click Continue.</p>\n<form id=\"f\" method=\"post\" action=\"${htmlEscape(action)}\">\n<input type=\"hidden\" name=\"manifest\" value=\"${htmlEscape(JSON.stringify(manifest))}\">\n<button type=\"submit\">Continue to GitHub</button>\n</form>\n<script>document.getElementById('f').submit()</script>\n</body></html>`;\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });\n res.end(page);\n return;\n }\n\n if (url.pathname === '/callback') {\n const code = url.searchParams.get('code') ?? '';\n const gotState = url.searchParams.get('state') ?? '';\n if (gotState !== state) {\n res.writeHead(400, { 'content-type': 'text/plain' });\n res.end('state mismatch');\n return;\n }\n if (code.length === 0) {\n res.writeHead(400, { 'content-type': 'text/plain' });\n res.end('missing code');\n return;\n }\n // Exchange the temporary code for the App's id + private key.\n void fetchImpl(`${apiBaseUrl}/app-manifests/${encodeURIComponent(code)}/conversions`, {\n method: 'POST',\n headers: {\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'agentbox',\n },\n })\n .then(async (r) => {\n if (!r.ok) throw new Error(`manifest conversion failed (→ ${String(r.status)})`);\n const body = (await r.json()) as {\n id?: number;\n slug?: string;\n pem?: string;\n html_url?: string;\n };\n if (typeof body.id !== 'number' || !body.slug || !body.pem) {\n throw new Error('manifest conversion response missing id/slug/pem');\n }\n const result: ManifestFlowResult = {\n appId: String(body.id),\n slug: body.slug,\n pem: body.pem,\n htmlUrl: body.html_url ?? `${githubUrl}/apps/${body.slug}`,\n installUrl: `${githubUrl}/apps/${body.slug}/installations/new`,\n };\n settled = true;\n res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });\n res.end(\n `<!doctype html><html><head><meta charset=\"utf-8\"></head><body><h2>GitHub App created ✓</h2>` +\n `<p>App: ${htmlEscape(result.slug)} (id ${result.appId}). You can close this tab and return to the terminal.</p></body></html>`,\n );\n server.close();\n resolve(result);\n })\n .catch((err: unknown) => {\n settled = true;\n res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });\n res.end('conversion failed');\n server.close();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n return;\n }\n\n res.writeHead(404);\n res.end();\n });\n\n const timer = setTimeout(\n () => {\n server.close();\n reject(new Error('timed out waiting for the GitHub App manifest flow to complete'));\n },\n opts.timeoutMs ?? 5 * 60_000,\n );\n if (typeof timer.unref === 'function') timer.unref();\n\n server.on('error', (err) => {\n clearTimeout(timer);\n reject(err);\n });\n server.listen(0, '127.0.0.1', () => {\n listenPort = (server.address() as AddressInfo).port;\n const startUrl = `http://127.0.0.1:${String(listenPort)}/`;\n log(`opening ${startUrl} to create the GitHub App…`);\n void Promise.resolve(opts.openBrowser(startUrl)).catch((err: unknown) => {\n log(`could not open the browser automatically: ${err instanceof Error ? err.message : String(err)}`);\n log(`open this URL manually: ${startUrl}`);\n });\n });\n });\n}\n","import { spawn } from 'node:child_process';\nimport { mkdtempSync, rmSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport {\n createGitDeployment,\n createGitProject,\n deleteProject,\n getDeployment,\n getProductionAlias,\n getProject,\n patchProjectSettings,\n projectHasEnv,\n resolveVercelApiAuth,\n upsertProjectEnv,\n type VercelProjectFull,\n} from '@agentbox/sandbox-vercel';\nimport { ensureFork, ghAvailable, ghLogin, ownerOf } from './github-fork.js';\nimport { openInBrowser } from './ensure-repo-installed.js';\n\n/**\n * Deploy the control plane to Vercel **from GitHub**, in tiers so it works for\n * everyone without a local checkout:\n * 1. If the deployer doesn't own `repo`, `gh`-fork it to their account.\n * 2. API deploy the owned/forked repo (headless; needs the Vercel GitHub App).\n * 3. Fallback: open the Vercel Deploy Button (clones the repo into the user's\n * account + installs the App + provisions Postgres in-browser), then finish\n * via the API (set the secrets + redeploy) — no manual paste.\n */\nexport interface VercelDeployOptions {\n /** App env baked into the build: GITHUB_APP_ID / _PRIVATE_KEY / ADMIN_TOKEN. */\n env: Record<string, string>;\n /** `owner/name` GitHub slug to deploy from. */\n repo: string;\n /** Branch / tag / sha to build. */\n ref: string;\n project?: string;\n log: (line: string) => void;\n}\n\nconst PROJECT_DEFAULT = 'agentbox-control-plane';\nconst ROOT_DIRECTORY = 'apps/hub';\n\n/** Raised when Vercel can't connect the repo (GitHub App not installed on the owner). */\nclass GitConnectError extends Error {}\n\nfunction connectedTo(p: VercelProjectFull | null, repo: string): boolean {\n return (\n !!p?.link &&\n p.link.type === 'github' &&\n `${p.link.org ?? ''}/${p.link.repo ?? ''}`.toLowerCase() === repo.toLowerCase()\n );\n}\n\nfunction isConnectError(msg: string): boolean {\n return /install the GitHub integration|integration first|github integration/i.test(msg);\n}\n\n/** Best-effort Neon provisioning via the logged-in `vercel` CLI, in a temp cwd. */\nfunction provisionNeon(teamId: string | undefined, projectId: string, log: (l: string) => void): Promise<void> {\n return new Promise((resolve) => {\n const work = mkdtempSync(join(tmpdir(), 'agentbox-neon-'));\n const env = { ...process.env, VERCEL_PROJECT_ID: projectId, ...(teamId ? { VERCEL_ORG_ID: teamId } : {}) };\n const child = spawn('vercel', ['integration', 'add', 'neon', '--non-interactive'], {\n cwd: work,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n const onData = (c: Buffer): void => {\n for (const l of c.toString('utf8').split(/\\r?\\n/)) if (l.trim()) log(`neon: ${l.trim()}`);\n };\n child.stdout.on('data', onData);\n child.stderr.on('data', onData);\n const done = (): void => {\n try {\n rmSync(work, { recursive: true, force: true });\n } catch {\n /* best-effort */\n }\n resolve();\n };\n child.on('error', (e) => {\n log(`neon: could not run \\`vercel integration add neon\\` (${e.message}) — continuing`);\n done();\n });\n child.on('close', (code) => {\n if (code !== 0) log(`neon: integration add exited ${String(code)} — continuing (it may already be attached)`);\n done();\n });\n });\n}\n\nasync function pollDeployment(\n token: string,\n teamId: string | undefined,\n id: string,\n log: (l: string) => void,\n): Promise<void> {\n const stop = Date.now() + 20 * 60_000;\n let last = '';\n while (Date.now() < stop) {\n const d = await getDeployment(token, teamId, id);\n if (d.readyState !== last) {\n log(`build: ${d.readyState.toLowerCase()}`);\n last = d.readyState;\n }\n if (d.readyState === 'READY') return;\n if (d.readyState === 'ERROR' || d.readyState === 'CANCELED' || d.readyState === 'BLOCKED') {\n throw new Error(\n `Vercel build ${d.readyState.toLowerCase()}${d.errorStep ? ` at ${d.errorStep}` : ''}: ${d.errorMessage ?? 'see the Vercel dashboard'}`,\n );\n }\n await new Promise((r) => setTimeout(r, 6_000));\n }\n throw new Error('timed out waiting for the Vercel build to finish');\n}\n\nfunction envVars(env: Record<string, string>): Array<{ key: string; value: string }> {\n return Object.entries(env).map(([key, value]) => ({ key, value }));\n}\n\ninterface DeployArgs {\n token: string;\n teamId: string | undefined;\n repo: string;\n ref: string;\n env: Record<string, string>;\n projectName: string;\n log: (line: string) => void;\n}\n\n/** Headless API deploy of a repo Vercel can connect (owned/forked). */\nasync function apiDeploy(a: DeployArgs): Promise<{ url: string }> {\n const [owner, repoName] = a.repo.split('/');\n a.log(`ensuring Vercel project \"${a.projectName}\" is connected to ${a.repo}…`);\n let project = await getProject(a.token, a.teamId, a.projectName);\n if (project && !connectedTo(project, a.repo)) {\n a.log(`project exists but is not connected to ${a.repo}; recreating…`);\n await deleteProject(a.token, a.teamId, project.id);\n project = null;\n }\n if (!project) {\n try {\n project = await createGitProject(a.token, a.teamId, {\n name: a.projectName,\n repo: a.repo,\n rootDirectory: ROOT_DIRECTORY,\n });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n if (isConnectError(msg)) throw new GitConnectError(msg);\n throw e;\n }\n } else {\n await patchProjectSettings(a.token, a.teamId, project.id, {\n framework: 'nextjs',\n rootDirectory: ROOT_DIRECTORY,\n });\n }\n\n // Idempotent: only provision Neon when the project has no Postgres yet —\n // re-running otherwise provisions an orphan Neon that collides on the\n // already-present POSTGRES_URL_NON_POOLING.\n if (await projectHasEnv(a.token, a.teamId, project.id, 'POSTGRES_URL')) {\n a.log('Postgres already attached — skipping Neon provisioning');\n } else {\n a.log('provisioning Neon Postgres…');\n await provisionNeon(a.teamId, project.id, a.log);\n }\n a.log('setting environment variables…');\n await upsertProjectEnv(a.token, a.teamId, project.id, envVars(a.env));\n\n a.log(`triggering a production build of ${a.repo}@${a.ref}…`);\n const dep = await createGitDeployment(a.token, a.teamId, {\n name: a.projectName,\n projectId: project.id,\n owner: owner!,\n repo: repoName!,\n ref: a.ref,\n });\n await pollDeployment(a.token, a.teamId, dep.id, a.log);\n const alias = (await getProductionAlias(a.token, a.teamId, project.id)) ?? dep.url ?? null;\n if (!alias) throw new Error('build is ready but no production URL was found');\n return { url: alias.startsWith('http') ? alias : `https://${alias}` };\n}\n\nfunction deployButtonUrl(repo: string, projectName: string): string {\n const p = new URLSearchParams({\n 'repository-url': `https://github.com/${repo}`,\n 'root-directory': ROOT_DIRECTORY,\n stores: '[{\"type\":\"postgres\"}]',\n 'project-name': projectName,\n 'repository-name': projectName,\n });\n return `https://vercel.com/new/clone?${p.toString()}`;\n}\n\n/**\n * Fallback when Vercel can't connect the repo via the API (App not installed):\n * the Deploy Button does the clone + App install + Postgres in-browser; we then\n * set the secrets + redeploy via the API (the control plane boots gracefully\n * unconfigured in the meantime).\n */\nasync function buttonDeploy(a: DeployArgs): Promise<{ url: string }> {\n const url = deployButtonUrl(a.repo, a.projectName);\n a.log(`opening the Vercel Deploy Button — complete the clone + Postgres setup in your browser:`);\n a.log(url);\n openInBrowser(url);\n\n a.log('waiting for the Vercel project to appear (finish the deploy in the browser)…');\n const stop = Date.now() + 10 * 60_000;\n let project: VercelProjectFull | null = null;\n while (Date.now() < stop) {\n project = await getProject(a.token, a.teamId, a.projectName);\n if (project?.link?.type === 'github' && project.link.repo) break;\n project = null;\n await new Promise((r) => setTimeout(r, 5_000));\n }\n if (!project?.link?.repo) {\n throw new Error(\n `timed out waiting for the Vercel project \"${a.projectName}\". Finish the browser deploy, then re-run, ` +\n `or set the env vars + redeploy in the Vercel dashboard.`,\n );\n }\n\n a.log('setting environment variables + redeploying…');\n await upsertProjectEnv(a.token, a.teamId, project.id, envVars(a.env));\n const dep = await createGitDeployment(a.token, a.teamId, {\n name: a.projectName,\n projectId: project.id,\n owner: project.link.org ?? ownerOf(a.repo),\n repo: project.link.repo,\n ref: a.ref,\n });\n await pollDeployment(a.token, a.teamId, dep.id, a.log);\n const alias = (await getProductionAlias(a.token, a.teamId, project.id)) ?? dep.url ?? null;\n if (!alias) throw new Error('redeploy is ready but no production URL was found');\n return { url: alias.startsWith('http') ? alias : `https://${alias}` };\n}\n\nexport async function deployControlPlaneToVercel(opts: VercelDeployOptions): Promise<{ url: string }> {\n const auth = await resolveVercelApiAuth();\n if (!auth) {\n throw new Error('not logged in to Vercel — run `agentbox vercel login` (or set VERCEL_TOKEN)');\n }\n const { token, teamId } = auth;\n const projectName = opts.project ?? PROJECT_DEFAULT;\n const [owner, repoName] = opts.repo.split('/');\n if (!owner || !repoName) throw new Error(`--repo must be \"owner/name\" (got \"${opts.repo}\")`);\n\n // Resolve the deploy target: if `gh` is available and the deployer doesn't own\n // the repo, fork it to their account (Vercel can only connect a repo whose\n // owner has the Vercel GitHub App). Without `gh`, deploy the repo as-is — the\n // API connect will fail for a non-owned repo and we fall through to the button.\n let target = opts.repo;\n if (await ghAvailable()) {\n const login = await ghLogin();\n if (login && login.toLowerCase() !== owner.toLowerCase()) {\n target = await ensureFork(opts.repo, login, opts.log);\n }\n }\n\n const args: DeployArgs = { token, teamId, repo: target, ref: opts.ref, env: opts.env, projectName, log: opts.log };\n try {\n return await apiDeploy(args);\n } catch (e) {\n if (e instanceof GitConnectError) {\n opts.log(`Vercel can't connect ${target} via the API (GitHub App not installed); using the Deploy Button…`);\n return buttonDeploy(args);\n }\n throw e;\n }\n}\n","import { spawn } from 'node:child_process';\n\n/**\n * Thin `gh` CLI wrappers for the Vercel deploy's auto-fork step. Vercel can only\n * connect a repo whose owner has the Vercel GitHub App, so a deployer who\n * doesn't own the target repo forks it to their own account first. `gh` is a\n * host tool (same as the relay's `gh pr` path) — absent/unauthed routes the\n * caller to the Deploy-Button fallback instead.\n */\nfunction gh(args: string[]): Promise<{ code: number; stdout: string; stderr: string }> {\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n let child;\n try {\n child = spawn('gh', args, { stdio: ['ignore', 'pipe', 'pipe'] });\n } catch {\n resolve({ code: 127, stdout: '', stderr: 'gh not found' });\n return;\n }\n child.stdout.on('data', (c: Buffer) => (stdout += c.toString('utf8')));\n child.stderr.on('data', (c: Buffer) => (stderr += c.toString('utf8')));\n child.on('error', () => resolve({ code: 127, stdout, stderr: stderr || 'gh not found' }));\n child.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));\n });\n}\n\nexport function ownerOf(repo: string): string {\n return repo.split('/')[0] ?? '';\n}\nexport function nameOf(repo: string): string {\n return repo.split('/')[1] ?? '';\n}\n\n/** Whether `gh` is installed AND authenticated. */\nexport async function ghAvailable(): Promise<boolean> {\n return (await gh(['auth', 'status'])).code === 0;\n}\n\n/** The authenticated GitHub login, or null. */\nexport async function ghLogin(): Promise<string | null> {\n const r = await gh(['api', 'user', '-q', '.login']);\n const login = r.stdout.trim();\n return r.code === 0 && login.length > 0 ? login : null;\n}\n\n/**\n * Fork `repo` to the authenticated user (idempotent — tolerates an existing\n * fork) and wait until the GitHub API sees it. Returns `<login>/<name>`.\n */\nexport async function ensureFork(repo: string, login: string, log: (l: string) => void): Promise<string> {\n const fork = `${login}/${nameOf(repo)}`;\n log(`forking ${repo} -> ${fork}…`);\n const f = await gh(['repo', 'fork', repo, '--clone=false']);\n if (f.code !== 0 && !/already exists/i.test(`${f.stderr}${f.stdout}`)) {\n throw new Error(`gh repo fork ${repo} failed: ${(f.stderr || f.stdout).trim()}`);\n }\n // Forks are created asynchronously — poll until the API resolves the fork.\n const stop = Date.now() + 60_000;\n while (Date.now() < stop) {\n const v = await gh(['api', `repos/${fork}`, '-q', '.full_name']);\n if (v.code === 0 && v.stdout.trim().toLowerCase() === fork.toLowerCase()) return fork;\n await new Promise((r) => setTimeout(r, 2_000));\n }\n throw new Error(`fork ${fork} did not become available within 60s`);\n}\n","import { confirm, isCancel, log as clog, note } from '@clack/prompts';\nimport { spawn } from 'node:child_process';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport type { GitPushMode } from '@agentbox/config';\nimport { GitHubAppLeaser, loadGitHubAppConfig, parseGitRemote } from '@agentbox/relay';\nimport { hostOpenCommand } from '@agentbox/sandbox-core';\n\nconst CP_DIR = join(homedir(), '.agentbox', 'control-plane');\nconst ENV_PATH = join(CP_DIR, 'control-plane.env');\nconst META_PATH = join(CP_DIR, 'control-plane.json');\nconst REPOS_STATE = join(CP_DIR, 'repos.json');\n\n/** Best-effort: open a URL in the host browser (never throws). */\nexport function openInBrowser(url: string): void {\n try {\n const child = spawn(hostOpenCommand(), [url], { detached: true, stdio: 'ignore' });\n child.unref();\n } catch {\n /* caller prints the URL to open manually */\n }\n}\n\ninterface ControlPlaneMeta {\n appId?: string;\n slug?: string;\n htmlUrl?: string;\n installUrl?: string;\n}\n\nexport function loadControlPlaneMeta(): ControlPlaneMeta | null {\n try {\n return JSON.parse(readFileSync(META_PATH, 'utf8')) as ControlPlaneMeta;\n } catch {\n return null;\n }\n}\n\n/** Load the setup-written App creds (+ admin token) into the env if not already set. */\nfunction loadLocalControlPlaneEnv(): void {\n if (!existsSync(ENV_PATH)) return;\n for (const line of readFileSync(ENV_PATH, 'utf8').split('\\n')) {\n const m = /^([A-Z_]+)=(.*)$/.exec(line.trim());\n if (m && !process.env[m[1]!]) process.env[m[1]!] = m[2];\n }\n}\n\n/** Resolve the project's origin into `owner/repo`, or null if absent/unparseable. */\nexport async function resolveOwnerRepo(projectRoot: string): Promise<{ owner: string; repo: string } | null> {\n const r = await execa('git', ['-C', projectRoot, 'remote', 'get-url', 'origin'], { reject: false });\n const origin = (r.stdout ?? '').trim();\n if (r.exitCode !== 0 || origin.length === 0) return null;\n try {\n const { path } = parseGitRemote(origin);\n const [owner, repo] = path.replace(/\\.git$/, '').split('/');\n if (!owner || !repo) return null;\n return { owner, repo };\n } catch {\n return null;\n }\n}\n\n/**\n * Whether the GitHub App is installed on owner/repo. Prefers the local App key\n * (works offline); falls back to the plane's admin endpoint; returns 'unknown'\n * when neither credential is available locally.\n */\nexport async function checkRepoInstalled(\n owner: string,\n repo: string,\n controlPlaneUrl: string | undefined,\n): Promise<boolean | 'unknown'> {\n loadLocalControlPlaneEnv();\n const appCfg = loadGitHubAppConfig();\n if (appCfg) {\n try {\n return await new GitHubAppLeaser(appCfg).isRepoInstalled(owner, repo);\n } catch {\n /* fall through to the plane check */\n }\n }\n const adminToken = process.env.AGENTBOX_RELAY_ADMIN_TOKEN;\n if (controlPlaneUrl && adminToken) {\n try {\n const u = `${controlPlaneUrl.replace(/\\/$/, '')}/admin/app/repo-installed?owner=${encodeURIComponent(owner)}&repo=${encodeURIComponent(repo)}`;\n const res = await fetch(u, {\n headers: { Authorization: `Bearer ${adminToken}` },\n signal: AbortSignal.timeout(8000),\n });\n if (res.ok) return Boolean(((await res.json()) as { installed?: boolean }).installed);\n } catch {\n /* unknown */\n }\n }\n return 'unknown';\n}\n\n/** The GitHub page where the user picks repositories for the App installation. */\nexport function addRepoUrl(meta: ControlPlaneMeta | null): string | null {\n return meta?.installUrl ?? (meta?.slug ? `https://github.com/apps/${meta.slug}/installations/new` : null);\n}\n\ntype ReposState = Record<string, { installed?: boolean; promptedAt?: string }>;\n\nfunction readReposState(): ReposState {\n try {\n return JSON.parse(readFileSync(REPOS_STATE, 'utf8')) as ReposState;\n } catch {\n return {};\n }\n}\nfunction writeReposState(state: ReposState): void {\n try {\n mkdirSync(CP_DIR, { recursive: true });\n writeFileSync(REPOS_STATE, JSON.stringify(state, null, 2) + '\\n', { mode: 0o600 });\n } catch {\n /* best-effort cache; never block a launch on it */\n }\n}\n\n/**\n * Before launching an agent against a configured control plane, make sure the\n * project repo is authorized on the GitHub App (else pushes can't lease a\n * token). Checks install status, prompts to open the add-repo page when\n * missing, and remembers the outcome so it never nags again. No-op without a\n * control plane, without an origin, or non-interactively (then it only warns).\n */\nexport async function ensureProjectRepoOnControlPlane(args: {\n controlPlaneUrl: string | undefined;\n gitPushMode?: GitPushMode;\n projectRoot: string;\n yes?: boolean;\n}): Promise<void> {\n const { controlPlaneUrl, projectRoot } = args;\n if (!controlPlaneUrl) return;\n // `relay` and `direct` push modes never lease from the plane, so the repo\n // doesn't need to be authorized on the control plane's GitHub App — skip the\n // check/nag. (`direct` uses credentials copied straight into the box.)\n if (args.gitPushMode === 'relay' || args.gitPushMode === 'direct') return;\n const ownerRepo = await resolveOwnerRepo(projectRoot);\n if (!ownerRepo) return;\n const { owner, repo } = ownerRepo;\n const key = `${controlPlaneUrl.replace(/\\/$/, '')}|${owner}/${repo}`;\n\n const state = readReposState();\n if (state[key]?.installed) return;\n\n const installed = await checkRepoInstalled(owner, repo, controlPlaneUrl);\n if (installed === true) {\n state[key] = { installed: true };\n writeReposState(state);\n return;\n }\n if (state[key]?.promptedAt) {\n // Already prompted once — don't re-nag with a blocking prompt, but a one-line\n // reminder beats a silent lease failure later. (The live check above still\n // auto-clears this and goes quiet once the repo is actually authorized.)\n clog.warn(\n `${owner}/${repo} isn't authorized on the control plane's GitHub App yet — run \\`agentbox hub add\\`.`,\n );\n return;\n }\n\n const meta = loadControlPlaneMeta();\n const url = addRepoUrl(meta);\n const nonInteractive = args.yes === true || process.env.AGENTBOX_PROMPT === 'off' || !process.stdout.isTTY;\n\n if (nonInteractive) {\n clog.warn(\n `Repo ${owner}/${repo} may not be authorized on the control plane's GitHub App; ` +\n `pushes/PRs will fail to lease until you run \\`agentbox hub add\\`.`,\n );\n state[key] = { promptedAt: new Date().toISOString() };\n writeReposState(state);\n return;\n }\n\n if (!url) {\n clog.warn(\n `Repo ${owner}/${repo} isn't authorized on the GitHub App and no App metadata was found locally. ` +\n `Run \\`agentbox hub add\\` from a machine that ran \\`hub setup\\`.`,\n );\n state[key] = { promptedAt: new Date().toISOString() };\n writeReposState(state);\n return;\n }\n\n const ok = await confirm({\n message: `Authorize ${owner}/${repo} on the GitHub App so this box can push / open PRs?`,\n initialValue: true,\n });\n if (!isCancel(ok) && ok) {\n openInBrowser(url);\n note(`Opened ${url}\\nSelect ${owner}/${repo}, approve, then return here.`, 'GitHub App');\n }\n state[key] = { promptedAt: new Date().toISOString() };\n writeReposState(state);\n}\n","import { readFile, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { deployControlPlaneToHetzner, readHetznerCredStatus } from '@agentbox/sandbox-hetzner';\n\n/**\n * CLI wrapper for the Hetzner control-plane deploy: precheck the token, run the\n * provisioning in `@agentbox/sandbox-hetzner`, and persist the deploy record so\n * a later command (or the user) can find / tear down the VPS.\n */\nexport interface HetznerDeployOptions {\n /** Path to the setup-written control-plane.env (scp'd to the VPS as `.env`). */\n envPath: string;\n /** Branch / tag / sha of the agentbox repo to deploy (default `main`). */\n repoRef?: string;\n /** Git repo the VPS clones (default the public agentbox repo). */\n repoUrl?: string;\n log: (line: string) => void;\n}\n\nexport async function runHetznerDeploy(opts: HetznerDeployOptions): Promise<{ url: string }> {\n if (readHetznerCredStatus().source === 'none') {\n throw new Error('no HCLOUD_TOKEN configured — run `agentbox hetzner login` first');\n }\n const envContent = await readFile(opts.envPath, 'utf8');\n const result = await deployControlPlaneToHetzner({\n envContent,\n repoRef: opts.repoRef,\n repoUrl: opts.repoUrl,\n onLog: opts.log,\n });\n const deployPath = join(homedir(), '.agentbox', 'control-plane', 'deploy.json');\n await writeFile(\n deployPath,\n JSON.stringify({ provider: 'hetzner', ...result }, null, 2) + '\\n',\n { mode: 0o600 },\n );\n return { url: result.url };\n}\n","import { randomBytes } from 'node:crypto';\nimport { isCancel, password, text } from '@clack/prompts';\n\n/** Env the deployed hub needs to enforce login + seed its first admin. */\nexport interface HubAuthEnv {\n AGENTBOX_HUB_AUTH: string;\n BETTER_AUTH_SECRET: string;\n AGENTBOX_HUB_ADMIN_EMAIL: string;\n AGENTBOX_HUB_ADMIN_PASSWORD: string;\n}\n\n/**\n * Collect the hub auth env for a deployed profile, prompting for anything not\n * already in the environment. Setting these turns login on (auth is secret-gated\n * on the hub), so a deployed hub is never left loginless. Returns null if the\n * operator cancels a prompt (deploy proceeds without login, as before).\n */\nexport async function resolveHubAuthEnv(): Promise<HubAuthEnv | null> {\n let email = process.env.AGENTBOX_HUB_ADMIN_EMAIL;\n let pass = process.env.AGENTBOX_HUB_ADMIN_PASSWORD;\n const secret = process.env.BETTER_AUTH_SECRET || randomBytes(32).toString('base64');\n\n if (!email) {\n const v = await text({\n message: 'Hub admin email (used to log in to the deployed hub UI)',\n validate: (s) => (/^.+@.+\\..+$/.test(s.trim()) ? undefined : 'enter a valid email'),\n });\n if (isCancel(v)) return null;\n email = v.trim();\n }\n if (!pass) {\n const v = await password({\n message: 'Hub admin password (min 8 characters)',\n validate: (s) => (s.length >= 8 ? undefined : 'at least 8 characters'),\n });\n if (isCancel(v)) return null;\n pass = v;\n }\n\n return {\n AGENTBOX_HUB_AUTH: 'on',\n BETTER_AUTH_SECRET: secret,\n AGENTBOX_HUB_ADMIN_EMAIL: email,\n AGENTBOX_HUB_ADMIN_PASSWORD: pass,\n };\n}\n","/**\n * The PC's client for a hub's public REST API (`/api/v1`) — the SAME surface the\n * tray and web UI speak. Its only local⇄remote difference is the base URL + token\n * (a control box's `AGENTBOX_HUB_API_KEY`, or a local hub's token), so a command\n * built on this client works against either by swapping the target.\n *\n * Distinct from {@link ControlPlaneAdminClient}, which speaks the INTERNAL relay\n * wire (`/admin/*` + `/remote/*`) — the box↔hub + credential plane that is not a\n * client API. Client-facing box operations (list, lifecycle, git, approvals)\n * belong here; custody / registration / RPC-lease stay on the admin client.\n */\n\n/** A hub box as the `/api/v1` list/get returns it (the UI view + raw host fields). */\nexport interface HubApiBox {\n id: string;\n name?: string;\n provider: string;\n /** Raw provider runtime state; absent on synthetic in-flight `job:` boxes. */\n state?: 'running' | 'paused' | 'stopped' | 'missing' | 'destroyed';\n /** Normalized lifecycle status (running | paused | stopped | creating | error). */\n status: string;\n branch: string;\n task: string;\n projectRoot?: string;\n projectIndex?: number;\n}\n\n/** A create-job's status as `/api/v1/jobs/:id` returns it. */\nexport interface HubApiJob {\n id: string;\n status: 'queued' | 'running' | 'done' | 'failed' | string;\n boxId?: string;\n login?: {\n required?: boolean;\n phase?: string;\n url?: string;\n error?: string;\n lastError?: string;\n };\n}\n\n/** A pending host-action approval as `/api/v1/approvals` returns it. */\nexport interface HubApiApproval {\n id: string;\n boxId: string;\n message: string;\n detail?: string;\n command?: string;\n cwd?: string;\n argv?: string[];\n defaultAnswer: 'y' | 'n';\n createdAt: number;\n}\n\n/** Result of a box git/service op (mirrors the backend `BoxOpResult`). */\nexport interface HubApiOpResult {\n ok: boolean;\n stdout?: string;\n stderr?: string;\n error?: string;\n}\n\nexport type HubLifecycleAction = 'start' | 'pause' | 'resume' | 'stop' | 'destroy';\nexport type HubGitOp = 'checkout' | 'branch' | 'pull' | 'push' | 'push-host';\n\nexport interface HubApiTarget {\n url: string;\n apiKey: string;\n fetchImpl?: typeof fetch;\n}\n\n/** An error carrying the `/api/v1` envelope's code + HTTP status. */\nexport class HubApiError extends Error {\n constructor(\n message: string,\n readonly code: string,\n readonly status: number,\n ) {\n super(message);\n this.name = 'HubApiError';\n }\n}\n\ninterface ApiErrorBody {\n error?: { code?: string; message?: string; details?: unknown };\n}\n\nexport class HubApiClient {\n private readonly base: string;\n private readonly token: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(target: HubApiTarget) {\n this.base = target.url.replace(/\\/+$/, '');\n this.token = target.apiKey;\n this.fetchImpl = target.fetchImpl ?? fetch;\n }\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const res = await this.fetchImpl(`${this.base}/api/v1${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.token}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n if (res.status === 204) return undefined as T;\n const text = await res.text();\n let parsed: unknown;\n try {\n parsed = text.length > 0 ? JSON.parse(text) : {};\n } catch {\n throw new HubApiError(`unexpected non-JSON response (${res.status})`, 'internal', res.status);\n }\n if (!res.ok) {\n const err = (parsed as ApiErrorBody).error;\n throw new HubApiError(\n err?.message ?? `request failed: ${res.status}`,\n err?.code ?? 'internal',\n res.status,\n );\n }\n return parsed as T;\n }\n\n /** All boxes the hub knows (its own + registered). Topology-agnostic read. */\n async listBoxes(): Promise<HubApiBox[]> {\n return (await this.request<{ boxes: HubApiBox[] }>('GET', '/boxes')).boxes;\n }\n\n /** One box by id (throws HubApiError 'not_found' when absent). */\n getBox(id: string): Promise<HubApiBox> {\n return this.request<HubApiBox>('GET', `/boxes/${encodeURIComponent(id)}`);\n }\n\n /** Lifecycle action on a box. Reverse-adoption lets the hub drive registered-only boxes. */\n async lifecycle(id: string, action: HubLifecycleAction): Promise<void> {\n await this.request<{ ok: true }>('POST', `/boxes/${encodeURIComponent(id)}/${action}`);\n }\n\n /** Real destroy: tears down the cloud resource AND reaps the hub's registration/custody. */\n destroy(id: string): Promise<void> {\n return this.lifecycle(id, 'destroy');\n }\n\n /** A git op against the box's branch. */\n git(id: string, op: HubGitOp, body: Record<string, unknown> = {}): Promise<HubApiOpResult> {\n return this.request<HubApiOpResult>('POST', `/boxes/${encodeURIComponent(id)}/git/${op}`, body);\n }\n\n /** Create-job status (poll until done/failed). */\n getJob(id: string): Promise<HubApiJob> {\n return this.request<HubApiJob>('GET', `/jobs/${encodeURIComponent(id)}`);\n }\n\n /** Pending host-action approvals across every box. */\n async listApprovals(): Promise<HubApiApproval[]> {\n return (await this.request<{ approvals: HubApiApproval[] }>('GET', '/approvals')).approvals;\n }\n\n /** Answer a pending approval by id. */\n async answerApproval(id: string, answer: 'y' | 'n'): Promise<void> {\n await this.request<{ ok: true }>('POST', `/approvals/${encodeURIComponent(id)}/answer`, { answer });\n }\n}\n","/**\n * `agentbox create --via-hub`: instead of creating a box locally, enqueue a\n * create job on the control box (`POST /remote/boxes`) and stream its progress\n * (`GET /remote/boxes/:id`). The resident hub worker claims the job and\n * provisions the box VPS-side, so a box can be created with the PC's providers\n * unconfigured (or the PC off after the enqueue).\n */\n\nimport type { CreateJobRequest, CreateJobRow } from '@agentbox/relay/control-plane';\n\nexport interface HubTarget {\n url: string;\n adminToken: string;\n fetchImpl?: typeof fetch;\n}\n\nasync function safeText(res: Response): Promise<string> {\n try {\n return (await res.text()).slice(0, 500);\n } catch {\n return '';\n }\n}\n\n/** Enqueue a create job; returns the job id. */\nexport async function enqueueCreateViaHub(target: HubTarget, request: CreateJobRequest): Promise<string> {\n const base = target.url.replace(/\\/+$/, '');\n const f = target.fetchImpl ?? fetch;\n const res = await f(`${base}/remote/boxes`, {\n method: 'POST',\n headers: { Authorization: `Bearer ${target.adminToken}`, 'Content-Type': 'application/json' },\n body: JSON.stringify(request),\n });\n if (res.status !== 202) {\n throw new Error(`enqueue failed: ${res.status} ${await safeText(res)}`);\n }\n return ((await res.json()) as { jobId: string }).jobId;\n}\n\n/** Fetch one job's current row. */\nexport async function getHubJob(target: HubTarget, jobId: string): Promise<CreateJobRow | null> {\n const base = target.url.replace(/\\/+$/, '');\n const f = target.fetchImpl ?? fetch;\n const res = await f(`${base}/remote/boxes/${encodeURIComponent(jobId)}`, {\n headers: { Authorization: `Bearer ${target.adminToken}` },\n });\n if (res.status === 404) return null;\n if (!res.ok) throw new Error(`job status failed: ${res.status} ${await safeText(res)}`);\n return (await res.json()) as CreateJobRow;\n}\n\n/**\n * Recent jobs on the control box's create queue, newest first.\n *\n * This is a different queue from the PC's local `~/.agentbox/queue/`: with a\n * control box configured, background `-i` cloud runs are enqueued HERE, so the\n * local queue alone is an incomplete picture of what's running.\n */\nexport async function listHubJobs(target: HubTarget): Promise<CreateJobRow[]> {\n const base = target.url.replace(/\\/+$/, '');\n const f = target.fetchImpl ?? fetch;\n const res = await f(`${base}/remote/boxes`, {\n headers: { Authorization: `Bearer ${target.adminToken}` },\n });\n if (!res.ok) throw new Error(`list jobs failed: ${res.status} ${await safeText(res)}`);\n // Tolerate a 200 that isn't the shape we expect (a proxy's interstitial, a\n // hub mid-upgrade): render an empty queue rather than iterating `undefined`.\n const body = (await res.json()) as { jobs?: unknown };\n return Array.isArray(body.jobs) ? (body.jobs as CreateJobRow[]) : [];\n}\n\nexport interface PollOptions {\n intervalMs?: number;\n /** Give up after this long. Default 30 min (a real cloud create can be slow). */\n timeoutMs?: number;\n onStatus?: (job: CreateJobRow) => void;\n /** Injectable for tests. */\n sleep?: (ms: number) => Promise<void>;\n now?: () => number;\n}\n\n/**\n * Poll a job until it reaches `done`/`failed` (or the timeout). Reports each\n * observed status transition via `onStatus`.\n */\nexport async function pollHubJob(\n target: HubTarget,\n jobId: string,\n opts: PollOptions = {},\n): Promise<CreateJobRow> {\n const intervalMs = opts.intervalMs ?? 3000;\n const timeoutMs = opts.timeoutMs ?? 30 * 60_000;\n const sleep = opts.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));\n const now = opts.now ?? Date.now;\n const deadline = now() + timeoutMs;\n let lastStatus = '';\n for (;;) {\n const job = await getHubJob(target, jobId);\n if (!job) throw new Error(`job ${jobId} disappeared from the control plane`);\n if (job.status !== lastStatus) {\n lastStatus = job.status;\n opts.onStatus?.(job);\n }\n if (job.status === 'done' || job.status === 'failed') return job;\n if (now() >= deadline) {\n throw new Error(`timed out waiting for job ${jobId} (last status: ${job.status})`);\n }\n await sleep(intervalMs);\n }\n}\n","import { log } from '@clack/prompts';\nimport { AmbiguousBoxError, BoxNotFoundError, ClaudeSessionError } from '@agentbox/sandbox-docker';\n\n/**\n * Map common lifecycle errors to user-facing messages and the right exit code,\n * then exit. Shared by all lifecycle commands so error UX stays consistent.\n */\nexport function handleLifecycleError(err: unknown): never {\n if (err instanceof BoxNotFoundError) {\n log.error(err.message);\n log.info('Run `agentbox list` to see available boxes.');\n process.exit(2);\n }\n if (err instanceof AmbiguousBoxError) {\n log.error(err.message);\n log.info('Specify more characters of the id, or use the full name.');\n process.exit(2);\n }\n if (err instanceof ClaudeSessionError) {\n log.error(err.message);\n process.exit(2);\n }\n const msg = err instanceof Error ? err.message : String(err);\n log.error(msg);\n process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAAA,WAAU,OAAAC,MAAK,QAAAC,OAAM,QAAQ,eAAe;AACrD,SAAS,eAAe;AACxB,SAAS,SAAAC,cAAa;AACtB,SAAS,cAAAC,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,OAAO,OAAO,YAAAC,WAAU,IAAI,aAAAC,kBAAiB;AACtD,SAAS,UAAU,WAAAC,UAAS,UAAAC,eAAc;AAC1C,SAAS,UAAU,SAAS,QAAAC,aAAY;AACxC,SAAS,cAAc,aAAa;AAsBpC,SAAS,eAAAC,oBAAmB;;;AC7B5B,SAAS,oBAAoB;AAE7B,SAAS,mBAAmB;AA0C5B,SAAS,WAAW,GAAmB;AACrC,SAAO,EAAE,QAAQ,MAAM,OAAO,EAAE,QAAQ,MAAM,MAAM,EAAE,QAAQ,MAAM,MAAM,EAAE,QAAQ,MAAM,QAAQ;AACpG;AAEA,eAAsB,yBACpB,MAC6B;AAC7B,QAAM,aAAa,KAAK,aAAa,sBAAsB,QAAQ,OAAO,EAAE;AAC5E,QAAM,cAAc,KAAK,cAAc,0BAA0B,QAAQ,OAAO,EAAE;AAClF,QAAM,YAAY,KAAK,aAAa;AACpC,QAAMC,OAAM,KAAK,QAAQ,MAAM;AAAA,EAAC;AAChC,QAAM,QAAQ,YAAY,EAAE,EAAE,SAAS,KAAK;AAE5C,SAAO,IAAI,QAA4B,CAAC,SAAS,WAAW;AAI1D,QAAI,aAAa;AACjB,QAAI,UAAU;AACd,UAAM,SAAS,aAAa,CAAC,K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,yBAAqB,GAAG;AAAA,EAC1B;AACF,CAAC;AAQH,eAAe,4BAA4B,KAA4B;AACrE,QAAM,SAAS,MAAM,qBAAqB,KAAK,EAAE,OAAO,KAAK,CAAC;AAC9D,MAAI,CAAC,OAAQ;AACb,QAAM,SAAmB,CAAC;AAC1B,aAAW,YAAY,8BAA8B;AACnD,UAAM,KAAK,MAAM,sBAAsB,UAAU;AAAA,MAC/C,iBAAiB,OAAO;AAAA,MACxB,YAAY,OAAO;AAAA,IACrB,CAAC,EAAE,MAAM,MAAM,KAAK;AACpB,QAAI,GAAI,QAAO,KAAK,QAAQ;AAAA,EAC9B;AACA,MAAI,OAAO,SAAS,GAAG;AACrB,IAAAA,KAAI,QAAQ,eAAe,OAAO,KAAK,IAAI,CAAC,kEAA6D;AAAA,EAC3G;AACF;AAOA,IAAM,+BAA+B,CAAC,WAAW,UAAU,OAAO,WAAW,cAAc;AAE3F,IAAM,YAAY,IAAI,QAAQ,QAAQ,EACnC,YAAY,sEAAsE,EAClF,WAAW,gBAAgB;AASvB,IAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;","names":["isCancel","log","note","spawn","existsSync","readFileSync","readFile","writeFile","homedir","tmpdir","join","randomBytes","log","spawn","join","log","spawn","spawn","log","join","spawn","homedir","join","join","homedir","randomBytes","isCancel","text","CP_DIR","join","homedir","ENV_PATH","META_PATH","existsSync","readFileSync","writeFile","randomBytes","note","log","isCancel","spawn","tmpdir","readFile"]}
|