@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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-e2b/src/env-loader.ts","../../../packages/sandbox-e2b/src/sdk.ts","../../../packages/sandbox-e2b/src/credentials.ts","../../../packages/sandbox-e2b/src/runtime-assets.ts","../../../packages/sandbox-e2b/src/prepared-state.ts"],"sourcesContent":["/**\n * E2B env auto-loader. The `e2b` SDK reads `E2B_API_KEY` (and optionally\n * `E2B_DOMAIN` for non-default deployments) from `process.env`. We seed those\n * from `~/.agentbox/secrets.env` (written by `agentbox e2b login`) so the SDK\n * Just Works after a one-time login — same pattern as the daytona / hetzner /\n * vercel env-loaders.\n *\n * Lookup order (first wins; process.env is never overwritten):\n * 1. `process.env` (already set in the shell).\n * 2. `~/.agentbox/secrets.env` — written by `agentbox e2b login`.\n *\n * Project-level `.env` / `.env.local` are intentionally NOT consulted: those\n * files belong to the app code being developed. Put host credentials in\n * `~/.agentbox/secrets.env` (or the shell env).\n *\n * Only E2B-prefixed keys are imported; the rest of the file is left alone.\n * Idempotent and side-effect-free after the first call.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\nconst E2B_KEYS = ['E2B_API_KEY', 'E2B_DOMAIN'] as const;\n\nlet loaded = false;\n\nexport function ensureE2bEnvLoaded(): void {\n if (loaded) return;\n loaded = true;\n importE2bFromFile(resolve(homedir(), '.agentbox', 'secrets.env'), E2B_KEYS);\n}\n\n/**\n * Force a re-read of `~/.agentbox/secrets.env`. Used by the interactive\n * `agentbox e2b login` flow after it persists the API key, so the same process\n * can pick it up without a restart.\n */\nexport function reloadE2bEnv(): void {\n loaded = false;\n ensureE2bEnvLoaded();\n}\n\nfunction importE2bFromFile(path: string, keys: readonly string[]): void {\n if (!existsSync(path)) return;\n let body: string;\n try {\n body = readFileSync(path, 'utf8');\n } catch {\n return;\n }\n const parsed = parseEnvFile(body);\n for (const key of keys) {\n if (process.env[key] !== undefined) continue;\n const value = parsed[key];\n if (typeof value === 'string') {\n process.env[key] = value;\n }\n }\n}\n\n/**\n * Minimal `.env` parser: handles `KEY=value`, `KEY=\"value\"`, `KEY='value'`,\n * `export KEY=value`, blank lines, and `#` comments. No variable interpolation\n * — predictable over feature-complete (matches the daytona / vercel loaders).\n */\nexport function parseEnvFile(body: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const rawLine of body.split(/\\r?\\n/)) {\n const line = rawLine.trim();\n if (line.length === 0 || line.startsWith('#')) continue;\n const stripped = line.startsWith('export ') ? line.slice('export '.length) : line;\n const eq = stripped.indexOf('=');\n if (eq <= 0) continue;\n const key = stripped.slice(0, eq).trim();\n let value = stripped.slice(eq + 1).trim();\n if (\n value.length >= 2 &&\n ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\")))\n ) {\n value = value.slice(1, -1);\n }\n out[key] = value;\n }\n return out;\n}\n","/**\n * Thin wrapper around the `e2b` SDK. Resolves the API key once and re-exports\n * the SDK surface the rest of the package uses from a single place (so tests\n * can mock `./sdk.js` instead of the package).\n *\n * E2B only ships one auth mode for first-party use: a single API key. The SDK\n * already reads `process.env.E2B_API_KEY` on each call, but we still expose\n * `resolveApiKey()` so callers can fail loud with an actionable error before\n * the SDK throws a generic \"401 unauthorized\" deep inside an op.\n */\n\nimport { Sandbox, Template } from 'e2b';\nimport { ensureE2bEnvLoaded } from './env-loader.js';\n\nexport { Sandbox, Template };\nexport type { SandboxOpts, SandboxInfo, SandboxState, SandboxListOpts, LogEntry, BuildInfo } from 'e2b';\n\n/**\n * Return the configured E2B API key. Throws an actionable error when nothing\n * is configured. Idempotent — env-loader caches itself after first call.\n */\nexport function resolveApiKey(): string {\n ensureE2bEnvLoaded();\n const k = process.env.E2B_API_KEY;\n if (!k) {\n throw new Error(\n 'E2B credentials not configured.\\n' +\n 'Run `agentbox e2b login` to paste your API key (from https://e2b.dev/dashboard?tab=keys), ' +\n 'or set E2B_API_KEY in the environment / ~/.agentbox/secrets.env.',\n );\n }\n return k;\n}\n\n/** True when an API key is configured. Used by the credential gate. */\nexport function hasUsableCredentials(): boolean {\n ensureE2bEnvLoaded();\n return Boolean(process.env.E2B_API_KEY);\n}\n","/**\n * Interactive E2B credential setup. Single mode — paste an API key from\n * https://e2b.dev/dashboard?tab=keys — much simpler than vercel's three-mode\n * flow. Persists to `~/.agentbox/secrets.env` (the canonical store, matching\n * daytona / hetzner / vercel).\n *\n * Non-interactive callers (no TTY): silent no-op, so scripted/CI runs surface\n * the SDK's own \"not configured\" error instead of hanging on a prompt.\n */\n\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\nimport { hostOpenCommand, writeManagedSecrets, type CredSetResult } from '@agentbox/sandbox-core';\nimport {\n cancel,\n confirm,\n intro,\n isCancel,\n log,\n note,\n outro,\n password,\n} from '@clack/prompts';\nimport { ensureE2bEnvLoaded, reloadE2bEnv } from './env-loader.js';\nimport { hasUsableCredentials } from './sdk.js';\n\n// Ctrl+C at a prompt resolves with the cancel symbol; turn that into a real\n// quit so the command never silently continues as if the user answered \"No\".\nfunction exitOnCancel<T>(v: T | symbol): T {\n if (isCancel(v)) {\n cancel('Cancelled.');\n process.exit(130);\n }\n return v as T;\n}\n\nconst DASHBOARD_KEYS_URL = 'https://e2b.dev/dashboard?tab=keys';\n\n/**\n * Keys we manage in `~/.agentbox/secrets.env`. On reconfigure we strip prior\n * values for these before appending so the file never accumulates duplicates.\n */\nconst MANAGED_KEYS = ['E2B_API_KEY'] as const;\n\nexport interface EnsureE2bCredentialsOptions {\n /** Re-prompt even when valid credentials are already present (`agentbox e2b login`). */\n force?: boolean;\n}\n\nexport async function ensureE2bCredentials(\n opts: EnsureE2bCredentialsOptions = {},\n): Promise<void> {\n ensureE2bEnvLoaded();\n\n if (!opts.force && hasUsableCredentials()) return;\n if (!process.stdin.isTTY) return;\n\n intro('E2B setup');\n note(\n `AgentBox needs an E2B API key to provision sandboxes.\\n` +\n `Get one from ${DASHBOARD_KEYS_URL} (free tier available), then paste it below.\\n` +\n `The key is stored in \\`~/.agentbox/secrets.env\\` (mode 0600) — no .env.local harvesting.`,\n 'Credentials required',\n );\n\n const openIt = exitOnCancel(\n await confirm({\n message: `Open ${DASHBOARD_KEYS_URL} to create a key?`,\n initialValue: true,\n }),\n );\n if (openIt) openDashboard();\n\n const key = exitOnCancel(\n await password({\n message: 'Paste your E2B API key',\n validate: (v) => (v && v.trim().length > 0 ? undefined : 'Cannot be empty'),\n }),\n );\n\n persistCredentials({ apiKey: key.trim() });\n reloadE2bEnv();\n log.success(`E2B credentials saved to ${secretsPath()}`);\n outro('Setup complete.');\n}\n\nfunction persistCredentials(creds: { apiKey: string }): void {\n writeManagedSecrets(MANAGED_KEYS, { E2B_API_KEY: creds.apiKey });\n}\n\n/**\n * Non-interactive credential set (the headless path the hub drives). Takes an\n * `{ apiKey }`, persists it to `~/.agentbox/secrets.env`, and reports status.\n * E2B has no cheap read-only auth probe, so — like the interactive flow — we\n * only require a non-empty key; a bad key surfaces on first sandbox create.\n */\nexport function setE2bCredentials(fields: Record<string, string>): CredSetResult {\n const apiKey = (fields.apiKey ?? '').trim();\n if (!apiKey) {\n return { ok: false, error: 'apiKey is required', status: { configured: false } };\n }\n persistCredentials({ apiKey });\n const cred = readE2bCredStatus();\n return { ok: true, status: { configured: cred.auth !== 'none', label: cred.auth } };\n}\n\nfunction openDashboard(): void {\n import('node:child_process')\n .then(({ spawnSync }) => {\n const r = spawnSync(hostOpenCommand(), [DASHBOARD_KEYS_URL], { stdio: 'ignore' });\n if (r.status !== 0) {\n log.warn(`Could not auto-open the browser — visit ${DASHBOARD_KEYS_URL} manually.`);\n }\n })\n .catch(() => {\n log.warn(`Could not auto-open the browser — visit ${DASHBOARD_KEYS_URL} manually.`);\n });\n}\n\nexport function secretsPath(): string {\n return resolve(homedir(), '.agentbox', 'secrets.env');\n}\n\nexport interface E2bCredStatus {\n auth: 'key' | 'none';\n token?: string;\n source: 'env' | 'secrets.env' | 'none';\n}\n\nexport function readE2bCredStatus(): E2bCredStatus {\n const shellHad = process.env.E2B_API_KEY !== undefined;\n ensureE2bEnvLoaded();\n const key = process.env.E2B_API_KEY;\n if (!key) return { auth: 'none', source: 'none' };\n return { auth: 'key', token: key, source: shellHad ? 'env' : 'secrets.env' };\n}\n\nexport function maskKey(value: string): string {\n if (value.length <= 8) return '*'.repeat(value.length);\n return `${value.slice(0, 4)}…${'*'.repeat(8)}${value.slice(-4)}`;\n}\n","/**\n * Resolver for the runtime payload baked into the E2B base template during\n * `prepareE2b()`. Same idea as the vercel resolver: a flat list of files to\n * `template.copy` into the build context, each resolved from either the\n * staged CLI runtime tree or the monorepo source tree.\n *\n * Lookup order per file:\n * 1. The CLI's staged runtime tree: `<cliRoot>/e2b/...`.\n * 2. The monorepo source tree (dev fallback) under `packages/`.\n *\n * Any missing file throws a clear error naming the paths tried. Includes the\n * shared dockerd launch helper — E2B microVMs DO support nested containers, so\n * the base template bakes the docker engine (in-box DinD).\n */\n\nimport { existsSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst SELF = dirname(fileURLToPath(import.meta.url));\n\nexport function findStagedCliRuntimeRoot(): string | undefined {\n const candidates = [resolve(SELF, '..', 'runtime'), resolve(SELF, '..', '..', 'runtime')];\n for (const c of candidates) {\n if (existsSync(resolve(c, 'e2b', 'scripts', 'build-template.sh'))) return c;\n }\n return undefined;\n}\n\nexport interface RuntimeAsset {\n /** Logical name (used in error messages + log lines). */\n name: string;\n /** Absolute path inside the template's build filesystem (Template.copy target). */\n remotePath: string;\n /** File mode to apply after upload. */\n remoteMode: number;\n}\n\n/**\n * Where each asset lands inside the sandbox during template build. build-template.sh\n * reads them from these fixed paths. The agent/runtime helpers go straight to\n * /usr/local/bin via the script; baked config files to /tmp for the script to\n * `install` into place.\n */\nexport const RUNTIME_ASSETS: readonly RuntimeAsset[] = [\n { name: 'build-template.sh', remotePath: '/tmp/agentbox-build-template.sh', remoteMode: 0o755 },\n { name: 'agentbox-ctl', remotePath: '/tmp/agentbox-ctl', remoteMode: 0o755 },\n { name: 'agentbox-dockerd-start', remotePath: '/tmp/agentbox-dockerd-start', remoteMode: 0o755 },\n { name: 'agentbox-vnc-start', remotePath: '/tmp/agentbox-vnc-start', remoteMode: 0o755 },\n { name: 'agentbox-checkpoint-cleanup', remotePath: '/tmp/agentbox-checkpoint-cleanup', remoteMode: 0o755 },\n { name: 'agentbox-open', remotePath: '/tmp/agentbox-open', remoteMode: 0o755 },\n { name: 'gh-shim', remotePath: '/tmp/agentbox-gh-shim', remoteMode: 0o755 },\n { name: 'git-shim', remotePath: '/tmp/agentbox-git-shim', remoteMode: 0o755 },\n { name: 'ntn-shim', remotePath: '/tmp/agentbox-ntn-shim', remoteMode: 0o755 },\n { name: 'linear-shim', remotePath: '/tmp/agentbox-linear-shim', remoteMode: 0o755 },\n { name: 'custom-system-CLAUDE.md', remotePath: '/tmp/agentbox-custom-CLAUDE.md', remoteMode: 0o644 },\n { name: 'claude-managed-settings.json', remotePath: '/tmp/agentbox-managed-settings.json', remoteMode: 0o644 },\n { name: 'agentbox-codex-hooks.json', remotePath: '/tmp/agentbox-codex-hooks.json', remoteMode: 0o644 },\n { name: 'agentbox-setup-skill.md', remotePath: '/tmp/agentbox-setup-skill.md', remoteMode: 0o644 },\n] as const;\n\nexport interface ResolvedAsset extends RuntimeAsset {\n localPath: string;\n}\n\nexport function candidatesFor(\n name: string,\n opts: { cliRuntimeRoot?: string; repoRoot?: string } = {},\n): string[] {\n const cliRoot = opts.cliRuntimeRoot;\n const monorepo = opts.repoRoot ?? guessRepoRoot();\n\n const monorepoRelative: Record<string, string[]> = {\n 'build-template.sh': ['packages/sandbox-e2b/scripts/build-template.sh'],\n 'agentbox-ctl': ['packages/ctl/dist/bin.cjs'],\n 'agentbox-dockerd-start': ['packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-vnc-start': ['packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-checkpoint-cleanup': ['packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup'],\n 'agentbox-open': ['packages/sandbox-docker/scripts/agentbox-open'],\n 'gh-shim': ['packages/sandbox-docker/scripts/gh-shim'],\n 'git-shim': ['packages/sandbox-docker/scripts/git-shim'],\n 'ntn-shim': ['packages/sandbox-docker/scripts/ntn-shim'],\n 'linear-shim': ['packages/sandbox-docker/scripts/linear-shim'],\n 'custom-system-CLAUDE.md': ['packages/sandbox-e2b/scripts/custom-system-CLAUDE.md'],\n 'claude-managed-settings.json': ['packages/sandbox-docker/scripts/claude-managed-settings.json'],\n 'agentbox-codex-hooks.json': ['packages/sandbox-docker/scripts/agentbox-codex-hooks.json'],\n 'agentbox-setup-skill.md': ['apps/cli/share/agentbox-setup/SKILL.md'],\n };\n\n const cliRelative: Record<string, string[]> = {\n 'build-template.sh': ['e2b/scripts/build-template.sh'],\n 'agentbox-ctl': ['e2b/ctl.cjs'],\n 'agentbox-dockerd-start': ['e2b/agentbox-dockerd-start', 'docker/packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-vnc-start': ['e2b/agentbox-vnc-start', 'docker/packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-checkpoint-cleanup': ['e2b/agentbox-checkpoint-cleanup', 'docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup'],\n 'agentbox-open': ['e2b/agentbox-open', 'docker/packages/sandbox-docker/scripts/agentbox-open'],\n 'gh-shim': ['e2b/gh-shim', 'docker/packages/sandbox-docker/scripts/gh-shim'],\n 'git-shim': ['e2b/git-shim', 'docker/packages/sandbox-docker/scripts/git-shim'],\n 'ntn-shim': ['e2b/ntn-shim', 'docker/packages/sandbox-docker/scripts/ntn-shim'],\n 'linear-shim': ['e2b/linear-shim', 'docker/packages/sandbox-docker/scripts/linear-shim'],\n 'custom-system-CLAUDE.md': ['e2b/custom-system-CLAUDE.md'],\n 'claude-managed-settings.json': ['e2b/claude-managed-settings.json', 'docker/packages/sandbox-docker/scripts/claude-managed-settings.json'],\n 'agentbox-codex-hooks.json': ['e2b/agentbox-codex-hooks.json', 'docker/packages/sandbox-docker/scripts/agentbox-codex-hooks.json'],\n 'agentbox-setup-skill.md': ['e2b/agentbox-setup-skill.md', 'docker/apps/cli/share/agentbox-setup/SKILL.md'],\n };\n\n const out: string[] = [];\n if (cliRoot) {\n for (const rel of cliRelative[name] ?? []) out.push(resolve(cliRoot, rel));\n }\n for (const rel of monorepoRelative[name] ?? []) out.push(resolve(monorepo, rel));\n return out;\n}\n\nexport function resolveRuntimeAssets(\n opts: { cliRuntimeRoot?: string; repoRoot?: string } = {},\n): ResolvedAsset[] {\n const out: ResolvedAsset[] = [];\n const missing: Array<{ name: string; tried: string[] }> = [];\n for (const asset of RUNTIME_ASSETS) {\n const cands = candidatesFor(asset.name, opts);\n const hit = cands.find((p) => existsSync(p));\n if (!hit) {\n missing.push({ name: asset.name, tried: cands });\n continue;\n }\n out.push({ ...asset, localPath: hit });\n }\n if (missing.length > 0) {\n const lines = missing.flatMap((m) => [` - ${m.name}: tried`, ...m.tried.map((p) => ` ${p}`)]);\n throw new Error(\n `e2b: could not resolve runtime assets needed to bake the base template:\\n` +\n lines.join('\\n') +\n `\\n\\nIf running from the monorepo, ensure \\`pnpm -w build\\` has run so packages/ctl/dist/bin.cjs exists.`,\n );\n }\n return out;\n}\n\nfunction guessRepoRoot(): string {\n let cur = SELF;\n for (let i = 0; i < 8; i++) {\n if (existsSync(resolve(cur, 'pnpm-workspace.yaml'))) return cur;\n const parent = dirname(cur);\n if (parent === cur) break;\n cur = parent;\n }\n return SELF;\n}\n","/**\n * Persisted record of what `agentbox prepare --provider e2b` has built.\n * Lives at `~/.agentbox/e2b-prepared.json` so the auto-prepare gate\n * (`ensureE2bBaseTemplate()`) and `backend.provision` can resolve the base\n * template every box boots from.\n *\n * Single tier for now — the shared base template (Debian + agentbox-ctl +\n * agents). Templates on E2B are id+tag-addressed reusable resources, so unlike\n * Vercel snapshots we don't worry about per-box snapshot eviction; one template\n * is reused for every create.\n *\n * Schema versioned so future shape changes can migrate; only `schema: 1` is\n * accepted today.\n */\n\nimport { claudeInstallFingerprint, computeContextSha256, readPreparedStateRaw, writePreparedStateRaw, preparedStatePathFor } from '@agentbox/sandbox-core';\nimport { UserFacingError } from '@agentbox/core';\nimport { findStagedCliRuntimeRoot, resolveRuntimeAssets } from './runtime-assets.js';\n\nconst SCHEMA = 1 as const;\n\nexport interface PreparedE2bBase {\n /** Opaque E2B template id (e.g. `tmpl_xxxx` or `name:tag`). Sandbox.create({ template }) boots from this. */\n templateId: string;\n /** Human-friendly template name passed to Template.build (e.g. `agentbox-base:latest`). */\n templateName?: string;\n /** Deterministic SHA-256 of the build context (build script + assets). */\n contextSha256?: string;\n /** Normalized `cpu-memory` GB size the template was baked with (absent = default resources). */\n size?: string;\n /** CLI version that produced this template (informational). */\n cliVersion?: string;\n /** Git short SHA of the CLI build (informational). */\n cliCommit?: string;\n /** ISO timestamp of bake completion. */\n createdAt: string;\n}\n\nexport interface PreparedE2bState {\n schema: typeof SCHEMA;\n /** The shared base template. Absent until first `agentbox prepare`. */\n base?: PreparedE2bBase;\n}\n\nexport function preparedStatePath(): string {\n return preparedStatePathFor('e2b');\n}\n\nexport function readPreparedState(): PreparedE2bState {\n const raw = readPreparedStateRaw('e2b');\n if (raw === null || typeof raw !== 'object') return { schema: SCHEMA };\n const parsed = raw as Partial<PreparedE2bState>;\n if (parsed.schema !== SCHEMA) {\n // Unknown/missing schema: refuse to read — the next prepare overwrites it.\n return { schema: SCHEMA };\n }\n return { schema: SCHEMA, base: parsed.base };\n}\n\nexport function writePreparedState(state: PreparedE2bState): void {\n writePreparedStateRaw('e2b', state);\n}\n\n/** Update one field of the state without forcing callers to read/merge/write. */\nexport function updatePreparedState(mutate: (s: PreparedE2bState) => void): void {\n const s = readPreparedState();\n mutate(s);\n writePreparedState(s);\n}\n\n/**\n * Compute the CURRENT build-context fingerprint for the e2b base template\n * (the SHA over every file `prepare` would copy into the Template build).\n * Side-effect-free — never builds. Returns `undefined` when the runtime\n * assets can't be resolved (dev tree without `pnpm -w build`) so the CLI\n * can degrade to \"can't tell, don't nag\" rather than flag a false stale.\n *\n * Used by `evaluateBaseFreshness` to compare against the stored value in\n * `e2b-prepared.json.base.contextSha256`. Must produce a byte-identical\n * hash to the one `prepare` writes — both go through the same\n * `resolveRuntimeAssets` + `computeContextSha256` chain.\n */\nexport async function currentE2bBaseFingerprintLive(\n claudeInstall: 'native' | 'npm' = 'native',\n): Promise<string | undefined> {\n try {\n const assets = resolveRuntimeAssets({ cliRuntimeRoot: findStagedCliRuntimeRoot() });\n // Fold in claudeInstall exactly as `prepare` does — otherwise an npm-baked\n // base never matches the stored (npm-folded) fingerprint.\n return claudeInstallFingerprint(\n await computeContextSha256(assets.map((a) => ({ rel: a.name, abs: a.localPath }))),\n claudeInstall,\n );\n } catch {\n return undefined;\n }\n}\n\n/**\n * First-use gate. If no base template is recorded, throw an actionable error\n * pointing at `agentbox prepare --provider e2b`. Called by `backend.provision`\n * (so `create` / `claude` trip it but `prepare` itself does not — same shape\n * as the hetzner/vercel gates).\n */\nexport function ensureE2bBaseTemplate(): void {\n const state = readPreparedState();\n if (state.base !== undefined) return;\n throw new UserFacingError(\n 'no E2B base template found.\\n' +\n 'Run `agentbox prepare --provider e2b` first — it bakes a custom template ' +\n 'with the agentbox runtime (agentbox-ctl, vscode user, claude/codex/opencode, tmux) ' +\n 'so per-box `create` boots ready in seconds.',\n );\n}\n"],"mappings":";;;;;;;;;;;;;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5B,SAAO,CAAC;AACR,qBAAmB,CAAC;AACtB;AAcA,eAAsB,8BACpB,gBAAkC,UACL;AAC7B,MAAI;AACF,UAAM,SAAS,qBAAqB,EAAE,gBAAgB,yBAAyB,EAAE,CAAC;AAGlF,WAAO;MACL,MAAM,qBAAqB,OAAO,IAAI,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,EAAE,UAAU,EAAE,CAAC;MACjF;IACF;EACF,QAAQ;AACN,WAAO;EACT;AACF;AAQO,SAAS,wBAA8B;AAC5C,QAAM,QAAQ,kBAAkB;AAChC,MAAI,MAAM,SAAS,OAAW;AAC9B,QAAM,IAAI;IACR;EAIF;AACF;","names":["homedir","resolve","existsSync","resolve","resolve","homedir","existsSync"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-digitalocean/src/index.ts","../../../packages/sandbox-digitalocean/src/backend.ts","../../../packages/sandbox-digitalocean/src/cloud-init.ts","../../../packages/sandbox-digitalocean/src/poll.ts","../../../packages/sandbox-digitalocean/src/prepare.ts","../../../packages/sandbox-digitalocean/src/ssh-key.ts","../../../packages/sandbox-digitalocean/src/ssh-cli.ts","../../../packages/sandbox-digitalocean/src/ssh-tunnel.ts","../../../packages/sandbox-digitalocean/src/provider-module.ts"],"sourcesContent":["/**\n * The DigitalOcean Droplet sandbox provider. A thin `CloudBackend` over\n * OpenSSH + the DigitalOcean API v2, composed via `@agentbox/sandbox-cloud`'s\n * `createCloudProvider` for the provider-agnostic scaffolding (workspace\n * seeding, ctl launch, state, relay polling, VNC, checkpoints).\n */\n\nimport type { Provider } from '@agentbox/core';\nimport type { ProviderModule } from '@agentbox/sandbox-core';\nimport { createCloudProvider } from '@agentbox/sandbox-cloud';\nimport { digitaloceanBackend, DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { prepareDigitalOceanProvider } from './prepare.js';\nimport { currentDigitalOceanBaseFingerprintLive } from './prepared-state.js';\nimport { ensureDigitalOceanCredentials, setDigitalOceanCredentials } from './credentials.js';\nimport { doctorChecks, readCredStatusSummary } from './provider-module.js';\n\nconst cloudProvider = createCloudProvider(digitaloceanBackend, {\n // s-2vcpu-4gb = 2 vCPU / 4 GB / 80 GB SSD.\n defaultResources: { cpu: 2, memory: 4, disk: 80 },\n});\n\nexport const digitaloceanProvider: Provider = {\n ...cloudProvider,\n prepare: prepareDigitalOceanProvider,\n baseFingerprint: () => currentDigitalOceanBaseFingerprintLive(),\n};\n\n/** Uniform surface the CLI provider loader resolves this package through. */\nexport const providerModule: ProviderModule = {\n provider: digitaloceanProvider,\n backend: digitaloceanBackend,\n ensureCredentials: ensureDigitalOceanCredentials,\n readCredStatus: readCredStatusSummary,\n setCredentials: setDigitalOceanCredentials,\n currentBaseFingerprintLive: (claudeInstall) => currentDigitalOceanBaseFingerprintLive(claudeInstall),\n doctorChecks,\n};\n\nexport { digitaloceanBackend, DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF };\nexport { ensureDigitalOceanEnvLoaded } from './env-loader.js';\nexport {\n ensureDigitalOceanCredentials,\n setDigitalOceanCredentials,\n readDigitalOceanCredStatus,\n secretsPath,\n maskKey,\n type EnsureDigitalOceanCredentialsOptions,\n type DigitalOceanCredStatus,\n} from './credentials.js';\nexport {\n ensureDigitalOceanBaseSnapshot,\n prepareDigitalOcean,\n prepareDigitalOceanProvider,\n type PrepareDigitalOceanOptions,\n type PrepareDigitalOceanResult,\n} from './prepare.js';\nexport { generateBoxCloudInit, generatePrepareCloudInit, type BoxCloudInitOptions, type PrepareCloudInitOptions } from './cloud-init.js';\nexport {\n RUNTIME_ASSETS,\n candidatesFor,\n resolveRuntimeAssets,\n type ResolvedAsset,\n type RuntimeAsset,\n} from './runtime-assets.js';\nexport { mintPrepareKey, mintSshKey, type MintedSshKey } from './ssh-key.js';\nexport {\n scpDownload,\n scpUpload,\n sshExec,\n sshOptArgs,\n waitForSsh,\n type SshExecOptions,\n type SshExecResult,\n type SshTargetArgs,\n} from './ssh-cli.js';\nexport { pollUntil, type PollOptions } from './poll.js';\nexport {\n currentDigitalOceanBaseFingerprintLive,\n preparedStatePath,\n readPreparedState,\n writePreparedState,\n updatePreparedState,\n type PreparedBaseSnapshot,\n type PreparedDigitalOceanState,\n} from './prepared-state.js';\nexport {\n makeDigitalOceanClient,\n DigitalOceanApiError,\n DEFAULT_DO_ENDPOINT,\n type CreateDropletRequest,\n type CreateFirewallRequest,\n type DigitalOceanAccount,\n type DigitalOceanAction,\n type DigitalOceanClient,\n type DigitalOceanDroplet,\n type DigitalOceanDropletStatus,\n type DigitalOceanFirewall,\n type DigitalOceanInboundRule,\n type DigitalOceanOutboundRule,\n type DigitalOceanProject,\n type DigitalOceanSize,\n type DigitalOceanSnapshot,\n} from './client.js';\nexport {\n validateSizeChoice,\n resolveProjectChoice,\n mapDigitalOceanProvisionError,\n type SizeChoice,\n} from './preflight.js';\nexport { detectEgressIp, type DetectEgressIpOptions } from './egress-ip.js';\nexport {\n allowAllOutboundRules,\n createPerBoxFirewall,\n deletePerBoxFirewall,\n findFirewallForDroplet,\n normalizeSourceCidr,\n sshInboundRules,\n syncFirewallSource,\n type CreateFirewallOptions,\n} from './firewall.js';\nexport { withDigitalOceanRetry, isAttemptTimeout, isRetriable } from './retry.js';\n","/**\n * DigitalOcean `CloudBackend` — maps the provider-neutral cloud primitives\n * onto OpenSSH + the DigitalOcean API v2. Mirrors the Hetzner backend; the\n * shape is identical (1 Droplet per box, SSH ControlMaster for all I/O,\n * per-box Cloud Firewall locked to the host egress IP, snapshot-based\n * checkpoints). The DigitalOcean-specific wrinkles:\n *\n * - `createDroplet` returns no IP — the droplet boots over ~30-60s, so we\n * poll `getDroplet` until status `active` + a public IPv4 appears.\n * - Droplet mutations (power_on/off, snapshot) return an *action id* that\n * must be polled via `getAction` until `completed`.\n * - The Cloud Firewall is created *before* the droplet and attached via a\n * unique per-box tag, so DigitalOcean auto-applies it at boot. The\n * firewall id is a UUID string, discovered at destroy/sync time by tag.\n */\n\nimport { existsSync } from 'node:fs';\nimport { rm, rename, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { execa } from 'execa';\nimport { resolve as resolvePath } from 'node:path';\nimport type {\n CloudBackend,\n CloudExecResult,\n CloudFileEntry,\n CloudHandle,\n CloudPreviewUrl,\n CloudProvisionRequest,\n CloudSandboxSummary,\n CloudState,\n} from '@agentbox/core';\nimport { generateBoxCloudInit } from './cloud-init.js';\nimport {\n DigitalOceanApiError,\n makeDigitalOceanClient,\n type DigitalOceanClient,\n type DigitalOceanDroplet,\n type DigitalOceanDropletStatus,\n} from './client.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport {\n createPerBoxFirewall,\n deletePerBoxFirewall,\n findFirewallForDroplet,\n normalizeSourceCidr,\n syncFirewallSource,\n} from './firewall.js';\nimport { pollUntil } from './poll.js';\nimport {\n mapDigitalOceanProvisionError,\n resolveProjectChoice,\n validateSizeChoice,\n} from './preflight.js';\nimport { readPreparedState } from './prepared-state.js';\nimport { ensureDigitalOceanBaseSnapshot } from './prepare.js';\nimport { mintSshKey } from './ssh-key.js';\nimport { describeInbound, parseInboundSpec, resolveInboundSources } from '@agentbox/sandbox-core';\nimport type { InboundPolicy } from '@agentbox/core';\nimport { waitForSsh, sshOptArgs, type SshTargetArgs } from './ssh-cli.js';\nimport { SshTunnelManager, defaultBoxSshDir } from './ssh-tunnel.js';\nimport { withDigitalOceanRetry } from './retry.js';\n\nexport const DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF = 'agentbox-base';\n\n/**\n * The cloud-provider scaffolding defaults `req.image` to `'agentbox/box:dev'`\n * (the docker provider's local image tag) when nothing else is specified.\n * That value is meaningless on DigitalOcean — we recognize it (alongside our\n * own sentinel + plain undefined) as \"use the digitalocean base snapshot.\"\n */\nconst SCAFFOLDING_FALLBACK_IMAGE = 'agentbox/box:dev';\nconst VPS_USER = 'vscode';\nconst PROVISION_SSH_DEADLINE_MS = 10 * 60_000;\nconst PROVISION_DROPLET_DEADLINE_MS = 5 * 60_000;\nconst ACTION_DEADLINE_MS = 5 * 60_000;\nconst SNAPSHOT_DEADLINE_MS = 30 * 60_000;\n// s-2vcpu-4gb: 2 vCPU / 4 GB / 80 GB SSD — the closest match to Hetzner's\n// cx23 default. nyc3 is a broadly-available US region.\nconst DIGITALOCEAN_DEFAULT_SIZE = 's-2vcpu-4gb';\nconst DIGITALOCEAN_DEFAULT_REGION = 'nyc3';\n\n/**\n * Secrets that must never land in the world-readable (0644) cloud-init\n * `/etc/agentbox/box.env`. The relay token reaches in-box ctl via the daemon's\n * 0600 `relay.env` (written by the bootstrap exec that carries these in its\n * process env); the bridge token stays in the daemon's process env. Mirrors the\n * Hetzner backend.\n */\nconst CLOUD_INIT_BOX_ENV_EXCLUDE = new Set<string>([\n 'AGENTBOX_RELAY_URL',\n 'AGENTBOX_RELAY_TOKEN',\n 'AGENTBOX_BRIDGE_TOKEN',\n]);\n\n/**\n * Build the cloud-init `box.env` passthrough: the `AGENTBOX_*` identity/portless\n * vars, with the relay/bridge secrets in `CLOUD_INIT_BOX_ENV_EXCLUDE` stripped\n * (cloud-init writes box.env 0644 — those secrets travel via the daemon's 0600\n * `relay.env` / process env instead). Exported for unit testing.\n */\nexport function cloudInitBoxEnv(\n env: Record<string, string | undefined> = {},\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(env)) {\n if (v !== undefined && k.startsWith('AGENTBOX_') && !CLOUD_INIT_BOX_ENV_EXCLUDE.has(k)) {\n out[k] = v;\n }\n }\n return out;\n}\n\n/** Module-level tunnel manager — one ControlMaster per box for this process. */\nconst tunnels = new SshTunnelManager();\n\n/**\n * Map a DigitalOcean droplet status onto the four-value `CloudState` everyone\n * else consumes. `new` (provisioning) reports as 'running' so callers don't\n * ping-pong; 'off' maps to 'paused' (DigitalOcean stop = power off, vs\n * Daytona's archive); 'archive' is a rare locked state we surface as paused.\n */\nfunction mapState(s: DigitalOceanDropletStatus | string | undefined): CloudState {\n switch (s) {\n case 'active':\n case 'new':\n return 'running';\n case 'off':\n case 'archive':\n return 'paused';\n default:\n return 'missing';\n }\n}\n\nfunction client(): DigitalOceanClient {\n return makeDigitalOceanClient();\n}\n\n/** Extract the droplet's public IPv4 address, if assigned yet. */\nfunction publicIpv4(droplet: DigitalOceanDroplet): string | undefined {\n return droplet.networks.v4.find((n) => n.type === 'public')?.ip_address;\n}\n\nasync function getDropletStrict(id: number): Promise<DigitalOceanDroplet> {\n const d = await client().getDroplet(id);\n if (!d) {\n throw new Error(`digitalocean: droplet ${String(id)} not found (already destroyed?)`);\n }\n return d;\n}\n\n/** Sanitize a box name into a DigitalOcean tag fragment (alnum / dash / underscore). */\nfunction sanitizeTag(name: string): string {\n return name.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 200);\n}\n\n/**\n * Poll a DigitalOcean action id until it reaches `completed`. Throws if the\n * action ends `errored` or the deadline elapses.\n */\nasync function waitAction(\n c: DigitalOceanClient,\n actionId: number,\n label: string,\n deadlineMs: number,\n): Promise<void> {\n await pollUntil(\n label,\n async () => {\n const a = await c.getAction(actionId);\n if (!a) return null;\n if (a.status === 'errored') {\n throw new Error(`digitalocean: action ${String(actionId)} (${label}) errored`);\n }\n return a.status === 'completed' ? a : null;\n },\n { deadlineMs, intervalMs: 2_000, maxIntervalMs: 8_000 },\n );\n}\n\n/**\n * Resolve a `CloudProvisionRequest.image|snapshot` into a DigitalOcean image\n * ref. Precedence: `req.snapshot` → `req.image`:\n * - the sentinel `agentbox-base` (or the scaffolding fallback / undefined)\n * → load the snapshot id from `digitalocean-prepared.json`.\n * - a numeric string → use as a snapshot/image id.\n * - any other string → treated as a snapshot name (checkpoint) and looked\n * up via the API; falls through to a DigitalOcean stock image slug.\n */\nasync function resolveImageRef(c: DigitalOceanClient, req: CloudProvisionRequest): Promise<number | string> {\n const ref = req.snapshot ?? req.image;\n if (!ref || ref === DIGITALOCEAN_DEFAULT_BOX_IMAGE_REF || ref === SCAFFOLDING_FALLBACK_IMAGE) {\n await ensureDigitalOceanBaseSnapshot();\n const state = readPreparedState();\n if (!state.base) {\n throw new Error(\n 'no DigitalOcean base snapshot found — run `agentbox prepare --provider digitalocean` to bake one.',\n );\n }\n return state.base.imageId;\n }\n if (/^\\d+$/.test(ref)) {\n return Number.parseInt(ref, 10);\n }\n // Try snapshot-by-name first (checkpoints use that), then fall through to a\n // DigitalOcean stock image slug (the user passed e.g. `ubuntu-24-04-x64`).\n const snap = (await c.listSnapshots()).find((s) => s.name === ref);\n if (snap) return Number.parseInt(snap.id, 10);\n return ref;\n}\n\n/**\n * Per-box state we need across method calls. Lives on disk under\n * `~/.agentbox/digitalocean/boxes/<sandboxId>/` and is the source of truth\n * for the SSH identity.\n */\ninterface PerBoxState {\n dir: string;\n identity: string;\n knownHosts: string;\n}\n\nfunction perBoxDir(sandboxId: string): string {\n return resolvePath(defaultBoxSshDir(sandboxId), '..');\n}\n\nasync function ensurePerBoxState(sandboxId: string): Promise<PerBoxState> {\n const dir = perBoxDir(sandboxId);\n const sshDir = join(dir, 'ssh');\n await mkdir(sshDir, { recursive: true, mode: 0o700 });\n return {\n dir,\n identity: join(sshDir, 'id_ed25519'),\n knownHosts: join(sshDir, 'known_hosts'),\n };\n}\n\nfunction bashScript(s: string): string {\n // Always run remote commands under bash -lc so /etc/profile.d/agentbox.sh\n // (and the PATH prepend / DISPLAY / AGENT_BROWSER_* it sets) get sourced.\n return `bash -lc ${shellQuote(s)}`;\n}\n\nfunction shellQuote(s: string): string {\n return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\nfunction buildSshTarget(state: PerBoxState, vpsIp: string, controlPath?: string): SshTargetArgs {\n return {\n host: vpsIp,\n user: VPS_USER,\n identity: state.identity,\n knownHosts: state.knownHosts,\n controlPath,\n };\n}\n\nasync function ensureTunnel(sandboxId: string, state: PerBoxState, vpsIp: string): Promise<void> {\n if (tunnels.has(sandboxId)) return;\n await tunnels.open({\n boxId: sandboxId,\n vpsHost: vpsIp,\n identity: state.identity,\n });\n}\n\n/**\n * Open the ControlMaster (if not already up) and return an SshTargetArgs\n * whose `controlPath` is set to the live master so exec/scp reuse it.\n */\nasync function ensureLiveTarget(sandboxId: string): Promise<{\n target: SshTargetArgs;\n state: PerBoxState;\n vpsIp: string;\n}> {\n const id = Number.parseInt(sandboxId, 10);\n if (!Number.isFinite(id)) {\n throw new Error(`digitalocean: invalid sandboxId ${sandboxId}`);\n }\n const droplet = await getDropletStrict(id);\n const vpsIp = publicIpv4(droplet);\n if (!vpsIp) {\n throw new Error(`digitalocean: droplet ${String(id)} has no public IPv4 address`);\n }\n const state = await ensurePerBoxState(sandboxId);\n if (!existsSync(state.identity)) {\n throw new Error(\n `digitalocean: per-box SSH key missing for sandbox ${sandboxId} (expected at ${state.identity}). ` +\n `If this box was created by a different host, you'll need to re-create it on this host.`,\n );\n }\n await ensureTunnel(sandboxId, state, vpsIp);\n const controlPath = tunnels.controlPath(sandboxId);\n return { target: buildSshTarget(state, vpsIp, controlPath), state, vpsIp };\n}\n\nexport const digitaloceanBackend: CloudBackend = {\n name: 'digitalocean',\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n const c = client();\n const onLog = req.onLog ?? (() => {});\n const progress = (s: string) => onLog(`digitalocean: ${s}`);\n\n // 1. Gate on the base snapshot existing + resolve the image ref.\n await ensureDigitalOceanBaseSnapshot();\n const imageRef = await resolveImageRef(c, req);\n\n // 1b. Preflight the size + region choice against the live catalog BEFORE\n // creating any billable resources (firewall, SSH key, droplet). A bad\n // `--size s-99vcpu` / `--location atlantis` fails fast here with a clear\n // message instead of a late, opaque API error after cleanup churn.\n const size = (req.size && req.size.trim()) || DIGITALOCEAN_DEFAULT_SIZE;\n const region =\n (req.location && req.location.trim()) ||\n req.env?.AGENTBOX_DIGITALOCEAN_REGION ||\n process.env.AGENTBOX_DIGITALOCEAN_REGION ||\n DIGITALOCEAN_DEFAULT_REGION;\n const choice = { size, region };\n // The base snapshot's min_disk_size gates the min plan disk. We only have it\n // for numeric snapshot refs; stock string refs (e.g. `ubuntu-24-04-x64`)\n // skip the disk check (snapshot null).\n const snapshotMeta =\n typeof imageRef === 'number' ? await c.getSnapshot(String(imageRef)) : null;\n const sizeCatalog = await c.listSizes();\n validateSizeChoice(choice, sizeCatalog, snapshotMeta);\n const plan = sizeCatalog.find((s) => s.slug === size);\n\n // The DO Project the box should land in (`box.digitaloceanProject`),\n // resolved from a name-or-id to an id here. This has to be a *preflight* check:\n // DigitalOcean has no project field on droplet-create, so the assignment can\n // only run once the Droplet exists — far too late to tell someone they typed\n // the project name wrong. Unset (the common case) costs no API call.\n const projectWanted = (req.project ?? '').trim();\n let projectId: string | null = null;\n if (projectWanted.length > 0) {\n projectId = resolveProjectChoice(projectWanted, await c.listProjects());\n }\n\n // 2. Resolve the inbound-access policy (`--inbound` / `box.inbound`) into\n // the firewall's source CIDRs. `locked`/`whitelist` need the host egress IP\n // (env override wins, else detect); `open` (0.0.0.0/0) skips detection.\n const inboundPolicy = parseInboundSpec(req.inbound);\n const egressOverride =\n req.env?.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE ?? process.env.AGENTBOX_DIGITALOCEAN_FIREWALL_SOURCE;\n const hostEgress =\n inboundPolicy.mode === 'open'\n ? null\n : egressOverride\n ? normalizeSourceCidr(egressOverride)\n : `${await detectEgressIp({ onLog })}/32`;\n const sources = resolveInboundSources(inboundPolicy, hostEgress);\n progress(`firewall inbound: ${describeInbound(inboundPolicy)} -> ${sources.join(', ')}`);\n\n // 3. Mint per-box SSH key into a temp dir keyed by a fresh stamp; we\n // rename it into the sandboxId-keyed dir once the droplet id is known.\n const stamp = Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);\n const tempDir = resolvePath(\n process.env.HOME ?? process.cwd(),\n '.agentbox',\n 'digitalocean',\n `pending-${stamp}`,\n 'ssh',\n );\n const key = await mintSshKey(tempDir, `agentbox-box-${req.name}-${stamp}`);\n const boxTag = `agentbox-${sanitizeTag(req.name)}-${stamp}`;\n\n let firewallId: string | null = null;\n let dropletId: number | null = null;\n try {\n // 4. Firewall — created with the per-box tag BEFORE the droplet, so\n // DigitalOcean auto-applies it the moment the droplet boots.\n const firewall = await createPerBoxFirewall(c, {\n name: `agentbox-${sanitizeTag(req.name)}-${stamp}`,\n sources,\n tag: boxTag,\n });\n firewallId = firewall.id;\n\n // 5. Cloud-init for the box: vscode user, pubkey, /etc/hosts alias,\n // optional box.env passthrough from req.env. The relay/bridge secrets are\n // stripped here (cloud-init writes box.env 0644) and reach the in-box ctl\n // via the daemon's 0600 relay.env / process env instead.\n const boxEnv = cloudInitBoxEnv(req.env);\n const cloudInit = generateBoxCloudInit({\n sshPubkey: key.publicKey,\n boxName: req.name,\n boxEnv: Object.keys(boxEnv).length > 0 ? boxEnv : undefined,\n });\n\n // 6. Create the droplet (tagged so the firewall applies). Map late DO\n // provision errors (droplet limit, out-of-capacity) to actionable\n // guidance while preserving the original.\n progress(`creating droplet '${req.name}' from image ${String(imageRef)} (${size} / ${region})`);\n let created;\n try {\n created = await withDigitalOceanRetry(\n { method: 'createDroplet', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () =>\n c.createDroplet({\n name: `agentbox-${sanitizeTag(req.name)}-${stamp}`,\n region,\n size,\n image: imageRef,\n user_data: cloudInit,\n tags: [boxTag, 'agentbox'],\n ipv6: false,\n }),\n );\n } catch (createErr) {\n throw mapDigitalOceanProvisionError(createErr, choice);\n }\n dropletId = created.droplet.id;\n progress(`droplet ${String(dropletId)} created; waiting for it to boot`);\n\n // 6b. Place the droplet in its DO Project. DigitalOcean has no project field\n // on droplet-create, so this can only happen now — which means it can fail on\n // a droplet that is otherwise perfectly good. Best-effort by design: a box\n // that works but sits in the wrong project is a cosmetic/billing annoyance,\n // whereas throwing here would hit the catch below and tear the whole box down.\n // The project *name* was already validated in the preflight, so anything that\n // fails here is a live API problem, not a typo.\n if (projectId !== null) {\n try {\n await c.assignProjectResources(projectId, [`do:droplet:${String(dropletId)}`]);\n progress(`droplet ${String(dropletId)} assigned to project ${projectWanted}`);\n } catch (assignErr) {\n onLog(\n `digitalocean: WARN — could not assign droplet ${String(dropletId)} to project ` +\n `${projectWanted} (continuing; it stays in the account's default project): ` +\n `${assignErr instanceof Error ? assignErr.message : String(assignErr)}`,\n );\n }\n }\n\n // 7. Poll until the droplet is active AND has a public IPv4 (DigitalOcean\n // returns neither at create time).\n const droplet = await pollUntil(\n `droplet ${String(dropletId)} active`,\n async () => {\n const d = await c.getDroplet(dropletId as number);\n return d && d.status === 'active' && publicIpv4(d) ? d : null;\n },\n { deadlineMs: PROVISION_DROPLET_DEADLINE_MS, intervalMs: 3_000, maxIntervalMs: 10_000 },\n );\n const vpsIp = publicIpv4(droplet);\n if (!vpsIp) {\n throw new Error(`digitalocean: droplet ${String(dropletId)} came up without a public IPv4`);\n }\n progress(`droplet ${String(dropletId)} at ${vpsIp}; waiting for ssh`);\n\n // 8. Move the freshly-minted key into the sandboxId-keyed final dir.\n const sandboxId = String(dropletId);\n const state = await ensurePerBoxState(sandboxId);\n await rename(key.privatePath, state.identity);\n await rename(key.publicPath, `${state.identity}.pub`);\n await rm(key.dir, { recursive: true, force: true });\n const pendingParent = resolvePath(key.dir, '..');\n await rm(pendingParent, { recursive: true, force: true });\n\n // 9. Wait for sshd to accept the new key.\n const up = await waitForSsh(buildSshTarget(state, vpsIp), PROVISION_SSH_DEADLINE_MS);\n if (!up) {\n throw new Error(\n `digitalocean: ssh on ${vpsIp} did not come up within ${String(PROVISION_SSH_DEADLINE_MS / 1000)}s; ` +\n `the droplet has been deleted. This is usually transient — just retry the create. ` +\n `If it keeps failing, check that your host's egress IP is stable (the box firewall is ` +\n `locked to it, so a mid-provision IP change blocks ssh).`,\n );\n }\n\n // 10. Open ControlMaster.\n await ensureTunnel(sandboxId, state, vpsIp);\n progress('ssh up; ControlMaster open');\n\n // Report the real resources for the chosen plan (DO reports memory in MB;\n // the cloud scaffold's `provisioned …` log line + the box record read\n // these). `plan` is present whenever the size validated against the\n // catalog above.\n return plan\n ? {\n sandboxId,\n inbound: inboundPolicy,\n resources: {\n cpu: plan.vcpus,\n memory: Math.round(plan.memory / 1024),\n disk: plan.disk,\n },\n }\n : { sandboxId, inbound: inboundPolicy };\n } catch (err) {\n // Cleanup on failure: droplet + firewall + temp ssh dir.\n if (dropletId !== null) {\n progress(`cleanup — deleting droplet ${String(dropletId)} after provision failure`);\n try {\n await c.deleteDroplet(dropletId);\n } catch (cleanupErr) {\n onLog(\n `digitalocean: WARN — failed to delete droplet ${String(dropletId)}; check the DigitalOcean dashboard. ${\n cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)\n }`,\n );\n }\n }\n if (firewallId !== null) {\n try {\n await deletePerBoxFirewall(c, firewallId, { tags: [boxTag] });\n } catch {\n // best-effort\n }\n }\n try {\n if (existsSync(key.dir)) await rm(key.dir, { recursive: true, force: true });\n if (dropletId !== null) {\n const finalDir = perBoxDir(String(dropletId));\n if (existsSync(finalDir)) await rm(finalDir, { recursive: true, force: true });\n }\n } catch {\n // best-effort\n }\n throw err;\n }\n },\n\n async get(sandboxId: string): Promise<CloudHandle | null> {\n const id = Number.parseInt(sandboxId, 10);\n if (!Number.isFinite(id)) return null;\n const droplet = await client().getDroplet(id);\n return droplet ? { sandboxId } : null;\n },\n\n async list(): Promise<CloudSandboxSummary[]> {\n const droplets = await client().listDroplets({ tag_name: 'agentbox' });\n return droplets.map((d) => ({\n sandboxId: String(d.id),\n name: d.name,\n createdAt: d.created_at,\n state: mapState(d.status),\n }));\n },\n\n async start(h: CloudHandle): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n const c = client();\n const action = await c.powerOn(id);\n await waitAction(c, action.id, `droplet ${h.sandboxId} power_on`, ACTION_DEADLINE_MS);\n // The action completing implies `active`, but sshd accepts connections a\n // little later — wait for it so the provider's relaunch exec doesn't hit\n // `Connection refused`. Mirrors the provision flow.\n const droplet = await pollUntil(\n `droplet ${h.sandboxId} active`,\n async () => {\n const d = await c.getDroplet(id);\n return d && d.status === 'active' && publicIpv4(d) ? d : null;\n },\n { deadlineMs: ACTION_DEADLINE_MS, intervalMs: 2_000, maxIntervalMs: 8_000 },\n );\n const vpsIp = publicIpv4(droplet);\n if (!vpsIp) {\n throw new Error(`digitalocean: droplet ${h.sandboxId} has no public IPv4 after start`);\n }\n const state = await ensurePerBoxState(h.sandboxId);\n const up = await waitForSsh(buildSshTarget(state, vpsIp), PROVISION_SSH_DEADLINE_MS);\n if (!up) {\n throw new Error(\n `digitalocean: ssh on ${vpsIp} did not come up within ${String(PROVISION_SSH_DEADLINE_MS / 1000)}s after start. ` +\n `This is usually transient — retry (\\`agentbox start\\` / \\`agentbox recover\\`). If it persists, check ` +\n `that your host's egress IP is stable (the box firewall is locked to it, so an IP change blocks ssh).`,\n );\n }\n },\n\n async stop(h: CloudHandle): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n const c = client();\n // Try graceful shutdown first; fall back to hard power-off on timeout.\n try {\n const action = await c.shutdown(id);\n await waitAction(c, action.id, `droplet ${h.sandboxId} shutdown`, 90_000);\n } catch {\n const action = await c.powerOff(id);\n await waitAction(c, action.id, `droplet ${h.sandboxId} power_off`, ACTION_DEADLINE_MS);\n }\n await tunnels.close(h.sandboxId);\n },\n\n async pause(h: CloudHandle): Promise<void> {\n // DigitalOcean has no archive primitive. Pause ≡ stop (power off).\n await this.stop(h);\n },\n\n async resume(h: CloudHandle): Promise<void> {\n await this.start(h);\n },\n\n async setInbound(h: CloudHandle, policy: InboundPolicy): Promise<{ sources: string[] }> {\n // Apply an inbound-access policy to the box's firewall (`agentbox inbound`).\n // `locked`/`whitelist` re-detect the host egress; `open` skips it.\n const c = client();\n const id = Number.parseInt(h.sandboxId, 10);\n const droplet = await getDropletStrict(id);\n const fw = await findFirewallForDroplet(c, id, droplet.tags ?? []);\n if (!fw) {\n throw new Error(`digitalocean: no per-box firewall found for droplet ${h.sandboxId}`);\n }\n const hostEgress = policy.mode === 'open' ? null : `${await detectEgressIp({})}/32`;\n const sources = resolveInboundSources(policy, hostEgress);\n await syncFirewallSource(c, fw, sources);\n return { sources };\n },\n\n async repairReachability(h: CloudHandle): Promise<{ changed: boolean; detail?: string }> {\n // Self-heal on a connection-establishment failure: if the host's CURRENT\n // egress IP isn't in the firewall's SSH sources (host moved networks),\n // re-sync — merging the stored whitelist so we don't narrow an open/\n // whitelisted box. `open` firewalls are already reachable → no-op.\n const c = client();\n const id = Number.parseInt(h.sandboxId, 10);\n const droplet = await c.getDroplet(id).catch(() => null);\n if (!droplet) return { changed: false };\n const policy: InboundPolicy = h.inbound ?? { mode: 'locked', sources: [] };\n if (policy.mode === 'open') return { changed: false };\n const fw = await findFirewallForDroplet(c, id, droplet.tags ?? []).catch(() => null);\n if (!fw) return { changed: false };\n const allowed = fw.inbound_rules.find((r) => r.ports === '22')?.sources.addresses ?? [];\n if (allowed.includes('0.0.0.0/0')) return { changed: false };\n const currentEgress = `${await detectEgressIp({})}/32`;\n if (allowed.includes(currentEgress)) return { changed: false };\n const sources = resolveInboundSources(policy, currentEgress);\n await syncFirewallSource(c, fw, sources);\n return {\n changed: true,\n detail: `firewall updated: SSH now allowed from ${sources.join(', ')} (was ${allowed.join(', ') || '(no rule)'})`,\n };\n },\n\n async destroy(h: CloudHandle): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n await tunnels.close(h.sandboxId);\n const c = client();\n // Discover the per-box firewall via the droplet's tags BEFORE we delete\n // the droplet (after deletion the droplet_ids match is gone).\n let firewallId: string | undefined;\n let firewallTags: readonly string[] | undefined;\n try {\n const droplet = await c.getDroplet(id);\n if (droplet) {\n const fw = await findFirewallForDroplet(c, id, droplet.tags);\n firewallId = fw?.id;\n // The firewall carries only the unique per-box tag (never the shared\n // `agentbox` tag), so this is the safe set to delete alongside it.\n firewallTags = fw?.tags;\n }\n } catch {\n // ignore — we'll still try to delete the droplet\n }\n try {\n await c.deleteDroplet(id);\n } catch (err) {\n if (!(err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === 'not_found'))) {\n throw err;\n }\n }\n if (firewallId) {\n await deletePerBoxFirewall(c, firewallId, { tags: firewallTags });\n }\n const dir = perBoxDir(h.sandboxId);\n try {\n await rm(dir, { recursive: true, force: true });\n } catch {\n // best-effort\n }\n },\n\n async state(h: CloudHandle): Promise<CloudState> {\n const id = Number.parseInt(h.sandboxId, 10);\n const d = await client().getDroplet(id);\n return d ? mapState(d.status) : 'missing';\n },\n\n async exec(h, cmd, opts): Promise<CloudExecResult> {\n const { target } = await ensureLiveTarget(h.sandboxId);\n const argv = [\n ...sshOptArgs(target),\n `${target.user}@${target.host}`,\n bashScript(opts?.cwd ? `cd ${shellQuote(opts.cwd)} && ${cmd}` : cmd),\n ];\n const res = await execa('ssh', argv, {\n reject: false,\n timeout: opts?.attemptTimeoutMs ?? 120_000,\n env: { ...process.env, ...(opts?.env ?? {}) },\n });\n return {\n exitCode: typeof res.exitCode === 'number' ? res.exitCode : 1,\n stdout: typeof res.stdout === 'string' ? res.stdout : '',\n stderr: typeof res.stderr === 'string' ? res.stderr : '',\n };\n },\n\n async uploadFile(h, localPath, remotePath): Promise<void> {\n const { target } = await ensureLiveTarget(h.sandboxId);\n const argv = [...sshOptArgs(target), localPath, `${target.user}@${target.host}:${remotePath}`];\n const res = await execa('scp', argv, { reject: false, timeout: 300_000 });\n if (res.exitCode !== 0) {\n throw new Error(`digitalocean: scp upload failed (exit ${String(res.exitCode)}): ${res.stderr || ''}`);\n }\n },\n\n async downloadFile(h, remotePath, localPath): Promise<void> {\n const { target } = await ensureLiveTarget(h.sandboxId);\n const argv = [...sshOptArgs(target), `${target.user}@${target.host}:${remotePath}`, localPath];\n const res = await execa('scp', argv, { reject: false, timeout: 300_000 });\n if (res.exitCode !== 0) {\n throw new Error(`digitalocean: scp download failed (exit ${String(res.exitCode)}): ${res.stderr || ''}`);\n }\n },\n\n async listFiles(h, remoteDir): Promise<CloudFileEntry[]> {\n const res = await this.exec(\n h,\n `find ${shellQuote(remoteDir)} -mindepth 1 -maxdepth 1 -printf '%f\\\\t%y\\\\n'`,\n );\n if (res.exitCode !== 0) return [];\n return res.stdout\n .split(/\\r?\\n/)\n .filter((line) => line.length > 0)\n .map((line) => {\n const [name, kind] = line.split('\\t');\n return { name: name ?? line, isDir: kind === 'd' };\n });\n },\n\n async previewUrl(h, port): Promise<CloudPreviewUrl> {\n await ensureLiveTarget(h.sandboxId);\n const localPort = await tunnels.forward(h.sandboxId, port);\n // Plain loopback URL — the SSH local forward is already auth-gated by the\n // tunnel. The cloud-provider layer adds the Portless alias.\n return { url: `http://127.0.0.1:${String(localPort)}` };\n },\n\n async signedPreviewUrl(h, port, _ttl): Promise<CloudPreviewUrl> {\n void _ttl;\n return this.previewUrl(h, port);\n },\n\n async refreshPreviewUrl(h, port): Promise<CloudPreviewUrl> {\n // Tear down the (likely dead) ControlMaster + cached `-L` forwards and\n // re-open from scratch. Called by the host poller after ECONNREFUSED on\n // the local port (host sleep/wake, network blip).\n const { state, vpsIp } = await ensureLiveTarget(h.sandboxId);\n await tunnels.refresh({\n boxId: h.sandboxId,\n vpsHost: vpsIp,\n identity: state.identity,\n });\n const localPort = await tunnels.forward(h.sandboxId, port);\n return { url: `http://127.0.0.1:${String(localPort)}` };\n },\n\n async startInBoxPortless(h, opts): Promise<void> {\n // Bring up a `portless` proxy inside the droplet mirroring the host's mode\n // so `<boxName>.localhost:<P>` resolves identically on both sides. The\n // `portless` CLI is baked into the base snapshot by install-box.sh.\n // Idempotent + best-effort. Mirrors the Hetzner backend.\n const tlsFlag = opts.tls ? '' : '--no-tls';\n const startCmd = `sudo portless proxy start ${tlsFlag} -p ${String(opts.proxyPort)}`.replace(/\\s+/g, ' ');\n const aliasCmd = `sudo portless alias ${shellQuote(opts.boxName)} ${String(opts.webPort)}`;\n const cmds = [startCmd, aliasCmd];\n if (opts.tls) {\n cmds.push(\n 'sudo agentbox-portless-trust /root/.portless/ca.pem >/dev/null 2>&1 || true',\n `echo 'export NODE_EXTRA_CA_CERTS=/usr/local/share/ca-certificates/agentbox-portless-ca.crt' | sudo tee /etc/profile.d/agentbox-portless-ca.sh >/dev/null || true`,\n );\n }\n await this.exec(h, cmds.join('; '));\n },\n\n async attachArgv(h): Promise<string[]> {\n const { target } = await ensureLiveTarget(h.sandboxId);\n // Reuse the ControlMaster via `-S <sock>` — no new auth handshake. Callers\n // append `-t '<cmd>'` in the `buildAttach` helper.\n return ['ssh', ...sshOptArgs(target), `${target.user}@${target.host}`];\n },\n\n async createSnapshot(h, name): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n const c = client();\n const action = await withDigitalOceanRetry(\n { method: 'snapshotDroplet', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () => c.snapshotDroplet(id, name),\n );\n await waitAction(c, action.id, `droplet ${h.sandboxId} snapshot`, SNAPSHOT_DEADLINE_MS);\n },\n\n async deleteSnapshot(name): Promise<void> {\n const c = client();\n const snap = (await c.listSnapshots()).find((s) => s.name === name);\n if (!snap) return;\n try {\n await c.deleteSnapshot(snap.id);\n } catch (err) {\n if (err instanceof DigitalOceanApiError && (err.statusCode === 404 || err.code === 'not_found')) return;\n throw err;\n }\n },\n};\n\n/** Exposed for the CLI's `firewall sync` / `show` subcommands. */\nexport { tunnels as _digitaloceanTunnels };\n","/**\n * Cloud-init `#cloud-config` user-data generators.\n *\n * Two flavors:\n * - **prepare** (`generatePrepareCloudInit`): for the temporary VPS that\n * `prepareDigitalOcean()` boots to bake the base snapshot. Just injects a\n * `root` SSH key — the install script does everything else over ssh.\n * - **box** (`generateBoxCloudInit`): for per-box VPSes provisioned from\n * the base snapshot. Injects the per-box ssh pubkey for `vscode`,\n * optionally writes `/etc/hosts` aliases and `box.env`.\n *\n * The cloud-init format is documented at https://cloudinit.readthedocs.io.\n * We emit it as a small hand-rolled YAML doc — using a full yaml lib would\n * be overkill for the handful of fields we touch (and pulls in the same\n * `yaml` dep `sandbox-cloud` already has, but we keep this package's dep\n * surface minimal).\n */\n\nexport interface PrepareCloudInitOptions {\n /** ed25519/rsa public key string (one line, OpenSSH format). */\n sshPubkey: string;\n}\n\n/**\n * Cloud-init for the temporary prepare VPS. We log in as `root` here (it's a\n * throwaway VPS that lives ~10–15 min) and run `install-box.sh` over ssh.\n * The install script then creates the `vscode` user, installs everything,\n * and writes the sshd hardening drop-in that disables root login — which\n * doesn't take effect until we reload sshd at the end of the script (the\n * orchestrator finishes its scp/ssh dance before that point).\n */\nexport function generatePrepareCloudInit(opts: PrepareCloudInitOptions): string {\n const pubkey = opts.sshPubkey.trim();\n return [\n '#cloud-config',\n // IMPORTANT: keep every emitted line ASCII-only. DigitalOcean's user-data\n // delivery truncates the cloud-config at the first non-ASCII byte (an em-dash\n // here silently dropped the whole doc -> no key injected -> ssh publickey\n // denied). See generateBoxCloudInit for the same constraint.\n '# AgentBox temporary prepare VPS - used by `agentbox prepare --provider digitalocean`',\n '# to bake the base snapshot. SSH key is single-use and discarded on VPS destroy.',\n 'disable_root: false',\n 'ssh_pwauth: false',\n // Inject the single-use key as a TOP-LEVEL `ssh_authorized_keys` (applies to\n // the default user, which is `root` on DigitalOcean images). The `users:`\n // block form does NOT inject a key for root on DO's Ubuntu 24.04 (cloud-init\n // special-cases root under `disable_root`), so key auth failed with\n // \"Permission denied (publickey)\". The top-level form is reliable.\n 'ssh_authorized_keys:',\n ` - ${yamlScalar(pubkey)}`,\n // DigitalOcean's Ubuntu 24.04 stock image ships root's password force-expired\n // (last-change date = 0), so PAM demands a change on first login — which\n // blocks even key-authed non-TTY commands (\"Password change required but no\n // TTY available\"). `chpasswd.expire:false` covers cloud-init's own run; the\n // runcmd resets root's last-change date to TODAY (clearing the forced-change\n // that `chage -E/-I/-M` alone does NOT touch) and disables all expiry.\n 'chpasswd:',\n ' expire: false',\n 'runcmd:',\n ' - [ passwd, -d, root ]',\n ' - [ bash, -lc, \"chage -d $(date +%Y-%m-%d) -E -1 -I -1 -M 99999 -m 0 root\" ]',\n ' - [ bash, -lc, \"echo agentbox-prepare-ready\" ]',\n '',\n ].join('\\n');\n}\n\nexport interface BoxCloudInitOptions {\n /** ed25519/rsa public key string (one line, OpenSSH format). */\n sshPubkey: string;\n /**\n * Box name. Used to write a `<boxName>.localhost → 127.0.0.1` /etc/hosts\n * entry so non-browser in-box clients (curl, fetch in Node) can hit the\n * symmetric Portless URL the host browser sees.\n */\n boxName: string;\n /**\n * Lines for `/etc/agentbox/box.env` — set as `KEY=VALUE` pairs. Cloud-init\n * `write_files` writes them as-is; no shell escaping is applied because\n * the file is sourced via `set -a; . /etc/agentbox/box.env; set +a`.\n */\n boxEnv?: Record<string, string>;\n}\n\n/**\n * Cloud-init for per-box VPSes provisioned from the base snapshot. The\n * base snapshot already has the `vscode` user, sshd hardening, agentbox-ctl,\n * etc. — this just injects the per-box key and any per-box config.\n */\nexport function generateBoxCloudInit(opts: BoxCloudInitOptions): string {\n const pubkey = opts.sshPubkey.trim();\n const lines: string[] = [\n '#cloud-config',\n // ASCII-only (see generatePrepareCloudInit): DO truncates user-data at the\n // first non-ASCII byte, which would drop the whole cloud-config.\n `# AgentBox per-box VPS - box '${opts.boxName}'`,\n 'disable_root: true',\n 'ssh_pwauth: false',\n // Same first-login expiry guard as the prepare cloud-init — keeps\n // DigitalOcean's Ubuntu hardening from blocking our key-based vscode login.\n 'chpasswd:',\n ' expire: false',\n 'users:',\n ' - name: vscode',\n ' lock_passwd: false',\n ' sudo: ALL=(ALL) NOPASSWD:ALL',\n ' ssh_authorized_keys:',\n ` - ${yamlScalar(pubkey)}`,\n ];\n\n const writeFiles: string[] = [\n ' path: /etc/hosts',\n ' append: true',\n ` content: \"127.0.0.1 ${opts.boxName}.localhost\\\\n\"`,\n ];\n lines.push('write_files:');\n lines.push(' - ' + writeFiles[0]);\n for (let i = 1; i < writeFiles.length; i++) {\n lines.push(' ' + writeFiles[i]);\n }\n\n if (opts.boxEnv && Object.keys(opts.boxEnv).length > 0) {\n const envContent = Object.entries(opts.boxEnv)\n .map(([k, v]) => `${k}=${v}`)\n .join('\\\\n') + '\\\\n';\n lines.push(' - path: /etc/agentbox/box.env');\n lines.push(' permissions: \"0644\"');\n lines.push(` content: \"${envContent}\"`);\n }\n\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Quote a string as a YAML scalar. ssh pubkeys may contain spaces and `+`\n * characters; the safe move is to wrap in double quotes and escape `\"` /\n * `\\` if they appear (they don't for ed25519/rsa). Returns the value\n * already-quoted (so the caller embeds it after the `- ` prefix).\n */\nfunction yamlScalar(value: string): string {\n // No `\"` or `\\` in a valid OpenSSH pubkey, so a bare double-quote wrap is\n // safe; we still guard so a future caller doesn't surprise us.\n if (/[\"\\\\]/.test(value)) {\n return JSON.stringify(value);\n }\n return `\"${value}\"`;\n}\n","/**\n * Polling helpers — wait for a DigitalOcean Cloud resource to reach a desired\n * state. Reused across the prepare flow + Phase 4 backend lifecycle.\n *\n * Bounded by `deadlineMs`; intervals grow modestly (1s → 2s → 4s, capped)\n * so a fast-completing action is observed quickly without hammering the\n * API for slow ones.\n */\n\nexport interface PollOptions {\n deadlineMs?: number;\n /** Starting interval; doubles per attempt up to `maxIntervalMs`. */\n intervalMs?: number;\n maxIntervalMs?: number;\n /** Optional logger for each poll attempt — useful to stream progress. */\n onPoll?: (line: string) => void;\n}\n\n/**\n * Poll `check()` until it returns a non-null value or `deadlineMs` elapses.\n * Throws on timeout with the supplied `label` in the message.\n */\nexport async function pollUntil<T>(\n label: string,\n check: () => Promise<T | null | undefined>,\n opts: PollOptions = {},\n): Promise<T> {\n const deadline = Date.now() + (opts.deadlineMs ?? 5 * 60_000);\n const max = opts.maxIntervalMs ?? 10_000;\n let interval = opts.intervalMs ?? 1_000;\n let attempt = 0;\n while (true) {\n attempt += 1;\n const out = await check();\n if (out !== null && out !== undefined) return out;\n if (Date.now() >= deadline) {\n throw new Error(`digitalocean: timed out waiting for ${label} after ${String(attempt)} attempts`);\n }\n opts.onPoll?.(`${label}: not ready yet (attempt ${String(attempt)}); polling again in ${String(interval)}ms`);\n await new Promise((r) => setTimeout(r, interval));\n interval = Math.min(interval * 2, max);\n }\n}\n","/**\n * `agentbox prepare --provider digitalocean` — bake the per-account DigitalOcean\n * base snapshot. DigitalOcean (like Hetzner) cannot build an image from a\n * Dockerfile, so we boot a throwaway Droplet, run `install-box.sh` over ssh,\n * snapshot it, and record the snapshot id.\n *\n * Flow:\n * 1. Mint an ephemeral SSH keypair under ~/.agentbox/digitalocean/prepare-<ts>/.\n * 2. Detect the host's egress IP and create a firewall locked to it,\n * bound to a per-prepare tag.\n * 3. Create a temp Droplet (Ubuntu 24.04, `s-2vcpu-4gb` default) with\n * cloud-init injecting the pubkey for `root` + the prepare tag.\n * 4. Poll until the droplet is active + sshd comes up.\n * 5. scp the runtime assets into /tmp.\n * 6. Run `bash /tmp/agentbox-install.sh` over ssh; stream stdout to the\n * prepare log via `onLog`.\n * 7. `snapshot` action on the Droplet; poll the action until completed,\n * then resolve the snapshot id by name.\n * 8. Delete the Droplet + firewall.\n * 9. Persist the snapshot id into `~/.agentbox/digitalocean-prepared.json`.\n *\n * Failure-mode discipline: each major step is wrapped in try/catch so the\n * temp Droplet + firewall are *always* cleaned up on failure (the user must\n * never end up with a forgotten paid Droplet due to a prepare error).\n */\n\nimport { join } from 'node:path';\nimport type { Provider } from '@agentbox/core';\nimport { UserFacingError } from '@agentbox/core';\nimport { claudeInstallFingerprint, computeContextSha256, readCliStamp } from '@agentbox/sandbox-core';\nimport {\n stageClaudeStaticForUpload,\n stageCodexStaticForUpload,\n stageAgentsStaticForUpload,\n stageOpencodeStaticForUpload,\n type StageResult,\n} from '@agentbox/sandbox-cloud';\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport { ensureDigitalOceanCredentials } from './credentials.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport { createPerBoxFirewall, deletePerBoxFirewall, normalizeSourceCidr } from './firewall.js';\nimport { resolveProjectChoice } from './preflight.js';\nimport { makeDigitalOceanClient, type DigitalOceanClient } from './client.js';\nimport { generatePrepareCloudInit } from './cloud-init.js';\nimport { preparedStatePath, readPreparedState, writePreparedState } from './prepared-state.js';\nimport { pollUntil } from './poll.js';\nimport {\n findStagedCliRuntimeRoot,\n resolveRuntimeAssets,\n type ResolvedAsset,\n} from './runtime-assets.js';\nimport { mintPrepareKey } from './ssh-key.js';\nimport { scpUpload, sshExec, waitForSsh, type SshTargetArgs } from './ssh-cli.js';\n\nexport interface PrepareDigitalOceanOptions {\n name?: string;\n hostWorkspace?: string;\n /** Force re-bake even when `~/.agentbox/digitalocean-prepared.json` has a usable base. */\n force?: boolean;\n /** DigitalOcean region slug (defaults to `nyc3`). */\n region?: string;\n /** Droplet size slug (defaults to `s-2vcpu-4gb` — 2 vCPU / 4 GB / 80 GB). */\n size?: string;\n /**\n * DigitalOcean Project (name or id) for the temp bake Droplet. Defaults to\n * `box.digitaloceanProject`, so the bake doesn't show up in the account's\n * default project while every box lands somewhere else.\n */\n project?: string;\n /**\n * How the bake installs Claude Code: `native` (default) or `npm`. Threaded\n * into install-box.sh via `AGENTBOX_CLAUDE_INSTALL`. The `npm` escape hatch\n * is for cloud egress IPs whose CDN the native installer 403s. Bake-time\n * only; part of the context fingerprint (a change re-bakes).\n */\n claudeInstall?: 'native' | 'npm';\n /**\n * Override the firewall source CIDR. Defaults to auto-detected egress IP\n * via `detectEgressIp()` (with `/32` appended). Pass `'0.0.0.0/0'` for the\n * explicit-open opt-in. A bare IP gets `/32` appended automatically.\n */\n firewallSource?: string;\n /** CLI runtime tree (set by the CLI to its dist neighbor). */\n cliRuntimeRoot?: string;\n /** Repo root for the dev fallback (defaults to `process.cwd()` walk). */\n repoRoot?: string;\n onLog?: (line: string) => void;\n}\n\nexport interface PrepareDigitalOceanResult {\n snapshotName?: string;\n /** DigitalOcean snapshot id (numeric) — also recorded in digitalocean-prepared.json. */\n imageId?: number;\n}\n\nconst TEMP_SIZE_DEFAULT = 's-2vcpu-4gb';\nconst TEMP_REGION_DEFAULT = 'nyc3';\nconst STOCK_IMAGE_SLUG = 'ubuntu-24-04-x64';\nconst PREPARE_SSH_DEADLINE_MS = 5 * 60_000;\nconst PROVISION_DROPLET_DEADLINE_MS = 5 * 60_000;\nconst INSTALL_SCRIPT_TIMEOUT_MS = 30 * 60_000;\nconst SNAPSHOT_DEADLINE_MS = 30 * 60_000;\n\n/** Look up a recorded base snapshot (numeric id) in the live snapshot list. */\nasync function snapshotStillExists(client: DigitalOceanClient, imageId: number): Promise<boolean> {\n try {\n const snaps = await client.listSnapshots();\n return snaps.some((s) => s.id === String(imageId));\n } catch {\n // If we can't reach the API, don't force a rebuild on a transient error.\n return true;\n }\n}\n\n/**\n * Bake the per-account DigitalOcean base snapshot. Resolves only after the\n * snapshot completes and the temp Droplet + firewall are gone. Persists\n * `{base.imageId, base.description, base.createdAt, base.contextSha256, …}`\n * into `~/.agentbox/digitalocean-prepared.json`.\n */\nexport async function prepareDigitalOcean(\n opts: PrepareDigitalOceanOptions = {},\n): Promise<PrepareDigitalOceanResult> {\n await ensureDigitalOceanCredentials();\n const client = makeDigitalOceanClient();\n const log = opts.onLog ?? (() => {});\n const progress = (step: string) => log(`prepare-digitalocean: ${step}`);\n\n // Skip-fast: if a base snapshot is already recorded *and* still on\n // DigitalOcean *and* the build-context fingerprint hasn't changed *and*\n // --force was not passed, return the existing record.\n const existingState = readPreparedState();\n const assets = resolveRuntimeAssets({\n cliRuntimeRoot: opts.cliRuntimeRoot ?? findStagedCliRuntimeRoot(),\n repoRoot: opts.repoRoot,\n });\n const claudeInstall = opts.claudeInstall ?? 'native';\n // Fold the Claude install mode into the fingerprint so switching native<->npm\n // re-bakes even though the staged asset files are identical (matches Hetzner).\n const contextSha = claudeInstallFingerprint(\n await computeContextSha256(assets.map((a) => ({ rel: a.name, abs: a.localPath }))),\n claudeInstall,\n );\n\n if (!opts.force && existingState.base) {\n const remote = await snapshotStillExists(client, existingState.base.imageId);\n if (remote && existingState.base.contextSha256 === contextSha) {\n progress(\n `base snapshot ${String(existingState.base.imageId)} already exists (fingerprint ${contextSha.slice(0, 12)} matches); skipping rebuild (pass --force to override)`,\n );\n return {\n snapshotName: existingState.base.description,\n imageId: existingState.base.imageId,\n };\n }\n if (!remote) {\n progress(`recorded base snapshot ${String(existingState.base.imageId)} is gone on DigitalOcean; rebuilding`);\n } else {\n progress(\n `build context changed (was ${existingState.base.contextSha256?.slice(0, 12) ?? '<none>'}, now ${contextSha.slice(0, 12)}); rebuilding base snapshot`,\n );\n }\n }\n\n // 1. Mint ephemeral key.\n progress('minting ephemeral ssh key');\n const key = await mintPrepareKey();\n let firewallId: string | null = null;\n let dropletId: number | null = null;\n // Hoisted so the failure-cleanup catch can delete the tag it minted.\n const stamp = Date.now().toString(36);\n const prepareTag = `agentbox-prepare-${stamp}`;\n try {\n progress('detecting host egress IP');\n const source = opts.firewallSource\n ? normalizeSourceCidr(opts.firewallSource)\n : `${await detectEgressIp({ onLog: log })}/32`;\n\n // 2. Create per-prepare firewall, bound to a unique tag.\n const firewallName = `agentbox-prepare-${stamp}`;\n progress(`creating firewall ${firewallName} (source ${source})`);\n const firewall = await createPerBoxFirewall(client, {\n name: firewallName,\n sources: [source],\n tag: prepareTag,\n });\n firewallId = firewall.id;\n\n // 3. Create temp Droplet (tagged so the firewall applies at boot).\n const dropletName = `agentbox-prepare-${stamp}`;\n const cloudInit = generatePrepareCloudInit({ sshPubkey: key.publicKey });\n const size = opts.size ?? TEMP_SIZE_DEFAULT;\n const region = opts.region ?? TEMP_REGION_DEFAULT;\n progress(`creating temp Droplet ${dropletName} (${size} / ${region})`);\n const created = await client.createDroplet({\n name: dropletName,\n region,\n size,\n image: STOCK_IMAGE_SLUG,\n user_data: cloudInit,\n tags: [prepareTag, 'agentbox', 'agentbox-prepare'],\n ipv6: false,\n });\n dropletId = created.droplet.id;\n\n // 3b. Place the bake Droplet in the same DO Project as the boxes, so it doesn't\n // surface in the account's default project for the 5-30 min it lives. Wholly\n // best-effort: a bake is expensive, and neither a project typo nor an API blip\n // is worth failing one over — the create path reports a bad project loudly.\n // Resolve config against the host workspace, NOT process.cwd(): a bake driven\n // by the hub's queued worker runs from the daemon's directory, which is not the\n // repo — so cwd would miss a per-repo `box.digitaloceanProject` and quietly bake\n // in the wrong project.\n const wantedProject = (\n opts.project ??\n (await loadEffectiveConfig(opts.hostWorkspace ?? process.cwd())).effective.box\n .digitaloceanProject\n ).trim();\n if (wantedProject.length > 0) {\n try {\n const projectId = resolveProjectChoice(wantedProject, await client.listProjects());\n await client.assignProjectResources(projectId, [`do:droplet:${String(dropletId)}`]);\n progress(`bake droplet assigned to project ${wantedProject}`);\n } catch (assignErr) {\n progress(\n `WARN — could not assign the bake droplet to project ${wantedProject} (continuing): ` +\n `${assignErr instanceof Error ? assignErr.message : String(assignErr)}`,\n );\n }\n }\n\n // 4. Wait for the droplet to become active + expose a public IPv4, then ssh.\n progress(`droplet ${String(dropletId)} created; waiting for it to boot`);\n const droplet = await pollUntil(\n `droplet ${String(dropletId)} active`,\n async () => {\n const d = await client.getDroplet(dropletId as number);\n const ip = d?.networks.v4.find((n) => n.type === 'public')?.ip_address;\n return d && d.status === 'active' && ip ? { d, ip } : null;\n },\n { deadlineMs: PROVISION_DROPLET_DEADLINE_MS, intervalMs: 3_000, maxIntervalMs: 10_000, onPoll: (l) => log(`prepare-digitalocean: ${l}`) },\n );\n const ip = droplet.ip;\n\n progress(`waiting for ssh on ${ip} (deadline ${String(PREPARE_SSH_DEADLINE_MS / 1000)}s)`);\n const sshTarget: SshTargetArgs = {\n host: ip,\n user: 'root',\n identity: key.privatePath,\n knownHosts: join(key.dir, 'known_hosts'),\n };\n const up = await waitForSsh(sshTarget, PREPARE_SSH_DEADLINE_MS);\n if (!up) {\n throw new Error(`digitalocean: ssh on ${ip} did not come up within ${String(PREPARE_SSH_DEADLINE_MS / 1000)}s`);\n }\n progress('ssh up — scp\\'ing runtime assets');\n\n // 5. scp every asset into /tmp/ **sequentially** (parallel uploads through\n // fresh ssh connections trip sshd's MaxStartups on a freshly-booted VPS).\n for (const asset of assets) {\n const remote = `/tmp/${asset.remoteBasename}`;\n log(`prepare-digitalocean: scp ${asset.name} -> ${remote}`);\n await scpUpload(sshTarget, asset.localPath, remote);\n if (asset.remoteMode !== undefined) {\n const modeOctal = asset.remoteMode.toString(8);\n await sshExec(sshTarget, `chmod ${modeOctal} ${remote}`);\n }\n }\n\n // 6. Run the install script, teeing the full trace to\n // /var/log/agentbox/install.log so it survives into the snapshot.\n progress('running install-box.sh on temp Droplet (this takes ~5-15 min)');\n const installRes = await sshExec(\n sshTarget,\n `sudo mkdir -p /var/log/agentbox && set -o pipefail && AGENTBOX_CLAUDE_INSTALL=${claudeInstall} bash -x /tmp/agentbox-install.sh 2>&1 | sudo tee /var/log/agentbox/install.log`,\n {\n timeoutMs: INSTALL_SCRIPT_TIMEOUT_MS,\n onLine: (line) => log(`[install] ${line}`),\n },\n );\n if (installRes.exitCode !== 0) {\n throw new Error(\n `install-box.sh failed on temp Droplet (exit ${String(installRes.exitCode)})\\n` +\n `Last stderr: ${installRes.stderr.slice(-500) || '(empty)'}\\n` +\n `The full install trace was streamed to the prepare log above (the '[install] …' lines; ` +\n `also in ~/.agentbox/logs/latest.log). No snapshot was created and the temp Droplet is being ` +\n `deleted, so the in-box /var/log/agentbox/install.log does not survive this failure.`,\n );\n }\n progress('install script complete');\n\n // 6b. Stage host agent static config (~/.claude, ~/.codex, opencode,\n // ~/.agents) into /home/vscode/ so in-box agents boot with plugins/skills/\n // settings already present. Mirrors the Hetzner/Daytona bake step.\n progress('staging host agent static config');\n const stagings: Array<{\n kind: 'claude' | 'codex' | 'opencode' | 'agents';\n tar: StageResult;\n dest: string;\n }> = [];\n try {\n const claudeTar = await stageClaudeStaticForUpload({ hostWorkspace: opts.hostWorkspace });\n for (const w of claudeTar.warnings) log(`prepare-digitalocean: ${w}`);\n if (claudeTar.tarballPath) stagings.push({ kind: 'claude', tar: claudeTar, dest: '/home/vscode/.claude' });\n else await claudeTar.cleanup();\n\n const codexTar = await stageCodexStaticForUpload();\n for (const w of codexTar.warnings) log(`prepare-digitalocean: ${w}`);\n if (codexTar.tarballPath) stagings.push({ kind: 'codex', tar: codexTar, dest: '/home/vscode/.codex' });\n else await codexTar.cleanup();\n\n const opencodeTar = await stageOpencodeStaticForUpload();\n for (const w of opencodeTar.warnings) log(`prepare-digitalocean: ${w}`);\n if (opencodeTar.tarballPath) stagings.push({ kind: 'opencode', tar: opencodeTar, dest: '/home/vscode/.local/share/opencode' });\n else await opencodeTar.cleanup();\n\n const agentsTar = await stageAgentsStaticForUpload();\n for (const w of agentsTar.warnings) log(`prepare-digitalocean: ${w}`);\n if (agentsTar.tarballPath) stagings.push({ kind: 'agents', tar: agentsTar, dest: '/home/vscode/.agents' });\n else await agentsTar.cleanup();\n\n for (const s of stagings) {\n const remote = `/tmp/agentbox-${s.kind}-static.tar.gz`;\n log(`prepare-digitalocean: scp ${s.kind} static (${s.tar.tarballPath}) -> ${remote}`);\n await scpUpload(sshTarget, s.tar.tarballPath as string, remote);\n const extractCmd =\n `sudo -u vscode mkdir -p ${s.dest} && ` +\n `sudo -u vscode tar -xzf ${remote} -C ${s.dest} --no-same-permissions --no-same-owner -m && ` +\n `rm -f ${remote}`;\n const r = await sshExec(sshTarget, extractCmd, { onLine: (line) => log(`[stage:${s.kind}] ${line}`) });\n if (r.exitCode !== 0) {\n throw new Error(\n `prepare-digitalocean: ${s.kind} static extract failed (exit ${String(r.exitCode)}): ${r.stderr.slice(-300)}`,\n );\n }\n progress(`baked ${s.kind} static config into snapshot`);\n }\n } finally {\n for (const s of stagings) await s.tar.cleanup();\n }\n\n // 7. Snapshot the droplet (async action), then resolve the snapshot id by\n // name. DigitalOcean supports live snapshots, so we don't power off.\n const description = opts.name ?? `agentbox-base-${stamp}`;\n progress(`creating snapshot '${description}' from droplet ${String(dropletId)}`);\n const action = await client.snapshotDroplet(dropletId, description);\n progress(`snapshot action ${String(action.id)} requested; polling until complete`);\n await pollUntil(\n `snapshot action ${String(action.id)}`,\n async () => {\n const a = await client.getAction(action.id);\n if (!a) return null;\n if (a.status === 'errored') {\n throw new Error(`digitalocean: snapshot action ${String(action.id)} errored`);\n }\n return a.status === 'completed' ? a : null;\n },\n { deadlineMs: SNAPSHOT_DEADLINE_MS, intervalMs: 3_000, maxIntervalMs: 10_000, onPoll: (l) => log(`prepare-digitalocean: ${l}`) },\n );\n const snap = (await client.listSnapshots()).find((s) => s.name === description);\n if (!snap) {\n throw new Error(`digitalocean: snapshot '${description}' completed but was not found in the snapshot list`);\n }\n const snapshotId = Number.parseInt(snap.id, 10);\n\n // 8. Persist before tearing down — if cleanup fails we still know about\n // the new snapshot.\n progress('persisting digitalocean-prepared.json');\n const state = readPreparedState();\n const cliStamp = readCliStamp();\n state.base = {\n imageId: snapshotId,\n description,\n createdAt: new Date().toISOString(),\n contextSha256: contextSha,\n cliVersion: cliStamp.cliVersion,\n cliCommit: cliStamp.cliCommit,\n };\n writePreparedState(state);\n log(`prepare-digitalocean: wrote ${preparedStatePath()}`);\n\n // 9. Cleanup: delete droplet first (cleanly detaches the firewall), then\n // the firewall.\n progress(`deleting temp Droplet ${String(dropletId)}`);\n await client.deleteDroplet(dropletId);\n dropletId = null;\n progress(`deleting per-prepare firewall ${firewallId}`);\n await deletePerBoxFirewall(client, firewallId, { tags: [prepareTag] });\n firewallId = null;\n\n progress(`prepare complete — base snapshot ${String(snapshotId)} (${description})`);\n return { snapshotName: description, imageId: snapshotId };\n } catch (err) {\n // Failure cleanup — best-effort. Always try to delete the Droplet first\n // (it costs money if left running). Surface the original error.\n if (dropletId !== null) {\n log(`prepare-digitalocean: cleanup — deleting temp Droplet ${String(dropletId)} after failure`);\n try {\n await client.deleteDroplet(dropletId);\n } catch (cleanupErr) {\n log(\n `prepare-digitalocean: WARN — failed to delete temp Droplet ${String(dropletId)}; check the DigitalOcean dashboard manually. ${\n cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)\n }`,\n );\n }\n }\n if (firewallId !== null) {\n log(`prepare-digitalocean: cleanup — deleting per-prepare firewall ${firewallId} after failure`);\n try {\n await deletePerBoxFirewall(client, firewallId, { tags: [prepareTag] });\n } catch (cleanupErr) {\n log(\n `prepare-digitalocean: WARN — failed to delete firewall ${firewallId}; check the DigitalOcean dashboard manually. ${\n cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)\n }`,\n );\n }\n }\n throw err;\n } finally {\n await key.cleanup();\n }\n}\n\n/**\n * Provider-level binding used by the CLI's `prepare` command. Matches the\n * shape of `hetznerProvider.prepare`.\n */\nexport const prepareDigitalOceanProvider: NonNullable<Provider['prepare']> = (req) =>\n prepareDigitalOcean({\n name: req.name,\n hostWorkspace: req.hostWorkspace ?? process.cwd(),\n force: req.force,\n // Region for the temp bake Droplet (defaults to nyc3 when unset). Resolved\n // by the CLI from `--location` / `box.digitaloceanRegion`.\n region: req.location,\n // Droplet size for the temp bake VPS (CLI `--size` / `box.sizeDigitalocean`).\n size: req.size,\n // Forward the Claude install mode (native | npm) so the `npm` escape hatch\n // (box.claudeInstall / --claude-install npm) reaches the bake — the native\n // installer's CDN 403s some datacenter egress IPs. (matches Hetzner.)\n claudeInstall: req.claudeInstall,\n onLog: req.onLog,\n });\n\n/**\n * First-use gate. If no base snapshot is recorded in\n * `~/.agentbox/digitalocean-prepared.json`, throws an actionable error\n * pointing at `agentbox prepare --provider digitalocean`.\n *\n * Called by `backend.provision()` lazily so `agentbox prepare --provider\n * digitalocean` itself can run without tripping the gate.\n */\nexport async function ensureDigitalOceanBaseSnapshot(): Promise<void> {\n const state = readPreparedState();\n if (state.base !== undefined) return;\n throw new UserFacingError(\n 'no DigitalOcean base snapshot found.\\n' +\n 'Run `agentbox prepare --provider digitalocean` first (DigitalOcean cannot build images from a Dockerfile,\\n' +\n 'so the base snapshot is a one-time prerequisite for cloud boxes on this backend).',\n );\n}\n\nexport type { ResolvedAsset };\n","/**\n * Per-box (and per-prepare-run) SSH key minting.\n *\n * AgentBox mints a fresh ed25519 keypair per box at provision time. The\n * private key never leaves the host; the public key is shipped to the VPS\n * via cloud-init `users:` (NOT the DigitalOcean SSH-keys-import API, which\n * would make the same pubkey available to attach to other VPSes the user\n * provisions — see the plan's §\"Key & key-lifecycle hygiene\").\n *\n * Storage layout (per the plan):\n * ~/.agentbox/boxes/<box-id>/ssh/\n * id_ed25519 (private, 0600)\n * id_ed25519.pub (public, 0644)\n * known_hosts (per-box, populated post-first-connect)\n * control.sock (ssh ControlMaster socket — created at runtime)\n *\n * For the temp prepare VPS we use a parallel path:\n * ~/.agentbox/digitalocean/prepare-<timestamp>/\n * deleted after the snapshot completes.\n */\n\nimport { dirname, resolve } from 'node:path';\nimport { mintSshKey, type MintedSshKey } from '@agentbox/sandbox-core';\n\n// `mintSshKey` / `MintedSshKey` are provider-neutral and now live in\n// `@agentbox/sandbox-core` (shared with the docker localhost sshd and the\n// Hetzner backend). Re-exported here so the DigitalOcean-internal call sites\n// keep importing from `./ssh-key.js`.\nexport { mintSshKey, type MintedSshKey };\n\n/**\n * Mint a temporary keypair for the prepare orchestrator. Returns the same\n * shape as `mintSshKey` plus a `cleanup()` that rm -rf's the directory.\n * The caller is expected to call `cleanup()` in a `finally` block.\n */\nexport async function mintPrepareKey(): Promise<MintedSshKey & { cleanup: () => Promise<void> }> {\n const root = resolve(homedirOrCwd(), '.agentbox', 'digitalocean', `prepare-${Date.now().toString(36)}`);\n const key = await mintSshKey(root, `agentbox-prepare-${new Date().toISOString().replace(/[:.]/g, '-')}`);\n return {\n ...key,\n cleanup: async () => {\n try {\n const { rm } = await import('node:fs/promises');\n await rm(dirname(key.privatePath), { recursive: true, force: true });\n } catch {\n // best-effort\n }\n },\n };\n}\n\nfunction homedirOrCwd(): string {\n try {\n // Lazy require so this module is import-safe even if `os` is shimmed\n // away in some weird bundle environment.\n return process.env.HOME ?? process.cwd();\n } catch {\n return process.cwd();\n }\n}\n","/**\n * The `ssh` / `scp` wrappers now live in `@agentbox/sandbox-core` — hetzner,\n * digitalocean and remote-docker all drive the same OpenSSH transport. Kept as\n * a re-export so this package's call sites keep their local import path.\n */\nexport {\n scpDownload,\n scpUpload,\n sshExec,\n sshOptArgs,\n waitForSsh,\n type SshExecOptions,\n type SshExecResult,\n type SshTargetArgs,\n} from '@agentbox/sandbox-core';\n","/**\n * `SshTunnelManager` now lives in `@agentbox/sandbox-core` — hetzner,\n * digitalocean and remote-docker all reuse one ControlMaster implementation.\n * Kept as a re-export so this package's call sites keep their local import path.\n *\n * DigitalOcean's per-box ssh state stays namespaced under `digitalocean/` so a\n * droplet id can't collide with a Hetzner server id sharing the same numeric\n * value; the namespace is bound here rather than at every call site.\n */\nimport {\n SshTunnelManager as CoreSshTunnelManager,\n defaultBoxSshDir as coreDefaultBoxSshDir,\n} from '@agentbox/sandbox-core';\n\nexport { controlSockPath } from '@agentbox/sandbox-core';\nexport type { PortForward, SshTunnelOpenOptions } from '@agentbox/sandbox-core';\n\nconst DIGITALOCEAN_SSH_NAMESPACE = 'digitalocean';\n\n/** Default per-box ssh dir: `~/.agentbox/digitalocean/boxes/<box-id>/ssh/`. */\nexport function defaultBoxSshDir(boxId: string): string {\n return coreDefaultBoxSshDir(boxId, DIGITALOCEAN_SSH_NAMESPACE);\n}\n\nexport class SshTunnelManager extends CoreSshTunnelManager {\n constructor() {\n super(DIGITALOCEAN_SSH_NAMESPACE);\n }\n}\n","/**\n * Doctor probes + normalized credential status for the digitalocean provider,\n * assembled into `providerModule` in `index.ts`. Moved out of apps/cli so the\n * CLI dispatches to it generically (see `@agentbox/sandbox-core`'s `ProviderModule`).\n */\n\nimport { errSummary, type CheckResult, type CredStatusSummary } from '@agentbox/sandbox-core';\nimport { detectPortless, portlessDoctorRow } from '@agentbox/sandbox-cloud';\nimport { readDigitalOceanCredStatus } from './credentials.js';\nimport { readPreparedState } from './prepared-state.js';\n\nexport function readCredStatusSummary(): CredStatusSummary {\n return { configured: readDigitalOceanCredStatus().source !== 'none' };\n}\n\nexport async function doctorChecks(): Promise<CheckResult[]> {\n try {\n const cred = readDigitalOceanCredStatus();\n const credRes: CheckResult =\n cred.source === 'none'\n ? {\n label: 'credentials',\n status: 'warn',\n detail: 'DIGITALOCEAN_TOKEN not set',\n hint: '`agentbox digitalocean login`',\n }\n : { label: 'credentials', status: 'ok', detail: `token from ${cred.source}` };\n\n const prepared = readPreparedState();\n const snapRes: CheckResult = prepared.base?.imageId\n ? {\n label: 'base snapshot',\n status: 'ok',\n detail: `snapshot ${String(prepared.base.imageId)} (${prepared.base.cliVersion ?? '—'})`,\n }\n : {\n label: 'base snapshot',\n status: 'warn',\n detail: 'not baked',\n hint: '`agentbox prepare --provider digitalocean`',\n };\n // Host Portless mints the <box>.localhost alias for the SSH-forwarded port;\n // without it digitalocean web URLs degrade to raw loopback.\n const portlessRes = portlessDoctorRow(await detectPortless());\n return [credRes, snapRes, portlessRes];\n } catch (err) {\n return [{ label: 'credentials', status: 'warn', detail: errSummary(err) }];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACgBA,SAAS,kBAAkB;AAC3B,SAAS,IAAI,QAAQ,aAAa;AAClC,SAAS,QAAAA,aAAY;AACrB,SAAS,aAAa;AACtB,SAAS,WAAW,mBAAmB;AGMvC,SAAS,YAAY;ACLrB,SAAS,SAAS,eAAe;AHU1B,SAAS,yBAAyB,MAAuC;AAC9E,QAAM,SAAS,KAAK,UAAU,KAAK;AACnC,SAAO;IACL;;;;;IAKA;IACA;IACA;IACA;;;;;;IAMA;IACA,OAAO,WAAW,MAAM,CAAC;;;;;;;IAOzB;IACA;IACA;IACA;IACA;IACA;IACA;EACF,EAAE,KAAK,IAAI;AACb;AAwBO,SAAS,qBAAqB,MAAmC;AACtE,QAAM,SAAS,KAAK,UAAU,KAAK;AACnC,QAAM,QAAkB;IACtB;;;IAGA,iCAAiC,KAAK,OAAO;IAC7C;IACA;;;IAGA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,WAAW,WAAW,MAAM,CAAC;EAC/B;AAEA,QAAM,aAAuB;IAC3B;IACA;IACA,2B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,kBAAkB,MAAM,eAAe,CAAC;AAC5D,WAAO,CAAC,SAAS,SAAS,WAAW;EACvC,SAAS,KAAK;AACZ,WAAO,CAAC,EAAE,OAAO,eAAe,QAAQ,QAAQ,QAAQ,WAAW,GAAG,EAAE,CAAC;EAC3E;AACF;ARhCA,IAAM,gBAAgB,oBAAoB,qBAAqB;;EAE7D,kBAAkB,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG;AAClD,CAAC;AAEM,IAAM,uBAAiC;EAC5C,GAAG;EACH,SAAS;EACT,iBAAiB,MAAM,uCAAuC;AAChE;AAGO,IAAM,iBAAiC;EAC5C,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,4BAA4B,CAAC,kBAAkB,uCAAuC,aAAa;EACnG;AACF;","names":["join","rm","client","ip","defaultBoxSshDir","SshTunnelManager","PROVISION_DROPLET_DEADLINE_MS","SNAPSHOT_DEADLINE_MS","join"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-daytona/src/index.ts","../../../packages/sandbox-daytona/src/checkpoint.ts","../../../packages/sandbox-daytona/src/prepare.ts","../../../packages/sandbox-daytona/src/prepare-vm.ts","../../../packages/sandbox-daytona/src/provider-module.ts","../../../packages/sandbox-daytona/src/status.ts"],"sourcesContent":["/**\n * The Daytona Cloud sandbox provider. A thin `CloudBackend` over\n * `@daytona/sdk`, composed via `@agentbox/sandbox-cloud`'s `createCloudProvider`\n * for everything provider-agnostic (workspace seeding, ctl launch, state).\n */\n\nimport type { Provider } from '@agentbox/core';\nimport type { ProviderModule } from '@agentbox/sandbox-core';\nimport { createCloudProvider } from '@agentbox/sandbox-cloud';\nimport { DAYTONA_DEFAULT_RESOURCES, daytonaBackend, DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { makeDaytonaCheckpoint } from './checkpoint.js';\nimport { prepareDaytona } from './prepare.js';\nimport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\nimport { ensureDaytonaCredentials, setDaytonaCredentials } from './credentials.js';\nimport { doctorChecks, readCredStatusSummary } from './provider-module.js';\n\nconst cloudProvider = createCloudProvider(daytonaBackend, {\n defaultResources: { ...DAYTONA_DEFAULT_RESOURCES },\n});\n\nexport const daytonaProvider: Provider = {\n ...cloudProvider,\n prepare: prepareDaytona,\n // Overrides the generic cloud checkpoint: a Daytona cold snapshot needs the\n // sandbox stopped, which kills the in-box daemons, so the capture has to\n // reconnect the box afterwards. See `makeDaytonaCheckpoint`.\n checkpoint: makeDaytonaCheckpoint(cloudProvider),\n baseFingerprint: () => currentDaytonaBaseFingerprintLive(),\n};\n\n/** Uniform surface the CLI provider loader resolves this package through. */\nexport const providerModule: ProviderModule = {\n provider: daytonaProvider,\n backend: daytonaBackend,\n ensureCredentials: ensureDaytonaCredentials,\n readCredStatus: readCredStatusSummary,\n setCredentials: setDaytonaCredentials,\n currentBaseFingerprintLive: (claudeInstall) => currentDaytonaBaseFingerprintLive(claudeInstall),\n doctorChecks,\n};\n\nexport { DAYTONA_DEFAULT_RESOURCES, daytonaBackend, DEFAULT_BOX_IMAGE_REF };\nexport { resolveDockerfileContext, type DockerfileContext } from './dockerfile-context.js';\nexport { ensureDaytonaEnvLoaded } from './env-loader.js';\nexport { currentDaytonaBaseFingerprintLive } from './prepared-state.js';\n// Called by the CLI provider registry to gate first-run interactive setup.\n// Plain async function — no commander surface — so adding it here doesn't\n// pull commander/clack into consumers' type graphs. The full CLI command\n// lives at the `./cli` subpath export.\nexport { ensureDaytonaCredentials, setDaytonaCredentials } from './credentials.js';\nexport type { EnsureDaytonaCredentialsOptions } from './credentials.js';\nexport {\n getDaytonaStatus,\n type DaytonaStatus,\n type DaytonaSnapshotSummary,\n type DaytonaVolumeSummary,\n} from './status.js';\n","/**\n * Daytona cloud checkpoints.\n *\n * Overrides the generic cloud checkpoint (`makeCloudCheckpoint`) because\n * Daytona's capture has two properties the generic one doesn't model:\n *\n * 1. **A cold snapshot requires the sandbox STOPPED, and Daytona will not stop\n * it for you.** (The hot, filesystem+memory variant needs `includeMemory`,\n * which the published TS SDK silently drops — so it's out of reach until\n * upstream fixes the wrapper.) So we stop, capture, and start again. The\n * stop kills the in-box `ctl` daemon, dockerd, VNC and the agent's tmux\n * session, so the box must be *reconnected* afterwards or the user is left\n * with a running sandbox whose services are all dead.\n *\n * 2. **A snapshot name must never be reused.** Recreating a snapshot under a\n * recently-deleted name yields one that reports `active` but cannot boot\n * (\"Sandbox failed to start: internal error\") — Daytona's delete is async\n * and racing it corrupts the new snapshot. `agentbox checkpoint rm <name>`\n * followed by a re-create with the same name would walk straight into that,\n * so the Daytona-side name carries a nonce while the user-facing checkpoint\n * name stays whatever they typed. The manifest maps one to the other.\n */\nimport type { BoxRecord, Provider, ProviderCheckpoint } from '@agentbox/core';\nimport {\n cloudSnapshotName,\n currentCloudBaseFingerprint,\n listCloudCheckpoints,\n removeCloudCheckpointDir,\n resolveCloudCheckpoint,\n writeCloudCheckpointManifest,\n} from '@agentbox/sandbox-cloud';\nimport { readCliStamp } from '@agentbox/sandbox-core';\nimport { daytonaBackend } from './backend.js';\n\nconst BACKEND_NAME = 'daytona';\n\nexport function makeDaytonaCheckpoint(cloudProvider: Provider): ProviderCheckpoint {\n return {\n async create(box: BoxRecord, name: string) {\n if (!box.projectRoot) {\n throw new Error(\n 'cloud checkpoint requires the box to have a project root (run `agentbox checkpoint` from inside the project)',\n );\n }\n const sandboxId = box.cloud?.sandboxId;\n if (!sandboxId) {\n throw new Error(`daytona box ${box.name} has no sandboxId — record is malformed`);\n }\n const handle = { sandboxId, sandboxClass: box.cloud?.sandboxClass };\n // Unique per capture — see the name-reuse note above.\n const snapshotName = `${cloudSnapshotName(box.projectRoot, name)}-${Math.floor(Date.now() / 1000).toString(36)}`;\n\n await daytonaBackend.createSnapshot?.(handle, snapshotName);\n\n // The capture stopped and restarted the sandbox, so everything the box was\n // running is gone. `reconnect` re-runs the bootstrap (ctl, dockerd, VNC,\n // preview URLs) — without it the box looks up but answers nothing.\n await cloudProvider.reconnect(box);\n\n const info = await writeCloudCheckpointManifest(box.projectRoot, BACKEND_NAME, name, {\n snapshotName,\n sourceBoxId: box.id,\n sourceBoxName: box.name,\n baseProvider: BACKEND_NAME,\n baseFingerprint: currentCloudBaseFingerprint(BACKEND_NAME),\n cliVersion: readCliStamp().cliVersion,\n });\n return { ref: info.name };\n },\n\n async list(projectRoot: string) {\n const entries = await listCloudCheckpoints(projectRoot, BACKEND_NAME);\n return entries.map((e) => ({ ref: e.name, createdAt: e.manifest.createdAt }));\n },\n\n async remove(projectRoot: string, ref: string) {\n const entry = await resolveCloudCheckpoint(projectRoot, BACKEND_NAME, ref);\n if (!entry) return;\n try {\n await daytonaBackend.deleteSnapshot?.(entry.manifest.snapshotName);\n } catch {\n // Best-effort: drop the local manifest even when the remote delete fails,\n // so the user isn't left holding a pointer to nothing.\n }\n await removeCloudCheckpointDir(projectRoot, BACKEND_NAME, ref);\n },\n };\n}\n","/**\n * Daytona-side implementation of the `Provider.prepare` hook (`agentbox\n * prepare --provider daytona`). One-time, user-triggered:\n *\n * 1. Stage filtered tarballs of the host's `~/.claude`, `~/.codex`, and\n * `~/.local/share/opencode` static config (no auth tokens — those go on\n * the per-org `agentbox-credentials` volume at create time).\n * 2. Build a layered Daytona `Image`: start from `Dockerfile.box`, then\n * `.addLocalFile()` each staged tarball + `.runCommands()` to extract\n * them into the right paths inside the image.\n * 3. Call `daytona.snapshot.create({ name, image }, { onLogs })` — Daytona\n * runs the build server-side, registers the result as an org-scoped\n * named snapshot, and returns when it's `active`.\n *\n * Replaces the old `agentbox daytona publish-snapshot` flow that\n * provisioned a sandbox + ran an in-sandbox bake + called the broken\n * `_experimental_createSnapshot`. The new path never provisions a sandbox.\n *\n * Source of truth for the public API:\n * https://www.daytona.io/docs/en/snapshots/\n */\n\nimport { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { dirname, join } from 'node:path';\nimport { Image } from '@daytona/sdk';\nimport type { PrepareOptions, PrepareResult } from '@agentbox/core';\nimport { DAYTONA_VM_REGION, type DaytonaSandboxClass } from '@agentbox/config';\nimport {\n claudeInstallFingerprint,\n stageAllAgentStatic,\n type AgentStaticStage,\n} from '@agentbox/sandbox-core';\nimport {\n DAYTONA_DEFAULT_RESOURCES,\n daytonaBackend,\n getClient,\n parseDaytonaSize,\n} from './backend.js';\nimport { resolveDaytonaCustomClaudeMd, resolveDockerfileContext } from './dockerfile-context.js';\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport {\n bakeDaytonaVmBase,\n deleteSnapshotQuietly,\n VmBaseImageUnavailableError,\n} from './prepare-vm.js';\nimport {\n computeDaytonaContextFingerprint,\n computeDockerBaseSha,\n preparedMatches,\n readPreparedDaytonaState,\n writePreparedDaytonaState,\n} from './prepared-state.js';\n\n/**\n * Default snapshot name. Keyed on the first 12 chars of the build-context\n * fingerprint so identical content produces the same snapshot name across\n * machines / CLI runs (idempotent): if the named snapshot already exists\n * on Daytona, prepare can short-circuit without uploading the build\n * context again. Falls back to a timestamp when fingerprinting fails\n * (partial dev rebuild).\n */\nexport function defaultSnapshotName(\n fingerprint: string | null,\n sizeKey?: string,\n sandboxClass?: DaytonaSandboxClass,\n): string {\n // The size suffix keeps re-sized bakes from colliding on one name, so a\n // `--size 2-4-8` snapshot doesn't overwrite the `4-8-20` one. Same for the\n // class: a VM and a container snapshot of the same context are different\n // artifacts and cannot substitute for each other. Container stays unsuffixed\n // so existing snapshot names keep resolving.\n const suffix = `${sizeKey ? `-${sizeKey}` : ''}${sandboxClass === 'linux-vm' ? '-vm' : ''}`;\n if (fingerprint) return `agentbox-base-${fingerprint.slice(0, 12)}${suffix}`;\n return `agentbox-base-${Math.floor(Date.now() / 1000).toString()}${suffix}`;\n}\n\n/**\n * Daytona build paths for a staged tool. The tarball is copied into the seed\n * build-context dir under `contextRel` (a RELATIVE name — the Daytona builder\n * only resolves COPY sources that map to a relative archive entry; an absolute\n * `addLocalFile` COPY silently fails to land), then COPYed to `remoteTar`.\n */\nfunction daytonaSeedPaths(kind: AgentStaticStage['kind']): { contextRel: string; remoteTar: string } {\n return {\n contextRel: `agentbox-seed-${kind}.tar.gz`,\n remoteTar: `/tmp/agentbox-seed-${kind}.tar.gz`,\n };\n}\n\n/** Relative name the daytona CLAUDE.md overlay is staged under in the seed context dir. */\nconst DAYTONA_CLAUDE_MD_REL = 'agentbox-custom-CLAUDE.md';\n\n/**\n * Build the appended Dockerfile commands for the seed bake. Every `COPY` source\n * is a RELATIVE name resolved against the seed build-context dir — the Daytona\n * builder drops absolute-source COPYs (they archive to a stripped relative entry\n * that the absolute source can't reference), so relative names are mandatory.\n * Runs as root (COPY drops files root-owned; chown -R + /etc/claude-code need\n * root), then restores `USER vscode` so the image keeps its default-user invariant.\n * Pure + exported for the regression test.\n */\nexport function buildDaytonaSeedCommands(\n usable: ReadonlyArray<Pick<AgentStaticStage, 'kind' | 'extractDir'>>,\n): string[] {\n const cmds: string[] = [\n 'USER root',\n `COPY ${DAYTONA_CLAUDE_MD_REL} /tmp/agentbox-custom-CLAUDE.md`,\n ...usable.map((s) => `COPY ${daytonaSeedPaths(s.kind).contextRel} ${daytonaSeedPaths(s.kind).remoteTar}`),\n 'RUN install -m 0644 /tmp/agentbox-custom-CLAUDE.md /etc/claude-code/CLAUDE.md && rm -f /tmp/agentbox-custom-CLAUDE.md',\n ...usable.map(\n (s) =>\n `RUN mkdir -p ${s.extractDir} && tar -xzf ${daytonaSeedPaths(s.kind).remoteTar} -C ${s.extractDir} --no-same-permissions --no-same-owner -m`,\n ),\n ];\n if (usable.length > 0) {\n // Own the extracted trees as the box user, then drop the staging tarballs.\n // ~/.agents is only present when the host had one (skills dir); guard it.\n cmds.push(\n 'RUN chown -R vscode:vscode /home/vscode/.claude /home/vscode/.codex /home/vscode/.local' +\n ' && ( [ -d /home/vscode/.agents ] && chown -R vscode:vscode /home/vscode/.agents || true )' +\n ' && rm -f /tmp/agentbox-seed-*.tar.gz',\n );\n }\n cmds.push('USER vscode');\n return cmds;\n}\n\n/**\n * Run `agentbox prepare --provider daytona`. Returns `{ snapshotName }` on\n * success so the CLI can pin it into the project config.\n */\nexport async function prepareDaytona(opts: PrepareOptions): Promise<PrepareResult> {\n ensureDaytonaEnvLoaded();\n const log = opts.onLog ?? (() => {});\n\n // Fingerprint the build context first so we can (a) name the snapshot\n // deterministically and (b) detect cache hits against the recorded\n // prepared state. Computed before staging so an early `null` (partial\n // dev rebuild) doesn't waste a tar staging cycle.\n const claudeInstall = opts.claudeInstall ?? 'native';\n\n // Bake-time resources. A `--size` / `box.sizeDaytona` like `4-8-20` sets the\n // snapshot's baked CPU/memory/disk (Daytona rejects resources on the create\n // snapshot path, so it MUST be set here). Normalize to a canonical\n // `cpu-memory-disk` string for the snapshot-name suffix + prepared-state so\n // `04-08-20` and `4-8-20` don't fork the cache.\n const sizeSpec = opts.size?.trim() || undefined;\n const sizeResources = sizeSpec ? parseDaytonaSize(sizeSpec) : undefined;\n if (sizeSpec && !sizeResources) {\n throw new Error(\n `invalid --size '${sizeSpec}' for daytona: expected 'cpu-memory-disk' GB, e.g. '4-8-20'.`,\n );\n }\n const sizeKey = sizeResources\n ? `${String(sizeResources.cpu)}-${String(sizeResources.memory)}-${String(sizeResources.disk)}`\n : undefined;\n\n // The class is fixed at bake time — a snapshot of one class cannot create a\n // sandbox of the other — so it belongs in the snapshot name and the cache key.\n let sandboxClass: DaytonaSandboxClass =\n opts.sandboxClass === 'container' ? 'container' : 'linux-vm';\n const rawFingerprint = await computeDaytonaContextFingerprint();\n // Fold the install mode into the sha so native↔npm are distinct cache\n // identities (`native` leaves the hash unchanged) — the snapshot name and the\n // prepared-state match both derive from it.\n const fingerprint = rawFingerprint\n ? {\n ...rawFingerprint,\n contextSha256: claudeInstallFingerprint(rawFingerprint.contextSha256, claudeInstall),\n }\n : rawFingerprint;\n // Not const: a linux-vm bake that finds no published base image downgrades to\n // container below, and must then drop the `-vm` suffix from its name.\n let snapshotName =\n opts.name ?? defaultSnapshotName(fingerprint?.contextSha256 ?? null, sizeKey, sandboxClass);\n\n const prepared = readPreparedDaytonaState();\n if (\n !opts.force &&\n fingerprint &&\n preparedMatches(prepared, fingerprint.contextSha256, sizeKey, sandboxClass)\n ) {\n // Confirm the snapshot still exists on Daytona before short-circuiting.\n // A \"yes locally, no on the server\" mismatch must rebuild.\n try {\n const existing = await getClient().snapshot.get(\n prepared?.base?.imageRef ?? snapshotName,\n );\n if (existing?.name) {\n log(\n `daytona snapshot '${existing.name}' up to date ` +\n `(fingerprint ${fingerprint.contextSha256.slice(0, 12)}) — skipping rebuild ` +\n `(pass --force to override)`,\n );\n return { snapshotName: existing.name };\n }\n log(\n `recorded snapshot '${prepared?.base?.imageRef ?? snapshotName}' not found on Daytona; rebuilding`,\n );\n } catch {\n log(\n `recorded snapshot lookup failed; rebuilding (pass --force to silence)`,\n );\n }\n } else if (!opts.force && fingerprint && prepared?.base?.contextSha256) {\n const bakedSize = prepared.extras?.size;\n const bakedClass = prepared.extras?.class ?? 'container';\n const sameContext = prepared.base.contextSha256 === fingerprint.contextSha256;\n if (sameContext && bakedClass !== sandboxClass) {\n log(\n `daytona sandbox class changed (was ${bakedClass}, now ${sandboxClass}); rebuilding snapshot`,\n );\n } else if (sameContext && bakedSize !== sizeKey) {\n log(\n `daytona size changed (was ${bakedSize ?? 'default'}, now ${sizeKey ?? 'default'}); ` +\n `rebuilding snapshot`,\n );\n } else {\n log(\n `daytona build context changed (was ${prepared.base.contextSha256.slice(0, 12)}, ` +\n `now ${fingerprint.contextSha256.slice(0, 12)}); rebuilding snapshot`,\n );\n }\n }\n\n const ctx = resolveDockerfileContext();\n if (!ctx) {\n throw new Error(\n 'could not locate AgentBox Dockerfile.box build context for the Daytona snapshot. ' +\n 'Set AGENTBOX_DOCKER_CONTEXT to the directory containing Dockerfile.box.',\n );\n }\n\n const daytonaClaudeMd = resolveDaytonaCustomClaudeMd();\n if (!daytonaClaudeMd) {\n throw new Error(\n 'could not locate packages/sandbox-daytona/scripts/custom-system-CLAUDE.md ' +\n '(or its staged runtime/daytona/ copy). Ensure `pnpm -w build` ran so the ' +\n 'CLI staging populated runtime/daytona/.',\n );\n }\n\n if (sandboxClass === 'linux-vm') {\n const dockerBaseSha = await computeDockerBaseSha(claudeInstall);\n if (!dockerBaseSha) {\n throw new Error(\n 'could not fingerprint the docker build context, which names the published box image ' +\n 'a linux-vm base must boot from. Ensure `pnpm -w build` ran, or set ' +\n '`agentbox config set box.daytonaClass container`.',\n );\n }\n try {\n const baked = await bakeDaytonaVmBase({\n client: getClient(opts.location ?? DAYTONA_VM_REGION),\n backend: daytonaBackend,\n regionId: opts.location ?? DAYTONA_VM_REGION,\n snapshotName,\n dockerBaseSha,\n registry: opts.registry,\n baseImage: opts.vmBaseImage,\n // Always explicit: a snapshot created with no `resources` gets Daytona's\n // 1 vCPU / 1 GiB / 3 GiB default, and the box image does not fit in 3 GiB\n // (the build dies mid-pull with a bare \"internal error\").\n resources: sizeResources ?? { ...DAYTONA_DEFAULT_RESOURCES },\n hostWorkspace: opts.hostWorkspace,\n claudeMdOverlay: daytonaClaudeMd,\n onLog: log,\n });\n if (fingerprint) {\n writePreparedDaytonaState({\n snapshotName: baked.snapshotName,\n contextSha256: fingerprint.contextSha256,\n size: sizeKey,\n class: 'linux-vm',\n env: baked.env,\n });\n log(`recorded daytona-prepared.json (fingerprint ${fingerprint.contextSha256.slice(0, 12)})`);\n }\n // Reap the snapshot this bake replaces. Only after the new one is recorded\n // — a failed bake must never leave the user with no base at all. Never the\n // one we just made, and never a container snapshot (a user who flips the\n // class back would want it).\n const superseded = prepared?.base?.imageRef;\n if (superseded && superseded !== baked.snapshotName && prepared?.extras?.class === 'linux-vm') {\n log(`removing superseded snapshot '${superseded}'`);\n await deleteSnapshotQuietly(getClient(opts.location ?? DAYTONA_VM_REGION), superseded);\n }\n return { snapshotName: baked.snapshotName };\n } catch (err) {\n if (!(err instanceof VmBaseImageUnavailableError)) throw err;\n // No published image for this context (a locally edited Dockerfile.box is\n // the usual cause — a contributor, not an end user). Daytona cannot build\n // a VM from a Dockerfile, so the only thing we *can* bake is a container.\n log(\n `daytona: ${err.message} This usually means a locally modified Dockerfile.box. ` +\n `Daytona can't build a linux-vm base from a Dockerfile, so falling back to a ` +\n `container snapshot (no pause/resume).`,\n );\n sandboxClass = 'container';\n // Re-derive the name without the `-vm` suffix, or we'd register a\n // container snapshot under a name that advertises a VM.\n snapshotName =\n opts.name ?? defaultSnapshotName(fingerprint?.contextSha256 ?? null, sizeKey, sandboxClass);\n }\n }\n\n const stages = await stageAllAgentStatic({ hostWorkspace: opts.hostWorkspace });\n // Surface staging warnings (codex Keychain landmine, etc.) before the\n // longer build kicks off.\n for (const s of stages) {\n for (const w of s.staged.warnings) log(w);\n }\n\n // The Daytona SDK's `Image.fromDockerfile` takes only a path — no build args —\n // and appended `.env()`/`.runCommands()` land *after* the base Dockerfile's\n // Claude RUN (too late, and a native 403 would already have failed the build).\n // So for npm mode we build from a sibling temp Dockerfile with the\n // `AGENTBOX_CLAUDE_INSTALL` ARG default flipped to `npm`. It must live in the\n // original's directory so the Dockerfile's relative COPY sources still resolve.\n let tempDockerfile: string | null = null;\n const dockerfilePath =\n claudeInstall === 'npm'\n ? (tempDockerfile = writeNpmDockerfile(ctx.dockerfile))\n : ctx.dockerfile;\n\n // Seed build-context dir: the daytona CLAUDE.md + each staged tarball are\n // copied here under RELATIVE names so the appended `COPY <name>` sources map\n // to relative archive entries the Daytona builder actually reconstructs.\n // (An absolute `addLocalFile` COPY emits `COPY /abs/tmp/x` but archives the\n // entry as the stripped `abs/tmp/x` — the mismatch silently drops the layer.)\n let seedContextDir: string | null = null;\n try {\n // git-lfs (binary + `git lfs install --system`) is inherited for free from\n // Dockerfile.box, so an in-box checkout of an LFS repo smudges real content.\n // No daytona-specific overlay step is needed; the host-side object seeding\n // lives in sandbox-cloud's workspace-seed (seedCloneLfsObjects).\n let image: Image = Image.fromDockerfile(dockerfilePath);\n\n seedContextDir = mkdtempSync(join(tmpdir(), 'agentbox-daytona-seed-'));\n // Overlay the daytona-specific /etc/claude-code/CLAUDE.md on top of the\n // docker-shaped one baked by Dockerfile.box (daytona boxes have no host\n // .git/ bind-mount, so the in-box hint needs daytona-specific git wording).\n copyFileSync(daytonaClaudeMd, join(seedContextDir, DAYTONA_CLAUDE_MD_REL));\n\n const usable = stages.filter((s) => s.staged.tarballPath !== null);\n for (const s of usable) {\n copyFileSync(s.staged.tarballPath as string, join(seedContextDir, daytonaSeedPaths(s.kind).contextRel));\n }\n\n image = image.dockerfileCommands(buildDaytonaSeedCommands(usable), seedContextDir);\n\n // Region: a container snapshot registers wherever the client points (the\n // account default unless the user pinned `box.daytonaRegion`).\n const client = getClient(opts.location ?? '');\n log(\n `creating Daytona snapshot '${snapshotName}'${sizeResources ? ` (${sizeKey})` : ''}…`,\n );\n const snapshot = await client.snapshot.create(\n {\n name: snapshotName,\n image,\n ...(sizeResources ? { resources: sizeResources } : {}),\n ...(opts.location ? { regionId: opts.location } : {}),\n },\n {\n onLogs: (chunk: string) => log(String(chunk).split('\\n').filter(Boolean).join(' ')),\n },\n );\n log(`snapshot '${snapshot.name}' is ${snapshot.state ?? 'created'}`);\n if (fingerprint) {\n writePreparedDaytonaState({\n snapshotName: snapshot.name ?? snapshotName,\n contextSha256: fingerprint.contextSha256,\n size: sizeKey,\n class: 'container',\n });\n log(\n `recorded daytona-prepared.json (fingerprint ${fingerprint.contextSha256.slice(0, 12)})`,\n );\n }\n return { snapshotName: snapshot.name ?? snapshotName };\n } finally {\n await Promise.all(stages.map((s) => s.staged.cleanup()));\n if (tempDockerfile) rmSync(tempDockerfile, { force: true });\n if (seedContextDir) rmSync(seedContextDir, { recursive: true, force: true });\n }\n}\n\n/**\n * Write a sibling copy of `Dockerfile.box` with the `AGENTBOX_CLAUDE_INSTALL`\n * ARG default flipped from `native` to `npm`, and return its path. A sibling\n * (same directory) keeps the Dockerfile's relative COPY sources resolvable.\n * Throws if the ARG line isn't found (Dockerfile drifted from this expectation).\n */\nfunction writeNpmDockerfile(originalPath: string): string {\n const original = readFileSync(originalPath, 'utf8');\n const flipped = original.replace(\n 'ARG AGENTBOX_CLAUDE_INSTALL=native',\n 'ARG AGENTBOX_CLAUDE_INSTALL=npm',\n );\n if (flipped === original) {\n throw new Error(\n `could not enable npm Claude install for Daytona: 'ARG AGENTBOX_CLAUDE_INSTALL=native' ` +\n `not found in ${originalPath}. The Dockerfile.box drifted from the expected shape.`,\n );\n }\n const target = join(dirname(originalPath), '.agentbox-claude-npm.Dockerfile');\n writeFileSync(target, flipped);\n return target;\n}\n","/**\n * The `linux-vm` half of `agentbox prepare --provider daytona`.\n *\n * The container path builds its base with Daytona's declarative builder\n * (`Image.fromDockerfile` + layered seed commands). **That is not available for\n * VMs** — Daytona builds a VM snapshot only from a prebuilt registry image\n * (verified 2026-07-12: passing an `Image` with `sandboxClass: LINUX_VM` fails\n * with `build snapshot: rpc error: code = Unauthenticated`). So the VM bake is\n * shaped like Hetzner's and Vercel's instead — boot once, provision in-place,\n * snapshot the result:\n *\n * 1. `snapshot.create` a VM snapshot straight from the published GHCR box\n * image (`ghcr.io/madarco/agentbox/box:sha-<docker-context-sha>`), which\n * CI already builds and publishes. ~66s, vs ~7 min for a Dockerfile build.\n * 2. Boot one throwaway sandbox from it and, in-place:\n * a. repair `sudo` (see below),\n * b. seed the host's agent static config + the daytona CLAUDE.md overlay.\n * 3. Stop it and cold-snapshot it as the real base, then delete it.\n *\n * ## Why sudo needs repairing\n *\n * Converting the container image into a VM rootfs strips setuid bits: `sudo`\n * lands as mode 0755 and cannot escalate (\"must be owned by uid 0 and have the\n * setuid bit set\"). Only mount/umount/su keep theirs. That breaks the seed\n * (installing `/etc/claude-code/CLAUDE.md` needs root) and breaks the\n * passwordless sudo the in-box agent is told it has. `create({ user: 'root' })`\n * is not a way out — the sandbox then fails to start.\n *\n * The escape hatch is the docker socket, which the image already gives us:\n * dockerd runs at boot and `vscode` is in the `docker` group, so a privileged\n * container can write the host VM's filesystem. The repair persists into the\n * snapshot, so every box booted from this base has working sudo from the start.\n */\nimport { createHash } from 'node:crypto';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport type { Daytona } from '@daytona/sdk';\nimport { SandboxClass } from '@daytona/sdk';\nimport { seedAgentStaticIntoCloudBox } from '@agentbox/sandbox-cloud';\nimport { BOX_IMAGE_REGISTRY, registryRefForSha } from '@agentbox/sandbox-core';\nimport { waitForSnapshotActive } from './snapshot-wait.js';\n\n/**\n * Restore sudo's setuid bit (and quiet its hostname warning) from inside the\n * box, by borrowing root from the docker daemon. Exported for the unit test.\n *\n * `--privileged -v /:/host` is what lets an unprivileged `vscode` write a\n * root-owned file: the container runs as root and sees the VM's rootfs at\n * /host. This is not a privilege escalation we are introducing — `vscode` is\n * already in the `docker` group, which is root-equivalent by construction.\n */\nexport function buildSudoRepairCommand(): string {\n return (\n 'docker run --rm --privileged -v /:/host alpine sh -c ' +\n `'chown root:root /host/usr/bin/sudo && chmod 4755 /host/usr/bin/sudo && ` +\n // sudo emits \"unable to resolve host <name>\" on every call when the box's\n // hostname has no /etc/hosts entry. Noisy, and it costs a DNS timeout.\n `grep -q \"\\\\b$(cat /host/etc/hostname)\\\\b\" /host/etc/hosts || ` +\n `echo \"127.0.0.1 $(cat /host/etc/hostname)\" >> /host/etc/hosts'`\n );\n}\n\n/** Poll until dockerd answers — it starts at boot, but not instantly. */\nexport function buildDockerWaitCommand(): string {\n return 'for i in $(seq 1 30); do docker info >/dev/null 2>&1 && exit 0; sleep 2; done; exit 1';\n}\n\nexport interface VmBaseBakeOptions {\n client: Daytona;\n backend: CloudBackend;\n /** Region the VM snapshot is registered in — only us-east-1 has VM runners. */\n regionId: string;\n /** Final base-snapshot name, pinned into `box.imageDaytona`. */\n snapshotName: string;\n /** Raw docker build-context sha — names the published GHCR image. */\n dockerBaseSha: string;\n /** Registry override (`box.imageRegistry`); empty = the public default. */\n registry?: string;\n /**\n * Explicit base image (`box.daytonaVmBaseImage`), bypassing the\n * fingerprint-tagged lookup. The escape hatch for a build context with no\n * published image — chiefly a locally modified `Dockerfile.box`, i.e. anyone\n * developing on the monorepo, since a local `pnpm build` regenerates\n * `packages/ctl/dist/bin.cjs` and shifts the context sha off CI's.\n */\n baseImage?: string;\n resources?: { cpu: number; memory: number; disk: number };\n hostWorkspace?: string;\n /** Host path to the daytona `/etc/claude-code/CLAUDE.md` overlay. */\n claudeMdOverlay: string;\n onLog?: (line: string) => void;\n}\n\n/**\n * Thrown when the GHCR image the VM base must boot from doesn't exist for this\n * build context — a locally edited `Dockerfile.box`, or an npm Claude install\n * (CI publishes only the native variant). The caller degrades to the container\n * class rather than dead-ending the user.\n */\nexport class VmBaseImageUnavailableError extends Error {}\n\n/** Does the registry actually have this tag? Anonymous HEAD — no docker needed. */\nexport async function ghcrTagExists(ref: string): Promise<boolean> {\n // ghcr.io/<owner>/<path>:<tag>\n const m = /^ghcr\\.io\\/(.+):([^:]+)$/.exec(ref);\n if (!m) return true; // non-GHCR registry: don't pretend to know; let the bake try.\n const [, repo, tag] = m;\n try {\n const tokenRes = await fetch(\n `https://ghcr.io/token?scope=repository:${repo}:pull&service=ghcr.io`,\n );\n if (!tokenRes.ok) return false;\n const { token } = (await tokenRes.json()) as { token?: string };\n if (!token) return false;\n const res = await fetch(`https://ghcr.io/v2/${repo}/manifests/${tag}`, {\n method: 'HEAD',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: [\n 'application/vnd.oci.image.index.v1+json',\n 'application/vnd.oci.image.manifest.v1+json',\n 'application/vnd.docker.distribution.manifest.list.v2+json',\n 'application/vnd.docker.distribution.manifest.v2+json',\n ].join(','),\n },\n });\n return res.ok;\n } catch {\n // Network trouble is not \"the tag is missing\" — let the bake surface the\n // real error rather than silently downgrading the user to a container.\n return true;\n }\n}\n\n/**\n * The image's declared environment (`ENV` in Dockerfile.box, plus PATH), read\n * from its config blob in the registry.\n *\n * A container inherits `ENV` from the image's *metadata*. A linux-vm does not:\n * the conversion turns the image into a rootfs, and metadata is not a file, so\n * every `ENV` silently disappears — `DISPLAY=:1` above all, which is why the\n * in-box browser died with \"Missing X server or $DISPLAY\" on a VM box while\n * working fine on docker and container-class daytona. (Same family as the\n * setuid-stripping the sudo repair works around.)\n *\n * Read rather than hardcoded: Dockerfile.box owns these values, and a copy here\n * would rot the first time someone adds an ENV. The config blob is a few hundred\n * bytes — no image pull.\n *\n * Returns null when the env can't be read (non-GHCR override, network trouble):\n * the caller warns and bakes anyway rather than failing the whole prepare.\n */\nexport async function fetchImageEnv(ref: string): Promise<string[] | null> {\n const m = /^ghcr\\.io\\/(.+):([^:]+)$/.exec(ref);\n if (!m) return null;\n const [, repo, tag] = m;\n const accept = [\n 'application/vnd.oci.image.index.v1+json',\n 'application/vnd.oci.image.manifest.v1+json',\n 'application/vnd.docker.distribution.manifest.list.v2+json',\n 'application/vnd.docker.distribution.manifest.v2+json',\n ].join(',');\n try {\n const tokenRes = await fetch(\n `https://ghcr.io/token?scope=repository:${repo}:pull&service=ghcr.io`,\n );\n if (!tokenRes.ok) return null;\n const { token } = (await tokenRes.json()) as { token?: string };\n if (!token) return null;\n const headers = { Authorization: `Bearer ${token}`, Accept: accept };\n\n const get = async (r: string): Promise<Record<string, unknown> | null> => {\n const res = await fetch(`https://ghcr.io/v2/${repo}/${r}`, { headers });\n return res.ok ? ((await res.json()) as Record<string, unknown>) : null;\n };\n\n let manifest = await get(`manifests/${tag}`);\n // Multi-arch index -> pick the linux/amd64 child (Daytona is x86_64 only).\n const children = manifest?.manifests as\n | Array<{ digest: string; platform?: { os?: string; architecture?: string } }>\n | undefined;\n if (children) {\n const amd64 = children.find(\n (c) => c.platform?.os === 'linux' && c.platform.architecture === 'amd64',\n );\n if (!amd64) return null;\n manifest = await get(`manifests/${amd64.digest}`);\n }\n const configDigest = (manifest?.config as { digest?: string } | undefined)?.digest;\n if (!configDigest) return null;\n const config = await get(`blobs/${configDigest}`);\n const env = (config?.config as { Env?: unknown } | undefined)?.Env;\n if (!Array.isArray(env)) return null;\n return env.filter((e): e is string => typeof e === 'string' && e.includes('='));\n } catch {\n return null;\n }\n}\n\n/**\n * Put the image's `ENV` back on disk in the VM, where a rootfs can carry it.\n *\n * Two files, because two kinds of process need it and neither reads the other's:\n * - `/etc/profile.d/` — login shells (the ssh attach, any `bash -lc`).\n * - `/etc/environment` — PAM, and it's the conventional home for these.\n *\n * The values are also handed to `create` as sandbox env vars (see the backend),\n * which is what covers plain non-login `exec` — the path `agent-browser` runs on.\n */\nexport function buildEnvRestoreCommand(env: string[]): string {\n const shQuote = (v: string): string => `'${v.replace(/'/g, `'\\\\''`)}'`;\n const profile = env\n .map((e) => {\n const i = e.indexOf('=');\n return `export ${e.slice(0, i)}=${shQuote(e.slice(i + 1))}`;\n })\n .join('\\n');\n const envFile = env.join('\\n');\n const b64 = (s: string): string => Buffer.from(`${s}\\n`, 'utf8').toString('base64');\n // base64 through a pipe: the values contain quotes and colons, and this command\n // is itself shipped through a shell.\n return (\n `printf %s '${b64(profile)}' | base64 -d | sudo tee /etc/profile.d/agentbox-image-env.sh >/dev/null && ` +\n `sudo chmod 644 /etc/profile.d/agentbox-image-env.sh && ` +\n `printf %s '${b64(envFile)}' | base64 -d | sudo tee -a /etc/environment >/dev/null`\n );\n}\n\n/** What a VM bake produced: the snapshot, and the image env it had to restore. */\nexport interface VmBaseBakeResult {\n snapshotName: string;\n /**\n * The image's `ENV`, recorded so `create` can also hand it to the sandbox.\n * The on-disk copy covers login shells; sandbox env vars cover the plain\n * non-login `exec` that `agent-browser` (and every other host-driven command)\n * runs on. Empty when the registry couldn't be read.\n */\n env: string[];\n}\n\n/**\n * Bake the linux-vm base snapshot.\n */\nexport async function bakeDaytonaVmBase(opts: VmBaseBakeOptions): Promise<VmBaseBakeResult> {\n const log = opts.onLog ?? (() => {});\n let imageEnv: string[] = [];\n const override = opts.baseImage?.trim();\n const registry = opts.registry && opts.registry.length > 0 ? opts.registry : BOX_IMAGE_REGISTRY;\n const imageRef = override || registryRefForSha(opts.dockerBaseSha, registry);\n\n // An explicit override is the user's problem to get right — if it doesn't\n // exist, Daytona's own error is clearer than a guess from us, and silently\n // downgrading them to a container would ignore what they asked for.\n if (!override && !(await ghcrTagExists(imageRef))) {\n throw new VmBaseImageUnavailableError(\n `the linux-vm base needs a published box image, and '${imageRef}' isn't in the registry.`,\n );\n }\n if (override) log(`using box.daytonaVmBaseImage override: ${imageRef}`);\n\n // Tier 1: the plain box image as a VM snapshot. Content-addressed by the\n // docker sha, so a re-bake with different agent config reuses it (this is the\n // expensive step — it pulls a ~2 GB image). An overridden image gets its own\n // name so it can't collide with a fingerprint-derived one.\n const vmBaseStem = override\n ? `agentbox-vmbase-x${sha12(override)}`\n : `agentbox-vmbase-${opts.dockerBaseSha.slice(0, 12)}`;\n\n let vmBaseName = vmBaseStem;\n if (await snapshotIsActive(opts.client, vmBaseName)) {\n log(`reusing linux-vm base image snapshot '${vmBaseName}'`);\n } else {\n vmBaseName = await createVmBaseSnapshot(opts, vmBaseStem, imageRef, log);\n }\n\n // Tier 2: boot it, provision in-place, snapshot the result.\n log('booting a throwaway sandbox to seed the base…');\n let sandbox;\n try {\n sandbox = await opts.client.create({ snapshot: vmBaseName }, { timeout: 900 });\n } catch {\n // A snapshot recreated under a recently-deleted name reports `active` but\n // cannot boot (\"Sandbox failed to start: internal error\") — Daytona's delete\n // is async and racing it corrupts the new snapshot. Nothing distinguishes\n // this from a healthy snapshot until you try to boot it, so treat a boot\n // failure as \"the base is poisoned\", rebuild under a name that has never\n // existed, and retry once.\n log(`linux-vm base '${vmBaseName}' failed to boot; rebuilding it under a fresh name…`);\n await deleteSnapshotQuietly(opts.client, vmBaseName);\n vmBaseName = await createVmBaseSnapshot(opts, `${vmBaseStem}-${nonce()}`, imageRef, log);\n sandbox = await opts.client.create({ snapshot: vmBaseName }, { timeout: 900 });\n }\n const handle: CloudHandle = { sandboxId: sandbox.id, sandboxClass: 'linux-vm' };\n try {\n const wait = await opts.backend.exec(handle, buildDockerWaitCommand());\n if (wait.exitCode !== 0) {\n throw new Error(\n 'dockerd never came up in the VM base, so sudo cannot be repaired ' +\n '(the repair borrows root from the docker socket).',\n );\n }\n log('repairing sudo (the VM rootfs conversion strips setuid bits)…');\n const repair = await opts.backend.exec(handle, buildSudoRepairCommand());\n if (repair.exitCode !== 0) {\n throw new Error(\n `failed to restore sudo in the VM base (exit ${String(repair.exitCode)}): ` +\n `${repair.stdout}${repair.stderr}`,\n );\n }\n\n // The conversion drops the image's ENV along with the setuid bits. Put it\n // back on disk (needs the sudo we just repaired). Without it a VM box has no\n // DISPLAY, and the in-box browser dies with \"Missing X server or $DISPLAY\".\n imageEnv = (await fetchImageEnv(imageRef)) ?? [];\n if (imageEnv.length > 0) {\n log(`restoring the image's ${String(imageEnv.length)} env vars (the VM conversion drops them)…`);\n const envFix = await opts.backend.exec(handle, buildEnvRestoreCommand(imageEnv));\n if (envFix.exitCode !== 0) {\n throw new Error(\n `failed to restore the image environment in the VM base (exit ${String(envFix.exitCode)}): ` +\n `${envFix.stdout}${envFix.stderr}`,\n );\n }\n } else {\n log(\n `warning: could not read the environment of '${imageRef}' from the registry — ` +\n `a VM box may come up without DISPLAY (no in-box browser).`,\n );\n }\n\n await seedAgentStaticIntoCloudBox(opts.backend, handle, {\n hostWorkspace: opts.hostWorkspace,\n claudeMdOverlay: opts.claudeMdOverlay,\n onLog: log,\n });\n\n // Cold snapshot: filesystem only, and Daytona requires the sandbox STOPPED.\n // It does not stop for you.\n log('stopping the sandbox to capture a cold snapshot…');\n await sandbox.stop();\n // Never reuse a name (see the boot-failure comment above): a re-bake gets a\n // fresh one and the snapshot it replaces is deleted afterwards. The name\n // doesn't need to be deterministic — prepared state records whatever we\n // pinned, and that's what the skip-rebuild check reads.\n const finalName = `${opts.snapshotName}-${nonce()}`;\n log(`capturing base snapshot '${finalName}'…`);\n await sandbox._experimental_createSnapshot(finalName, 900);\n await waitForSnapshotActive(opts.client, finalName);\n log(`snapshot '${finalName}' is active`);\n return { snapshotName: finalName, env: imageEnv };\n } finally {\n // Always reap the throwaway — an orphan VM bills by the hour.\n try {\n await sandbox.delete(120);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log(`warning: could not delete the temporary bake sandbox ${sandbox.id}: ${msg}`);\n }\n }\n}\n\n/** Stable 12-hex digest of an image ref, for a collision-free snapshot name. */\nfunction sha12(s: string): string {\n return createHash('sha256').update(s).digest('hex').slice(0, 12);\n}\n\n/** Short, monotonic, never-reused token for a snapshot name. */\nfunction nonce(): string {\n return Math.floor(Date.now() / 1000).toString(36);\n}\n\nasync function createVmBaseSnapshot(\n opts: VmBaseBakeOptions,\n name: string,\n imageRef: string,\n log: (line: string) => void,\n): Promise<string> {\n log(`creating linux-vm base image snapshot '${name}' from ${imageRef}…`);\n await opts.client.snapshot.create(\n {\n name,\n image: imageRef,\n sandboxClass: SandboxClass.LINUX_VM,\n regionId: opts.regionId,\n // Always explicit: a snapshot with no `resources` gets Daytona's 1 vCPU /\n // 1 GiB / 3 GiB default, and the box image does not fit in 3 GiB — the\n // build dies mid-pull with a bare \"internal error\".\n resources: opts.resources ?? { cpu: 2, memory: 4, disk: 8 },\n },\n { onLogs: (c: string) => log(String(c).split('\\n').filter(Boolean).join(' ')) },\n );\n return name;\n}\n\nasync function snapshotIsActive(client: Daytona, name: string): Promise<boolean> {\n try {\n const snap = await client.snapshot.get(name);\n return snap?.state === 'active';\n } catch {\n return false;\n }\n}\n\n/** Best-effort delete — used to reap a superseded or poisoned snapshot. */\nexport async function deleteSnapshotQuietly(client: Daytona, name: string): Promise<void> {\n try {\n const snap = await client.snapshot.get(name);\n await client.snapshot.delete(snap);\n } catch {\n /* already gone, or never existed */\n }\n}\n","/**\n * Doctor probes + normalized credential status for the daytona provider,\n * assembled into `providerModule` in `index.ts`. Moved out of apps/cli so the\n * CLI dispatches to it generically (see `@agentbox/sandbox-core`'s `ProviderModule`).\n */\n\nimport { loadEffectiveConfig, resolveDaytonaClass } from '@agentbox/config';\nimport { errSummary, type CheckResult, type CredStatusSummary } from '@agentbox/sandbox-core';\nimport { readPreparedDaytonaState } from './prepared-state.js';\nimport { getDaytonaStatus, hasDaytonaCredentials } from './status.js';\n\nexport function readCredStatusSummary(): CredStatusSummary {\n // Credentials only — no network. This runs in the install wizard's provider\n // step just to answer \"logged in?\", and it used to fetch the whole snapshot +\n // volume inventory to do it.\n return { configured: hasDaytonaCredentials().configured };\n}\n\nexport async function doctorChecks(): Promise<CheckResult[]> {\n try {\n // Snapshots only: the rows below render the snapshot count and nothing else,\n // so the volume list was a second API round-trip whose result was discarded.\n const status = await getDaytonaStatus({ volumes: false });\n if (!status.configured) {\n return [\n {\n label: 'credentials',\n status: 'warn',\n // The SDK's reason is a paragraph (env-var enumeration) — doctor just\n // needs the vercel/e2b-style one-liner; `prepare --status` keeps it.\n detail: 'not configured',\n hint: '`agentbox daytona login`',\n },\n ];\n }\n const credRes: CheckResult = { label: 'credentials', status: 'ok', detail: 'configured' };\n return [credRes, await baseSnapshotCheck(status.snapshots.length)];\n } catch (err) {\n return [{ label: 'credentials', status: 'warn', detail: errSummary(err) }];\n }\n}\n\n/**\n * A snapshot existing isn't enough: a snapshot's class is immutable and can only\n * create sandboxes of that same class, so a container base with\n * `box.daytonaClass: linux-vm` configured is unusable — every create would fail.\n * Counting snapshots would report that as healthy, so compare the class too.\n */\nasync function baseSnapshotCheck(snapshotCount: number): Promise<CheckResult> {\n if (snapshotCount === 0) {\n return {\n label: 'base snapshot',\n status: 'warn',\n detail: 'none',\n hint: '`agentbox prepare --provider daytona`',\n };\n }\n const prepared = readPreparedDaytonaState();\n // Absent `class` = a snapshot baked before classes existed, which was\n // necessarily a container.\n const bakedClass = prepared?.base ? (prepared.extras?.class ?? 'container') : undefined;\n\n let wantClass: string | undefined;\n try {\n wantClass = resolveDaytonaClass((await loadEffectiveConfig(process.cwd())).effective);\n } catch {\n // No project config to read (e.g. doctor run outside a project) — the count\n // is still worth reporting; just don't claim anything about the class.\n }\n\n if (bakedClass && wantClass && bakedClass !== wantClass) {\n return {\n label: 'base snapshot',\n status: 'warn',\n detail: `baked as '${bakedClass}' but box.daytonaClass is '${wantClass}' — creates will fail`,\n hint: '`agentbox prepare --provider daytona --force`',\n };\n }\n return {\n label: 'base snapshot',\n status: 'ok',\n detail: `${String(snapshotCount)} agentbox snapshot(s)${bakedClass ? ` (base: ${bakedClass})` : ''}`,\n };\n}\n","/**\n * Read-only status helpers for `agentbox prepare` (no-args mode). Surfaces\n * the user-facing inventory of agentbox-owned base images / snapshots /\n * volumes on the configured Daytona org so the user can see at a glance\n * what's already prepared and what isn't.\n *\n * Daytona-side state lives in two places:\n * - **Snapshots** — built by `agentbox prepare --provider daytona`. Listed\n * filtered to `agentbox*` so we don't surface unrelated org snapshots.\n * - **Volumes** — the per-org `agentbox-credentials` volume created lazily\n * by `ensureAgentVolumesForCloud` on first `agentbox create --provider\n * daytona`.\n *\n * All calls swallow auth/network errors and return an empty section — the\n * status command must work for users who don't have Daytona configured.\n */\n\nimport { ensureDaytonaEnvLoaded } from './env-loader.js';\nimport { getClient } from './backend.js';\n\nexport interface DaytonaSnapshotSummary {\n name: string;\n state?: string;\n /** Snapshot size in GB, as reported by Daytona (may be undefined for non-`active` states). */\n sizeGb?: number;\n createdAt?: string;\n errorReason?: string;\n}\n\nexport interface DaytonaVolumeSummary {\n name: string;\n id: string;\n state?: string;\n createdAt?: string;\n lastUsedAt?: string;\n}\n\nexport interface DaytonaStatus {\n /** True when Daytona credentials are present + the SDK could connect. */\n configured: boolean;\n /** Snapshots whose name starts with `agentbox` (case-insensitive). */\n snapshots: DaytonaSnapshotSummary[];\n /** Volumes whose name starts with `agentbox` (case-insensitive). */\n volumes: DaytonaVolumeSummary[];\n /** Non-fatal explanation when `configured` is false. */\n reason?: string;\n}\n\nfunction isAgentboxName(name: unknown): boolean {\n return typeof name === 'string' && name.toLowerCase().startsWith('agentbox');\n}\n\n/**\n * Upper bound on a status list call. This is a *diagnostic* read — a hung API\n * must degrade to \"couldn't list\" rather than stall the caller. `doctor` in\n * particular prints no spinner, so an unbounded await just looks like a freeze.\n * Mirrors the bound the cloud-state probes already use host-side.\n */\nconst STATUS_PROBE_TIMEOUT_MS = 8000;\n\nfunction withStatusTimeout<T>(p: Promise<T>, what: string): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const t = setTimeout(\n () => reject(new Error(`${what} timed out after ${String(STATUS_PROBE_TIMEOUT_MS)}ms`)),\n STATUS_PROBE_TIMEOUT_MS,\n );\n // The SDK call keeps running; we just stop waiting on it. unref so a pending\n // timer can't hold the process open after the CLI is done.\n t.unref?.();\n p.then(\n (v) => {\n clearTimeout(t);\n resolve(v);\n },\n (e: unknown) => {\n clearTimeout(t);\n reject(e instanceof Error ? e : new Error(String(e)));\n },\n );\n });\n}\n\n/**\n * Are Daytona credentials present? Credential-only: constructs the SDK client\n * (which throws when no key/JWT is configured) and makes **no network call**.\n *\n * This is what `configured` in {@link DaytonaStatus} has always meant — the\n * status helper sets it as soon as the client is built, before any list. Callers\n * that only want that answer (the install wizard's provider picker, doctor's\n * \"credentials\" row) should ask here rather than pay for two API round-trips.\n */\nexport function hasDaytonaCredentials(): { configured: boolean; reason?: string } {\n try {\n ensureDaytonaEnvLoaded();\n getClient();\n return { configured: true };\n } catch (err) {\n return {\n configured: false,\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n}\n\nexport interface DaytonaStatusOptions {\n /**\n * Fetch the volume list. Each list is a separate round-trip to the Daytona\n * API, and `doctor` renders only the snapshot count — so it asks for snapshots\n * alone and halves the network cost of the check. `prepare --status`, which\n * prints the volume inventory, leaves this on. Default true (the full picture).\n */\n volumes?: boolean;\n}\n\n/**\n * Collect a read-only summary of agentbox-owned snapshots + volumes on the\n * Daytona org. Never throws — failure paths return `configured: false` with\n * a one-line reason.\n *\n * Only reaches the network when credentials are present: with no key `getClient()`\n * throws and we return `configured: false` before any request — so an unconfigured\n * machine pays nothing.\n */\nexport async function getDaytonaStatus(opts: DaytonaStatusOptions = {}): Promise<DaytonaStatus> {\n const wantVolumes = opts.volumes !== false;\n try {\n ensureDaytonaEnvLoaded();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n\n let client;\n try {\n client = getClient();\n } catch (err) {\n return {\n configured: false,\n snapshots: [],\n volumes: [],\n reason: err instanceof Error ? err.message.split('\\n')[0] : String(err),\n };\n }\n\n const snapshots: DaytonaSnapshotSummary[] = [];\n const volumes: DaytonaVolumeSummary[] = [];\n const reasons: string[] = [];\n\n // Both lists are independent round-trips; issue them together rather than\n // back to back. Each is bounded — an unreachable/slow Daytona must degrade to\n // \"couldn't list\" rather than hang `doctor` (which has no spinner at all, so a\n // stall just looks like a freeze).\n const listSnapshots = async (): Promise<void> => {\n try {\n const list = await withStatusTimeout(client.snapshot.list(), 'snapshot list');\n const items = (list as { items?: unknown[] }).items ?? (Array.isArray(list) ? list : []);\n for (const s of items) {\n const dto = s as { name?: unknown; state?: unknown; size?: unknown; createdAt?: unknown; errorReason?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n snapshots.push({\n name: dto.name as string,\n state: typeof dto.state === 'string' ? dto.state : undefined,\n sizeGb: typeof dto.size === 'number' ? dto.size : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n errorReason: typeof dto.errorReason === 'string' ? dto.errorReason : undefined,\n });\n }\n } catch (err) {\n reasons.push(\n `snapshot list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`,\n );\n }\n };\n\n const listVolumes = async (): Promise<void> => {\n try {\n const list = await withStatusTimeout(client.volume.list(), 'volume list');\n const items: unknown[] = Array.isArray(list)\n ? list\n : ((list as { items?: unknown[] }).items ?? []);\n for (const v of items) {\n const dto = v as { name?: unknown; id?: unknown; state?: unknown; createdAt?: unknown; lastUsedAt?: unknown };\n if (!isAgentboxName(dto.name)) continue;\n volumes.push({\n name: dto.name as string,\n id: typeof dto.id === 'string' ? dto.id : '',\n state: typeof dto.state === 'string' ? dto.state : undefined,\n createdAt: typeof dto.createdAt === 'string' ? dto.createdAt : undefined,\n lastUsedAt: typeof dto.lastUsedAt === 'string' ? dto.lastUsedAt : undefined,\n });\n }\n } catch (err) {\n reasons.push(\n `volume list failed: ${err instanceof Error ? err.message.split('\\n')[0] : String(err)}`,\n );\n }\n };\n\n await Promise.all(wantVolumes ? [listSnapshots(), listVolumes()] : [listSnapshots()]);\n const reason = reasons.length > 0 ? reasons.join('; ') : undefined;\n\n return {\n configured: true,\n snapshots: snapshots.sort((a, b) => (b.createdAt ?? '').localeCompare(a.createdAt ?? '')),\n volumes: volumes.sort((a, b) => a.name.localeCompare(b.name)),\n reason,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEsBA,SAAS,cAAc,aAAa,cAAc,QAAQ,qBAAqB;AAC/E,SAAS,cAAc;AACvB,SAAS,SAAS,YAAY;AAC9B,SAAS,aAAa;ACQtB,SAAS,kBAAkB;AAG3B,SAAS,oBAAoB;AFF7B,IAAM,eAAe;AAEd,SAAS,sBAAsBA,gBAA6C;AACjF,SAAO;IACL,MAAM,OAAO,KAAgB,MAAc;AACzC,UAAI,CAAC,IAAI,aAAa;AACpB,cAAM,IAAI;UACR;QACF;MACF;AACA,YAAM,YAAY,IAAI,OAAO;AAC7B,UAAI,CAAC,WAAW;AACd,cAAM,IAAI,MAAM,eAAe,IAAI,IAAI,8CAAyC;MAClF;AACA,YAAM,SAAS,EAAE,WAAW,cAAc,IAAI,OAAO,aAAa;AAElE,YAAM,eAAe,GAAG,kBAAkB,IAAI,aAAa,IAAI,CAAC,IAAI,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,EAAE,SAAS,EAAE,CAAC;AAE9G,YAAM,eAAe,iBAAiB,QAAQ,YAAY;AAK1D,YAAMA,eAAc,UAAU,GAAG;AAEjC,YAAM,OAAO,MAAM,6BAA6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