@madarco/agentbox 0.26.1 → 0.27.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README.md +1 -1
- package/dist/{_cloud-attach-7WRQH6XZ.js → _cloud-attach-WDGM6FL5.js} +4 -4
- package/dist/{chunk-UIFL7F2G.js → chunk-26IKZRTT.js} +2 -2
- package/dist/chunk-G3H2L3O2.js +0 -0
- package/dist/{chunk-DJQMK4RN.js → chunk-HR7NHH5J.js} +14 -9
- package/dist/chunk-HR7NHH5J.js.map +1 -0
- package/dist/{chunk-K5KOLYIL.js → chunk-IDH5A4RR.js} +2 -2
- package/dist/{chunk-ZY7M7MXH.js → chunk-JE6UI5YR.js} +10 -10
- package/dist/chunk-JGZSA5ZI.js +0 -0
- package/dist/{chunk-7ZZAZPYX.js → chunk-KWOEUFVA.js} +2 -2
- package/dist/{chunk-BA2VLJVU.js → chunk-LL7NCMUU.js} +3 -3
- package/dist/{chunk-I2OAJS3L.js → chunk-NEF6MDJO.js} +4 -4
- package/dist/{chunk-I2OAJS3L.js.map → chunk-NEF6MDJO.js.map} +1 -1
- package/dist/{dist-YA7EXBGG.js → chunk-SJ75AIA2.js} +486 -92
- package/dist/chunk-SJ75AIA2.js.map +1 -0
- package/dist/{chunk-PK2QF4IR.js → chunk-UJEH2NJT.js} +27 -14
- package/dist/chunk-UJEH2NJT.js.map +1 -0
- package/dist/{chunk-DQHMDDAT.js → chunk-V5XXJH63.js} +2 -2
- package/dist/chunk-WJFZJZIM.js +0 -0
- package/dist/cloud-poller-SUNA6ZQC-7M5LJHHE.js +0 -0
- package/dist/{dist-DTNYMBQ5.js → dist-FTKS2GI4.js} +5 -5
- package/dist/{dist-5IICYSR6.js → dist-KQTMCVME.js} +5 -5
- package/dist/{dist-5IICYSR6.js.map → dist-KQTMCVME.js.map} +1 -1
- package/dist/{dist-AR5CHRSV.js → dist-O3LKOIE7.js} +5 -5
- package/dist/{dist-POVRY7HO.js → dist-OO52HARR.js} +3 -3
- package/dist/{dist-K4LNH3EC.js → dist-TSFVB7AI.js} +5 -5
- package/dist/dist-U2SVLJUQ.js +0 -0
- package/dist/{dist-XYY6SIKG.js → dist-WVYAURMF.js} +5 -5
- package/dist/dist-Z6L5MM5D.js +46 -0
- package/dist/index.js +392 -211
- package/dist/index.js.map +1 -1
- package/dist/{prepared-state-75DIZ55S-W6NU3S3B.js → prepared-state-75DIZ55S-TNJXWMXV.js} +2 -2
- package/dist/prepared-state-75DIZ55S-TNJXWMXV.js.map +1 -0
- package/package.json +31 -29
- package/runtime/_shared/agentbox-checkpoint-cleanup +0 -0
- package/runtime/_shared/agentbox-dockerd-start +0 -0
- package/runtime/_shared/agentbox-open +0 -0
- package/runtime/_shared/agentbox-portless-trust +0 -0
- package/runtime/_shared/agentbox-vnc-start +0 -0
- package/runtime/_shared/ctl.cjs +0 -0
- package/runtime/_shared/gh-shim +0 -0
- package/runtime/_shared/git-shim +0 -0
- package/runtime/_shared/linear-shim +0 -0
- package/runtime/_shared/ntn-shim +0 -0
- package/runtime/digitalocean/agentbox-checkpoint-cleanup +0 -0
- package/runtime/digitalocean/agentbox-dockerd-start +0 -0
- package/runtime/digitalocean/agentbox-open +0 -0
- package/runtime/digitalocean/agentbox-portless-trust +0 -0
- package/runtime/digitalocean/agentbox-vnc-start +0 -0
- package/runtime/digitalocean/ctl.cjs +0 -0
- package/runtime/digitalocean/gh-shim +0 -0
- package/runtime/digitalocean/git-shim +0 -0
- package/runtime/digitalocean/linear-shim +0 -0
- package/runtime/digitalocean/ntn-shim +0 -0
- package/runtime/digitalocean/scripts/install-box.sh +0 -0
- package/runtime/docker/packages/ctl/dist/bin.cjs +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-dockerd-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-open +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-portless-trust +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-sshd-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-vnc-start +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/chromium-resolver +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/gh-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/git-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/linear-shim +0 -0
- package/runtime/docker/packages/sandbox-docker/scripts/ntn-shim +0 -0
- package/runtime/e2b/agentbox-checkpoint-cleanup +0 -0
- package/runtime/e2b/agentbox-dockerd-start +0 -0
- package/runtime/e2b/agentbox-open +0 -0
- package/runtime/e2b/agentbox-vnc-start +0 -0
- package/runtime/e2b/ctl.cjs +0 -0
- package/runtime/e2b/gh-shim +0 -0
- package/runtime/e2b/git-shim +0 -0
- package/runtime/e2b/linear-shim +0 -0
- package/runtime/e2b/ntn-shim +0 -0
- package/runtime/e2b/scripts/build-template.sh +0 -0
- package/runtime/hetzner/agentbox-checkpoint-cleanup +0 -0
- package/runtime/hetzner/agentbox-dockerd-start +0 -0
- package/runtime/hetzner/agentbox-open +0 -0
- package/runtime/hetzner/agentbox-portless-trust +0 -0
- package/runtime/hetzner/agentbox-vnc-start +0 -0
- package/runtime/hetzner/ctl.cjs +0 -0
- package/runtime/hetzner/gh-shim +0 -0
- package/runtime/hetzner/git-shim +0 -0
- package/runtime/hetzner/linear-shim +0 -0
- package/runtime/hetzner/ntn-shim +0 -0
- package/runtime/hetzner/scripts/install-box.sh +0 -0
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/prerender-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/routes-manifest.json +22 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +1 -1
- 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/(auth)/signin/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route.js +2 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/docs/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route.js +2 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/openapi.json/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page/server-reference-manifest.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/server-reference-manifest.json +12 -12
- 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/server-reference-manifest.json +11 -11
- 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/server-reference-manifest.json +8 -8
- 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.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/_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/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_api_v1_hosts_route_actions_0b_404_.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0web_next-internal_server_app_(dashboard)_api_v1_hosts_[alias]_route_actions_0swypy5.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/0zhp_better-auth_dist_adapters_kysely-adapter_index_mjs_1rl4qnh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_hosts_[alias]_bake_route_actions_1-_pu3n.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0a7djvw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0bmro0b._.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]__0keu6we._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0t4qmv-._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0xh14bo._.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]__13ioh5z._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1k8g143._.js → [root-of-the-server]__19pc87s._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4xycg._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1hqla7-._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1md9kdw._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/_0760z6y._.js +4 -4
- package/runtime/hub/apps/hub/.next/server/chunks/_1bng7w9._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_openapi_ts_1yokmzt._.js +14 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/044u_hub__next-internal_server_app_(dashboard)_projects_[id]_page_actions_15f56np.js +1 -1
- 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/[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]__10bfmwi._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/[root-of-the-server]__18qvdzb._.js +1 -1
- 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/_03s-ah2._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0kpdmm-._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0ozyjt1._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0r4px38._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_18w2zeh._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0od97-d._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(dashboard)_approvals_page_actions_1mi0bpn.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(dashboard)_boxes_[id]_page_actions_0k7kgn2.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub__next-internal_server_app_(dashboard)_page_actions_1t3u0xy.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_[id]_page_tsx_1-j_972._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_boxes_components_box-table_tsx_0a9pyn_._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_app_(dashboard)_settings_page_tsx_0hv6n82._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/.next/server/server-reference-manifest.js +1 -1
- package/runtime/hub/apps/hub/.next/server/server-reference-manifest.json +18 -18
- package/runtime/hub/apps/hub/.next/static/chunks/070w7h5rh5ja6.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/1_ur0im1g7_s9.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/{000a1sa7te1h8.js → 2awpm9w8crker.js} +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/{3-zanu4ioia5i.js → 2gfw8-qyx5xi_.js} +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/30de2x24ntwkg.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3e5n630psqst8.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/3tqnniym2yvpb.js +1 -0
- package/runtime/hub/apps/hub/.next/static/chunks/{3dfjrxx-dy644.css → 42uysd_max-yq.css} +1 -1
- package/runtime/hub/apps/hub/{chunk-BARD2DI6.js → chunk-EHBJKZCL.js} +13 -8
- package/runtime/hub/apps/hub/{chunk-4QY2VZCF.js → chunk-RXYOWSSN.js} +19 -13
- package/runtime/hub/apps/hub/{chunk-XZZXPEVV.js → chunk-YJ5MJOXK.js} +1 -1
- package/runtime/hub/apps/hub/{dist-3ENKQN5G.js → dist-3I7KUI6W.js} +3 -3
- package/runtime/hub/apps/hub/{dist-WAZKGVYL.js → dist-6FPPUSWZ.js} +2 -2
- package/runtime/hub/apps/hub/{dist-NNBELNA7.js → dist-DX6IYMAH.js} +300 -109
- package/runtime/hub/apps/hub/{dist-RJJ2SDYO.js → dist-G6TXUSPZ.js} +3 -3
- package/runtime/hub/apps/hub/{dist-AE6IV4FV.js → dist-GTVVXCBP.js} +3 -3
- package/runtime/hub/apps/hub/{dist-6VGJOQYK.js → dist-JG45OFT2.js} +3 -3
- package/runtime/hub/apps/hub/{dist-TU7D6UTB.js → dist-LYDHYTP2.js} +3 -3
- package/runtime/hub/apps/hub/{prepared-state-75DIZ55S-NYEDSU2U.js → prepared-state-75DIZ55S-2IFNUHHM.js} +1 -1
- package/runtime/hub/apps/hub/server.js +136 -19
- package/runtime/relay/bin.cjs +0 -0
- package/runtime/vercel/agentbox-checkpoint-cleanup +0 -0
- package/runtime/vercel/agentbox-dockerd-start +0 -0
- package/runtime/vercel/agentbox-open +0 -0
- package/runtime/vercel/agentbox-vnc-start +0 -0
- package/runtime/vercel/ctl.cjs +0 -0
- package/runtime/vercel/gh-shim +0 -0
- package/runtime/vercel/git-shim +0 -0
- package/runtime/vercel/linear-shim +0 -0
- package/runtime/vercel/ntn-shim +0 -0
- package/runtime/vercel/scripts/provision.sh +0 -0
- package/LICENSE +0 -21
- package/dist/chunk-DJQMK4RN.js.map +0 -1
- package/dist/chunk-PK2QF4IR.js.map +0 -1
- package/dist/chunk-ZYKNSHOH.js +0 -259
- package/dist/chunk-ZYKNSHOH.js.map +0 -1
- package/dist/dist-YA7EXBGG.js.map +0 -1
- package/runtime/hub/apps/hub/.next/server/chunks/0-fj_better-auth_dist_adapters_kysely-adapter_index_mjs_0btft52._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1bqbkd5._.js +0 -14
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qa4a0v._.js +0 -14
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_09gdzmo._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0tgpglr._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_1laion6._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/apps_hub_0b_hsjl._.js +0 -3
- package/runtime/hub/apps/hub/.next/static/chunks/1c5w3kqosumog.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/1o3ot_9-8jgzc.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/1z4elhg8gyq98.js +0 -1
- package/runtime/hub/apps/hub/.next/static/chunks/3uq9hf-roasav.js +0 -1
- /package/dist/{_cloud-attach-7WRQH6XZ.js.map → _cloud-attach-WDGM6FL5.js.map} +0 -0
- /package/dist/{chunk-UIFL7F2G.js.map → chunk-26IKZRTT.js.map} +0 -0
- /package/dist/{chunk-K5KOLYIL.js.map → chunk-IDH5A4RR.js.map} +0 -0
- /package/dist/{chunk-ZY7M7MXH.js.map → chunk-JE6UI5YR.js.map} +0 -0
- /package/dist/{chunk-7ZZAZPYX.js.map → chunk-KWOEUFVA.js.map} +0 -0
- /package/dist/{chunk-BA2VLJVU.js.map → chunk-LL7NCMUU.js.map} +0 -0
- /package/dist/{chunk-DQHMDDAT.js.map → chunk-V5XXJH63.js.map} +0 -0
- /package/dist/{dist-DTNYMBQ5.js.map → dist-FTKS2GI4.js.map} +0 -0
- /package/dist/{dist-AR5CHRSV.js.map → dist-O3LKOIE7.js.map} +0 -0
- /package/dist/{dist-POVRY7HO.js.map → dist-OO52HARR.js.map} +0 -0
- /package/dist/{dist-K4LNH3EC.js.map → dist-TSFVB7AI.js.map} +0 -0
- /package/dist/{dist-XYY6SIKG.js.map → dist-WVYAURMF.js.map} +0 -0
- /package/dist/{prepared-state-75DIZ55S-W6NU3S3B.js.map → dist-Z6L5MM5D.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{mJYh9UHTsLaGGyRjBSvme → PWF2iHQOg9-rRyfqVDLrh}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{mJYh9UHTsLaGGyRjBSvme → PWF2iHQOg9-rRyfqVDLrh}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{mJYh9UHTsLaGGyRjBSvme → PWF2iHQOg9-rRyfqVDLrh}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/sandbox-hetzner/src/env-loader.ts","../../../packages/sandbox-hetzner/src/client.ts","../../../packages/sandbox-hetzner/src/credentials.ts","../../../packages/sandbox-hetzner/src/egress-ip.ts","../../../packages/sandbox-hetzner/src/retry.ts","../../../packages/sandbox-hetzner/src/firewall.ts","../../../packages/sandbox-hetzner/src/runtime-assets.ts","../../../packages/sandbox-hetzner/src/prepared-state.ts","../../../packages/sandbox-hetzner/src/index.ts","../../../packages/sandbox-hetzner/src/backend.ts","../../../packages/sandbox-hetzner/src/cloud-init.ts","../../../packages/sandbox-hetzner/src/poll.ts","../../../packages/sandbox-hetzner/src/preflight.ts","../../../packages/sandbox-hetzner/src/prepare.ts","../../../packages/sandbox-hetzner/src/ssh-key.ts","../../../packages/sandbox-hetzner/src/ssh-cli.ts","../../../packages/sandbox-hetzner/src/ssh-tunnel.ts","../../../packages/sandbox-hetzner/src/provider-module.ts","../../../packages/sandbox-hetzner/src/control-plane-deploy.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\n/**\n * Hetzner env auto-loader — mirrors `ensureDaytonaEnvLoaded()`. The Hetzner\n * REST client reads `HCLOUD_TOKEN` from `process.env`. We pull it in from\n * `~/.agentbox/secrets.env` so the client Just Works after the user runs\n * `agentbox hetzner login` once.\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 hetzner login`.\n *\n * Project-level `.env` / `.env.local` are intentionally NOT consulted: those\n * files belong to the app code being developed, and a `HCLOUD_TOKEN` there\n * is typically meant for in-box infrastructure work, not for the host CLI to\n * harvest and provision VPSes with.\n *\n * Only Hetzner-prefixed keys are imported. Idempotent + side-effect-free\n * after the first call.\n */\nconst HETZNER_KEYS = ['HCLOUD_TOKEN', 'HCLOUD_ENDPOINT'] as const;\n\nlet loaded = false;\n\nexport function ensureHetznerEnvLoaded(): void {\n if (loaded) return;\n loaded = true;\n importHetznerFromFile(resolve(homedir(), '.agentbox', 'secrets.env'));\n}\n\nfunction importHetznerFromFile(path: 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 HETZNER_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 with spaces\"`,\n * `KEY='value with $special chars'`, `export KEY=value`, blank lines, and\n * `#` comments. Same shape as the daytona env-loader's parser — kept local\n * here rather than imported across packages to avoid the cycle (daytona\n * doesn't import from hetzner and shouldn't start now).\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 * Hetzner Cloud REST API client — hand-rolled fetch wrapper.\n *\n * Why not an SDK: the Hetzner SDK options are limited (no official JS SDK\n * with strict types at the time of writing), and the subset of the API we\n * need is small (servers, images, firewalls, plus a handful of read-only\n * lookups). A hand-rolled client gives us strict typing of just the fields\n * we touch, no heavy dep tree, and full control over the retry wrapper.\n *\n * Auth: bearer token in `HCLOUD_TOKEN` env. The env-loader pulls it from\n * `~/.agentbox/secrets.env` so the user only sets it once via\n * `agentbox hetzner login`.\n *\n * Errors: REST responses get unwrapped into typed `HetznerApiError`s that\n * carry the response `status` + the API's `error.code` / `error.message`.\n * Network failures bubble up as raw `Error`s with a `code` property\n * (ECONNRESET, ETIMEDOUT, …) — the retry wrapper classifies both shapes.\n */\n\nimport { ensureHetznerEnvLoaded } from './env-loader.js';\n\nexport const DEFAULT_HCLOUD_ENDPOINT = 'https://api.hetzner.cloud/v1';\n\n/**\n * Coarse Hetzner Cloud Server lifecycle states we care about. Hetzner has a\n * dozen finer-grained ones (`initializing`, `migrating`, `rebuilding`, …);\n * we map them in `backend.ts` to the four-value `CloudState` everyone else\n * consumes. Listed here so the client return types stay narrow.\n */\nexport type HetznerServerStatus =\n | 'running'\n | 'initializing'\n | 'starting'\n | 'stopping'\n | 'off'\n | 'deleting'\n | 'migrating'\n | 'rebuilding'\n | 'unknown';\n\nexport interface HetznerServer {\n id: number;\n name: string;\n status: HetznerServerStatus;\n created: string;\n public_net: {\n ipv4: { ip: string; blocked: boolean } | null;\n ipv6: { ip: string; blocked: boolean } | null;\n };\n server_type: { name: string; cores: number; memory: number; disk: number };\n image: { id: number; name?: string; description?: string; type: string } | null;\n labels: Record<string, string>;\n}\n\nexport interface HetznerAction {\n id: number;\n command: string;\n status: 'running' | 'success' | 'error';\n progress: number;\n error?: { code: string; message: string };\n}\n\nexport interface HetznerImage {\n id: number;\n type: 'system' | 'snapshot' | 'backup' | 'app';\n status: 'available' | 'creating' | 'unavailable';\n name?: string;\n description: string;\n image_size?: number;\n disk_size: number;\n /** CPU architecture the image is built for. Snapshots inherit the source VPS. */\n architecture?: 'x86' | 'arm';\n created: string;\n labels: Record<string, string>;\n bound_to?: number;\n}\n\n/**\n * A Hetzner server type (VPS plan), narrowed to the fields the preflight\n * validator reads. `memory`/`disk` are GB (memory is a float, e.g. `4`, `7.75`).\n * `prices[].location` is the authoritative \"offered here\" list. `deprecation`\n * is a non-null object once the type is on the deprecation path (the legacy\n * `deprecated` boolean mirrors it). See GET /server_types.\n */\nexport interface HetznerServerType {\n id: number;\n name: string;\n cores: number;\n memory: number;\n disk: number;\n architecture: 'x86' | 'arm';\n deprecated?: boolean;\n deprecation?: { announced?: string; unavailable_after?: string } | null;\n prices: Array<{ location: string }>;\n}\n\nexport interface HetznerFirewall {\n id: number;\n name: string;\n rules: HetznerFirewallRule[];\n applied_to: Array<{ type: 'server'; server: { id: number } }>;\n}\n\nexport interface HetznerFirewallRule {\n direction: 'in' | 'out';\n protocol: 'tcp' | 'udp' | 'icmp' | 'esp' | 'gre';\n port?: string;\n source_ips?: string[];\n destination_ips?: string[];\n description?: string;\n}\n\nexport interface HetznerSshKey {\n id: number;\n name: string;\n fingerprint: string;\n public_key: string;\n labels: Record<string, string>;\n}\n\nexport interface CreateServerRequest {\n name: string;\n server_type: string;\n image: string | number;\n location?: string;\n datacenter?: string;\n user_data?: string;\n ssh_keys?: Array<string | number>;\n firewalls?: Array<{ firewall: number }>;\n labels?: Record<string, string>;\n start_after_create?: boolean;\n public_net?: {\n enable_ipv4?: boolean;\n enable_ipv6?: boolean;\n };\n}\n\nexport interface CreateFirewallRequest {\n name: string;\n rules: HetznerFirewallRule[];\n labels?: Record<string, string>;\n apply_to?: Array<{ type: 'server'; server: { id: number } }>;\n}\n\n/**\n * Strongly-typed Hetzner API error. The Hetzner API consistently returns\n * `{ error: { code, message, details? } }` for 4xx/5xx (https://docs.hetzner.cloud/#errors).\n * We unwrap that into this class so callers can do `instanceof\n * HetznerApiError` and inspect `.code` / `.statusCode` without parsing the\n * body again.\n */\nexport class HetznerApiError extends Error {\n readonly statusCode: number;\n readonly code: string;\n readonly details?: unknown;\n constructor(statusCode: number, code: string, message: string, details?: unknown) {\n super(`hetzner ${String(statusCode)} ${code}: ${message}`);\n this.name = 'HetznerApiError';\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Subset of the Hetzner Cloud API the agentbox provider talks to. Methods\n * map 1:1 to REST endpoints; each operation is small + idempotent-where-the-\n * API-is-idempotent. The retry wrapper around the provider methods handles\n * transient 5xx / connection failures.\n */\nexport interface HetznerClient {\n /** GET /servers/{id}. Returns null on 404 so callers don't have to try/catch. */\n getServer(id: number): Promise<HetznerServer | null>;\n /** POST /servers. Returns the created server + the create action handle. */\n createServer(req: CreateServerRequest): Promise<{ server: HetznerServer; action: HetznerAction }>;\n /** GET /servers (with optional label selector). */\n listServers(opts?: { label_selector?: string }): Promise<HetznerServer[]>;\n /** DELETE /servers/{id}. Returns the action handle. Idempotent on 404. */\n deleteServer(id: number): Promise<HetznerAction | null>;\n /** POST /servers/{id}/actions/poweron. */\n powerOn(id: number): Promise<HetznerAction>;\n /** POST /servers/{id}/actions/poweroff. */\n powerOff(id: number): Promise<HetznerAction>;\n /** POST /servers/{id}/actions/shutdown — graceful, sends ACPI. */\n shutdown(id: number): Promise<HetznerAction>;\n /** POST /servers/{id}/actions/create_image — snapshot of the live disk. */\n createImage(\n id: number,\n body: { type: 'snapshot' | 'backup'; description?: string; labels?: Record<string, string> },\n ): Promise<{ image: HetznerImage; action: HetznerAction }>;\n /** GET /images/{id}. Returns null on 404. */\n getImage(id: number): Promise<HetznerImage | null>;\n /** GET /server_types — the VPS-plan catalog (paginated). Used by the create preflight. */\n listServerTypes(): Promise<HetznerServerType[]>;\n /** GET /images (filterable). */\n listImages(opts?: {\n type?: 'system' | 'snapshot' | 'backup' | 'app';\n label_selector?: string;\n name?: string;\n }): Promise<HetznerImage[]>;\n /** DELETE /images/{id}. Idempotent on 404. */\n deleteImage(id: number): Promise<void>;\n /** POST /firewalls. */\n createFirewall(req: CreateFirewallRequest): Promise<HetznerFirewall>;\n /** POST /firewalls/{id}/actions/set_rules. Replaces the entire rule set. */\n setFirewallRules(id: number, rules: HetznerFirewallRule[]): Promise<HetznerAction[]>;\n /** GET /firewalls/{id}. Returns null on 404. */\n getFirewall(id: number): Promise<HetznerFirewall | null>;\n /** DELETE /firewalls/{id}. Idempotent on 404. */\n deleteFirewall(id: number): Promise<void>;\n /**\n * GET /locations — used by `agentbox hetzner login` to validate the token\n * with a cheap unauthenticated-shape call (the endpoint requires a valid\n * token but returns a small, stable response).\n */\n listLocations(): Promise<Array<{ id: number; name: string; city: string; country: string }>>;\n}\n\ninterface MakeClientOptions {\n /** Override the bearer token (else read from `HCLOUD_TOKEN`). */\n token?: string;\n /** Override the API base URL (else read from `HCLOUD_ENDPOINT` or use the default). */\n endpoint?: string;\n /** Per-request fetch impl (tests inject this). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Build a Hetzner Cloud client bound to the current `HCLOUD_TOKEN`. The token\n * is resolved at construction time, so re-running `agentbox hetzner login` in\n * the middle of a long-lived process won't pick up the new token without a\n * fresh `makeHetznerClient()` call (we accept this — the CLI re-imports the\n * provider on each invocation).\n */\nexport function makeHetznerClient(opts: MakeClientOptions = {}): HetznerClient {\n ensureHetznerEnvLoaded();\n const rawToken = opts.token ?? process.env.HCLOUD_TOKEN;\n if (!rawToken || rawToken.trim().length === 0) {\n throw new Error(\n 'Hetzner credentials not configured: HCLOUD_TOKEN is empty.\\n' +\n 'Run `agentbox hetzner login` interactively, or set HCLOUD_TOKEN in the environment.',\n );\n }\n // Bind to a const so the type narrows for the closures below — without\n // this the `req()` closure sees the original `string | undefined` shape.\n const token: string = rawToken.trim();\n const endpoint = (opts.endpoint ?? process.env.HCLOUD_ENDPOINT ?? DEFAULT_HCLOUD_ENDPOINT).replace(/\\/$/, '');\n const fetchImpl = opts.fetchImpl ?? fetch;\n\n async function req<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown,\n ): Promise<T | null> {\n const url = `${endpoint}${path}`;\n const init: RequestInit = {\n method,\n headers: {\n Authorization: `Bearer ${token}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n };\n const res = await fetchImpl(url, init);\n if (res.status === 204) return null;\n if (res.status === 404) return null;\n if (!res.ok) {\n let parsed: { error?: { code?: string; message?: string; details?: unknown } } = {};\n try {\n parsed = (await res.json()) as typeof parsed;\n } catch {\n // body wasn't json\n }\n const code = parsed.error?.code ?? `http_${String(res.status)}`;\n const msg = parsed.error?.message ?? res.statusText ?? 'unknown error';\n throw new HetznerApiError(res.status, code, msg, parsed.error?.details);\n }\n const text = await res.text();\n if (text.length === 0) return null;\n return JSON.parse(text) as T;\n }\n\n async function reqExpect<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown,\n ): Promise<T> {\n const out = await req<T>(method, path, body);\n if (out === null) {\n throw new HetznerApiError(0, 'empty_response', `expected a body from ${method} ${path}`);\n }\n return out;\n }\n\n return {\n async getServer(id) {\n const r = await req<{ server: HetznerServer }>('GET', `/servers/${String(id)}`);\n return r?.server ?? null;\n },\n async createServer(reqBody) {\n const r = await reqExpect<{ server: HetznerServer; action: HetznerAction }>(\n 'POST',\n '/servers',\n reqBody,\n );\n return { server: r.server, action: r.action };\n },\n async listServers(opts) {\n const params = new URLSearchParams();\n if (opts?.label_selector) params.set('label_selector', opts.label_selector);\n params.set('per_page', '50');\n const all: HetznerServer[] = [];\n let pageNum = 1;\n while (true) {\n params.set('page', String(pageNum));\n const r = await reqExpect<{\n servers: HetznerServer[];\n meta?: { pagination?: { next_page?: number | null } };\n }>('GET', `/servers?${params.toString()}`);\n all.push(...r.servers);\n const next = r.meta?.pagination?.next_page;\n if (typeof next !== 'number') break;\n pageNum = next;\n }\n return all;\n },\n async deleteServer(id) {\n const r = await req<{ action: HetznerAction }>('DELETE', `/servers/${String(id)}`);\n return r?.action ?? null;\n },\n async powerOn(id) {\n const r = await reqExpect<{ action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/poweron`,\n );\n return r.action;\n },\n async powerOff(id) {\n const r = await reqExpect<{ action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/poweroff`,\n );\n return r.action;\n },\n async shutdown(id) {\n const r = await reqExpect<{ action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/shutdown`,\n );\n return r.action;\n },\n async createImage(id, body) {\n const r = await reqExpect<{ image: HetznerImage; action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/create_image`,\n body,\n );\n return { image: r.image, action: r.action };\n },\n async getImage(id) {\n const r = await req<{ image: HetznerImage }>('GET', `/images/${String(id)}`);\n return r?.image ?? null;\n },\n async listServerTypes() {\n const params = new URLSearchParams();\n params.set('per_page', '50');\n const all: HetznerServerType[] = [];\n let pageNum = 1;\n while (true) {\n params.set('page', String(pageNum));\n const r = await reqExpect<{\n server_types: HetznerServerType[];\n meta?: { pagination?: { next_page?: number | null } };\n }>('GET', `/server_types?${params.toString()}`);\n all.push(...r.server_types);\n const next = r.meta?.pagination?.next_page;\n if (typeof next !== 'number') break;\n pageNum = next;\n }\n return all;\n },\n async listImages(opts) {\n const params = new URLSearchParams();\n if (opts?.type) params.set('type', opts.type);\n if (opts?.label_selector) params.set('label_selector', opts.label_selector);\n if (opts?.name) params.set('name', opts.name);\n params.set('per_page', '50');\n const all: HetznerImage[] = [];\n let pageNum = 1;\n while (true) {\n params.set('page', String(pageNum));\n const r = await reqExpect<{\n images: HetznerImage[];\n meta?: { pagination?: { next_page?: number | null } };\n }>('GET', `/images?${params.toString()}`);\n all.push(...r.images);\n const next = r.meta?.pagination?.next_page;\n if (typeof next !== 'number') break;\n pageNum = next;\n }\n return all;\n },\n async deleteImage(id) {\n await req<unknown>('DELETE', `/images/${String(id)}`);\n },\n async createFirewall(reqBody) {\n const r = await reqExpect<{ firewall: HetznerFirewall }>('POST', '/firewalls', reqBody);\n return r.firewall;\n },\n async setFirewallRules(id, rules) {\n const r = await reqExpect<{ actions: HetznerAction[] }>(\n 'POST',\n `/firewalls/${String(id)}/actions/set_rules`,\n { rules },\n );\n return r.actions;\n },\n async getFirewall(id) {\n const r = await req<{ firewall: HetznerFirewall }>('GET', `/firewalls/${String(id)}`);\n return r?.firewall ?? null;\n },\n async deleteFirewall(id) {\n await req<unknown>('DELETE', `/firewalls/${String(id)}`);\n },\n async listLocations() {\n const r = await reqExpect<{\n locations: Array<{ id: number; name: string; city: string; country: string }>;\n }>('GET', '/locations');\n return r.locations;\n },\n };\n}\n","import { spawnSync } from 'node:child_process';\nimport { hostOpenCommand, writeManagedSecrets, type CredSetResult } from '@agentbox/sandbox-core';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\nimport {\n cancel,\n confirm,\n isCancel,\n intro,\n log,\n note,\n outro,\n password,\n spinner,\n} from '@clack/prompts';\nimport { makeHetznerClient } from './client.js';\nimport { ensureHetznerEnvLoaded } from './env-loader.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://console.hetzner.cloud/projects';\n\n/**\n * Keys we manage in `~/.agentbox/secrets.env`. When the user reconfigures\n * we strip prior values before appending so the file never accumulates\n * duplicates. `HCLOUD_ENDPOINT` is honored but we don't prompt for it\n * (default endpoint covers 100% of users).\n */\nconst MANAGED_KEYS = ['HCLOUD_TOKEN', 'HCLOUD_ENDPOINT'] as const;\ntype ManagedKey = (typeof MANAGED_KEYS)[number];\n\nexport interface EnsureHetznerCredentialsOptions {\n /** Re-prompt even when valid credentials are already present (used by `agentbox hetzner login`). */\n force?: boolean;\n}\n\n/**\n * First-run interactive setup for Hetzner credentials. Walks the user\n * through creating a project API token, pasting it, validating, and\n * persisting to `~/.agentbox/secrets.env`.\n *\n * No-op when credentials are already configured (env var or our secrets\n * file). Silent no-op when stdin isn't a TTY so scripted/CI callers get\n * the API \"401 unauthorized\" error instead of a hung prompt.\n *\n * Mirrors `ensureDaytonaCredentials()` in shape so the registry's first-\n * run gate stays uniform across providers.\n */\nexport async function ensureHetznerCredentials(\n opts: EnsureHetznerCredentialsOptions = {},\n): Promise<void> {\n ensureHetznerEnvLoaded();\n\n if (!opts.force && hasUsableCredentials()) return;\n if (!process.stdin.isTTY) return;\n\n intro('Hetzner Cloud setup');\n note(\n `AgentBox needs a Hetzner Cloud API token (project-scoped) to provision VPSes.\\n\\n` +\n `1. Open ${DASHBOARD_KEYS_URL}\\n` +\n `2. Pick a project (or create one).\\n` +\n `3. Security → API Tokens → Generate API Token (Read + Write).`,\n 'API token required',\n );\n\n const open = exitOnCancel(\n await confirm({\n message: `Open ${DASHBOARD_KEYS_URL} in your browser?`,\n initialValue: true,\n }),\n );\n if (open) openDashboard();\n\n // One retry on auth failure (typos / expired token are the common case).\n for (let attempt = 0; attempt < 2; attempt++) {\n const creds = await promptForCredentials();\n\n const result = await validateCredentials(creds);\n if (result.ok) {\n persistCredentials(creds);\n log.success(`Hetzner credentials saved to ${secretsPath()}`);\n outro('Setup complete.');\n return;\n }\n if (result.kind === 'auth' && attempt === 0) {\n log.error(`That token was rejected by Hetzner: ${result.message}`);\n log.info('Try again, or press Ctrl-C to cancel.');\n continue;\n }\n if (result.kind === 'network') {\n log.warn(`Could not reach Hetzner to validate (${result.message}) — saving anyway.`);\n persistCredentials(creds);\n log.success(`Hetzner credentials saved to ${secretsPath()}`);\n outro('Setup complete (unvalidated).');\n return;\n }\n throw new Error(`Hetzner credentials rejected: ${result.message}`);\n }\n}\n\nfunction hasUsableCredentials(): boolean {\n return typeof process.env.HCLOUD_TOKEN === 'string' && process.env.HCLOUD_TOKEN.length > 0;\n}\n\ninterface Credentials {\n token: string;\n endpoint?: string;\n}\n\nasync function promptForCredentials(): Promise<Credentials> {\n const token = exitOnCancel(\n await password({\n message: 'Paste your Hetzner Cloud API token',\n validate(v) {\n if (!v || v.trim().length === 0) return 'Cannot be empty';\n return undefined;\n },\n }),\n );\n return { token: token.trim() };\n}\n\ntype ValidationResult =\n | { ok: true }\n | { ok: false; kind: 'auth'; message: string }\n | { ok: false; kind: 'network'; message: string };\n\nasync function validateCredentials(creds: Credentials): Promise<ValidationResult> {\n const s = spinner();\n s.start('Validating credentials with Hetzner');\n\n try {\n const client = makeHetznerClient({ token: creds.token, endpoint: creds.endpoint });\n // `listLocations()` is a cheap, deterministic call that exercises auth +\n // basic API reachability without provisioning anything.\n await client.listLocations();\n s.stop('Hetzner credentials accepted');\n return { ok: true };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n s.stop('Hetzner credentials check failed');\n if (/401|403|unauthor|forbidden|invalid|token/i.test(message)) {\n return { ok: false, kind: 'auth', message };\n }\n return { ok: false, kind: 'network', message };\n }\n}\n\nfunction persistCredentials(creds: Credentials): void {\n const record: Record<string, string> = { HCLOUD_TOKEN: creds.token };\n if (creds.endpoint) record.HCLOUD_ENDPOINT = creds.endpoint;\n writeManagedSecrets(MANAGED_KEYS, record);\n}\n\n/**\n * Non-interactive credential set (the headless path the hub drives). Validates\n * `{ token, endpoint? }` against the Hetzner API (a cheap `listLocations`), then\n * persists to `~/.agentbox/secrets.env`. A network failure still persists (so an\n * offline host isn't blocked) but reports `ok:true` with a warning label.\n */\nexport async function setHetznerCredentials(\n fields: Record<string, string>,\n): Promise<CredSetResult> {\n const token = (fields.token ?? '').trim();\n const endpoint = (fields.endpoint ?? '').trim() || undefined;\n if (!token) {\n return { ok: false, error: 'token is required', status: { configured: false } };\n }\n const creds: Credentials = { token, endpoint };\n const result = await validateCredentials(creds);\n if (!result.ok && result.kind === 'auth') {\n return { ok: false, error: `token rejected by Hetzner: ${result.message}`, status: { configured: false } };\n }\n persistCredentials(creds);\n const label = result.ok ? 'token' : 'token (unvalidated)';\n return { ok: true, status: { configured: true, label } };\n}\n\nfunction openDashboard(): void {\n try {\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 } 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 HetznerCredStatus {\n token?: string;\n endpoint?: string;\n source: 'env' | 'secrets.env' | 'none';\n}\n\nexport function readHetznerCredStatus(): HetznerCredStatus {\n const shellHadToken = !!process.env.HCLOUD_TOKEN;\n ensureHetznerEnvLoaded();\n const token = process.env.HCLOUD_TOKEN;\n const endpoint = process.env.HCLOUD_ENDPOINT;\n if (!token) return { source: 'none' };\n return {\n token,\n endpoint,\n source: shellHadToken ? 'env' : 'secrets.env',\n };\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/** Snapshot of the managed env keys (used by tests around `applyToEnv`). */\nexport function snapshotManagedEnv(): Record<ManagedKey, string | undefined> {\n const out = {} as Record<ManagedKey, string | undefined>;\n for (const k of MANAGED_KEYS) out[k] = process.env[k];\n return out;\n}\n\nexport function restoreManagedEnv(snap: Record<ManagedKey, string | undefined>): void {\n for (const k of MANAGED_KEYS) {\n if (snap[k] === undefined) delete process.env[k];\n else process.env[k] = snap[k];\n }\n}\n","/**\n * Host egress-IP detection for the Hetzner firewall lock-down. Probes three\n * independent providers in sequence; first 3s success wins. Fails loud\n * (throws) if all three fail — we do **not** silently fall back to\n * `0.0.0.0/0`, because that would defeat the safe-by-default firewall.\n *\n * The user can always override the auto-detect via\n * `--firewall-source <cidr>` (or `--firewall-source 0.0.0.0/0` for the\n * explicit dynamic-IP opt-in).\n */\n\nconst PROBES = [\n 'https://api.ipify.org',\n 'https://ifconfig.io/ip',\n 'https://icanhazip.com',\n] as const;\n\nconst TIMEOUT_MS = 3_000;\n\nconst IPV4_RE = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\nconst IPV6_RE = /^[0-9a-fA-F:]+$/;\n\nexport interface DetectEgressIpOptions {\n /** Override the probe list (tests inject this). */\n probes?: readonly string[];\n /** Per-probe timeout in ms (default 3_000). */\n timeoutMs?: number;\n /** Override `fetch` (tests inject this). */\n fetchImpl?: typeof fetch;\n /** Best-effort logger for probe attempts. */\n onLog?: (line: string) => void;\n}\n\n/**\n * Detect the host's egress IP. Returns the bare IP string (no `/32`); the\n * caller composes the CIDR.\n *\n * Throws when no probe responded. The error message lists each probe that\n * was tried so the user can see whether their network is blocking a\n * specific provider.\n */\nexport async function detectEgressIp(opts: DetectEgressIpOptions = {}): Promise<string> {\n const probes = opts.probes ?? PROBES;\n const timeout = opts.timeoutMs ?? TIMEOUT_MS;\n const fetchImpl = opts.fetchImpl ?? fetch;\n const errors: string[] = [];\n\n for (const url of probes) {\n try {\n const ip = await raceTimeout(probe(url, fetchImpl), timeout);\n if (ip) {\n opts.onLog?.(`egress-ip: detected ${ip} via ${url}`);\n return ip;\n }\n errors.push(`${url}: empty/invalid response`);\n } catch (err) {\n errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n throw new Error(\n `could not auto-detect the host's egress IP — all ${String(probes.length)} probes failed:\\n` +\n errors.map((e) => ` - ${e}`).join('\\n') +\n `\\nOverride with --firewall-source <cidr> (e.g. --firewall-source 0.0.0.0/0 for the explicit-open opt-in).`,\n );\n}\n\nasync function probe(url: string, fetchImpl: typeof fetch): Promise<string | null> {\n const res = await fetchImpl(url, { method: 'GET' });\n if (!res.ok) return null;\n const body = (await res.text()).trim();\n if (IPV4_RE.test(body)) {\n // Cheap sanity: each octet in 0–255.\n const parts = body.split('.').map((p) => Number.parseInt(p, 10));\n if (parts.every((p) => p >= 0 && p <= 255)) return body;\n return null;\n }\n // We do not currently use IPv6 for firewall rules (Hetzner accepts them\n // but the rest of the provider talks IPv4), but accept the probe answer\n // so a v6-only network surfaces an actionable error rather than a silent\n // empty result. Composing the CIDR is the caller's job.\n if (IPV6_RE.test(body) && body.includes(':')) return body;\n return null;\n}\n\nasync function raceTimeout<T>(p: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`probe timed out after ${String(ms)}ms`)), ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * Bounded retry wrapper for Hetzner Cloud API calls — mirrors\n * `withDaytonaRetry` in shape and intent. Hetzner is generally well-behaved\n * but the public API does rate-limit (429) and occasionally returns 502/504\n * during regional incidents; without bounded retries those propagate as\n * wedges in the calling lifecycle code.\n *\n * Non-idempotent ops (`provision`, `createImage`) pass\n * `retryOnAmbiguous: false` so a 504 after the request reached the origin\n * doesn't create a duplicate billable resource.\n */\n\nimport { HetznerApiError } from './client.js';\n\nexport interface WithRetryOptions {\n /** Method name, used in retry log lines. */\n method: string;\n /** Per-attempt timeout (ms). Default 30_000. */\n attemptTimeoutMs?: number;\n /** Backoff before attempts 2, 3, … (ms). Default [1000, 2000, 4000]. */\n backoffMs?: readonly number[];\n /**\n * Whether to retry on errors where we can't be sure the server applied\n * the request — connection failures, per-attempt timeouts, and 5xx\n * responses. Set false for non-idempotent operations (e.g. `provision`,\n * `createImage`) where a retry could create a duplicate resource.\n */\n retryOnAmbiguous: boolean;\n /** Override the default `process.stderr` retry sink (used by tests). */\n onRetry?: (line: string) => void;\n}\n\nconst DEFAULT_BACKOFF: readonly number[] = [1000, 2000, 4000];\nconst DEFAULT_ATTEMPT_TIMEOUT_MS = 30_000;\n\nclass AttemptTimeoutError extends Error {\n constructor(method: string, ms: number) {\n super(`hetzner ${method}: per-attempt timeout after ${String(ms)}ms`);\n this.name = 'AttemptTimeoutError';\n }\n}\n\nexport function isAttemptTimeout(err: unknown): err is AttemptTimeoutError {\n return err instanceof AttemptTimeoutError;\n}\n\n/**\n * Classify an error as retriable or not. `allowAmbiguous` gates the cases\n * where the server may or may not have applied the request — the caller\n * decides based on idempotency.\n */\nexport function isRetriable(err: unknown, allowAmbiguous: boolean): boolean {\n if (err instanceof HetznerApiError) {\n // Rate limit: always back off — the server told us to.\n if (err.statusCode === 429 || err.code === 'rate_limit_exceeded') return true;\n // 5xx: ambiguous (the API may or may not have applied the change).\n if (err.statusCode >= 500 && err.statusCode <= 599) return allowAmbiguous;\n // Hetzner conflict / locked errors: the API tells us to wait — same as\n // rate-limit semantically. `conflict` is what `delete_server` returns\n // when another action (e.g. our own poweroff) is still in flight.\n if (err.code === 'locked' || err.code === 'conflict') return true;\n // Everything else is a permanent client error (auth, validation, not_found).\n return false;\n }\n\n if (err instanceof AttemptTimeoutError) return allowAmbiguous;\n\n // Raw fetch / undici errors. The Node fetch impl wraps low-level errors in\n // `{ cause }`; we check both shapes for portability.\n if (err && typeof err === 'object') {\n const candidates: unknown[] = [err, (err as { cause?: unknown }).cause];\n for (const c of candidates) {\n if (!c || typeof c !== 'object') continue;\n const code = (c as { code?: unknown }).code;\n if (\n code === 'ECONNRESET' ||\n code === 'ETIMEDOUT' ||\n code === 'ECONNABORTED' ||\n code === 'EAI_AGAIN' ||\n code === 'ECONNREFUSED' ||\n code === 'ENOTFOUND' ||\n code === 'UND_ERR_SOCKET' ||\n code === 'UND_ERR_CONNECT_TIMEOUT'\n ) {\n return allowAmbiguous;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Run `fn`, retrying on transient failures with capped exponential backoff.\n * Each attempt is bounded by `attemptTimeoutMs` via Promise.race; total\n * wall-clock = sum(backoffMs) + maxAttempts * attemptTimeoutMs.\n */\nexport async function withHetznerRetry<T>(\n opts: WithRetryOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const backoff = opts.backoffMs ?? DEFAULT_BACKOFF;\n const maxAttempts = backoff.length + 1;\n const timeoutMs = opts.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;\n const log = opts.onRetry ?? defaultRetryLog;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await raceTimeout(fn(), timeoutMs, opts.method);\n } catch (err) {\n const last = attempt === maxAttempts;\n if (last || !isRetriable(err, opts.retryOnAmbiguous)) throw err;\n const delay = backoff[attempt - 1] ?? backoff[backoff.length - 1] ?? 4000;\n log(\n `hetzner ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`,\n );\n await sleep(delay);\n }\n }\n throw new Error(`withHetznerRetry: exhausted attempts for ${opts.method}`);\n}\n\nfunction defaultRetryLog(line: string): void {\n process.stderr.write(`\\n[hetzner-retry] ${line}\\n`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function raceTimeout<T>(p: Promise<T>, ms: number, method: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new AttemptTimeoutError(method, ms)), ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction errorSummary(err: unknown): string {\n if (err instanceof HetznerApiError) {\n return `HetznerApiError ${String(err.statusCode)} ${err.code}: ${truncate(err.message)}`;\n }\n if (err instanceof Error) {\n const code = (err as { code?: unknown }).code;\n return code !== undefined\n ? `${err.name}(${String(code)}): ${truncate(err.message)}`\n : `${err.name}: ${truncate(err.message)}`;\n }\n return truncate(String(err));\n}\n\nfunction truncate(s: string, max = 160): string {\n return s.length > max ? `${s.slice(0, max)}…` : s;\n}\n","/**\n * Hetzner Cloud Firewall provisioning + drift sync.\n *\n * Defense-in-depth model (recapped from\n * ~/.claude/plans/how-to-safely-create-parallel-pebble.md §\"The safety model\"):\n *\n * 1. In-VPS services bind to loopback (the load-bearing layer).\n * 2. Hetzner Cloud Firewall locks SSH to the host's egress IP — applied\n * here at provision time, before the VPS first boots. Everything else\n * is denied inbound; outbound is unrestricted.\n * 3. sshd hardening (PasswordAuthentication no, AllowUsers vscode, …)\n * written by cloud-init at first boot.\n *\n * Layer 2 is what this module provisions. The firewall is per-box (1:1 with\n * the VPS) so an egress-IP-drift on one box doesn't affect siblings, and a\n * destroy cleanly removes everything we created.\n */\n\nimport { HetznerApiError, type HetznerClient, type HetznerFirewall, type HetznerFirewallRule } from './client.js';\nimport { withHetznerRetry } from './retry.js';\n\n/**\n * Build the SSH-only inbound rule for one or more source CIDRs. Hetzner's\n * `source_ips` is a list, so all allowed CIDRs ride a single tcp/22 rule (host\n * egress for `locked`, `0.0.0.0/0`+`::/0` for `open`, host egress + the\n * whitelist for `whitelist`). Outbound is left unrestricted (empty rules array\n * = \"no inbound besides this one\"). Accepts a bare string for back-compat.\n */\nexport function sshOnlyInboundRule(sources: string | string[]): HetznerFirewallRule[] {\n const source_ips = Array.isArray(sources) ? sources : [sources];\n return [\n {\n direction: 'in',\n protocol: 'tcp',\n port: '22',\n source_ips,\n description: 'agentbox: SSH inbound',\n },\n ];\n}\n\n/**\n * Inbound rules for a control-plane VPS: SSH locked to the host's egress IP,\n * but HTTP(S) open to the world (cloud boxes from arbitrary IPs reach the plane,\n * and Caddy needs :80/:443 for the Let's Encrypt ACME challenge + serving). The\n * Next app's own port is never exposed — Caddy fronts it on the compose network.\n */\nexport function controlPlaneInboundRules(hostCidr: string): HetznerFirewallRule[] {\n return [\n {\n direction: 'in',\n protocol: 'tcp',\n port: '22',\n source_ips: [hostCidr],\n description: 'agentbox control plane: SSH from host egress IP only',\n },\n {\n direction: 'in',\n protocol: 'tcp',\n port: '80',\n source_ips: ['0.0.0.0/0', '::/0'],\n description: 'agentbox control plane: HTTP (ACME challenge + redirect)',\n },\n {\n direction: 'in',\n protocol: 'tcp',\n port: '443',\n source_ips: ['0.0.0.0/0', '::/0'],\n description: 'agentbox control plane: HTTPS',\n },\n ];\n}\n\nexport interface CreateFirewallOptions {\n /** Human-readable name persisted with the firewall (visible in the Hetzner dashboard). */\n name: string;\n /** Inbound source CIDRs (already normalized/resolved by the caller). */\n sources: string[];\n /** Labels merged onto the firewall (we always add `agentbox.managed=true`). */\n labels?: Record<string, string>;\n}\n\n/**\n * Provision a fresh per-box firewall locked to the given source CIDR.\n * Returns the created `HetznerFirewall` so the caller can persist\n * `firewallId` on the box record.\n */\nexport async function createPerBoxFirewall(\n client: HetznerClient,\n opts: CreateFirewallOptions,\n): Promise<HetznerFirewall> {\n return withHetznerRetry(\n { method: 'createFirewall', retryOnAmbiguous: false, attemptTimeoutMs: 60_000 },\n () =>\n client.createFirewall({\n name: opts.name,\n rules: sshOnlyInboundRule(opts.sources),\n labels: {\n 'agentbox.managed': 'true',\n 'agentbox.role': 'box',\n ...opts.labels,\n },\n }),\n );\n}\n\n/**\n * Re-detect the egress IP and replace the firewall's rule set with the new\n * source. Used by `agentbox hetzner firewall sync <box>` after the host\n * laptop moves networks. Cheap operation — no VPS restart involved.\n *\n * Idempotent on the API: setting the same rules again is a no-op from the\n * user's point of view (the API still returns an action handle, but it\n * resolves instantly).\n */\nexport async function syncFirewallSource(\n client: HetznerClient,\n firewallId: number,\n sources: string | string[],\n): Promise<void> {\n await withHetznerRetry(\n { method: 'setFirewallRules', retryOnAmbiguous: true, attemptTimeoutMs: 60_000 },\n () => client.setFirewallRules(firewallId, sshOnlyInboundRule(sources)),\n );\n}\n\n/**\n * Delete a per-box firewall. Idempotent on 404 (the API surfaces it as a\n * `not_found` error which the retry classifier won't retry; we swallow it\n * here so destroy paths don't need a special-case).\n *\n * Hetzner returns 409 `conflict` if the firewall is still attached to a\n * server when we try to delete it — `deleteServer()` returns as soon as the\n * delete action is *enqueued*, not after the server's firewall attachment\n * is torn down, so a quick subsequent `deleteFirewall()` will collide.\n * We poll for a short window (default 60s, intervals doubled to 8s) to\n * cover the typical 5–15s detach lag before giving up.\n */\nexport async function deletePerBoxFirewall(\n client: HetznerClient,\n firewallId: number,\n opts: { detachWaitMs?: number } = {},\n): Promise<void> {\n const deadline = Date.now() + (opts.detachWaitMs ?? 60_000);\n let interval = 1_000;\n while (true) {\n try {\n await withHetznerRetry(\n { method: 'deleteFirewall', retryOnAmbiguous: true, attemptTimeoutMs: 30_000 },\n () => client.deleteFirewall(firewallId),\n );\n return;\n } catch (err) {\n if (err instanceof HetznerApiError && (err.statusCode === 404 || err.code === 'not_found')) {\n return;\n }\n const stillAttached =\n err instanceof HetznerApiError &&\n (err.statusCode === 409 ||\n err.code === 'conflict' ||\n err.code === 'resource_in_use');\n if (stillAttached && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, interval));\n interval = Math.min(interval * 2, 8_000);\n continue;\n }\n throw err;\n }\n }\n}\n\n/**\n * Whether the firewall's allowed SSH sources need re-syncing to include the\n * current egress: true when the current egress isn't already allowed AND the\n * firewall isn't wide-open (`0.0.0.0/0`, the `open` policy / dynamic-IP opt-in).\n * Pure so the hint + auto-sync decision is unit-testable without the Hetzner\n * API. Empty sources (no SSH rule) counts as a mismatch worth syncing. Accepts\n * a bare string for back-compat callers.\n */\nexport function firewallNeedsSync(\n allowedSources: string | string[] | undefined,\n currentEgress: string,\n): boolean {\n const list = Array.isArray(allowedSources)\n ? allowedSources\n : allowedSources\n ? [allowedSources]\n : [];\n if (list.includes('0.0.0.0/0')) return false;\n return !list.includes(currentEgress);\n}\n\n/**\n * Normalize a source spec into a CIDR. Accepts:\n * - bare IPv4 → appends `/32`\n * - bare IPv6 → appends `/128`\n * - already-CIDR (anything with `/`) → returned as-is\n *\n * Whitespace is trimmed. Does **not** validate the address itself — that's\n * either the API's job (it'll reject bad CIDRs with a clear `validation`\n * error) or `detectEgressIp`'s job (it only returns valid IPv4/IPv6).\n */\nexport function normalizeSourceCidr(raw: string): string {\n const trimmed = raw.trim();\n if (trimmed.includes('/')) return trimmed;\n if (trimmed.includes(':')) return `${trimmed}/128`;\n return `${trimmed}/32`;\n}\n","/**\n * Resolver for the on-disk files we need to ship into a fresh VPS during\n * `prepareHetzner()` — same shape as the docker provider's runtime/docker\n * staging, but lighter (no Dockerfile build, just a flat tarball of files\n * to scp into /tmp).\n *\n * Lookup order for each file:\n * 1. The CLI's staged runtime tree: `<cliRoot>/runtime/hetzner/...`\n * (populated by `apps/cli/scripts/stage-runtime.mjs`).\n * 2. The monorepo source tree (dev fallback): the file's canonical\n * package-relative path under `packages/`.\n *\n * Failure mode: any missing file throws a clear error naming the lookup\n * paths so a partial dev rebuild is obvious to debug.\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\n/**\n * Locate the staged `runtime/hetzner/` tree. Two candidates:\n *\n * 1. Bundled CLI: the hetzner module is inlined into apps/cli's dist/, so\n * `dirname(import.meta.url)` is `<cliRoot>/dist`; the staged runtime\n * sits at `<cliRoot>/runtime/hetzner`.\n * 2. Workspace dev: this module's dist is at\n * `packages/sandbox-hetzner/dist/`. There's no staged runtime there;\n * callers fall through to the monorepo source paths in\n * `candidatesFor()`. Returns undefined in that case.\n *\n * The CLI doesn't have to pass `cliRuntimeRoot` explicitly — this helper\n * picks it up by inspecting where the module was loaded from.\n */\nexport function findStagedCliRuntimeRoot(): string | undefined {\n const candidates = [\n resolve(SELF, '..', 'runtime'), // <cliRoot>/dist/.. → <cliRoot> then /runtime\n resolve(SELF, '..', '..', 'runtime'), // chunk-NNNN.js at <cliRoot>/dist/<sub>/.. → <cliRoot>/runtime\n ];\n for (const c of candidates) {\n if (existsSync(resolve(c, 'hetzner', 'scripts', 'install-box.sh'))) return c;\n }\n return undefined;\n}\n\n/**\n * Each runtime asset has a stable, well-known destination basename in\n * `/tmp` on the prepare VPS and is resolved from one of N candidate\n * source paths on the host.\n */\nexport interface RuntimeAsset {\n /** Logical name (used in error messages + log lines). */\n name: string;\n /** Basename on the prepare VPS (under /tmp/). */\n remoteBasename: string;\n /** Optional file mode at scp-time. */\n remoteMode?: number;\n}\n\nexport const RUNTIME_ASSETS: readonly RuntimeAsset[] = [\n { name: 'install-box.sh', remoteBasename: 'agentbox-install.sh', remoteMode: 0o755 },\n { name: 'agentbox-ctl', remoteBasename: 'agentbox-ctl', remoteMode: 0o755 },\n { name: 'agentbox-vnc-start', remoteBasename: 'agentbox-vnc-start', remoteMode: 0o755 },\n { name: 'agentbox-dockerd-start', remoteBasename: 'agentbox-dockerd-start', remoteMode: 0o755 },\n { name: 'agentbox-portless-trust', remoteBasename: 'agentbox-portless-trust', remoteMode: 0o755 },\n { name: 'agentbox-checkpoint-cleanup', remoteBasename: 'agentbox-checkpoint-cleanup', remoteMode: 0o755 },\n { name: 'agentbox-open', remoteBasename: 'agentbox-open', remoteMode: 0o755 },\n { name: 'gh-shim', remoteBasename: 'agentbox-gh-shim', remoteMode: 0o755 },\n { name: 'git-shim', remoteBasename: 'agentbox-git-shim', remoteMode: 0o755 },\n { name: 'ntn-shim', remoteBasename: 'agentbox-ntn-shim', remoteMode: 0o755 },\n { name: 'linear-shim', remoteBasename: 'agentbox-linear-shim', remoteMode: 0o755 },\n { name: 'custom-system-CLAUDE.md', remoteBasename: 'agentbox-custom-CLAUDE.md', remoteMode: 0o644 },\n { name: 'claude-managed-settings.json', remoteBasename: 'agentbox-managed-settings.json', remoteMode: 0o644 },\n { name: 'agentbox-codex-hooks.json', remoteBasename: 'agentbox-codex-hooks.json', remoteMode: 0o644 },\n { name: 'agentbox-setup-skill.md', remoteBasename: 'agentbox-setup-skill.md', remoteMode: 0o644 },\n] as const;\n\nexport interface ResolvedAsset extends RuntimeAsset {\n localPath: string;\n}\n\n/**\n * Build the candidate search paths for a given asset. Tries CLI runtime\n * first, then the monorepo source tree. The first one that exists wins.\n *\n * `cliRuntimeRoot` is provided by the caller because we don't know how the\n * embedding CLI lays out its dist (the @madarco/agentbox CLI puts dist + a\n * sibling runtime/ next to it; tests pass a tmp dir). Use the helper\n * `findCliRuntimeRoot()` below from the calling context that has the right\n * anchor (typically `import.meta.url` of an apps/cli module).\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 // Map logical → relative paths (relative to either anchor).\n const monorepoRelative: Record<string, string[]> = {\n 'install-box.sh': ['packages/sandbox-hetzner/scripts/install-box.sh'],\n 'agentbox-ctl': ['packages/ctl/dist/bin.cjs'],\n 'agentbox-vnc-start': ['packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-dockerd-start': ['packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-portless-trust': ['packages/sandbox-docker/scripts/agentbox-portless-trust'],\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-hetzner/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 // CLI-runtime-tree relative paths (mirrors the staging layout).\n const cliRelative: Record<string, string[]> = {\n 'install-box.sh': ['hetzner/scripts/install-box.sh'],\n 'agentbox-ctl': ['hetzner/ctl.cjs'],\n 'agentbox-vnc-start': ['hetzner/agentbox-vnc-start', 'docker/packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-dockerd-start': ['hetzner/agentbox-dockerd-start', 'docker/packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-portless-trust': ['hetzner/agentbox-portless-trust', 'docker/packages/sandbox-docker/scripts/agentbox-portless-trust'],\n 'agentbox-checkpoint-cleanup': ['hetzner/agentbox-checkpoint-cleanup', 'docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup'],\n 'agentbox-open': ['hetzner/agentbox-open', 'docker/packages/sandbox-docker/scripts/agentbox-open'],\n 'gh-shim': ['hetzner/gh-shim', 'docker/packages/sandbox-docker/scripts/gh-shim'],\n 'git-shim': ['hetzner/git-shim', 'docker/packages/sandbox-docker/scripts/git-shim'],\n 'ntn-shim': ['hetzner/ntn-shim', 'docker/packages/sandbox-docker/scripts/ntn-shim'],\n 'linear-shim': ['hetzner/linear-shim', 'docker/packages/sandbox-docker/scripts/linear-shim'],\n 'custom-system-CLAUDE.md': ['hetzner/custom-system-CLAUDE.md'],\n 'claude-managed-settings.json': ['hetzner/claude-managed-settings.json', 'docker/packages/sandbox-docker/scripts/claude-managed-settings.json'],\n 'agentbox-codex-hooks.json': ['hetzner/agentbox-codex-hooks.json', 'docker/packages/sandbox-docker/scripts/agentbox-codex-hooks.json'],\n 'agentbox-setup-skill.md': ['hetzner/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\n/**\n * Resolve every runtime asset to its absolute on-host path. Throws an\n * actionable error if any asset can't be found (lists every path tried).\n */\nexport function resolveRuntimeAssets(opts: {\n cliRuntimeRoot?: string;\n 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 `hetzner: could not resolve runtime assets — these files are needed to install on the prepare VPS:\\n` +\n lines.join('\\n') +\n `\\n\\nIf you are running from the monorepo, ensure \\`pnpm -w build\\` has run so packages/ctl/dist/bin.cjs exists. ` +\n `If you are running from a published CLI bundle, the runtime/hetzner tree should be staged automatically.`,\n );\n }\n return out;\n}\n\n/** Best-effort: walk up from this file looking for `pnpm-workspace.yaml`. */\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; // fall through to itself; resolution will fail with a clear error\n}\n","/**\n * Persisted record of what `agentbox prepare --provider hetzner` has built.\n * Lives at `~/.agentbox/hetzner-prepared.json` so the auto-prepare gate\n * (`ensureHetznerBaseSnapshot()`) and runtime image resolution can see it.\n *\n * Only the shared `base` snapshot is recorded here — built once per Hetzner\n * project / API token: Ubuntu + deps + agentbox-ctl + agents + agent-browser,\n * baked from `install-box.sh`.\n *\n * The per-project snapshot tier is NOT a separate registry: it's the existing\n * `agentbox checkpoint create --set-default` + `box.defaultCheckpointHetzner`\n * flow (see `docs/cloud-create-flow.md` §\"base vs project snapshot\"), and\n * auto-capture at the end of setup is driven by the `/agentbox-setup` skill\n * (`agentbox-ctl checkpoint --set-default`), cross-provider. So there's no\n * `projects[<hash>]` map here.\n *\n * Schema versioned so future shape changes can migrate.\n */\n\nimport { claudeInstallFingerprint, computeContextSha256, preparedStatePathFor, readPreparedStateRaw, writePreparedStateRaw } from '@agentbox/sandbox-core';\nimport { findStagedCliRuntimeRoot, resolveRuntimeAssets } from './runtime-assets.js';\n\n/**\n * Schema history:\n * 1 — `base.imageId`, `base.description`, `base.createdAt`,\n * `base.installScriptSha256?`\n * 2 — `base.installScriptSha256` → `base.contextSha256` (now covers every\n * asset we scp'd in, not just the install script); `base.cliVersion`\n * and `base.cliCommit?` added so we can warn when an old snapshot\n * predates the running CLI.\n *\n * Read-time migration is lossy in one direction: a schema-1 file is lifted\n * to schema 2 by *renaming* `installScriptSha256` to `contextSha256`. The\n * hash doesn't change but the meaning narrows (install script only → full\n * asset list), so the next `agentbox prepare --provider hetzner` run will\n * recompute and overwrite. A legacy `projects` key (an early, never-wired\n * per-project tier) is simply ignored — removing the field doesn't break\n * reads, so no schema bump is needed.\n */\nconst SCHEMA = 2 as const;\n\nexport interface PreparedBaseSnapshot {\n /** Hetzner image id (numeric — opaque, but stable across `getImage` calls). */\n imageId: number;\n /** User-facing description (matches the firewall-dashboard rows). */\n description: string;\n /** ISO timestamp of bake-completion. */\n createdAt: string;\n /**\n * Deterministic SHA-256 of the build context (every file scp'd into the\n * prepare VPS). Rebuild when it changes.\n */\n contextSha256?: string;\n /** CLI version that produced this snapshot (informational). */\n cliVersion?: string;\n /** Git short SHA of the CLI build (informational). */\n cliCommit?: string;\n}\n\nexport interface PreparedHetznerState {\n schema: typeof SCHEMA;\n /** The shared base snapshot. Absent until first `agentbox prepare`. */\n base?: PreparedBaseSnapshot;\n}\n\ninterface LegacyV1Base {\n imageId: number;\n description: string;\n createdAt: string;\n installScriptSha256?: string;\n}\n\ninterface LegacyV1State {\n schema: 1;\n base?: LegacyV1Base;\n}\n\nexport function preparedStatePath(): string {\n return preparedStatePathFor('hetzner');\n}\n\nexport function readPreparedState(): PreparedHetznerState {\n const raw = readPreparedStateRaw('hetzner');\n if (raw === null || typeof raw !== 'object') return { schema: SCHEMA };\n const parsed = raw as Partial<PreparedHetznerState> | LegacyV1State;\n if ((parsed as { schema?: unknown }).schema === 1) {\n const v1 = parsed as LegacyV1State;\n return migrateFromV1(v1);\n }\n if (parsed.schema !== SCHEMA) {\n // Unknown schema: don't crash, just refuse to read — the file will be\n // overwritten on the next successful prepare.\n return { schema: SCHEMA };\n }\n return {\n schema: SCHEMA,\n base: parsed.base,\n };\n}\n\nfunction migrateFromV1(v1: LegacyV1State): PreparedHetznerState {\n // The v1 `installScriptSha256` covered only `install-box.sh`, not the full\n // asset list a v2 `contextSha256` represents. Lifting it forward as a\n // placeholder fingerprint means the next prepare run will mismatch and\n // rebuild — exactly what we want, since the broader hash semantics also\n // changed.\n const base: PreparedBaseSnapshot | undefined = v1.base\n ? {\n imageId: v1.base.imageId,\n description: v1.base.description,\n createdAt: v1.base.createdAt,\n contextSha256: v1.base.installScriptSha256,\n }\n : undefined;\n return {\n schema: SCHEMA,\n base,\n };\n}\n\nexport function writePreparedState(state: PreparedHetznerState): void {\n writePreparedStateRaw('hetzner', state);\n}\n\n/**\n * Convenience helper: update one field of the state without forcing callers\n * to read/merge/write themselves.\n */\nexport function updatePreparedState(mutate: (s: PreparedHetznerState) => void): void {\n const s = readPreparedState();\n mutate(s);\n writePreparedState(s);\n}\n\n/**\n * Compute the CURRENT build-context fingerprint for the hetzner base snapshot\n * (the SHA over every file `prepare` would scp into the prepare VPS).\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\".\n *\n * Used by `evaluateBaseFreshness` to compare against the stored value in\n * `hetzner-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 currentHetznerBaseFingerprintLive(\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 * The Hetzner Cloud VPS sandbox provider. A thin `CloudBackend` over OpenSSH\n * + the Hetzner Cloud REST API, 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 * **Phase 2 status:** the SDK shim (auth + REST client + retry + firewall\n * + egress IP) is wired; `hetznerBackend` is a stub whose per-method bodies\n * throw `notImplemented` until Phase 4 plumbs in SSH ControlMaster +\n * provisioning. The provider is registered so `--provider hetzner` resolves\n * cleanly and the build is honest about what's missing.\n */\n\nimport type { Provider } from '@agentbox/core';\nimport type { ProviderModule } from '@agentbox/sandbox-core';\nimport { createCloudProvider } from '@agentbox/sandbox-cloud';\nimport { hetznerBackend, HETZNER_DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { prepareHetznerProvider } from './prepare.js';\nimport { currentHetznerBaseFingerprintLive } from './prepared-state.js';\nimport { ensureHetznerCredentials, setHetznerCredentials } from './credentials.js';\nimport { doctorChecks, readCredStatusSummary } from './provider-module.js';\n\nconst cloudProvider = createCloudProvider(hetznerBackend, {\n defaultResources: { cpu: 2, memory: 4, disk: 40 },\n});\n\nexport const hetznerProvider: Provider = {\n ...cloudProvider,\n prepare: prepareHetznerProvider,\n baseFingerprint: () => currentHetznerBaseFingerprintLive(),\n};\n\n/** Uniform surface the CLI provider loader resolves this package through. */\nexport const providerModule: ProviderModule = {\n provider: hetznerProvider,\n backend: hetznerBackend,\n ensureCredentials: ensureHetznerCredentials,\n readCredStatus: readCredStatusSummary,\n setCredentials: setHetznerCredentials,\n currentBaseFingerprintLive: (claudeInstall) => currentHetznerBaseFingerprintLive(claudeInstall),\n doctorChecks,\n};\n\nexport { hetznerBackend, HETZNER_DEFAULT_BOX_IMAGE_REF };\nexport { ensureHetznerEnvLoaded } from './env-loader.js';\nexport {\n ensureHetznerCredentials,\n setHetznerCredentials,\n readHetznerCredStatus,\n secretsPath,\n maskKey,\n type EnsureHetznerCredentialsOptions,\n type HetznerCredStatus,\n} from './credentials.js';\nexport {\n ensureHetznerBaseSnapshot,\n prepareHetzner,\n prepareHetznerProvider,\n type PrepareHetznerOptions,\n type PrepareHetznerResult,\n} from './prepare.js';\nexport { generateBoxCloudInit, generatePrepareCloudInit, controlPlaneCloudInit, type BoxCloudInitOptions, type PrepareCloudInitOptions, type ControlPlaneCloudInitOptions } from './cloud-init.js';\nexport {\n deployControlPlaneToHetzner,\n type ControlPlaneHetznerDeployOptions,\n type ControlPlaneHetznerDeployResult,\n} from './control-plane-deploy.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 currentHetznerBaseFingerprintLive,\n preparedStatePath,\n readPreparedState,\n writePreparedState,\n updatePreparedState,\n type PreparedBaseSnapshot,\n type PreparedHetznerState,\n} from './prepared-state.js';\nexport {\n makeHetznerClient,\n HetznerApiError,\n DEFAULT_HCLOUD_ENDPOINT,\n type CreateFirewallRequest,\n type CreateServerRequest,\n type HetznerAction,\n type HetznerClient,\n type HetznerFirewall,\n type HetznerFirewallRule,\n type HetznerImage,\n type HetznerServer,\n type HetznerServerStatus,\n type HetznerServerType,\n type HetznerSshKey,\n} from './client.js';\nexport {\n validateServerChoice,\n mapHetznerProvisionError,\n type ServerChoice,\n} from './preflight.js';\nexport { detectEgressIp, type DetectEgressIpOptions } from './egress-ip.js';\nexport {\n createPerBoxFirewall,\n deletePerBoxFirewall,\n normalizeSourceCidr,\n sshOnlyInboundRule,\n syncFirewallSource,\n type CreateFirewallOptions,\n} from './firewall.js';\nexport { withHetznerRetry, isAttemptTimeout, isRetriable } from './retry.js';\n","/**\n * Hetzner `CloudBackend` — maps the provider-neutral cloud primitives onto\n * OpenSSH + the Hetzner Cloud REST API.\n *\n * Design rationale + the safety/tunneling model live in the plan at\n * `~/.claude/plans/how-to-safely-create-parallel-pebble.md` and the live\n * status doc at `docs/hertzner_backlog.md`. The short version:\n *\n * - 1:1 VPS-per-box. Each box gets a per-box ed25519 keypair (private key\n * never leaves the host) and a per-box Hetzner Cloud Firewall locked to\n * the host's egress IP.\n * - All comms (exec, file I/O, port forwards for bridge / web / VNC) flow\n * over one persistent `ssh` ControlMaster owned by `SshTunnelManager`.\n * - `previewUrl(port)` mints an `ssh -L 127.0.0.1:<localPort>:127.0.0.1:<remote>`\n * on demand. The cloud-provider scaffolding (`createCloudProvider`) then\n * decorates those URLs with Portless aliases for symmetric\n * `<box-name>.localhost` semantics — handled provider-side rather than\n * here so the backend stays focused on plumbing.\n * - Checkpoints map to Hetzner `create_image` snapshots; default no-pause,\n * opt-in pause via `createSnapshot({pause: true})`.\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 HetznerApiError,\n makeHetznerClient,\n type HetznerClient,\n type HetznerImage,\n type HetznerServer,\n type HetznerServerStatus,\n} from './client.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport {\n createPerBoxFirewall,\n deletePerBoxFirewall,\n firewallNeedsSync,\n normalizeSourceCidr,\n syncFirewallSource,\n} from './firewall.js';\nimport { pollUntil } from './poll.js';\nimport { mapHetznerProvisionError, validateServerChoice } from './preflight.js';\nimport { readPreparedState } from './prepared-state.js';\nimport { ensureHetznerBaseSnapshot } 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 { withHetznerRetry } from './retry.js';\n\nexport const HETZNER_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 Hetzner — we recognize it (alongside our own\n * sentinel + plain undefined) as \"use the hetzner base snapshot.\"\n */\nconst SCAFFOLDING_FALLBACK_IMAGE = 'agentbox/box:dev';\nconst VPS_USER = 'vscode';\nconst PROVISION_SSH_DEADLINE_MS = 10 * 60_000;\nconst ACTION_DEADLINE_MS = 5 * 60_000;\nconst SNAPSHOT_DEADLINE_MS = 20 * 60_000;\n// `cx22` was deprecated by Hetzner in early 2026; `cx23` is the drop-in\n// replacement with the same 2 vCPU / 4 GB / 40 GB shape on x86.\nconst HETZNER_DEFAULT_SERVER_TYPE = 'cx23';\nconst HETZNER_DEFAULT_LOCATION = 'nbg1';\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`; the bridge token stays in the daemon's process env.\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 Hetzner's per-server status onto the four-value `CloudState` everyone\n * else consumes. Transitional ones ('starting', 'rebuilding', …) are reported\n * as 'running' so callers don't ping-pong; 'off' maps to 'paused' because\n * Hetzner's stop = power off (vs Daytona's archive).\n */\nfunction mapState(s: HetznerServerStatus | string | undefined): CloudState {\n switch (s) {\n case 'running':\n return 'running';\n case 'starting':\n case 'initializing':\n case 'stopping':\n case 'migrating':\n case 'rebuilding':\n return 'running';\n case 'off':\n return 'paused';\n case 'deleting':\n case 'unknown':\n default:\n return 'missing';\n }\n}\n\nfunction client(): HetznerClient {\n return makeHetznerClient();\n}\n\nasync function getServerStrict(id: number): Promise<HetznerServer> {\n const s = await client().getServer(id);\n if (!s) {\n throw new Error(`hetzner: server ${String(id)} not found (already destroyed?)`);\n }\n return s;\n}\n\n/** Lookup an image by description (\"snapshot name\" in user-facing terms). */\nasync function findImageByDescription(c: HetznerClient, description: string): Promise<HetznerImage | null> {\n const all = await c.listImages({ type: 'snapshot' });\n return all.find((i) => i.description === description) ?? null;\n}\n\n/**\n * Resolve a `CloudProvisionRequest.image|snapshot` into a Hetzner image id.\n * Precedence: `req.snapshot` → `req.image`:\n * - the sentinel `agentbox-base` → load id from `hetzner-prepared.json`.\n * - a numeric string → use as-is.\n * - any other string → treated as a snapshot description (checkpoint name)\n * and looked up via the API.\n */\nasync function resolveImageId(c: HetznerClient, req: CloudProvisionRequest): Promise<number | string> {\n const ref = req.snapshot ?? req.image;\n if (!ref || ref === HETZNER_DEFAULT_BOX_IMAGE_REF || ref === SCAFFOLDING_FALLBACK_IMAGE) {\n await ensureHetznerBaseSnapshot();\n const state = readPreparedState();\n if (!state.base) {\n throw new Error(\n 'no Hetzner base snapshot found — run `agentbox prepare --provider hetzner` 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-description first (checkpoints use that), then fall through\n // to Hetzner stock images (the user passed e.g. `ubuntu-24.04`).\n const snap = await findImageByDescription(c, ref);\n if (snap) return snap.id;\n return ref;\n}\n\n/**\n * Capture per-box state we need across method calls. Lives on disk under\n * `~/.agentbox/hetzner/boxes/<sandboxId>/` and is the source of truth for\n * the SSH identity + firewall id + cached IP.\n */\ninterface PerBoxState {\n dir: string;\n identity: string;\n knownHosts: string;\n firewallId?: number;\n firewallSource?: string;\n vpsIp?: 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\n/**\n * The per-box firewall's current SSH source vs the host's live egress IP. Best-\n * effort and called ONLY on a connection-failure path (the open-failed hint and\n * `recover`'s auto-sync), never on the happy path — `egressIpCached` keeps the\n * probe from storming across retries. Returns null when there's no firewall or\n * we can't determine the state.\n */\ninterface FirewallEgressStatus {\n firewallId: number;\n /** All CIDRs the firewall currently allows for inbound SSH (`source_ips`). */\n allowedSources: string[];\n /** The host's current egress IP as a `/32` CIDR. */\n currentEgress: string;\n /** Friendly box ref for the `firewall sync` hint (the `agentbox.box` label). */\n boxRef: string;\n}\n\nasync function firewallEgressStatus(sandboxId: string): Promise<FirewallEgressStatus | null> {\n const id = Number.parseInt(sandboxId, 10);\n if (!Number.isFinite(id)) return null;\n const server = await client().getServer(id);\n if (!server) return null;\n const firewallId = Number.parseInt(server.labels['agentbox.firewall'] ?? '', 10);\n if (!Number.isFinite(firewallId)) return null;\n const firewall = await client().getFirewall(firewallId);\n const sshRule = firewall?.rules.find((r) => r.direction === 'in' && r.port === '22');\n const allowedSources = sshRule?.source_ips ?? [];\n // A FRESH probe (not cached): this runs only on a connection-failure path, and\n // a stale value could read the new IP as \"unchanged\" and skip the heal — the\n // very mismatch we exist to catch. The poller already de-dupes its recover\n // calls and `recover --all` is sequential, so fresh probing here won't storm.\n const currentEgress = `${await detectEgressIp({})}/32`;\n return {\n firewallId,\n allowedSources,\n currentEgress,\n boxRef: server.labels['agentbox.box'] ?? sandboxId,\n };\n}\n\nasync function ensureTunnel(sandboxId: string, state: PerBoxState, vpsIp: string): Promise<void> {\n if (tunnels.has(sandboxId)) return;\n try {\n await tunnels.open({\n boxId: sandboxId,\n vpsHost: vpsIp,\n identity: state.identity,\n });\n } catch (err) {\n // A host egress-IP change locks us out of the per-box firewall, surfacing as\n // an opaque SSH connect timeout. Best-effort: detect the mismatch and enrich\n // the error with the fix. Never let the diagnostic mask the original error\n // on a match (box is just down) or a probe failure.\n const s = await firewallEgressStatus(sandboxId).catch(() => null);\n if (s && firewallNeedsSync(s.allowedSources, s.currentEgress)) {\n throw new Error(\n `${(err as Error).message}\\n\\n` +\n `hetzner: SSH is blocked by the box firewall — it allows ${s.allowedSources.join(', ') || '(no rule)'} ` +\n `but your egress IP is now ${s.currentEgress}. Your IP changed; run:\\n` +\n ` agentbox hetzner firewall sync ${s.boxRef}\\n` +\n `(or \\`agentbox recover ${s.boxRef}\\`, which auto-syncs).`,\n );\n }\n throw err;\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(`hetzner: invalid sandboxId ${sandboxId}`);\n }\n const server = await getServerStrict(id);\n const vpsIp = server.public_net.ipv4?.ip;\n if (!vpsIp) {\n throw new Error(`hetzner: server ${String(id)} has no IPv4 address`);\n }\n const state = await ensurePerBoxState(sandboxId);\n if (!existsSync(state.identity)) {\n throw new Error(\n `hetzner: 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 hetznerBackend: CloudBackend = {\n name: 'hetzner',\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n const c = client();\n const onLog = req.onLog ?? (() => {});\n const progress = (s: string) => onLog(`hetzner: ${s}`);\n\n // 1. Gate on the base snapshot existing (lifts the Phase-2 placeholder).\n await ensureHetznerBaseSnapshot();\n const imageRef = await resolveImageId(c, req);\n\n // 1b. Preflight the server-type + location choice against the live catalog\n // BEFORE creating any billable resources (firewall, SSH key, server). A bad\n // `--size cax31` / `--size cx99` / `--location atlantis` fails fast here with\n // a clear message instead of a late, opaque API error after cleanup churn.\n const serverType = (req.size && req.size.trim()) || HETZNER_DEFAULT_SERVER_TYPE;\n const location = (req.location && req.location.trim()) || HETZNER_DEFAULT_LOCATION;\n const choice = { serverType, location };\n // The base image's disk_size gates the min server disk. We only have it for\n // numeric snapshot refs; stock string refs (e.g. `ubuntu-24.04`) skip the\n // disk check (image null).\n const image = typeof imageRef === 'number' ? await c.getImage(imageRef) : null;\n const catalog = await c.listServerTypes();\n validateServerChoice(choice, catalog, image);\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_HETZNER_FIREWALL_SOURCE ?? process.env.AGENTBOX_HETZNER_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 uuid; we\n // rename it to `~/.agentbox/hetzner/boxes/<sandboxId>/ssh/` once the\n // server 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 'hetzner',\n `pending-${stamp}`,\n 'ssh',\n );\n const key = await mintSshKey(tempDir, `agentbox-box-${req.name}-${stamp}`);\n\n let firewallId: number | null = null;\n let serverId: number | null = null;\n try {\n // 4. Firewall.\n const firewall = await createPerBoxFirewall(c, {\n name: `agentbox-${req.name}-${stamp}`,\n sources,\n labels: {\n 'agentbox.box': req.name,\n 'agentbox.role': 'box',\n },\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 tokens are\n // deliberately excluded — cloud-init writes box.env world-readable (0644),\n // and these secrets reach the in-box ctl via the daemon's 0600 relay.env\n // (relay token) and its process env (bridge token) 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 server. Map late Hetzner provision errors (account limit,\n // out-of-capacity) to actionable guidance while preserving the original.\n progress(\n `creating VPS '${req.name}' from image ${String(imageRef)} (${serverType} / ${location})`,\n );\n let created;\n try {\n created = await withHetznerRetry(\n { method: 'createServer', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () =>\n c.createServer({\n name: `agentbox-${req.name}-${stamp}`,\n server_type: serverType,\n image: imageRef,\n location,\n user_data: cloudInit,\n firewalls: [{ firewall: firewall.id }],\n labels: {\n 'agentbox.managed': 'true',\n 'agentbox.role': 'box',\n 'agentbox.box': req.name,\n 'agentbox.firewall': String(firewall.id),\n },\n start_after_create: true,\n }),\n );\n } catch (createErr) {\n throw mapHetznerProvisionError(createErr, choice);\n }\n serverId = created.server.id;\n const provisioned = created.server.server_type;\n const vpsIp = created.server.public_net.ipv4?.ip;\n if (!vpsIp) {\n throw new Error(`hetzner: server ${String(serverId)} came up without an IPv4 address`);\n }\n progress(`server ${String(serverId)} provisioned at ${vpsIp}; waiting for ssh`);\n\n // 7. Move the freshly-minted key from its temp location into the\n // sandboxId-keyed final dir, then rm the temp parent. We move file-\n // by-file rather than renaming the whole dir because `ensurePerBoxState`\n // had to mkdir the final dir before we knew the sandbox id (so the\n // tunnel manager + state-restoration paths can find it later).\n const sandboxId = String(serverId);\n const state = await ensurePerBoxState(sandboxId);\n await rename(key.privatePath, state.identity);\n await rename(key.publicPath, `${state.identity}.pub`);\n // Drop the now-empty temp dir + its `pending-XXX` parent.\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 // 8. 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 `hetzner: ssh on ${vpsIp} did not come up within ${String(PROVISION_SSH_DEADLINE_MS / 1000)}s; ` +\n `the server 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 // 9. Open ControlMaster.\n await ensureTunnel(sandboxId, state, vpsIp);\n progress('ssh up; ControlMaster open');\n\n // Agent credentials are seeded by `createCloudProvider`'s unified\n // post-provision step (`seedAgentVolumesIfFresh`) via `uploadFile` +\n // `exec` over the live ControlMaster — the symlinks baked into\n // install-box.sh route ~/.claude/.credentials.json etc. through to\n // `~/.agentbox-creds/<agent>/`.\n //\n // Report the REAL resources from the create response (the plan's\n // cores/memory/disk), not our static defaults — the record + the cloud\n // scaffold's `provisioned …` log line read this.\n return {\n sandboxId,\n inbound: inboundPolicy,\n resources: {\n cpu: provisioned.cores,\n memory: provisioned.memory,\n disk: provisioned.disk,\n },\n };\n } catch (err) {\n // Cleanup on failure: server + firewall + temp ssh dir.\n if (serverId !== null) {\n progress(`cleanup — deleting server ${String(serverId)} after provision failure`);\n try {\n await c.deleteServer(serverId);\n } catch (cleanupErr) {\n onLog(\n `hetzner: WARN — failed to delete server ${String(serverId)}; check the Hetzner dashboard manually. ${\n cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)\n }`,\n );\n }\n }\n if (firewallId !== null) {\n try {\n await deletePerBoxFirewall(c, firewallId);\n } catch {\n // best-effort\n }\n }\n // Clean the temp ssh dir (or its renamed location if we got that far).\n try {\n if (existsSync(key.dir)) await rm(key.dir, { recursive: true, force: true });\n if (serverId !== null) {\n const finalDir = perBoxDir(String(serverId));\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 server = await client().getServer(id);\n return server ? { sandboxId } : null;\n },\n\n async list(): Promise<CloudSandboxSummary[]> {\n const servers = await client().listServers({ label_selector: 'agentbox.managed=true' });\n return servers.map((s) => ({\n sandboxId: String(s.id),\n name: s.labels['agentbox.box'] ?? s.name,\n createdAt: s.created,\n state: mapState(s.status),\n }));\n },\n\n async start(h: CloudHandle): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n await client().powerOn(id);\n // The API reports `running` ~10-30s before sshd actually accepts\n // connections. Callers (the provider's `reEnsureCloudBox` relaunch) SSH-exec\n // immediately after start()/resume(), so wait for the API state AND for ssh\n // to be ready — otherwise the first exec hits `Connection refused` and the\n // daemons never get relaunched. Mirrors the provision flow's waitForSsh.\n await pollUntil(\n `server ${h.sandboxId} running`,\n async () => {\n const s = await client().getServer(id);\n return s?.status === 'running' ? s : null;\n },\n { deadlineMs: ACTION_DEADLINE_MS, intervalMs: 2_000, maxIntervalMs: 8_000 },\n );\n const server = await getServerStrict(id);\n const vpsIp = server.public_net.ipv4?.ip;\n if (!vpsIp) {\n throw new Error(`hetzner: server ${h.sandboxId} has no IPv4 address 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 `hetzner: 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 // Try graceful shutdown first; fall back to power-off after a short wait.\n try {\n await client().shutdown(id);\n await pollUntil(\n `server ${h.sandboxId} off`,\n async () => {\n const s = await client().getServer(id);\n return s?.status === 'off' ? s : null;\n },\n { deadlineMs: 60_000, intervalMs: 2_000, maxIntervalMs: 8_000 },\n );\n } catch {\n await client().powerOff(id);\n }\n await tunnels.close(h.sandboxId);\n },\n\n async pause(h: CloudHandle): Promise<void> {\n // Hetzner has no archive primitive. Pause ≡ stop.\n await this.stop(h);\n },\n\n async resume(h: CloudHandle): Promise<void> {\n await this.start(h);\n },\n\n async destroy(h: CloudHandle): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n await tunnels.close(h.sandboxId);\n // Discover the per-box firewall via labels so we don't need to\n // round-trip through the server's `firewalls[]` (which is absent from\n // our typed slice anyway).\n const c = client();\n let firewallId: number | undefined;\n try {\n const server = await c.getServer(id);\n firewallId = server\n ? Number.parseInt(server.labels['agentbox.firewall'] ?? '', 10)\n : undefined;\n } catch {\n // ignore — we'll still try to delete the server\n }\n try {\n await c.deleteServer(id);\n } catch (err) {\n if (!(err instanceof HetznerApiError && (err.statusCode === 404 || err.code === 'not_found'))) {\n throw err;\n }\n }\n if (firewallId && Number.isFinite(firewallId)) {\n await deletePerBoxFirewall(c, firewallId);\n }\n // Clean the per-box ssh dir.\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 s = await client().getServer(id);\n return s ? mapState(s.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 = [\n ...sshOptArgs(target),\n localPath,\n `${target.user}@${target.host}:${remotePath}`,\n ];\n const res = await execa('scp', argv, { reject: false, timeout: 300_000 });\n if (res.exitCode !== 0) {\n throw new Error(`hetzner: 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 = [\n ...sshOptArgs(target),\n `${target.user}@${target.host}:${remotePath}`,\n localPath,\n ];\n const res = await execa('scp', argv, { reject: false, timeout: 300_000 });\n if (res.exitCode !== 0) {\n throw new Error(`hetzner: 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 // -L for nicer dir-detection on symlinks; `--printf` is non-portable so\n // use a small awk wrap that prints `<name>\\t<d|f>` per entry.\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 const { state, vpsIp } = await ensureLiveTarget(h.sandboxId);\n void state;\n void vpsIp;\n const localPort = await tunnels.forward(h.sandboxId, port);\n // Plain loopback URL — no preview-token here (SSH local forward is\n // already auth-gated by the tunnel itself). The cloud-provider layer\n // adds the Portless alias for symmetric `<box-name>.localhost` URLs.\n return { url: `http://127.0.0.1:${String(localPort)}` };\n },\n\n async signedPreviewUrl(h, port, _ttl): Promise<CloudPreviewUrl> {\n // SSH tunnels have no signed-URL primitive — they're already loopback-\n // only and the cloud-provider layer's bridge-token enforces auth. The\n // signed form is functionally equivalent to the unsigned one here.\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 + every cached `-L` forward\n // for this box and re-open from scratch. Called by the host\n // CloudBoxPoller when ECONNREFUSED on the local port shows that the\n // master died (host sleep/wake, transient network blip). Without this\n // the poller would back off forever against a stale localPort.\n const { state, vpsIp } = await ensureLiveTarget(h.sandboxId);\n void state;\n void vpsIp;\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 repairReachability(h): Promise<{ changed: boolean; detail?: string }> {\n // Re-sync the per-box firewall to the host's CURRENT egress IP, but only\n // when it actually changed — the host laptop moved networks and the\n // firewall is now blocking us. Called by the CLI ONLY on a connection-\n // establishment failure (`recover`, the initial attach connect), never on a\n // mid-session drop. A `0.0.0.0/0` firewall (explicit dynamic-IP opt-in) is\n // already open, so it's a no-op.\n const policy: InboundPolicy = h.inbound ?? { mode: 'locked', sources: [] };\n if (policy.mode === 'open') return { changed: false };\n const s = await firewallEgressStatus(h.sandboxId).catch(() => null);\n if (!s || !firewallNeedsSync(s.allowedSources, s.currentEgress)) return { changed: false };\n // Merge the stored whitelist with the refreshed egress so a drift heal\n // never narrows a whitelisted box down to just the host IP.\n const sources = resolveInboundSources(policy, s.currentEgress);\n await syncFirewallSource(client(), s.firewallId, sources);\n return {\n changed: true,\n detail: `firewall updated: SSH now allowed from ${sources.join(', ')} (was ${s.allowedSources.join(', ') || '(no rule)'})`,\n };\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 id = Number.parseInt(h.sandboxId, 10);\n const server = await client().getServer(id);\n if (!server) throw new Error(`hetzner: server ${h.sandboxId} not found`);\n const firewallId = Number.parseInt(server.labels['agentbox.firewall'] ?? '', 10);\n if (!Number.isFinite(firewallId)) {\n throw new Error(`hetzner: no per-box firewall recorded for server ${h.sandboxId}`);\n }\n const hostEgress = policy.mode === 'open' ? null : `${await detectEgressIp({})}/32`;\n const sources = resolveInboundSources(policy, hostEgress);\n await syncFirewallSource(client(), firewallId, sources);\n return { sources };\n },\n\n async startInBoxPortless(h, opts): Promise<void> {\n // Bring up a `portless` proxy *inside the VPS* mirroring the host's\n // mode so `<boxName>.localhost:<P>` resolves to the same content on\n // both sides. The `portless` CLI is baked into the base snapshot by\n // install-box.sh:316. Idempotent — `portless proxy start` exits 0 if a\n // proxy is already running on the port. Best-effort: a failure here\n // just means the in-box symmetric URL won't resolve; the host URL\n // still works.\n //\n // Run as root (vscode has NOPASSWD sudo): portless's :443/:80 TLS\n // proxy self-elevates to root anyway, and its state lands in\n // /root/.portless. A subsequent `portless alias` from vscode would\n // write to /home/vscode/.portless and the proxy wouldn't see it —\n // the two state dirs are disjoint. Using sudo for both keeps them\n // pointed at the same `/root/.portless`.\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 // The TLS mirror serves its own self-signed CA at /root/.portless/ca.pem.\n // `portless proxy start` only trusts it in the system store — not the box\n // user's NSS db, which Chromium / Playwright read — so the VNC browser and\n // Playwright fail with a cert error on `https://<box>.localhost`. Trust it\n // everywhere (system store + vscode NSS db) and point Node at it via\n // NODE_EXTRA_CA_CERTS. Best-effort: the helper never exits non-zero.\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, no\n // SSH-token mint pressure (unlike Daytona). Callers append `-t '<cmd>'`\n // or similar in the `buildAttach` helper.\n return [\n 'ssh',\n ...sshOptArgs(target),\n `${target.user}@${target.host}`,\n ];\n },\n\n async createSnapshot(h, name): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n const c = client();\n const { image } = await withHetznerRetry(\n { method: 'createImage', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () =>\n c.createImage(id, {\n type: 'snapshot',\n description: name,\n labels: { 'agentbox.role': 'ckpt', 'agentbox.box': h.sandboxId },\n }),\n );\n await pollUntil(\n `image ${String(image.id)} availability`,\n async () => {\n const img = await c.getImage(image.id);\n return img?.status === 'available' ? img : null;\n },\n { deadlineMs: SNAPSHOT_DEADLINE_MS, intervalMs: 3_000, maxIntervalMs: 10_000 },\n );\n },\n\n async deleteSnapshot(name): Promise<void> {\n const c = client();\n const img = await findImageByDescription(c, name);\n if (!img) return;\n try {\n await c.deleteImage(img.id);\n } catch (err) {\n if (err instanceof HetznerApiError && (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 _hetznerTunnels };\n\n","/**\n * Cloud-init `#cloud-config` user-data generators.\n *\n * Two flavors:\n * - **prepare** (`generatePrepareCloudInit`): for the temporary VPS that\n * `prepareHetzner()` 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 '# AgentBox temporary prepare VPS — used by `agentbox prepare --provider hetzner`',\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 // Hetzner's Ubuntu 24.04 stock image enforces a first-login password\n // change for root. With key-based auth that path can't run (no TTY),\n // so sshd refuses with \"Password change required but no TTY available.\"\n // Telling cloud-init to NOT expire passwords + clearing root's expiry\n // via `passwd -d` removes the gate. Belt-and-braces: the chpasswd block\n // covers cloud-init's own users-and-groups run; the runcmd covers the\n // case where the image's pre-baked expiry survives cloud-init.\n 'chpasswd:',\n ' expire: false',\n 'users:',\n ' - name: root',\n ' lock_passwd: false',\n ' ssh_authorized_keys:',\n ` - ${yamlScalar(pubkey)}`,\n 'runcmd:',\n ' - [ passwd, -d, root ]',\n ' - [ chage, -E, \"-1\", -I, \"-1\", -M, \"99999\", root ]',\n ' - [ bash, -lc, \"echo agentbox-prepare-ready\" ]',\n '',\n ].join('\\n');\n}\n\nexport interface ControlPlaneCloudInitOptions {\n /** ed25519/rsa public key string (one line, OpenSSH format) for `root`. */\n sshPubkey: string;\n /** Public git repo to clone the control-plane app from. */\n repoUrl: string;\n /** Branch / tag / sha to check out. */\n repoRef: string;\n}\n\n/**\n * Cloud-init for a control-plane VPS (stock Ubuntu, not the box snapshot).\n * Logs in as `root`, installs Docker + git, and clones the agentbox repo to\n * `/opt/agentbox`. The orchestrator then scp's the secret env + Caddy config\n * and runs `docker compose up` over ssh — secrets never go in user-data (which\n * is readable from cloud metadata).\n */\nexport function controlPlaneCloudInit(opts: ControlPlaneCloudInitOptions): string {\n const pubkey = opts.sshPubkey.trim();\n return [\n '#cloud-config',\n '# AgentBox control-plane VPS — provisioned by `agentbox control-plane setup --deploy hetzner`.',\n 'disable_root: false',\n 'ssh_pwauth: false',\n 'chpasswd:',\n ' expire: false',\n 'users:',\n ' - name: root',\n ' lock_passwd: false',\n ' ssh_authorized_keys:',\n ` - ${yamlScalar(pubkey)}`,\n 'runcmd:',\n ' - [ passwd, -d, root ]',\n ' - [ chage, -E, \"-1\", -I, \"-1\", -M, \"99999\", root ]',\n ' - [ bash, -lc, \"curl -fsSL https://get.docker.com | sh\" ]',\n ' - [ bash, -lc, \"apt-get update && apt-get install -y git\" ]',\n ` - [ bash, -lc, \"git clone --depth 1 --branch ${shArg(opts.repoRef)} ${shArg(opts.repoUrl)} /opt/agentbox || git clone ${shArg(opts.repoUrl)} /opt/agentbox\" ]`,\n '',\n ].join('\\n');\n}\n\n/** Single-quote a value for embedding inside a `bash -lc \"...\"` cloud-init step. */\nfunction shArg(value: string): string {\n // Only used for repo URL/ref (no shell metachars in practice); guard anyway.\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\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 `# 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 // Hetzner'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 Hetzner 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(`hetzner: 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 * Pure Hetzner create preflight — no network. Given a fetched `/server_types`\n * catalog and (optionally) the base image, validate the user's server-type +\n * location choice BEFORE we start creating billable resources (firewall, SSH\n * key, server), and map the late provision errors Hetzner returns into\n * actionable guidance.\n *\n * Kept side-effect-free so it unit-tests against fake catalogs/images. The\n * backend fetches the catalog + image and calls in.\n */\n\nimport { UserFacingError } from '@agentbox/core';\nimport { HetznerApiError, type HetznerImage, type HetznerServerType } from './client.js';\n\nexport interface ServerChoice {\n serverType: string;\n location: string;\n}\n\n/** A non-deprecated x86 type is deprecated iff the `deprecation` object is set. */\nfunction isDeprecated(t: HetznerServerType): boolean {\n return t.deprecated === true || (t.deprecation !== undefined && t.deprecation !== null);\n}\n\n/**\n * Up to `limit` non-deprecated x86 type names from the catalog, cheapest-looking\n * first (the catalog is roughly ordered by size, so preserve its order). Used to\n * suggest alternatives when the user's type is unknown.\n */\nfunction suggestTypes(catalog: HetznerServerType[], limit = 6): string[] {\n return catalog\n .filter((t) => t.architecture === 'x86' && !isDeprecated(t))\n .map((t) => t.name)\n .slice(0, limit);\n}\n\n/** Locations (from `prices[].location`) where a given type is offered. */\nfunction offeredLocations(t: HetznerServerType): string[] {\n const seen = new Set<string>();\n for (const p of t.prices) {\n if (p.location) seen.add(p.location);\n }\n return [...seen];\n}\n\n/**\n * Validate a server-type + location choice against the live catalog and the\n * base image, throwing a `UserFacingError` with a fix on the first problem.\n * Checks, in order: type exists → is x86 (ARM `cax*` snapshots aren't\n * supported) → not deprecated → disk fits the image → location offers the type.\n *\n * `image` is null when the box boots from a Hetzner stock image ref (a plain\n * string like `ubuntu-24.04`, not a numeric snapshot id) — the disk check is\n * skipped in that case since we don't have the image's `disk_size`.\n */\nexport function validateServerChoice(\n choice: ServerChoice,\n catalog: HetznerServerType[],\n image: HetznerImage | null,\n): void {\n const { serverType, location } = choice;\n const type = catalog.find((t) => t.name === serverType);\n\n if (!type) {\n const suggestions = suggestTypes(catalog);\n const hint =\n suggestions.length > 0 ? ` Valid types include: ${suggestions.join(', ')}.` : '';\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" does not exist.${hint}\\n` +\n 'Set one with `--size <type>` or `agentbox config set box.sizeHetzner <type>`.',\n );\n }\n\n if (type.architecture !== 'x86') {\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" is ${type.architecture} (ARM). AgentBox base ` +\n 'snapshots are x86-only, so ARM types (e.g. `cax*`) are not supported.\\n' +\n `Pick an x86 type instead: ${suggestTypes(catalog).join(', ')}.`,\n );\n }\n\n if (isDeprecated(type)) {\n const after = type.deprecation?.unavailable_after;\n const when = after ? ` (unavailable after ${after})` : '';\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" is deprecated${when} and can't be used for new servers.\\n` +\n `Pick a current type instead: ${suggestTypes(catalog).join(', ')}.`,\n );\n }\n\n // Snapshot disk must fit the plan's disk. Skip for stock string refs (image\n // null) — we don't have a disk_size to compare, and Hetzner sizes those itself.\n if (image && typeof image.disk_size === 'number' && type.disk < image.disk_size) {\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" has a ${String(type.disk)} GB disk, but the base ` +\n `snapshot needs at least ${String(image.disk_size)} GB.\\n` +\n 'Choose a larger type (bigger plans have bigger disks).',\n );\n }\n\n const locations = offeredLocations(type);\n if (locations.length > 0 && !locations.includes(location)) {\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" is not offered in location \"${location}\".\\n` +\n `It is available in: ${locations.join(', ')}.\\n` +\n 'Pick one with `--location <name>` or `agentbox config set box.hetznerLocation <name>`.',\n );\n }\n}\n\n/**\n * Map a Hetzner provision error (from `createServer`) into a friendlier\n * `UserFacingError`, preserving the original message. Non-Hetzner errors and\n * unrecognized codes pass through unchanged so we never hide an unexpected\n * failure. Called around the `createServer` call in the backend.\n */\nexport function mapHetznerProvisionError(err: unknown, choice: ServerChoice): unknown {\n if (!(err instanceof HetznerApiError)) return err;\n const { serverType, location } = choice;\n\n if (err.code === 'resource_limit_exceeded') {\n return new UserFacingError(\n `Hetzner refused to create the server: your account resource limit was exceeded ` +\n `(${err.message}).\\n` +\n 'New Hetzner Cloud accounts start with a low server limit. Request an increase in ' +\n 'the Hetzner Console (Limits page: https://console.hetzner.cloud/ → your project → ' +\n 'Limits), then retry.',\n );\n }\n\n if (err.code === 'resource_unavailable' || err.code === 'placement_error') {\n return new UserFacingError(\n `Hetzner has no capacity for \"${serverType}\" in \"${location}\" right now ` +\n `(${err.message}).\\n` +\n 'Retry, or pick another datacenter with `--location fsn1` / `hel1` / `ash` ' +\n '(or `agentbox config set box.hetznerLocation <name>`).',\n );\n }\n\n return err;\n}\n","/**\n * `agentbox prepare --provider hetzner` — bake the per-org Hetzner base\n * snapshot. Mirrors the user request: \"for `agentbox prepare` (and first\n * time hetzner is used) start a VM and set it up and snapshot as base image\n * (there's no way to start a VPS from an existing dockerfile).\"\n *\n * Flow:\n * 1. Mint an ephemeral SSH keypair under\n * ~/.agentbox/hetzner/prepare-<ts>/.\n * 2. Detect the host's egress IP and create a firewall locked to it,\n * named `agentbox-prepare-<ts>`.\n * 3. Create a temp VPS (Ubuntu 24.04, `cx22` default) with cloud-init\n * injecting the pubkey for `root`.\n * 4. Poll until cloud-init + sshd come up.\n * 5. scp the runtime assets (install script + agentbox-ctl + helpers +\n * baked config files) into /tmp.\n * 6. Run `bash /tmp/agentbox-install.sh` over ssh; stream stdout to the\n * prepare log via the `onLog` callback.\n * 7. `create_image` snapshot of the VPS; poll until `available`.\n * 8. Delete the VPS + firewall.\n * 9. Persist the snapshot id into `~/.agentbox/hetzner-prepared.json`.\n *\n * Failure-mode discipline: each major step is wrapped in try/catch so the\n * temp VPS + firewall are *always* cleaned up on failure (the user must\n * never end up with a forgotten €4/mo VPS due to a prepare error).\n *\n * The user requested noisy logging — every BEGIN/END marker from the\n * install script is forwarded verbatim into the prepare log, plus our own\n * step boundaries from `progress()`.\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 { ensureHetznerCredentials } from './credentials.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport { createPerBoxFirewall, deletePerBoxFirewall, normalizeSourceCidr } from './firewall.js';\nimport { makeHetznerClient } 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 PrepareHetznerOptions {\n name?: string;\n hostWorkspace?: string;\n /** Force re-bake even when `~/.agentbox/hetzner-prepared.json` has a usable base. */\n force?: boolean;\n /** Hetzner location (defaults to `nbg1`). */\n location?: string;\n /** Server type (defaults to `cx22` — 2 vCPU / 4 GB / 40 GB / ~€4/mo). */\n serverType?: string;\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\n * the explicit-open opt-in. Passing a bare IP appends `/32` 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 /** How install-box.sh installs Claude Code (`native` default | `npm`). */\n claudeInstall?: 'native' | 'npm';\n onLog?: (line: string) => void;\n}\n\nexport interface PrepareHetznerResult {\n snapshotName?: string;\n /** Hetzner image id (numeric) — also recorded in hetzner-prepared.json. */\n imageId?: number;\n}\n\n// `cx22` was deprecated by Hetzner in early 2026; `cx23` is the drop-in\n// replacement with the same 2 vCPU / 4 GB / 40 GB shape on x86. Users can\n// still override via `prepareHetzner({serverType: ...})`.\nconst TEMP_SERVER_TYPE_DEFAULT = 'cx23';\nconst TEMP_SERVER_LOCATION_DEFAULT = 'nbg1';\nconst PREPARE_SSH_DEADLINE_MS = 5 * 60_000;\nconst INSTALL_SCRIPT_TIMEOUT_MS = 30 * 60_000;\nconst SNAPSHOT_DEADLINE_MS = 20 * 60_000;\n\n/**\n * Bake the per-org Hetzner base snapshot. Resolves only after the image is\n * `available` and the temp VPS + firewall are gone. Persists `{base.imageId,\n * base.description, base.createdAt, base.installScriptSha256}` into\n * `~/.agentbox/hetzner-prepared.json`.\n */\nexport async function prepareHetzner(\n opts: PrepareHetznerOptions = {},\n): Promise<PrepareHetznerResult> {\n await ensureHetznerCredentials();\n const client = makeHetznerClient();\n const log = opts.onLog ?? (() => {});\n const progress = (step: string) => log(`prepare-hetzner: ${step}`);\n\n // Skip-fast: if a base snapshot is already recorded *and* its image is\n // still on Hetzner *and* the build-context fingerprint hasn't changed *and*\n // --force was not passed, return the existing record.\n const existingState = readPreparedState();\n // Prefer an explicit override; otherwise auto-detect the published-CLI\n // staged runtime tree by inspecting where this module was loaded from.\n const assets = resolveRuntimeAssets({\n cliRuntimeRoot: opts.cliRuntimeRoot ?? findStagedCliRuntimeRoot(),\n repoRoot: opts.repoRoot,\n });\n // Fingerprint = hash of every asset we scp into the prepare VPS. Keyed on\n // logical name (stable across staged-vs-monorepo layouts) so two CLIs with\n // the same staged tree produce the same hash.\n const claudeInstall = opts.claudeInstall ?? 'native';\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 client.getImage(existingState.base.imageId).catch(() => null);\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(\n `recorded base snapshot ${String(existingState.base.imageId)} is gone on Hetzner; rebuilding`,\n );\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 + detect egress IP in parallel.\n progress('minting ephemeral ssh key');\n const key = await mintPrepareKey();\n let firewallId: number | null = null;\n let serverId: number | null = null;\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.\n const stamp = Date.now().toString(36);\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 labels: { 'agentbox.role': 'prepare' },\n });\n firewallId = firewall.id;\n\n // 3. Create temp VPS.\n const serverName = `agentbox-prepare-${stamp}`;\n const cloudInit = generatePrepareCloudInit({ sshPubkey: key.publicKey });\n progress(\n `creating temp VPS ${serverName} (${opts.serverType ?? TEMP_SERVER_TYPE_DEFAULT} / ${opts.location ?? TEMP_SERVER_LOCATION_DEFAULT})`,\n );\n const created = await client.createServer({\n name: serverName,\n server_type: opts.serverType ?? TEMP_SERVER_TYPE_DEFAULT,\n image: 'ubuntu-24.04',\n location: opts.location ?? TEMP_SERVER_LOCATION_DEFAULT,\n user_data: cloudInit,\n firewalls: [{ firewall: firewall.id }],\n labels: { 'agentbox.managed': 'true', 'agentbox.role': 'prepare' },\n start_after_create: true,\n });\n serverId = created.server.id;\n const ip = created.server.public_net.ipv4?.ip;\n if (!ip) {\n throw new Error('hetzner: temp VPS came up without an IPv4 address');\n }\n\n // 4. Wait for sshd.\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(\n `hetzner: ssh on ${ip} did not come up within ${String(PREPARE_SSH_DEADLINE_MS / 1000)}s`,\n );\n }\n progress(\"ssh up — scp'ing runtime assets\");\n\n // 5. scp every asset into /tmp/ **sequentially**. Parallel uploads\n // through 10 fresh ssh connections trip sshd's MaxStartups (10:30:100\n // default) on a freshly-booted VPS — surviving connections look fine\n // but some randomly write 0 bytes to the destination. The sequential\n // form is plenty fast (each file is small, total ~1MB).\n for (const asset of assets) {\n const remote = `/tmp/${asset.remoteBasename}`;\n log(`prepare-hetzner: 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. We trace via `bash -x` and tee the full\n // output to /var/log/agentbox/install.log on the VPS so the trace\n // survives into the snapshot — handy when diagnosing a step that ran\n // (or didn't) deep inside the install. Stream stdout/stderr through\n // `onLog` so `prepare.log` shows the BEGIN/END markers in real time.\n // `set -o pipefail` so the pipe's exit code is bash's, not tee's.\n progress('running install-box.sh on temp VPS (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 // Exit 71 is install-box.sh's dedicated sentinel for \"Claude Code native\n // installer failed after its retries\" — almost always a transient\n // Cloudflare 403 that claude.ai / downloads.claude.ai return to\n // cloud-datacenter egress IPs under load. Surface an actionable message\n // instead of the opaque generic one (stderr is empty here because the\n // install runs `bash -x ... 2>&1 | tee`, merging stderr into stdout).\n if (installRes.exitCode === 71) {\n throw new Error(\n `Claude Code's native installer could not be reached from the Hetzner VPS after 3 retries (~5 min).\\n` +\n `This is a transient Cloudflare 403. It usually clears within a few minutes.\\n\\n` +\n `What to do: wait a moment, then re-run \\`agentbox prepare --provider hetzner --force\\`.\\n` +\n `Full trace: /var/log/agentbox/install.log inside any box made from the resulting snapshot.`,\n );\n }\n throw new Error(\n `install-box.sh failed on temp VPS (exit ${String(installRes.exitCode)})\\n` +\n `Last stderr: ${installRes.stderr.slice(-500) || '(empty)'}\\n` +\n `The full trace was preserved at /var/log/agentbox/install.log inside any box made from the resulting snapshot.`,\n );\n }\n progress('install script complete');\n\n // 6b. Stage host agent static config (~/.claude plugins/skills/settings/\n // _claude.json, ~/.codex config + prompts, ~/.local/share/opencode), scp\n // each tarball, extract into /home/vscode/ as the `vscode` user. Mirrors\n // the Daytona bake step (`Image.addLocalFile` + `Image.runCommands`),\n // adapted for our ssh+scp model. Without this, the in-box claude/codex/\n // opencode boot with no plugins, no skills, no settings, and prompt the\n // user to log in fresh on every box.\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-hetzner: ${w}`);\n if (claudeTar.tarballPath)\n 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-hetzner: ${w}`);\n if (codexTar.tarballPath)\n 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-hetzner: ${w}`);\n if (opencodeTar.tarballPath)\n stagings.push({\n kind: 'opencode',\n tar: opencodeTar,\n dest: '/home/vscode/.local/share/opencode',\n });\n else await opencodeTar.cleanup();\n\n // ~/.agents (cross-agent Agent Skills) — codex reads ~/.agents/skills.\n const agentsTar = await stageAgentsStaticForUpload();\n for (const w of agentsTar.warnings) log(`prepare-hetzner: ${w}`);\n if (agentsTar.tarballPath)\n 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-hetzner: scp ${s.kind} static (${s.tar.tarballPath}) -> ${remote}`);\n await scpUpload(sshTarget, s.tar.tarballPath as string, remote);\n // Extract as vscode so the files land owned by uid 1000. The dir\n // already exists (created by the install script's credential-pivot\n // step) — extract into it, don't replace it.\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, {\n onLine: (line) => log(`[stage:${s.kind}] ${line}`),\n });\n if (r.exitCode !== 0) {\n throw new Error(\n `prepare-hetzner: ${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.\n const description = opts.name ?? `agentbox-base-${stamp}`;\n progress(`creating snapshot '${description}' from VPS ${String(serverId)}`);\n const snap = await client.createImage(serverId, {\n type: 'snapshot',\n description,\n labels: { 'agentbox.role': 'base', 'agentbox.schema': '1' },\n });\n progress(\n `snapshot create requested (image id ${String(snap.image.id)}); polling until available`,\n );\n const ready = await pollUntil(\n `image ${String(snap.image.id)} availability`,\n async () => {\n const img = await client.getImage(snap.image.id);\n if (!img) return null;\n if (img.status === 'available') return img;\n return null;\n },\n {\n deadlineMs: SNAPSHOT_DEADLINE_MS,\n intervalMs: 3_000,\n maxIntervalMs: 10_000,\n onPoll: (l) => log(`prepare-hetzner: ${l}`),\n },\n );\n\n // 8. Persist before tearing down — if the cleanup fails we still know\n // about the new snapshot.\n progress('persisting hetzner-prepared.json');\n const state = readPreparedState();\n const cliStamp = readCliStamp();\n state.base = {\n imageId: ready.id,\n description: ready.description,\n createdAt: new Date().toISOString(),\n contextSha256: contextSha,\n cliVersion: cliStamp.cliVersion,\n cliCommit: cliStamp.cliCommit,\n };\n writePreparedState(state);\n log(`prepare-hetzner: wrote ${preparedStatePath()}`);\n\n // 9. Cleanup: delete server first (cleanly detaches from firewall),\n // then the firewall.\n progress(`deleting temp VPS ${String(serverId)}`);\n await client.deleteServer(serverId);\n serverId = null;\n progress(`deleting per-prepare firewall ${String(firewallId)}`);\n await deletePerBoxFirewall(client, firewallId);\n firewallId = null;\n\n progress(`prepare complete — base snapshot ${String(ready.id)} (${ready.description})`);\n return { snapshotName: ready.description, imageId: ready.id };\n } catch (err) {\n // Failure cleanup — best-effort. Always try to delete the VPS first\n // (it costs €4/mo if left running). Surface the original error in any\n // case.\n if (serverId !== null) {\n log(`prepare-hetzner: cleanup — deleting temp VPS ${String(serverId)} after failure`);\n try {\n await client.deleteServer(serverId);\n } catch (cleanupErr) {\n log(\n `prepare-hetzner: WARN — failed to delete temp VPS ${String(serverId)}; check the Hetzner dashboard manually. ${\n cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)\n }`,\n );\n }\n }\n if (firewallId !== null) {\n log(\n `prepare-hetzner: cleanup — deleting per-prepare firewall ${String(firewallId)} after failure`,\n );\n try {\n await deletePerBoxFirewall(client, firewallId);\n } catch (cleanupErr) {\n log(\n `prepare-hetzner: WARN — failed to delete firewall ${String(firewallId)}; check the Hetzner 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 `daytonaProvider.prepare`.\n */\nexport const prepareHetznerProvider: NonNullable<Provider['prepare']> = (req) =>\n prepareHetzner({\n name: req.name,\n hostWorkspace: req.hostWorkspace ?? process.cwd(),\n force: req.force,\n // Datacenter for the temp bake VPS (defaults to nbg1 when unset). Resolved\n // by the CLI from `--location` / `box.hetznerLocation`.\n location: req.location,\n onLog: req.onLog,\n // Forward the Claude install mode (native | npm). Without this the Hetzner\n // bake always ran the native `curl install.sh`, whose CDN 403s datacenter\n // egress IPs — the `npm` escape hatch (box.claudeInstall / --claude-install\n // npm) never reached the bake. (matches prepareVercelProvider.)\n claudeInstall: req.claudeInstall,\n });\n\n/**\n * First-use gate. If no base snapshot is recorded in\n * `~/.agentbox/hetzner-prepared.json`, throws an actionable error pointing\n * at `agentbox prepare --provider hetzner`.\n *\n * This is called by `backend.provision()` (lazily, from Phase 4 onward) so\n * `agentbox prepare --provider hetzner` itself can run without tripping\n * the gate.\n *\n * Phase 4 will widen this to also re-check the image is still on Hetzner\n * (404 → retrigger prepare prompt). For now it just gates on the local\n * record so the build is honest about the failure mode.\n */\nexport async function ensureHetznerBaseSnapshot(): Promise<void> {\n const state = readPreparedState();\n if (state.base !== undefined) return;\n throw new UserFacingError(\n 'no Hetzner base snapshot found.\\n' +\n 'Run `agentbox prepare --provider hetzner` first (Hetzner 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 Hetzner 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/hetzner/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). Re-exported\n// here so the Hetzner-internal call sites 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', 'hetzner', `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 * Hetzner's per-box ssh dir is un-namespaced (`~/.agentbox/boxes/<id>/ssh/`) —\n * it predates the namespace argument, and moving it would orphan the keys of\n * every already-running box.\n */\nexport {\n SshTunnelManager,\n defaultBoxSshDir,\n type PortForward,\n type SshTunnelOpenOptions,\n} from '@agentbox/sandbox-core';\n","/**\n * Doctor probes + normalized credential status for the hetzner 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 { readHetznerCredStatus } from './credentials.js';\nimport { readPreparedState } from './prepared-state.js';\n\nexport function readCredStatusSummary(): CredStatusSummary {\n return { configured: readHetznerCredStatus().source !== 'none' };\n}\n\nexport async function doctorChecks(): Promise<CheckResult[]> {\n try {\n const cred = readHetznerCredStatus();\n const credRes: CheckResult =\n cred.source === 'none'\n ? {\n label: 'credentials',\n status: 'warn',\n detail: 'HCLOUD_TOKEN not set',\n hint: '`agentbox hetzner 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: `image ${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 hetzner`',\n };\n // Host Portless mints the <box>.localhost alias for the SSH-forwarded port;\n // without it hetzner 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","/**\n * Deploy the AgentBox hosted control plane (the `apps/hub` Next.js +\n * Postgres app) to a fresh Hetzner VPS, reachable over HTTPS at\n * `https://<ipv4>.sslip.io` (sslip.io resolves the host to the IP; Caddy auto-\n * provisions a Let's Encrypt cert — no domain or DNS setup needed).\n *\n * Shape:\n * 1. firewall — SSH from the host egress IP, :80/:443 open (ACME + serving).\n * 2. cloud-init — stock Ubuntu boots, installs Docker + git, clones the repo.\n * 3. over ssh (as root): scp the secret `.env` + a Caddy compose overlay, then\n * `docker compose up -d --build` (Postgres + the app + Caddy, all in-compose).\n * 4. poll `https://<domain>/healthz` until the cert + app are live.\n * Secrets ride scp (per-deploy key), never cloud-init user-data (cloud metadata).\n */\n\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { makeHetznerClient, type HetznerServer } from './client.js';\nimport { controlPlaneCloudInit } from './cloud-init.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport { controlPlaneInboundRules, normalizeSourceCidr } from './firewall.js';\nimport { mintSshKey } from './ssh-key.js';\nimport { scpUpload, sshExec, waitForSsh, type SshTargetArgs } from './ssh-cli.js';\nimport { withHetznerRetry } from './retry.js';\n\nexport interface ControlPlaneHetznerDeployOptions {\n /** Contents of `control-plane.env` — GITHUB_APP_ID / _PRIVATE_KEY / ADMIN_TOKEN. */\n envContent: string;\n /** Override the public hostname (default `<ipv4>.sslip.io`). */\n domain?: string;\n /** Public git repo cloned on the VPS (default the agentbox repo). */\n repoUrl?: string;\n /** Branch / tag / sha to deploy (default `main`). */\n repoRef?: string;\n serverType?: string;\n location?: string;\n serverImage?: string;\n onLog?: (line: string) => void;\n}\n\nexport interface ControlPlaneHetznerDeployResult {\n url: string;\n serverId: number;\n ip: string;\n domain: string;\n firewallId: number;\n sshKeyDir: string;\n}\n\nconst REMOTE_APP_DIR = '/opt/agentbox/apps/hub';\n\nfunction caddyfile(domain: string): string {\n // Caddy auto-provisions a Let's Encrypt cert for the site address and reverse-\n // proxies to the Next app on the compose network (the app listens on :3000).\n return `${domain} {\\n\\treverse_proxy app:3000\\n}\\n`;\n}\n\nconst CADDY_COMPOSE = `services:\n caddy:\n image: caddy:2.8\n restart: unless-stopped\n ports:\n - '80:80'\n - '443:443'\n volumes:\n - ${REMOTE_APP_DIR}/Caddyfile:/etc/caddy/Caddyfile:ro\n - caddy_data:/data\n - caddy_config:/config\n depends_on:\n - app\nvolumes:\n caddy_data:\n caddy_config:\n`;\n\nasync function serverIpv4(\n client: ReturnType<typeof makeHetznerClient>,\n server: HetznerServer,\n deadlineMs: number,\n): Promise<string> {\n if (server.public_net.ipv4?.ip) return server.public_net.ipv4.ip;\n const stop = Date.now() + deadlineMs;\n while (Date.now() < stop) {\n const s = await client.getServer(server.id);\n if (s?.public_net.ipv4?.ip) return s.public_net.ipv4.ip;\n await new Promise((r) => setTimeout(r, 3_000));\n }\n throw new Error(`server ${String(server.id)} never got a public IPv4`);\n}\n\nasync function pollHealthz(url: string, deadlineMs: number, log: (l: string) => void): Promise<void> {\n const stop = Date.now() + deadlineMs;\n let lastErr = '';\n while (Date.now() < stop) {\n try {\n const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8000) });\n if (res.ok) return;\n lastErr = `HTTP ${String(res.status)}`;\n } catch (e) {\n lastErr = e instanceof Error ? e.name : String(e);\n }\n log(`waiting for ${url}/healthz (cert + app)… ${lastErr}`);\n await new Promise((r) => setTimeout(r, 6_000));\n }\n throw new Error(`control plane did not become healthy at ${url} (${lastErr})`);\n}\n\nexport async function deployControlPlaneToHetzner(\n opts: ControlPlaneHetznerDeployOptions,\n): Promise<ControlPlaneHetznerDeployResult> {\n const log = opts.onLog ?? (() => {});\n const repoUrl = opts.repoUrl ?? 'https://github.com/madarco/agentbox.git';\n const repoRef = opts.repoRef ?? 'main';\n const client = makeHetznerClient();\n\n const stamp = Date.now().toString(36);\n const name = `agentbox-control-plane-${stamp}`;\n\n log('detecting host egress IP for the firewall…');\n const hostCidr = normalizeSourceCidr(await detectEgressIp());\n\n log('creating the control-plane firewall (:22 host-only, :80/:443 open)…');\n const firewall = await withHetznerRetry(\n { method: 'createFirewall', retryOnAmbiguous: false, attemptTimeoutMs: 60_000 },\n () =>\n client.createFirewall({\n name,\n rules: controlPlaneInboundRules(hostCidr),\n labels: { 'agentbox.managed': 'true', 'agentbox.role': 'control-plane' },\n }),\n );\n\n const keyDir = join(homedir(), '.agentbox', 'control-plane', 'ssh', stamp);\n const key = await mintSshKey(keyDir, `agentbox-control-plane-${stamp}`);\n const knownHosts = join(keyDir, 'known_hosts');\n\n log(`provisioning ${opts.serverType ?? 'cx23'} VPS (cloning ${repoUrl}@${repoRef})…`);\n const { server } = await withHetznerRetry(\n { method: 'createServer', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () =>\n client.createServer({\n name,\n server_type: opts.serverType ?? 'cx23',\n image: opts.serverImage ?? 'ubuntu-24.04',\n location: opts.location ?? 'nbg1',\n user_data: controlPlaneCloudInit({ sshPubkey: key.publicKey, repoUrl, repoRef }),\n firewalls: [{ firewall: firewall.id }],\n labels: { 'agentbox.managed': 'true', 'agentbox.role': 'control-plane' },\n start_after_create: true,\n }),\n );\n\n const ip = await serverIpv4(client, server, 60_000);\n const domain = opts.domain ?? `${ip}.sslip.io`;\n const url = `https://${domain}`;\n const target: SshTargetArgs = { host: ip, user: 'root', identity: key.privatePath, knownHosts };\n\n log(`VPS ${ip} up; waiting for ssh…`);\n if (!(await waitForSsh(target, 5 * 60_000))) {\n throw new Error(`ssh never came up on ${ip}`);\n }\n log('waiting for cloud-init (Docker + repo clone)…');\n await sshExec(target, 'cloud-init status --wait || true', { timeoutMs: 12 * 60_000, onLine: log });\n const cloned = await sshExec(target, `test -d ${REMOTE_APP_DIR}`);\n if (cloned.exitCode !== 0) {\n throw new Error('repo clone did not complete on the VPS (cloud-init failed)');\n }\n\n // Stage the secret env + Caddy config locally, then scp them up.\n const staging = join(tmpdir(), `agentbox-cp-deploy-${stamp}`);\n await mkdir(staging, { recursive: true });\n try {\n const envLocal = join(staging, 'control-plane.env');\n const caddyLocal = join(staging, 'Caddyfile');\n const composeLocal = join(staging, 'docker-compose.caddy.yml');\n await writeFile(envLocal, opts.envContent, { mode: 0o600 });\n await writeFile(caddyLocal, caddyfile(domain));\n await writeFile(composeLocal, CADDY_COMPOSE);\n log('uploading env + Caddy config…');\n await scpUpload(target, envLocal, `${REMOTE_APP_DIR}/.env`);\n await scpUpload(target, caddyLocal, `${REMOTE_APP_DIR}/Caddyfile`);\n await scpUpload(target, composeLocal, `${REMOTE_APP_DIR}/docker-compose.caddy.yml`);\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n\n log('building + starting the control plane (docker compose up --build)…');\n const up = await sshExec(\n target,\n `cd ${REMOTE_APP_DIR} && docker compose -f docker-compose.yml -f docker-compose.caddy.yml up -d --build`,\n { timeoutMs: 25 * 60_000, onLine: log },\n );\n if (up.exitCode !== 0) {\n throw new Error(`docker compose up failed (exit ${String(up.exitCode)}): ${up.stderr || up.stdout}`);\n }\n\n log(`provisioned; waiting for HTTPS at ${url} …`);\n await pollHealthz(url, 3 * 60_000, log);\n\n const result: ControlPlaneHetznerDeployResult = {\n url,\n serverId: server.id,\n ip,\n domain,\n firewallId: firewall.id,\n sshKeyDir: keyDir,\n };\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,eAAe;AEFxB,SAAS,iBAAiB;AAE1B,SAAS,WAAAA,gBAAe;AACxB,SAAS,WAAAC,gBAAe;AACxB;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;OACK;AIEP,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,SAAS,WAAAD,gBAAe;AACjC,SAAS,qBAAqB;ANI9B,IAAM,eAAe,CAAC,gBAAgB,iBAAiB;AAEvD,IAAI,SAAS;AAEN,SAAS,yBAA+B;AAC7C,MAAI,OAAQ;AACZ,WAAS;AACT,wBAAsB,QAAQ,QAAQ,GAAG,aAAa,aAAa,CAAC;AACtE;AAEA,SAAS,sBAAsB,MAAoB;AACjD,MAAI,CAAC,WAAW,IAAI,EAAG;AACvB,MA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,GAAG,UAAU,GAAG,MAAM,EAAE;EACrG;AAEA,EAAAA,KAAI,qCAAqC,GAAG,SAAI;AAChD,QAAM,YAAY,KAAK,IAAI,KAAQA,IAAG;AAEtC,QAAM,SAA0C;IAC9C;IACA,UAAU,OAAO;IACjB;IACA;IACA,YAAY,SAAS;IACrB,WAAW;EACb;AACA,SAAO;AACT;AV3LA,IAAM,gBAAgB,oBAAoB,gBAAgB;EACxD,kBAAkB,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG;AAClD,CAAC;AAEM,IAAM,kBAA4B;EACvC,GAAG;EACH,SAAS;EACT,iBAAiB,MAAM,kCAAkC;AAC3D;AAGO,IAAM,iBAAiC;EAC5C,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,4BAA4B,CAAC,kBAAkB,kCAAkC,aAAa;EAC9F;AACF;","names":["homedir","resolve","existsSync","opts","client","resolve","homedir","log","raceTimeout","existsSync","existsSync","join","dirname","resolve","mkdir","rm","homedir","join","resolve","dirname","client","log","UserFacingError","SNAPSHOT_DEADLINE_MS","existsSync"]}
|
|
1
|
+
{"version":3,"sources":["../../../packages/sandbox-hetzner/src/env-loader.ts","../../../packages/sandbox-hetzner/src/client.ts","../../../packages/sandbox-hetzner/src/credentials.ts","../../../packages/sandbox-hetzner/src/egress-ip.ts","../../../packages/sandbox-hetzner/src/retry.ts","../../../packages/sandbox-hetzner/src/firewall.ts","../../../packages/sandbox-hetzner/src/runtime-assets.ts","../../../packages/sandbox-hetzner/src/prepared-state.ts","../../../packages/sandbox-hetzner/src/index.ts","../../../packages/sandbox-hetzner/src/backend.ts","../../../packages/sandbox-hetzner/src/cloud-init.ts","../../../packages/sandbox-hetzner/src/poll.ts","../../../packages/sandbox-hetzner/src/preflight.ts","../../../packages/sandbox-hetzner/src/prepare.ts","../../../packages/sandbox-hetzner/src/ssh-key.ts","../../../packages/sandbox-hetzner/src/ssh-cli.ts","../../../packages/sandbox-hetzner/src/ssh-tunnel.ts","../../../packages/sandbox-hetzner/src/provider-module.ts","../../../packages/sandbox-hetzner/src/control-plane-deploy.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\n\n/**\n * Hetzner env auto-loader — mirrors `ensureDaytonaEnvLoaded()`. The Hetzner\n * REST client reads `HCLOUD_TOKEN` from `process.env`. We pull it in from\n * `~/.agentbox/secrets.env` so the client Just Works after the user runs\n * `agentbox hetzner login` once.\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 hetzner login`.\n *\n * Project-level `.env` / `.env.local` are intentionally NOT consulted: those\n * files belong to the app code being developed, and a `HCLOUD_TOKEN` there\n * is typically meant for in-box infrastructure work, not for the host CLI to\n * harvest and provision VPSes with.\n *\n * Only Hetzner-prefixed keys are imported. Idempotent + side-effect-free\n * after the first call.\n */\nconst HETZNER_KEYS = ['HCLOUD_TOKEN', 'HCLOUD_ENDPOINT'] as const;\n\nlet loaded = false;\n\nexport function ensureHetznerEnvLoaded(): void {\n if (loaded) return;\n loaded = true;\n importHetznerFromFile(resolve(homedir(), '.agentbox', 'secrets.env'));\n}\n\nfunction importHetznerFromFile(path: 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 HETZNER_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 with spaces\"`,\n * `KEY='value with $special chars'`, `export KEY=value`, blank lines, and\n * `#` comments. Same shape as the daytona env-loader's parser — kept local\n * here rather than imported across packages to avoid the cycle (daytona\n * doesn't import from hetzner and shouldn't start now).\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 * Hetzner Cloud REST API client — hand-rolled fetch wrapper.\n *\n * Why not an SDK: the Hetzner SDK options are limited (no official JS SDK\n * with strict types at the time of writing), and the subset of the API we\n * need is small (servers, images, firewalls, plus a handful of read-only\n * lookups). A hand-rolled client gives us strict typing of just the fields\n * we touch, no heavy dep tree, and full control over the retry wrapper.\n *\n * Auth: bearer token in `HCLOUD_TOKEN` env. The env-loader pulls it from\n * `~/.agentbox/secrets.env` so the user only sets it once via\n * `agentbox hetzner login`.\n *\n * Errors: REST responses get unwrapped into typed `HetznerApiError`s that\n * carry the response `status` + the API's `error.code` / `error.message`.\n * Network failures bubble up as raw `Error`s with a `code` property\n * (ECONNRESET, ETIMEDOUT, …) — the retry wrapper classifies both shapes.\n */\n\nimport { ensureHetznerEnvLoaded } from './env-loader.js';\n\nexport const DEFAULT_HCLOUD_ENDPOINT = 'https://api.hetzner.cloud/v1';\n\n/**\n * Coarse Hetzner Cloud Server lifecycle states we care about. Hetzner has a\n * dozen finer-grained ones (`initializing`, `migrating`, `rebuilding`, …);\n * we map them in `backend.ts` to the four-value `CloudState` everyone else\n * consumes. Listed here so the client return types stay narrow.\n */\nexport type HetznerServerStatus =\n | 'running'\n | 'initializing'\n | 'starting'\n | 'stopping'\n | 'off'\n | 'deleting'\n | 'migrating'\n | 'rebuilding'\n | 'unknown';\n\nexport interface HetznerServer {\n id: number;\n name: string;\n status: HetznerServerStatus;\n created: string;\n public_net: {\n ipv4: { ip: string; blocked: boolean } | null;\n ipv6: { ip: string; blocked: boolean } | null;\n };\n server_type: { name: string; cores: number; memory: number; disk: number };\n image: { id: number; name?: string; description?: string; type: string } | null;\n labels: Record<string, string>;\n}\n\nexport interface HetznerAction {\n id: number;\n command: string;\n status: 'running' | 'success' | 'error';\n progress: number;\n error?: { code: string; message: string };\n}\n\nexport interface HetznerImage {\n id: number;\n type: 'system' | 'snapshot' | 'backup' | 'app';\n status: 'available' | 'creating' | 'unavailable';\n name?: string;\n description: string;\n image_size?: number;\n disk_size: number;\n /** CPU architecture the image is built for. Snapshots inherit the source VPS. */\n architecture?: 'x86' | 'arm';\n created: string;\n labels: Record<string, string>;\n bound_to?: number;\n}\n\n/**\n * A Hetzner server type (VPS plan), narrowed to the fields the preflight\n * validator reads. `memory`/`disk` are GB (memory is a float, e.g. `4`, `7.75`).\n * `prices[].location` is the authoritative \"offered here\" list. `deprecation`\n * is a non-null object once the type is on the deprecation path (the legacy\n * `deprecated` boolean mirrors it). See GET /server_types.\n */\nexport interface HetznerServerType {\n id: number;\n name: string;\n cores: number;\n memory: number;\n disk: number;\n architecture: 'x86' | 'arm';\n deprecated?: boolean;\n deprecation?: { announced?: string; unavailable_after?: string } | null;\n prices: Array<{ location: string }>;\n}\n\nexport interface HetznerFirewall {\n id: number;\n name: string;\n rules: HetznerFirewallRule[];\n applied_to: Array<{ type: 'server'; server: { id: number } }>;\n}\n\nexport interface HetznerFirewallRule {\n direction: 'in' | 'out';\n protocol: 'tcp' | 'udp' | 'icmp' | 'esp' | 'gre';\n port?: string;\n source_ips?: string[];\n destination_ips?: string[];\n description?: string;\n}\n\nexport interface HetznerSshKey {\n id: number;\n name: string;\n fingerprint: string;\n public_key: string;\n labels: Record<string, string>;\n}\n\nexport interface CreateServerRequest {\n name: string;\n server_type: string;\n image: string | number;\n location?: string;\n datacenter?: string;\n user_data?: string;\n ssh_keys?: Array<string | number>;\n firewalls?: Array<{ firewall: number }>;\n labels?: Record<string, string>;\n start_after_create?: boolean;\n public_net?: {\n enable_ipv4?: boolean;\n enable_ipv6?: boolean;\n };\n}\n\nexport interface CreateFirewallRequest {\n name: string;\n rules: HetznerFirewallRule[];\n labels?: Record<string, string>;\n apply_to?: Array<{ type: 'server'; server: { id: number } }>;\n}\n\n/**\n * Strongly-typed Hetzner API error. The Hetzner API consistently returns\n * `{ error: { code, message, details? } }` for 4xx/5xx (https://docs.hetzner.cloud/#errors).\n * We unwrap that into this class so callers can do `instanceof\n * HetznerApiError` and inspect `.code` / `.statusCode` without parsing the\n * body again.\n */\nexport class HetznerApiError extends Error {\n readonly statusCode: number;\n readonly code: string;\n readonly details?: unknown;\n constructor(statusCode: number, code: string, message: string, details?: unknown) {\n super(`hetzner ${String(statusCode)} ${code}: ${message}`);\n this.name = 'HetznerApiError';\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Subset of the Hetzner Cloud API the agentbox provider talks to. Methods\n * map 1:1 to REST endpoints; each operation is small + idempotent-where-the-\n * API-is-idempotent. The retry wrapper around the provider methods handles\n * transient 5xx / connection failures.\n */\nexport interface HetznerClient {\n /** GET /servers/{id}. Returns null on 404 so callers don't have to try/catch. */\n getServer(id: number): Promise<HetznerServer | null>;\n /** POST /servers. Returns the created server + the create action handle. */\n createServer(req: CreateServerRequest): Promise<{ server: HetznerServer; action: HetznerAction }>;\n /** GET /servers (with optional label selector). */\n listServers(opts?: { label_selector?: string }): Promise<HetznerServer[]>;\n /** DELETE /servers/{id}. Returns the action handle. Idempotent on 404. */\n deleteServer(id: number): Promise<HetznerAction | null>;\n /** POST /servers/{id}/actions/poweron. */\n powerOn(id: number): Promise<HetznerAction>;\n /** POST /servers/{id}/actions/poweroff. */\n powerOff(id: number): Promise<HetznerAction>;\n /** POST /servers/{id}/actions/shutdown — graceful, sends ACPI. */\n shutdown(id: number): Promise<HetznerAction>;\n /** POST /servers/{id}/actions/create_image — snapshot of the live disk. */\n createImage(\n id: number,\n body: { type: 'snapshot' | 'backup'; description?: string; labels?: Record<string, string> },\n ): Promise<{ image: HetznerImage; action: HetznerAction }>;\n /** GET /images/{id}. Returns null on 404. */\n getImage(id: number): Promise<HetznerImage | null>;\n /** GET /server_types — the VPS-plan catalog (paginated). Used by the create preflight. */\n listServerTypes(): Promise<HetznerServerType[]>;\n /** GET /images (filterable). */\n listImages(opts?: {\n type?: 'system' | 'snapshot' | 'backup' | 'app';\n label_selector?: string;\n name?: string;\n }): Promise<HetznerImage[]>;\n /** DELETE /images/{id}. Idempotent on 404. */\n deleteImage(id: number): Promise<void>;\n /** POST /firewalls. */\n createFirewall(req: CreateFirewallRequest): Promise<HetznerFirewall>;\n /** POST /firewalls/{id}/actions/set_rules. Replaces the entire rule set. */\n setFirewallRules(id: number, rules: HetznerFirewallRule[]): Promise<HetznerAction[]>;\n /** GET /firewalls/{id}. Returns null on 404. */\n getFirewall(id: number): Promise<HetznerFirewall | null>;\n /** DELETE /firewalls/{id}. Idempotent on 404. */\n deleteFirewall(id: number): Promise<void>;\n /**\n * GET /locations — used by `agentbox hetzner login` to validate the token\n * with a cheap unauthenticated-shape call (the endpoint requires a valid\n * token but returns a small, stable response).\n */\n listLocations(): Promise<Array<{ id: number; name: string; city: string; country: string }>>;\n}\n\ninterface MakeClientOptions {\n /** Override the bearer token (else read from `HCLOUD_TOKEN`). */\n token?: string;\n /** Override the API base URL (else read from `HCLOUD_ENDPOINT` or use the default). */\n endpoint?: string;\n /** Per-request fetch impl (tests inject this). */\n fetchImpl?: typeof fetch;\n}\n\n/**\n * Build a Hetzner Cloud client bound to the current `HCLOUD_TOKEN`. The token\n * is resolved at construction time, so re-running `agentbox hetzner login` in\n * the middle of a long-lived process won't pick up the new token without a\n * fresh `makeHetznerClient()` call (we accept this — the CLI re-imports the\n * provider on each invocation).\n */\nexport function makeHetznerClient(opts: MakeClientOptions = {}): HetznerClient {\n ensureHetznerEnvLoaded();\n const rawToken = opts.token ?? process.env.HCLOUD_TOKEN;\n if (!rawToken || rawToken.trim().length === 0) {\n throw new Error(\n 'Hetzner credentials not configured: HCLOUD_TOKEN is empty.\\n' +\n 'Run `agentbox hetzner login` interactively, or set HCLOUD_TOKEN in the environment.',\n );\n }\n // Bind to a const so the type narrows for the closures below — without\n // this the `req()` closure sees the original `string | undefined` shape.\n const token: string = rawToken.trim();\n const endpoint = (opts.endpoint ?? process.env.HCLOUD_ENDPOINT ?? DEFAULT_HCLOUD_ENDPOINT).replace(/\\/$/, '');\n const fetchImpl = opts.fetchImpl ?? fetch;\n\n async function req<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown,\n ): Promise<T | null> {\n const url = `${endpoint}${path}`;\n const init: RequestInit = {\n method,\n headers: {\n Authorization: `Bearer ${token}`,\n ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),\n },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n };\n const res = await fetchImpl(url, init);\n if (res.status === 204) return null;\n if (res.status === 404) return null;\n if (!res.ok) {\n let parsed: { error?: { code?: string; message?: string; details?: unknown } } = {};\n try {\n parsed = (await res.json()) as typeof parsed;\n } catch {\n // body wasn't json\n }\n const code = parsed.error?.code ?? `http_${String(res.status)}`;\n const msg = parsed.error?.message ?? res.statusText ?? 'unknown error';\n throw new HetznerApiError(res.status, code, msg, parsed.error?.details);\n }\n const text = await res.text();\n if (text.length === 0) return null;\n return JSON.parse(text) as T;\n }\n\n async function reqExpect<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown,\n ): Promise<T> {\n const out = await req<T>(method, path, body);\n if (out === null) {\n throw new HetznerApiError(0, 'empty_response', `expected a body from ${method} ${path}`);\n }\n return out;\n }\n\n return {\n async getServer(id) {\n const r = await req<{ server: HetznerServer }>('GET', `/servers/${String(id)}`);\n return r?.server ?? null;\n },\n async createServer(reqBody) {\n const r = await reqExpect<{ server: HetznerServer; action: HetznerAction }>(\n 'POST',\n '/servers',\n reqBody,\n );\n return { server: r.server, action: r.action };\n },\n async listServers(opts) {\n const params = new URLSearchParams();\n if (opts?.label_selector) params.set('label_selector', opts.label_selector);\n params.set('per_page', '50');\n const all: HetznerServer[] = [];\n let pageNum = 1;\n while (true) {\n params.set('page', String(pageNum));\n const r = await reqExpect<{\n servers: HetznerServer[];\n meta?: { pagination?: { next_page?: number | null } };\n }>('GET', `/servers?${params.toString()}`);\n all.push(...r.servers);\n const next = r.meta?.pagination?.next_page;\n if (typeof next !== 'number') break;\n pageNum = next;\n }\n return all;\n },\n async deleteServer(id) {\n const r = await req<{ action: HetznerAction }>('DELETE', `/servers/${String(id)}`);\n return r?.action ?? null;\n },\n async powerOn(id) {\n const r = await reqExpect<{ action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/poweron`,\n );\n return r.action;\n },\n async powerOff(id) {\n const r = await reqExpect<{ action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/poweroff`,\n );\n return r.action;\n },\n async shutdown(id) {\n const r = await reqExpect<{ action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/shutdown`,\n );\n return r.action;\n },\n async createImage(id, body) {\n const r = await reqExpect<{ image: HetznerImage; action: HetznerAction }>(\n 'POST',\n `/servers/${String(id)}/actions/create_image`,\n body,\n );\n return { image: r.image, action: r.action };\n },\n async getImage(id) {\n const r = await req<{ image: HetznerImage }>('GET', `/images/${String(id)}`);\n return r?.image ?? null;\n },\n async listServerTypes() {\n const params = new URLSearchParams();\n params.set('per_page', '50');\n const all: HetznerServerType[] = [];\n let pageNum = 1;\n while (true) {\n params.set('page', String(pageNum));\n const r = await reqExpect<{\n server_types: HetznerServerType[];\n meta?: { pagination?: { next_page?: number | null } };\n }>('GET', `/server_types?${params.toString()}`);\n all.push(...r.server_types);\n const next = r.meta?.pagination?.next_page;\n if (typeof next !== 'number') break;\n pageNum = next;\n }\n return all;\n },\n async listImages(opts) {\n const params = new URLSearchParams();\n if (opts?.type) params.set('type', opts.type);\n if (opts?.label_selector) params.set('label_selector', opts.label_selector);\n if (opts?.name) params.set('name', opts.name);\n params.set('per_page', '50');\n const all: HetznerImage[] = [];\n let pageNum = 1;\n while (true) {\n params.set('page', String(pageNum));\n const r = await reqExpect<{\n images: HetznerImage[];\n meta?: { pagination?: { next_page?: number | null } };\n }>('GET', `/images?${params.toString()}`);\n all.push(...r.images);\n const next = r.meta?.pagination?.next_page;\n if (typeof next !== 'number') break;\n pageNum = next;\n }\n return all;\n },\n async deleteImage(id) {\n await req<unknown>('DELETE', `/images/${String(id)}`);\n },\n async createFirewall(reqBody) {\n const r = await reqExpect<{ firewall: HetznerFirewall }>('POST', '/firewalls', reqBody);\n return r.firewall;\n },\n async setFirewallRules(id, rules) {\n const r = await reqExpect<{ actions: HetznerAction[] }>(\n 'POST',\n `/firewalls/${String(id)}/actions/set_rules`,\n { rules },\n );\n return r.actions;\n },\n async getFirewall(id) {\n const r = await req<{ firewall: HetznerFirewall }>('GET', `/firewalls/${String(id)}`);\n return r?.firewall ?? null;\n },\n async deleteFirewall(id) {\n await req<unknown>('DELETE', `/firewalls/${String(id)}`);\n },\n async listLocations() {\n const r = await reqExpect<{\n locations: Array<{ id: number; name: string; city: string; country: string }>;\n }>('GET', '/locations');\n return r.locations;\n },\n };\n}\n","import { spawnSync } from 'node:child_process';\nimport { hostOpenCommand, writeManagedSecrets, type CredSetResult } from '@agentbox/sandbox-core';\nimport { homedir } from 'node:os';\nimport { resolve } from 'node:path';\nimport {\n cancel,\n confirm,\n isCancel,\n intro,\n log,\n note,\n outro,\n password,\n spinner,\n} from '@clack/prompts';\nimport { makeHetznerClient } from './client.js';\nimport { ensureHetznerEnvLoaded } from './env-loader.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://console.hetzner.cloud/projects';\n\n/**\n * Keys we manage in `~/.agentbox/secrets.env`. When the user reconfigures\n * we strip prior values before appending so the file never accumulates\n * duplicates. `HCLOUD_ENDPOINT` is honored but we don't prompt for it\n * (default endpoint covers 100% of users).\n */\nconst MANAGED_KEYS = ['HCLOUD_TOKEN', 'HCLOUD_ENDPOINT'] as const;\ntype ManagedKey = (typeof MANAGED_KEYS)[number];\n\nexport interface EnsureHetznerCredentialsOptions {\n /** Re-prompt even when valid credentials are already present (used by `agentbox hetzner login`). */\n force?: boolean;\n}\n\n/**\n * First-run interactive setup for Hetzner credentials. Walks the user\n * through creating a project API token, pasting it, validating, and\n * persisting to `~/.agentbox/secrets.env`.\n *\n * No-op when credentials are already configured (env var or our secrets\n * file). Silent no-op when stdin isn't a TTY so scripted/CI callers get\n * the API \"401 unauthorized\" error instead of a hung prompt.\n *\n * Mirrors `ensureDaytonaCredentials()` in shape so the registry's first-\n * run gate stays uniform across providers.\n */\nexport async function ensureHetznerCredentials(\n opts: EnsureHetznerCredentialsOptions = {},\n): Promise<void> {\n ensureHetznerEnvLoaded();\n\n if (!opts.force && hasUsableCredentials()) return;\n if (!process.stdin.isTTY) return;\n\n intro('Hetzner Cloud setup');\n note(\n `AgentBox needs a Hetzner Cloud API token (project-scoped) to provision VPSes.\\n\\n` +\n `1. Open ${DASHBOARD_KEYS_URL}\\n` +\n `2. Pick a project (or create one).\\n` +\n `3. Security → API Tokens → Generate API Token (Read + Write).`,\n 'API token required',\n );\n\n const open = exitOnCancel(\n await confirm({\n message: `Open ${DASHBOARD_KEYS_URL} in your browser?`,\n initialValue: true,\n }),\n );\n if (open) openDashboard();\n\n // One retry on auth failure (typos / expired token are the common case).\n for (let attempt = 0; attempt < 2; attempt++) {\n const creds = await promptForCredentials();\n\n const result = await validateCredentials(creds);\n if (result.ok) {\n persistCredentials(creds);\n log.success(`Hetzner credentials saved to ${secretsPath()}`);\n outro('Setup complete.');\n return;\n }\n if (result.kind === 'auth' && attempt === 0) {\n log.error(`That token was rejected by Hetzner: ${result.message}`);\n log.info('Try again, or press Ctrl-C to cancel.');\n continue;\n }\n if (result.kind === 'network') {\n log.warn(`Could not reach Hetzner to validate (${result.message}) — saving anyway.`);\n persistCredentials(creds);\n log.success(`Hetzner credentials saved to ${secretsPath()}`);\n outro('Setup complete (unvalidated).');\n return;\n }\n throw new Error(`Hetzner credentials rejected: ${result.message}`);\n }\n}\n\nfunction hasUsableCredentials(): boolean {\n return typeof process.env.HCLOUD_TOKEN === 'string' && process.env.HCLOUD_TOKEN.length > 0;\n}\n\ninterface Credentials {\n token: string;\n endpoint?: string;\n}\n\nasync function promptForCredentials(): Promise<Credentials> {\n const token = exitOnCancel(\n await password({\n message: 'Paste your Hetzner Cloud API token',\n validate(v) {\n if (!v || v.trim().length === 0) return 'Cannot be empty';\n return undefined;\n },\n }),\n );\n return { token: token.trim() };\n}\n\ntype ValidationResult =\n | { ok: true }\n | { ok: false; kind: 'auth'; message: string }\n | { ok: false; kind: 'network'; message: string };\n\nasync function validateCredentials(creds: Credentials): Promise<ValidationResult> {\n const s = spinner();\n s.start('Validating credentials with Hetzner');\n\n try {\n const client = makeHetznerClient({ token: creds.token, endpoint: creds.endpoint });\n // `listLocations()` is a cheap, deterministic call that exercises auth +\n // basic API reachability without provisioning anything.\n await client.listLocations();\n s.stop('Hetzner credentials accepted');\n return { ok: true };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n s.stop('Hetzner credentials check failed');\n if (/401|403|unauthor|forbidden|invalid|token/i.test(message)) {\n return { ok: false, kind: 'auth', message };\n }\n return { ok: false, kind: 'network', message };\n }\n}\n\nfunction persistCredentials(creds: Credentials): void {\n const record: Record<string, string> = { HCLOUD_TOKEN: creds.token };\n if (creds.endpoint) record.HCLOUD_ENDPOINT = creds.endpoint;\n writeManagedSecrets(MANAGED_KEYS, record);\n}\n\n/**\n * Non-interactive credential set (the headless path the hub drives). Validates\n * `{ token, endpoint? }` against the Hetzner API (a cheap `listLocations`), then\n * persists to `~/.agentbox/secrets.env`. A network failure still persists (so an\n * offline host isn't blocked) but reports `ok:true` with a warning label.\n */\nexport async function setHetznerCredentials(\n fields: Record<string, string>,\n): Promise<CredSetResult> {\n const token = (fields.token ?? '').trim();\n const endpoint = (fields.endpoint ?? '').trim() || undefined;\n if (!token) {\n return { ok: false, error: 'token is required', status: { configured: false } };\n }\n const creds: Credentials = { token, endpoint };\n const result = await validateCredentials(creds);\n if (!result.ok && result.kind === 'auth') {\n return { ok: false, error: `token rejected by Hetzner: ${result.message}`, status: { configured: false } };\n }\n persistCredentials(creds);\n const label = result.ok ? 'token' : 'token (unvalidated)';\n return { ok: true, status: { configured: true, label } };\n}\n\nfunction openDashboard(): void {\n try {\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 } 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 HetznerCredStatus {\n token?: string;\n endpoint?: string;\n source: 'env' | 'secrets.env' | 'none';\n}\n\nexport function readHetznerCredStatus(): HetznerCredStatus {\n const shellHadToken = !!process.env.HCLOUD_TOKEN;\n ensureHetznerEnvLoaded();\n const token = process.env.HCLOUD_TOKEN;\n const endpoint = process.env.HCLOUD_ENDPOINT;\n if (!token) return { source: 'none' };\n return {\n token,\n endpoint,\n source: shellHadToken ? 'env' : 'secrets.env',\n };\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/** Snapshot of the managed env keys (used by tests around `applyToEnv`). */\nexport function snapshotManagedEnv(): Record<ManagedKey, string | undefined> {\n const out = {} as Record<ManagedKey, string | undefined>;\n for (const k of MANAGED_KEYS) out[k] = process.env[k];\n return out;\n}\n\nexport function restoreManagedEnv(snap: Record<ManagedKey, string | undefined>): void {\n for (const k of MANAGED_KEYS) {\n if (snap[k] === undefined) delete process.env[k];\n else process.env[k] = snap[k];\n }\n}\n","/**\n * Host egress-IP detection for the Hetzner firewall lock-down. Probes three\n * independent providers in sequence; first 3s success wins. Fails loud\n * (throws) if all three fail — we do **not** silently fall back to\n * `0.0.0.0/0`, because that would defeat the safe-by-default firewall.\n *\n * The user can always override the auto-detect via\n * `--firewall-source <cidr>` (or `--firewall-source 0.0.0.0/0` for the\n * explicit dynamic-IP opt-in).\n */\n\nconst PROBES = [\n 'https://api.ipify.org',\n 'https://ifconfig.io/ip',\n 'https://icanhazip.com',\n] as const;\n\nconst TIMEOUT_MS = 3_000;\n\nconst IPV4_RE = /^(?:\\d{1,3}\\.){3}\\d{1,3}$/;\nconst IPV6_RE = /^[0-9a-fA-F:]+$/;\n\nexport interface DetectEgressIpOptions {\n /** Override the probe list (tests inject this). */\n probes?: readonly string[];\n /** Per-probe timeout in ms (default 3_000). */\n timeoutMs?: number;\n /** Override `fetch` (tests inject this). */\n fetchImpl?: typeof fetch;\n /** Best-effort logger for probe attempts. */\n onLog?: (line: string) => void;\n}\n\n/**\n * Detect the host's egress IP. Returns the bare IP string (no `/32`); the\n * caller composes the CIDR.\n *\n * Throws when no probe responded. The error message lists each probe that\n * was tried so the user can see whether their network is blocking a\n * specific provider.\n */\nexport async function detectEgressIp(opts: DetectEgressIpOptions = {}): Promise<string> {\n const probes = opts.probes ?? PROBES;\n const timeout = opts.timeoutMs ?? TIMEOUT_MS;\n const fetchImpl = opts.fetchImpl ?? fetch;\n const errors: string[] = [];\n\n for (const url of probes) {\n try {\n const ip = await raceTimeout(probe(url, fetchImpl), timeout);\n if (ip) {\n opts.onLog?.(`egress-ip: detected ${ip} via ${url}`);\n return ip;\n }\n errors.push(`${url}: empty/invalid response`);\n } catch (err) {\n errors.push(`${url}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n throw new Error(\n `could not auto-detect the host's egress IP — all ${String(probes.length)} probes failed:\\n` +\n errors.map((e) => ` - ${e}`).join('\\n') +\n `\\nOverride with --firewall-source <cidr> (e.g. --firewall-source 0.0.0.0/0 for the explicit-open opt-in).`,\n );\n}\n\nasync function probe(url: string, fetchImpl: typeof fetch): Promise<string | null> {\n const res = await fetchImpl(url, { method: 'GET' });\n if (!res.ok) return null;\n const body = (await res.text()).trim();\n if (IPV4_RE.test(body)) {\n // Cheap sanity: each octet in 0–255.\n const parts = body.split('.').map((p) => Number.parseInt(p, 10));\n if (parts.every((p) => p >= 0 && p <= 255)) return body;\n return null;\n }\n // We do not currently use IPv6 for firewall rules (Hetzner accepts them\n // but the rest of the provider talks IPv4), but accept the probe answer\n // so a v6-only network surfaces an actionable error rather than a silent\n // empty result. Composing the CIDR is the caller's job.\n if (IPV6_RE.test(body) && body.includes(':')) return body;\n return null;\n}\n\nasync function raceTimeout<T>(p: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`probe timed out after ${String(ms)}ms`)), ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * Bounded retry wrapper for Hetzner Cloud API calls — mirrors\n * `withDaytonaRetry` in shape and intent. Hetzner is generally well-behaved\n * but the public API does rate-limit (429) and occasionally returns 502/504\n * during regional incidents; without bounded retries those propagate as\n * wedges in the calling lifecycle code.\n *\n * Non-idempotent ops (`provision`, `createImage`) pass\n * `retryOnAmbiguous: false` so a 504 after the request reached the origin\n * doesn't create a duplicate billable resource.\n */\n\nimport { HetznerApiError } from './client.js';\n\nexport interface WithRetryOptions {\n /** Method name, used in retry log lines. */\n method: string;\n /** Per-attempt timeout (ms). Default 30_000. */\n attemptTimeoutMs?: number;\n /** Backoff before attempts 2, 3, … (ms). Default [1000, 2000, 4000]. */\n backoffMs?: readonly number[];\n /**\n * Whether to retry on errors where we can't be sure the server applied\n * the request — connection failures, per-attempt timeouts, and 5xx\n * responses. Set false for non-idempotent operations (e.g. `provision`,\n * `createImage`) where a retry could create a duplicate resource.\n */\n retryOnAmbiguous: boolean;\n /** Override the default `process.stderr` retry sink (used by tests). */\n onRetry?: (line: string) => void;\n}\n\nconst DEFAULT_BACKOFF: readonly number[] = [1000, 2000, 4000];\nconst DEFAULT_ATTEMPT_TIMEOUT_MS = 30_000;\n\nclass AttemptTimeoutError extends Error {\n constructor(method: string, ms: number) {\n super(`hetzner ${method}: per-attempt timeout after ${String(ms)}ms`);\n this.name = 'AttemptTimeoutError';\n }\n}\n\nexport function isAttemptTimeout(err: unknown): err is AttemptTimeoutError {\n return err instanceof AttemptTimeoutError;\n}\n\n/**\n * Classify an error as retriable or not. `allowAmbiguous` gates the cases\n * where the server may or may not have applied the request — the caller\n * decides based on idempotency.\n */\nexport function isRetriable(err: unknown, allowAmbiguous: boolean): boolean {\n if (err instanceof HetznerApiError) {\n // Rate limit: always back off — the server told us to.\n if (err.statusCode === 429 || err.code === 'rate_limit_exceeded') return true;\n // 5xx: ambiguous (the API may or may not have applied the change).\n if (err.statusCode >= 500 && err.statusCode <= 599) return allowAmbiguous;\n // Hetzner conflict / locked errors: the API tells us to wait — same as\n // rate-limit semantically. `conflict` is what `delete_server` returns\n // when another action (e.g. our own poweroff) is still in flight.\n if (err.code === 'locked' || err.code === 'conflict') return true;\n // Everything else is a permanent client error (auth, validation, not_found).\n return false;\n }\n\n if (err instanceof AttemptTimeoutError) return allowAmbiguous;\n\n // Raw fetch / undici errors. The Node fetch impl wraps low-level errors in\n // `{ cause }`; we check both shapes for portability.\n if (err && typeof err === 'object') {\n const candidates: unknown[] = [err, (err as { cause?: unknown }).cause];\n for (const c of candidates) {\n if (!c || typeof c !== 'object') continue;\n const code = (c as { code?: unknown }).code;\n if (\n code === 'ECONNRESET' ||\n code === 'ETIMEDOUT' ||\n code === 'ECONNABORTED' ||\n code === 'EAI_AGAIN' ||\n code === 'ECONNREFUSED' ||\n code === 'ENOTFOUND' ||\n code === 'UND_ERR_SOCKET' ||\n code === 'UND_ERR_CONNECT_TIMEOUT'\n ) {\n return allowAmbiguous;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Run `fn`, retrying on transient failures with capped exponential backoff.\n * Each attempt is bounded by `attemptTimeoutMs` via Promise.race; total\n * wall-clock = sum(backoffMs) + maxAttempts * attemptTimeoutMs.\n */\nexport async function withHetznerRetry<T>(\n opts: WithRetryOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const backoff = opts.backoffMs ?? DEFAULT_BACKOFF;\n const maxAttempts = backoff.length + 1;\n const timeoutMs = opts.attemptTimeoutMs ?? DEFAULT_ATTEMPT_TIMEOUT_MS;\n const log = opts.onRetry ?? defaultRetryLog;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await raceTimeout(fn(), timeoutMs, opts.method);\n } catch (err) {\n const last = attempt === maxAttempts;\n if (last || !isRetriable(err, opts.retryOnAmbiguous)) throw err;\n const delay = backoff[attempt - 1] ?? backoff[backoff.length - 1] ?? 4000;\n log(\n `hetzner ${opts.method}: attempt ${String(attempt)} failed (${errorSummary(err)}); retrying in ${String(delay)}ms`,\n );\n await sleep(delay);\n }\n }\n throw new Error(`withHetznerRetry: exhausted attempts for ${opts.method}`);\n}\n\nfunction defaultRetryLog(line: string): void {\n process.stderr.write(`\\n[hetzner-retry] ${line}\\n`);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function raceTimeout<T>(p: Promise<T>, ms: number, method: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n p,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new AttemptTimeoutError(method, ms)), ms);\n }),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n\nfunction errorSummary(err: unknown): string {\n if (err instanceof HetznerApiError) {\n return `HetznerApiError ${String(err.statusCode)} ${err.code}: ${truncate(err.message)}`;\n }\n if (err instanceof Error) {\n const code = (err as { code?: unknown }).code;\n return code !== undefined\n ? `${err.name}(${String(code)}): ${truncate(err.message)}`\n : `${err.name}: ${truncate(err.message)}`;\n }\n return truncate(String(err));\n}\n\nfunction truncate(s: string, max = 160): string {\n return s.length > max ? `${s.slice(0, max)}…` : s;\n}\n","/**\n * Hetzner Cloud Firewall provisioning + drift sync.\n *\n * Defense-in-depth model (recapped from\n * ~/.claude/plans/how-to-safely-create-parallel-pebble.md §\"The safety model\"):\n *\n * 1. In-VPS services bind to loopback (the load-bearing layer).\n * 2. Hetzner Cloud Firewall locks SSH to the host's egress IP — applied\n * here at provision time, before the VPS first boots. Everything else\n * is denied inbound; outbound is unrestricted.\n * 3. sshd hardening (PasswordAuthentication no, AllowUsers vscode, …)\n * written by cloud-init at first boot.\n *\n * Layer 2 is what this module provisions. The firewall is per-box (1:1 with\n * the VPS) so an egress-IP-drift on one box doesn't affect siblings, and a\n * destroy cleanly removes everything we created.\n */\n\nimport { HetznerApiError, type HetznerClient, type HetznerFirewall, type HetznerFirewallRule } from './client.js';\nimport { withHetznerRetry } from './retry.js';\n\n/**\n * Build the SSH-only inbound rule for one or more source CIDRs. Hetzner's\n * `source_ips` is a list, so all allowed CIDRs ride a single tcp/22 rule (host\n * egress for `locked`, `0.0.0.0/0`+`::/0` for `open`, host egress + the\n * whitelist for `whitelist`). Outbound is left unrestricted (empty rules array\n * = \"no inbound besides this one\"). Accepts a bare string for back-compat.\n */\nexport function sshOnlyInboundRule(sources: string | string[]): HetznerFirewallRule[] {\n const source_ips = Array.isArray(sources) ? sources : [sources];\n return [\n {\n direction: 'in',\n protocol: 'tcp',\n port: '22',\n source_ips,\n description: 'agentbox: SSH inbound',\n },\n ];\n}\n\n/**\n * Inbound rules for a control-plane VPS: SSH locked to the host's egress IP,\n * but HTTP(S) open to the world (cloud boxes from arbitrary IPs reach the plane,\n * and Caddy needs :80/:443 for the Let's Encrypt ACME challenge + serving). The\n * Next app's own port is never exposed — Caddy fronts it on the compose network.\n */\nexport function controlPlaneInboundRules(hostCidr: string): HetznerFirewallRule[] {\n return [\n {\n direction: 'in',\n protocol: 'tcp',\n port: '22',\n source_ips: [hostCidr],\n description: 'agentbox control plane: SSH from host egress IP only',\n },\n {\n direction: 'in',\n protocol: 'tcp',\n port: '80',\n source_ips: ['0.0.0.0/0', '::/0'],\n description: 'agentbox control plane: HTTP (ACME challenge + redirect)',\n },\n {\n direction: 'in',\n protocol: 'tcp',\n port: '443',\n source_ips: ['0.0.0.0/0', '::/0'],\n description: 'agentbox control plane: HTTPS',\n },\n ];\n}\n\nexport interface CreateFirewallOptions {\n /** Human-readable name persisted with the firewall (visible in the Hetzner dashboard). */\n name: string;\n /** Inbound source CIDRs (already normalized/resolved by the caller). */\n sources: string[];\n /** Labels merged onto the firewall (we always add `agentbox.managed=true`). */\n labels?: Record<string, string>;\n}\n\n/**\n * Provision a fresh per-box firewall locked to the given source CIDR.\n * Returns the created `HetznerFirewall` so the caller can persist\n * `firewallId` on the box record.\n */\nexport async function createPerBoxFirewall(\n client: HetznerClient,\n opts: CreateFirewallOptions,\n): Promise<HetznerFirewall> {\n return withHetznerRetry(\n { method: 'createFirewall', retryOnAmbiguous: false, attemptTimeoutMs: 60_000 },\n () =>\n client.createFirewall({\n name: opts.name,\n rules: sshOnlyInboundRule(opts.sources),\n labels: {\n 'agentbox.managed': 'true',\n 'agentbox.role': 'box',\n ...opts.labels,\n },\n }),\n );\n}\n\n/**\n * Re-detect the egress IP and replace the firewall's rule set with the new\n * source. Used by `agentbox hetzner firewall sync <box>` after the host\n * laptop moves networks. Cheap operation — no VPS restart involved.\n *\n * Idempotent on the API: setting the same rules again is a no-op from the\n * user's point of view (the API still returns an action handle, but it\n * resolves instantly).\n */\nexport async function syncFirewallSource(\n client: HetznerClient,\n firewallId: number,\n sources: string | string[],\n): Promise<void> {\n await withHetznerRetry(\n { method: 'setFirewallRules', retryOnAmbiguous: true, attemptTimeoutMs: 60_000 },\n () => client.setFirewallRules(firewallId, sshOnlyInboundRule(sources)),\n );\n}\n\n/**\n * Delete a per-box firewall. Idempotent on 404 (the API surfaces it as a\n * `not_found` error which the retry classifier won't retry; we swallow it\n * here so destroy paths don't need a special-case).\n *\n * Hetzner returns 409 `conflict` if the firewall is still attached to a\n * server when we try to delete it — `deleteServer()` returns as soon as the\n * delete action is *enqueued*, not after the server's firewall attachment\n * is torn down, so a quick subsequent `deleteFirewall()` will collide.\n * We poll for a short window (default 60s, intervals doubled to 8s) to\n * cover the typical 5–15s detach lag before giving up.\n */\nexport async function deletePerBoxFirewall(\n client: HetznerClient,\n firewallId: number,\n opts: { detachWaitMs?: number } = {},\n): Promise<void> {\n const deadline = Date.now() + (opts.detachWaitMs ?? 60_000);\n let interval = 1_000;\n while (true) {\n try {\n await withHetznerRetry(\n { method: 'deleteFirewall', retryOnAmbiguous: true, attemptTimeoutMs: 30_000 },\n () => client.deleteFirewall(firewallId),\n );\n return;\n } catch (err) {\n if (err instanceof HetznerApiError && (err.statusCode === 404 || err.code === 'not_found')) {\n return;\n }\n const stillAttached =\n err instanceof HetznerApiError &&\n (err.statusCode === 409 ||\n err.code === 'conflict' ||\n err.code === 'resource_in_use');\n if (stillAttached && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, interval));\n interval = Math.min(interval * 2, 8_000);\n continue;\n }\n throw err;\n }\n }\n}\n\n/**\n * Whether the firewall's allowed SSH sources need re-syncing to include the\n * current egress: true when the current egress isn't already allowed AND the\n * firewall isn't wide-open (`0.0.0.0/0`, the `open` policy / dynamic-IP opt-in).\n * Pure so the hint + auto-sync decision is unit-testable without the Hetzner\n * API. Empty sources (no SSH rule) counts as a mismatch worth syncing. Accepts\n * a bare string for back-compat callers.\n */\nexport function firewallNeedsSync(\n allowedSources: string | string[] | undefined,\n currentEgress: string,\n): boolean {\n const list = Array.isArray(allowedSources)\n ? allowedSources\n : allowedSources\n ? [allowedSources]\n : [];\n if (list.includes('0.0.0.0/0')) return false;\n return !list.includes(currentEgress);\n}\n\n/**\n * Normalize a source spec into a CIDR. Accepts:\n * - bare IPv4 → appends `/32`\n * - bare IPv6 → appends `/128`\n * - already-CIDR (anything with `/`) → returned as-is\n *\n * Whitespace is trimmed. Does **not** validate the address itself — that's\n * either the API's job (it'll reject bad CIDRs with a clear `validation`\n * error) or `detectEgressIp`'s job (it only returns valid IPv4/IPv6).\n */\nexport function normalizeSourceCidr(raw: string): string {\n const trimmed = raw.trim();\n if (trimmed.includes('/')) return trimmed;\n if (trimmed.includes(':')) return `${trimmed}/128`;\n return `${trimmed}/32`;\n}\n","/**\n * Resolver for the on-disk files we need to ship into a fresh VPS during\n * `prepareHetzner()` — same shape as the docker provider's runtime/docker\n * staging, but lighter (no Dockerfile build, just a flat tarball of files\n * to scp into /tmp).\n *\n * Lookup order for each file:\n * 1. The CLI's staged runtime tree: `<cliRoot>/runtime/hetzner/...`\n * (populated by `apps/cli/scripts/stage-runtime.mjs`).\n * 2. The monorepo source tree (dev fallback): the file's canonical\n * package-relative path under `packages/`.\n *\n * Failure mode: any missing file throws a clear error naming the lookup\n * paths so a partial dev rebuild is obvious to debug.\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\n/**\n * Locate the staged `runtime/hetzner/` tree. Two candidates:\n *\n * 1. Bundled CLI: the hetzner module is inlined into apps/cli's dist/, so\n * `dirname(import.meta.url)` is `<cliRoot>/dist`; the staged runtime\n * sits at `<cliRoot>/runtime/hetzner`.\n * 2. Workspace dev: this module's dist is at\n * `packages/sandbox-hetzner/dist/`. There's no staged runtime there;\n * callers fall through to the monorepo source paths in\n * `candidatesFor()`. Returns undefined in that case.\n *\n * The CLI doesn't have to pass `cliRuntimeRoot` explicitly — this helper\n * picks it up by inspecting where the module was loaded from.\n */\nexport function findStagedCliRuntimeRoot(): string | undefined {\n const candidates = [\n resolve(SELF, '..', 'runtime'), // <cliRoot>/dist/.. → <cliRoot> then /runtime\n resolve(SELF, '..', '..', 'runtime'), // chunk-NNNN.js at <cliRoot>/dist/<sub>/.. → <cliRoot>/runtime\n ];\n for (const c of candidates) {\n if (existsSync(resolve(c, 'hetzner', 'scripts', 'install-box.sh'))) return c;\n }\n return undefined;\n}\n\n/**\n * Each runtime asset has a stable, well-known destination basename in\n * `/tmp` on the prepare VPS and is resolved from one of N candidate\n * source paths on the host.\n */\nexport interface RuntimeAsset {\n /** Logical name (used in error messages + log lines). */\n name: string;\n /** Basename on the prepare VPS (under /tmp/). */\n remoteBasename: string;\n /** Optional file mode at scp-time. */\n remoteMode?: number;\n}\n\nexport const RUNTIME_ASSETS: readonly RuntimeAsset[] = [\n { name: 'install-box.sh', remoteBasename: 'agentbox-install.sh', remoteMode: 0o755 },\n { name: 'agentbox-ctl', remoteBasename: 'agentbox-ctl', remoteMode: 0o755 },\n { name: 'agentbox-vnc-start', remoteBasename: 'agentbox-vnc-start', remoteMode: 0o755 },\n { name: 'agentbox-dockerd-start', remoteBasename: 'agentbox-dockerd-start', remoteMode: 0o755 },\n { name: 'agentbox-portless-trust', remoteBasename: 'agentbox-portless-trust', remoteMode: 0o755 },\n { name: 'agentbox-checkpoint-cleanup', remoteBasename: 'agentbox-checkpoint-cleanup', remoteMode: 0o755 },\n { name: 'agentbox-open', remoteBasename: 'agentbox-open', remoteMode: 0o755 },\n { name: 'gh-shim', remoteBasename: 'agentbox-gh-shim', remoteMode: 0o755 },\n { name: 'git-shim', remoteBasename: 'agentbox-git-shim', remoteMode: 0o755 },\n { name: 'ntn-shim', remoteBasename: 'agentbox-ntn-shim', remoteMode: 0o755 },\n { name: 'linear-shim', remoteBasename: 'agentbox-linear-shim', remoteMode: 0o755 },\n { name: 'custom-system-CLAUDE.md', remoteBasename: 'agentbox-custom-CLAUDE.md', remoteMode: 0o644 },\n { name: 'claude-managed-settings.json', remoteBasename: 'agentbox-managed-settings.json', remoteMode: 0o644 },\n { name: 'agentbox-codex-hooks.json', remoteBasename: 'agentbox-codex-hooks.json', remoteMode: 0o644 },\n { name: 'agentbox-setup-skill.md', remoteBasename: 'agentbox-setup-skill.md', remoteMode: 0o644 },\n] as const;\n\nexport interface ResolvedAsset extends RuntimeAsset {\n localPath: string;\n}\n\n/**\n * Build the candidate search paths for a given asset. Tries CLI runtime\n * first, then the monorepo source tree. The first one that exists wins.\n *\n * `cliRuntimeRoot` is provided by the caller because we don't know how the\n * embedding CLI lays out its dist (the @madarco/agentbox CLI puts dist + a\n * sibling runtime/ next to it; tests pass a tmp dir). Use the helper\n * `findCliRuntimeRoot()` below from the calling context that has the right\n * anchor (typically `import.meta.url` of an apps/cli module).\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 // Map logical → relative paths (relative to either anchor).\n const monorepoRelative: Record<string, string[]> = {\n 'install-box.sh': ['packages/sandbox-hetzner/scripts/install-box.sh'],\n 'agentbox-ctl': ['packages/ctl/dist/bin.cjs'],\n 'agentbox-vnc-start': ['packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-dockerd-start': ['packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-portless-trust': ['packages/sandbox-docker/scripts/agentbox-portless-trust'],\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-hetzner/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 // CLI-runtime-tree relative paths (mirrors the staging layout).\n const cliRelative: Record<string, string[]> = {\n 'install-box.sh': ['hetzner/scripts/install-box.sh'],\n 'agentbox-ctl': ['hetzner/ctl.cjs'],\n 'agentbox-vnc-start': ['hetzner/agentbox-vnc-start', 'docker/packages/sandbox-docker/scripts/agentbox-vnc-start'],\n 'agentbox-dockerd-start': ['hetzner/agentbox-dockerd-start', 'docker/packages/sandbox-docker/scripts/agentbox-dockerd-start'],\n 'agentbox-portless-trust': ['hetzner/agentbox-portless-trust', 'docker/packages/sandbox-docker/scripts/agentbox-portless-trust'],\n 'agentbox-checkpoint-cleanup': ['hetzner/agentbox-checkpoint-cleanup', 'docker/packages/sandbox-docker/scripts/agentbox-checkpoint-cleanup'],\n 'agentbox-open': ['hetzner/agentbox-open', 'docker/packages/sandbox-docker/scripts/agentbox-open'],\n 'gh-shim': ['hetzner/gh-shim', 'docker/packages/sandbox-docker/scripts/gh-shim'],\n 'git-shim': ['hetzner/git-shim', 'docker/packages/sandbox-docker/scripts/git-shim'],\n 'ntn-shim': ['hetzner/ntn-shim', 'docker/packages/sandbox-docker/scripts/ntn-shim'],\n 'linear-shim': ['hetzner/linear-shim', 'docker/packages/sandbox-docker/scripts/linear-shim'],\n 'custom-system-CLAUDE.md': ['hetzner/custom-system-CLAUDE.md'],\n 'claude-managed-settings.json': ['hetzner/claude-managed-settings.json', 'docker/packages/sandbox-docker/scripts/claude-managed-settings.json'],\n 'agentbox-codex-hooks.json': ['hetzner/agentbox-codex-hooks.json', 'docker/packages/sandbox-docker/scripts/agentbox-codex-hooks.json'],\n 'agentbox-setup-skill.md': ['hetzner/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\n/**\n * Resolve every runtime asset to its absolute on-host path. Throws an\n * actionable error if any asset can't be found (lists every path tried).\n */\nexport function resolveRuntimeAssets(opts: {\n cliRuntimeRoot?: string;\n 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 `hetzner: could not resolve runtime assets — these files are needed to install on the prepare VPS:\\n` +\n lines.join('\\n') +\n `\\n\\nIf you are running from the monorepo, ensure \\`pnpm -w build\\` has run so packages/ctl/dist/bin.cjs exists. ` +\n `If you are running from a published CLI bundle, the runtime/hetzner tree should be staged automatically.`,\n );\n }\n return out;\n}\n\n/** Best-effort: walk up from this file looking for `pnpm-workspace.yaml`. */\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; // fall through to itself; resolution will fail with a clear error\n}\n","/**\n * Persisted record of what `agentbox prepare --provider hetzner` has built.\n * Lives at `~/.agentbox/hetzner-prepared.json` so the auto-prepare gate\n * (`ensureHetznerBaseSnapshot()`) and runtime image resolution can see it.\n *\n * Only the shared `base` snapshot is recorded here — built once per Hetzner\n * project / API token: Ubuntu + deps + agentbox-ctl + agents + agent-browser,\n * baked from `install-box.sh`.\n *\n * The per-project snapshot tier is NOT a separate registry: it's the existing\n * `agentbox checkpoint create --set-default` + `box.defaultCheckpointHetzner`\n * flow (see `docs/cloud-create-flow.md` §\"base vs project snapshot\"), and\n * auto-capture at the end of setup is driven by the `/agentbox-setup` skill\n * (`agentbox-ctl checkpoint --set-default`), cross-provider. So there's no\n * `projects[<hash>]` map here.\n *\n * Schema versioned so future shape changes can migrate.\n */\n\nimport { claudeInstallFingerprint, computeContextSha256, preparedStatePathFor, readPreparedStateRaw, writePreparedStateRaw } from '@agentbox/sandbox-core';\nimport { findStagedCliRuntimeRoot, resolveRuntimeAssets } from './runtime-assets.js';\n\n/**\n * Schema history:\n * 1 — `base.imageId`, `base.description`, `base.createdAt`,\n * `base.installScriptSha256?`\n * 2 — `base.installScriptSha256` → `base.contextSha256` (now covers every\n * asset we scp'd in, not just the install script); `base.cliVersion`\n * and `base.cliCommit?` added so we can warn when an old snapshot\n * predates the running CLI.\n *\n * Read-time migration is lossy in one direction: a schema-1 file is lifted\n * to schema 2 by *renaming* `installScriptSha256` to `contextSha256`. The\n * hash doesn't change but the meaning narrows (install script only → full\n * asset list), so the next `agentbox prepare --provider hetzner` run will\n * recompute and overwrite. A legacy `projects` key (an early, never-wired\n * per-project tier) is simply ignored — removing the field doesn't break\n * reads, so no schema bump is needed.\n */\nconst SCHEMA = 2 as const;\n\nexport interface PreparedBaseSnapshot {\n /** Hetzner image id (numeric — opaque, but stable across `getImage` calls). */\n imageId: number;\n /** User-facing description (matches the firewall-dashboard rows). */\n description: string;\n /** ISO timestamp of bake-completion. */\n createdAt: string;\n /**\n * Deterministic SHA-256 of the build context (every file scp'd into the\n * prepare VPS). Rebuild when it changes.\n */\n contextSha256?: string;\n /** CLI version that produced this snapshot (informational). */\n cliVersion?: string;\n /** Git short SHA of the CLI build (informational). */\n cliCommit?: string;\n}\n\nexport interface PreparedHetznerState {\n schema: typeof SCHEMA;\n /** The shared base snapshot. Absent until first `agentbox prepare`. */\n base?: PreparedBaseSnapshot;\n}\n\ninterface LegacyV1Base {\n imageId: number;\n description: string;\n createdAt: string;\n installScriptSha256?: string;\n}\n\ninterface LegacyV1State {\n schema: 1;\n base?: LegacyV1Base;\n}\n\nexport function preparedStatePath(): string {\n return preparedStatePathFor('hetzner');\n}\n\nexport function readPreparedState(): PreparedHetznerState {\n const raw = readPreparedStateRaw('hetzner');\n if (raw === null || typeof raw !== 'object') return { schema: SCHEMA };\n const parsed = raw as Partial<PreparedHetznerState> | LegacyV1State;\n if ((parsed as { schema?: unknown }).schema === 1) {\n const v1 = parsed as LegacyV1State;\n return migrateFromV1(v1);\n }\n if (parsed.schema !== SCHEMA) {\n // Unknown schema: don't crash, just refuse to read — the file will be\n // overwritten on the next successful prepare.\n return { schema: SCHEMA };\n }\n return {\n schema: SCHEMA,\n base: parsed.base,\n };\n}\n\nfunction migrateFromV1(v1: LegacyV1State): PreparedHetznerState {\n // The v1 `installScriptSha256` covered only `install-box.sh`, not the full\n // asset list a v2 `contextSha256` represents. Lifting it forward as a\n // placeholder fingerprint means the next prepare run will mismatch and\n // rebuild — exactly what we want, since the broader hash semantics also\n // changed.\n const base: PreparedBaseSnapshot | undefined = v1.base\n ? {\n imageId: v1.base.imageId,\n description: v1.base.description,\n createdAt: v1.base.createdAt,\n contextSha256: v1.base.installScriptSha256,\n }\n : undefined;\n return {\n schema: SCHEMA,\n base,\n };\n}\n\nexport function writePreparedState(state: PreparedHetznerState): void {\n writePreparedStateRaw('hetzner', state);\n}\n\n/**\n * Convenience helper: update one field of the state without forcing callers\n * to read/merge/write themselves.\n */\nexport function updatePreparedState(mutate: (s: PreparedHetznerState) => void): void {\n const s = readPreparedState();\n mutate(s);\n writePreparedState(s);\n}\n\n/**\n * Compute the CURRENT build-context fingerprint for the hetzner base snapshot\n * (the SHA over every file `prepare` would scp into the prepare VPS).\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\".\n *\n * Used by `evaluateBaseFreshness` to compare against the stored value in\n * `hetzner-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 currentHetznerBaseFingerprintLive(\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 * The Hetzner Cloud VPS sandbox provider. A thin `CloudBackend` over OpenSSH\n * + the Hetzner Cloud REST API, 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 * **Phase 2 status:** the SDK shim (auth + REST client + retry + firewall\n * + egress IP) is wired; `hetznerBackend` is a stub whose per-method bodies\n * throw `notImplemented` until Phase 4 plumbs in SSH ControlMaster +\n * provisioning. The provider is registered so `--provider hetzner` resolves\n * cleanly and the build is honest about what's missing.\n */\n\nimport type { Provider } from '@agentbox/core';\nimport type { ProviderModule } from '@agentbox/sandbox-core';\nimport { createCloudProvider } from '@agentbox/sandbox-cloud';\nimport { hetznerBackend, HETZNER_DEFAULT_BOX_IMAGE_REF } from './backend.js';\nimport { prepareHetznerProvider } from './prepare.js';\nimport { currentHetznerBaseFingerprintLive } from './prepared-state.js';\nimport { ensureHetznerCredentials, setHetznerCredentials } from './credentials.js';\nimport { doctorChecks, readCredStatusSummary } from './provider-module.js';\n\nconst cloudProvider = createCloudProvider(hetznerBackend, {\n defaultResources: { cpu: 2, memory: 4, disk: 40 },\n});\n\nexport const hetznerProvider: Provider = {\n ...cloudProvider,\n prepare: prepareHetznerProvider,\n baseFingerprint: () => currentHetznerBaseFingerprintLive(),\n};\n\n/** Uniform surface the CLI provider loader resolves this package through. */\nexport const providerModule: ProviderModule = {\n provider: hetznerProvider,\n backend: hetznerBackend,\n ensureCredentials: ensureHetznerCredentials,\n readCredStatus: readCredStatusSummary,\n setCredentials: setHetznerCredentials,\n currentBaseFingerprintLive: (claudeInstall) => currentHetznerBaseFingerprintLive(claudeInstall),\n doctorChecks,\n};\n\nexport { hetznerBackend, HETZNER_DEFAULT_BOX_IMAGE_REF };\nexport { ensureHetznerEnvLoaded } from './env-loader.js';\nexport {\n ensureHetznerCredentials,\n setHetznerCredentials,\n readHetznerCredStatus,\n secretsPath,\n maskKey,\n type EnsureHetznerCredentialsOptions,\n type HetznerCredStatus,\n} from './credentials.js';\nexport {\n ensureHetznerBaseSnapshot,\n prepareHetzner,\n prepareHetznerProvider,\n type PrepareHetznerOptions,\n type PrepareHetznerResult,\n} from './prepare.js';\nexport { generateBoxCloudInit, generatePrepareCloudInit, controlPlaneCloudInit, type BoxCloudInitOptions, type PrepareCloudInitOptions, type ControlPlaneCloudInitOptions } from './cloud-init.js';\nexport {\n deployControlPlaneToHetzner,\n type ControlPlaneHetznerDeployOptions,\n type ControlPlaneHetznerDeployResult,\n} from './control-plane-deploy.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 currentHetznerBaseFingerprintLive,\n preparedStatePath,\n readPreparedState,\n writePreparedState,\n updatePreparedState,\n type PreparedBaseSnapshot,\n type PreparedHetznerState,\n} from './prepared-state.js';\nexport {\n makeHetznerClient,\n HetznerApiError,\n DEFAULT_HCLOUD_ENDPOINT,\n type CreateFirewallRequest,\n type CreateServerRequest,\n type HetznerAction,\n type HetznerClient,\n type HetznerFirewall,\n type HetznerFirewallRule,\n type HetznerImage,\n type HetznerServer,\n type HetznerServerStatus,\n type HetznerServerType,\n type HetznerSshKey,\n} from './client.js';\nexport {\n validateServerChoice,\n mapHetznerProvisionError,\n type ServerChoice,\n} from './preflight.js';\nexport { detectEgressIp, type DetectEgressIpOptions } from './egress-ip.js';\nexport {\n createPerBoxFirewall,\n deletePerBoxFirewall,\n normalizeSourceCidr,\n sshOnlyInboundRule,\n syncFirewallSource,\n type CreateFirewallOptions,\n} from './firewall.js';\nexport { withHetznerRetry, isAttemptTimeout, isRetriable } from './retry.js';\n","/**\n * Hetzner `CloudBackend` — maps the provider-neutral cloud primitives onto\n * OpenSSH + the Hetzner Cloud REST API.\n *\n * Design rationale + the safety/tunneling model live in the plan at\n * `~/.claude/plans/how-to-safely-create-parallel-pebble.md` and the live\n * status doc at `docs/hertzner_backlog.md`. The short version:\n *\n * - 1:1 VPS-per-box. Each box gets a per-box ed25519 keypair (private key\n * never leaves the host) and a per-box Hetzner Cloud Firewall locked to\n * the host's egress IP.\n * - All comms (exec, file I/O, port forwards for bridge / web / VNC) flow\n * over one persistent `ssh` ControlMaster owned by `SshTunnelManager`.\n * - `previewUrl(port)` mints an `ssh -L 127.0.0.1:<localPort>:127.0.0.1:<remote>`\n * on demand. The cloud-provider scaffolding (`createCloudProvider`) then\n * decorates those URLs with Portless aliases for symmetric\n * `<box-name>.localhost` semantics — handled provider-side rather than\n * here so the backend stays focused on plumbing.\n * - Checkpoints map to Hetzner `create_image` snapshots; default no-pause,\n * opt-in pause via `createSnapshot({pause: true})`.\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 HetznerApiError,\n makeHetznerClient,\n type HetznerClient,\n type HetznerImage,\n type HetznerServer,\n type HetznerServerStatus,\n} from './client.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport {\n createPerBoxFirewall,\n deletePerBoxFirewall,\n firewallNeedsSync,\n normalizeSourceCidr,\n syncFirewallSource,\n} from './firewall.js';\nimport { pollUntil } from './poll.js';\nimport { mapHetznerProvisionError, validateServerChoice } from './preflight.js';\nimport { readPreparedState } from './prepared-state.js';\nimport { ensureHetznerBaseSnapshot } 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 { withHetznerRetry } from './retry.js';\n\nexport const HETZNER_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 Hetzner — we recognize it (alongside our own\n * sentinel + plain undefined) as \"use the hetzner base snapshot.\"\n */\nconst SCAFFOLDING_FALLBACK_IMAGE = 'agentbox/box:dev';\nconst VPS_USER = 'vscode';\nconst PROVISION_SSH_DEADLINE_MS = 10 * 60_000;\nconst ACTION_DEADLINE_MS = 5 * 60_000;\nconst SNAPSHOT_DEADLINE_MS = 20 * 60_000;\n// `cx22` was deprecated by Hetzner in early 2026; `cx23` is the drop-in\n// replacement with the same 2 vCPU / 4 GB / 40 GB shape on x86.\nconst HETZNER_DEFAULT_SERVER_TYPE = 'cx23';\nconst HETZNER_DEFAULT_LOCATION = 'nbg1';\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`; the bridge token stays in the daemon's process env.\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 Hetzner's per-server status onto the four-value `CloudState` everyone\n * else consumes. Transitional ones ('starting', 'rebuilding', …) are reported\n * as 'running' so callers don't ping-pong; 'off' maps to 'paused' because\n * Hetzner's stop = power off (vs Daytona's archive).\n */\nfunction mapState(s: HetznerServerStatus | string | undefined): CloudState {\n switch (s) {\n case 'running':\n return 'running';\n case 'starting':\n case 'initializing':\n case 'stopping':\n case 'migrating':\n case 'rebuilding':\n return 'running';\n case 'off':\n return 'paused';\n case 'deleting':\n case 'unknown':\n default:\n return 'missing';\n }\n}\n\nfunction client(): HetznerClient {\n return makeHetznerClient();\n}\n\nasync function getServerStrict(id: number): Promise<HetznerServer> {\n const s = await client().getServer(id);\n if (!s) {\n throw new Error(`hetzner: server ${String(id)} not found (already destroyed?)`);\n }\n return s;\n}\n\n/** Lookup an image by description (\"snapshot name\" in user-facing terms). */\nasync function findImageByDescription(c: HetznerClient, description: string): Promise<HetznerImage | null> {\n const all = await c.listImages({ type: 'snapshot' });\n return all.find((i) => i.description === description) ?? null;\n}\n\n/**\n * Resolve a `CloudProvisionRequest.image|snapshot` into a Hetzner image id.\n * Precedence: `req.snapshot` → `req.image`:\n * - the sentinel `agentbox-base` → load id from `hetzner-prepared.json`.\n * - a numeric string → use as-is.\n * - any other string → treated as a snapshot description (checkpoint name)\n * and looked up via the API.\n */\nasync function resolveImageId(c: HetznerClient, req: CloudProvisionRequest): Promise<number | string> {\n const ref = req.snapshot ?? req.image;\n if (!ref || ref === HETZNER_DEFAULT_BOX_IMAGE_REF || ref === SCAFFOLDING_FALLBACK_IMAGE) {\n await ensureHetznerBaseSnapshot();\n const state = readPreparedState();\n if (!state.base) {\n throw new Error(\n 'no Hetzner base snapshot found — run `agentbox prepare --provider hetzner` 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-description first (checkpoints use that), then fall through\n // to Hetzner stock images (the user passed e.g. `ubuntu-24.04`).\n const snap = await findImageByDescription(c, ref);\n if (snap) return snap.id;\n return ref;\n}\n\n/**\n * Capture per-box state we need across method calls. Lives on disk under\n * `~/.agentbox/hetzner/boxes/<sandboxId>/` and is the source of truth for\n * the SSH identity + firewall id + cached IP.\n */\ninterface PerBoxState {\n dir: string;\n identity: string;\n knownHosts: string;\n firewallId?: number;\n firewallSource?: string;\n vpsIp?: 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\n/**\n * The per-box firewall's current SSH source vs the host's live egress IP. Best-\n * effort and called ONLY on a connection-failure path (the open-failed hint and\n * `recover`'s auto-sync), never on the happy path — `egressIpCached` keeps the\n * probe from storming across retries. Returns null when there's no firewall or\n * we can't determine the state.\n */\ninterface FirewallEgressStatus {\n firewallId: number;\n /** All CIDRs the firewall currently allows for inbound SSH (`source_ips`). */\n allowedSources: string[];\n /** The host's current egress IP as a `/32` CIDR. */\n currentEgress: string;\n /** Friendly box ref for the `firewall sync` hint (the `agentbox.box` label). */\n boxRef: string;\n}\n\nasync function firewallEgressStatus(sandboxId: string): Promise<FirewallEgressStatus | null> {\n const id = Number.parseInt(sandboxId, 10);\n if (!Number.isFinite(id)) return null;\n const server = await client().getServer(id);\n if (!server) return null;\n const firewallId = Number.parseInt(server.labels['agentbox.firewall'] ?? '', 10);\n if (!Number.isFinite(firewallId)) return null;\n const firewall = await client().getFirewall(firewallId);\n const sshRule = firewall?.rules.find((r) => r.direction === 'in' && r.port === '22');\n const allowedSources = sshRule?.source_ips ?? [];\n // A FRESH probe (not cached): this runs only on a connection-failure path, and\n // a stale value could read the new IP as \"unchanged\" and skip the heal — the\n // very mismatch we exist to catch. The poller already de-dupes its recover\n // calls and `recover --all` is sequential, so fresh probing here won't storm.\n const currentEgress = `${await detectEgressIp({})}/32`;\n return {\n firewallId,\n allowedSources,\n currentEgress,\n boxRef: server.labels['agentbox.box'] ?? sandboxId,\n };\n}\n\nasync function ensureTunnel(sandboxId: string, state: PerBoxState, vpsIp: string): Promise<void> {\n if (tunnels.has(sandboxId)) return;\n try {\n await tunnels.open({\n boxId: sandboxId,\n vpsHost: vpsIp,\n identity: state.identity,\n });\n } catch (err) {\n // A host egress-IP change locks us out of the per-box firewall, surfacing as\n // an opaque SSH connect timeout. Best-effort: detect the mismatch and enrich\n // the error with the fix. Never let the diagnostic mask the original error\n // on a match (box is just down) or a probe failure.\n const s = await firewallEgressStatus(sandboxId).catch(() => null);\n if (s && firewallNeedsSync(s.allowedSources, s.currentEgress)) {\n throw new Error(\n `${(err as Error).message}\\n\\n` +\n `hetzner: SSH is blocked by the box firewall — it allows ${s.allowedSources.join(', ') || '(no rule)'} ` +\n `but your egress IP is now ${s.currentEgress}. Your IP changed; run:\\n` +\n ` agentbox hetzner firewall sync ${s.boxRef}\\n` +\n `(or \\`agentbox recover ${s.boxRef}\\`, which auto-syncs).`,\n );\n }\n throw err;\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(`hetzner: invalid sandboxId ${sandboxId}`);\n }\n const server = await getServerStrict(id);\n const vpsIp = server.public_net.ipv4?.ip;\n if (!vpsIp) {\n throw new Error(`hetzner: server ${String(id)} has no IPv4 address`);\n }\n const state = await ensurePerBoxState(sandboxId);\n if (!existsSync(state.identity)) {\n throw new Error(\n `hetzner: 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 hetznerBackend: CloudBackend = {\n name: 'hetzner',\n\n async provision(req: CloudProvisionRequest): Promise<CloudHandle> {\n const c = client();\n const onLog = req.onLog ?? (() => {});\n const progress = (s: string) => onLog(`hetzner: ${s}`);\n\n // 1. Gate on the base snapshot existing (lifts the Phase-2 placeholder).\n await ensureHetznerBaseSnapshot();\n const imageRef = await resolveImageId(c, req);\n\n // 1b. Preflight the server-type + location choice against the live catalog\n // BEFORE creating any billable resources (firewall, SSH key, server). A bad\n // `--size cax31` / `--size cx99` / `--location atlantis` fails fast here with\n // a clear message instead of a late, opaque API error after cleanup churn.\n const serverType = (req.size && req.size.trim()) || HETZNER_DEFAULT_SERVER_TYPE;\n const location = (req.location && req.location.trim()) || HETZNER_DEFAULT_LOCATION;\n const choice = { serverType, location };\n // The base image's disk_size gates the min server disk. We only have it for\n // numeric snapshot refs; stock string refs (e.g. `ubuntu-24.04`) skip the\n // disk check (image null).\n const image = typeof imageRef === 'number' ? await c.getImage(imageRef) : null;\n const catalog = await c.listServerTypes();\n validateServerChoice(choice, catalog, image);\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_HETZNER_FIREWALL_SOURCE ?? process.env.AGENTBOX_HETZNER_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 uuid; we\n // rename it to `~/.agentbox/hetzner/boxes/<sandboxId>/ssh/` once the\n // server 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 'hetzner',\n `pending-${stamp}`,\n 'ssh',\n );\n const key = await mintSshKey(tempDir, `agentbox-box-${req.name}-${stamp}`);\n\n let firewallId: number | null = null;\n let serverId: number | null = null;\n try {\n // 4. Firewall.\n const firewall = await createPerBoxFirewall(c, {\n name: `agentbox-${req.name}-${stamp}`,\n sources,\n labels: {\n 'agentbox.box': req.name,\n 'agentbox.role': 'box',\n },\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 tokens are\n // deliberately excluded — cloud-init writes box.env world-readable (0644),\n // and these secrets reach the in-box ctl via the daemon's 0600 relay.env\n // (relay token) and its process env (bridge token) 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 server. Map late Hetzner provision errors (account limit,\n // out-of-capacity) to actionable guidance while preserving the original.\n progress(\n `creating VPS '${req.name}' from image ${String(imageRef)} (${serverType} / ${location})`,\n );\n let created;\n try {\n created = await withHetznerRetry(\n { method: 'createServer', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () =>\n c.createServer({\n name: `agentbox-${req.name}-${stamp}`,\n server_type: serverType,\n image: imageRef,\n location,\n user_data: cloudInit,\n firewalls: [{ firewall: firewall.id }],\n labels: {\n 'agentbox.managed': 'true',\n 'agentbox.role': 'box',\n 'agentbox.box': req.name,\n 'agentbox.firewall': String(firewall.id),\n },\n start_after_create: true,\n }),\n );\n } catch (createErr) {\n throw mapHetznerProvisionError(createErr, choice);\n }\n serverId = created.server.id;\n const provisioned = created.server.server_type;\n const vpsIp = created.server.public_net.ipv4?.ip;\n if (!vpsIp) {\n throw new Error(`hetzner: server ${String(serverId)} came up without an IPv4 address`);\n }\n progress(`server ${String(serverId)} provisioned at ${vpsIp}; waiting for ssh`);\n\n // 7. Move the freshly-minted key from its temp location into the\n // sandboxId-keyed final dir, then rm the temp parent. We move file-\n // by-file rather than renaming the whole dir because `ensurePerBoxState`\n // had to mkdir the final dir before we knew the sandbox id (so the\n // tunnel manager + state-restoration paths can find it later).\n const sandboxId = String(serverId);\n const state = await ensurePerBoxState(sandboxId);\n await rename(key.privatePath, state.identity);\n await rename(key.publicPath, `${state.identity}.pub`);\n // Drop the now-empty temp dir + its `pending-XXX` parent.\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 // 8. 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 `hetzner: ssh on ${vpsIp} did not come up within ${String(PROVISION_SSH_DEADLINE_MS / 1000)}s; ` +\n `the server 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 // 9. Open ControlMaster.\n await ensureTunnel(sandboxId, state, vpsIp);\n progress('ssh up; ControlMaster open');\n\n // Agent credentials are seeded by `createCloudProvider`'s unified\n // post-provision step (`seedAgentVolumesIfFresh`) via `uploadFile` +\n // `exec` over the live ControlMaster — the symlinks baked into\n // install-box.sh route ~/.claude/.credentials.json etc. through to\n // `~/.agentbox-creds/<agent>/`.\n //\n // Report the REAL resources from the create response (the plan's\n // cores/memory/disk), not our static defaults — the record + the cloud\n // scaffold's `provisioned …` log line read this.\n return {\n sandboxId,\n inbound: inboundPolicy,\n resources: {\n cpu: provisioned.cores,\n memory: provisioned.memory,\n disk: provisioned.disk,\n },\n };\n } catch (err) {\n // Cleanup on failure: server + firewall + temp ssh dir.\n if (serverId !== null) {\n progress(`cleanup — deleting server ${String(serverId)} after provision failure`);\n try {\n await c.deleteServer(serverId);\n } catch (cleanupErr) {\n onLog(\n `hetzner: WARN — failed to delete server ${String(serverId)}; check the Hetzner dashboard manually. ${\n cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)\n }`,\n );\n }\n }\n if (firewallId !== null) {\n try {\n await deletePerBoxFirewall(c, firewallId);\n } catch {\n // best-effort\n }\n }\n // Clean the temp ssh dir (or its renamed location if we got that far).\n try {\n if (existsSync(key.dir)) await rm(key.dir, { recursive: true, force: true });\n if (serverId !== null) {\n const finalDir = perBoxDir(String(serverId));\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 server = await client().getServer(id);\n return server ? { sandboxId } : null;\n },\n\n async list(): Promise<CloudSandboxSummary[]> {\n const servers = await client().listServers({ label_selector: 'agentbox.managed=true' });\n return servers.map((s) => ({\n sandboxId: String(s.id),\n name: s.labels['agentbox.box'] ?? s.name,\n createdAt: s.created,\n state: mapState(s.status),\n }));\n },\n\n async start(h: CloudHandle): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n await client().powerOn(id);\n // The API reports `running` ~10-30s before sshd actually accepts\n // connections. Callers (the provider's `reEnsureCloudBox` relaunch) SSH-exec\n // immediately after start()/resume(), so wait for the API state AND for ssh\n // to be ready — otherwise the first exec hits `Connection refused` and the\n // daemons never get relaunched. Mirrors the provision flow's waitForSsh.\n await pollUntil(\n `server ${h.sandboxId} running`,\n async () => {\n const s = await client().getServer(id);\n return s?.status === 'running' ? s : null;\n },\n { deadlineMs: ACTION_DEADLINE_MS, intervalMs: 2_000, maxIntervalMs: 8_000 },\n );\n const server = await getServerStrict(id);\n const vpsIp = server.public_net.ipv4?.ip;\n if (!vpsIp) {\n throw new Error(`hetzner: server ${h.sandboxId} has no IPv4 address 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 `hetzner: 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 // Try graceful shutdown first; fall back to power-off after a short wait.\n try {\n await client().shutdown(id);\n await pollUntil(\n `server ${h.sandboxId} off`,\n async () => {\n const s = await client().getServer(id);\n return s?.status === 'off' ? s : null;\n },\n { deadlineMs: 60_000, intervalMs: 2_000, maxIntervalMs: 8_000 },\n );\n } catch {\n await client().powerOff(id);\n }\n await tunnels.close(h.sandboxId);\n },\n\n async pause(h: CloudHandle): Promise<void> {\n // Hetzner has no archive primitive. Pause ≡ stop.\n await this.stop(h);\n },\n\n async resume(h: CloudHandle): Promise<void> {\n await this.start(h);\n },\n\n async destroy(h: CloudHandle): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n await tunnels.close(h.sandboxId);\n // Discover the per-box firewall via labels so we don't need to\n // round-trip through the server's `firewalls[]` (which is absent from\n // our typed slice anyway).\n const c = client();\n let firewallId: number | undefined;\n try {\n const server = await c.getServer(id);\n firewallId = server\n ? Number.parseInt(server.labels['agentbox.firewall'] ?? '', 10)\n : undefined;\n } catch {\n // ignore — we'll still try to delete the server\n }\n try {\n await c.deleteServer(id);\n } catch (err) {\n if (!(err instanceof HetznerApiError && (err.statusCode === 404 || err.code === 'not_found'))) {\n throw err;\n }\n }\n if (firewallId && Number.isFinite(firewallId)) {\n await deletePerBoxFirewall(c, firewallId);\n }\n // Clean the per-box ssh dir.\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 s = await client().getServer(id);\n return s ? mapState(s.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 = [\n ...sshOptArgs(target),\n localPath,\n `${target.user}@${target.host}:${remotePath}`,\n ];\n const res = await execa('scp', argv, { reject: false, timeout: 300_000 });\n if (res.exitCode !== 0) {\n throw new Error(`hetzner: 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 = [\n ...sshOptArgs(target),\n `${target.user}@${target.host}:${remotePath}`,\n localPath,\n ];\n const res = await execa('scp', argv, { reject: false, timeout: 300_000 });\n if (res.exitCode !== 0) {\n throw new Error(`hetzner: 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 // -L for nicer dir-detection on symlinks; `--printf` is non-portable so\n // use a small awk wrap that prints `<name>\\t<d|f>` per entry.\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 const { state, vpsIp } = await ensureLiveTarget(h.sandboxId);\n void state;\n void vpsIp;\n const localPort = await tunnels.forward(h.sandboxId, port);\n // Plain loopback URL — no preview-token here (SSH local forward is\n // already auth-gated by the tunnel itself). The cloud-provider layer\n // adds the Portless alias for symmetric `<box-name>.localhost` URLs.\n return { url: `http://127.0.0.1:${String(localPort)}` };\n },\n\n async signedPreviewUrl(h, port, _ttl): Promise<CloudPreviewUrl> {\n // SSH tunnels have no signed-URL primitive — they're already loopback-\n // only and the cloud-provider layer's bridge-token enforces auth. The\n // signed form is functionally equivalent to the unsigned one here.\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 + every cached `-L` forward\n // for this box and re-open from scratch. Called by the host\n // CloudBoxPoller when ECONNREFUSED on the local port shows that the\n // master died (host sleep/wake, transient network blip). Without this\n // the poller would back off forever against a stale localPort.\n const { state, vpsIp } = await ensureLiveTarget(h.sandboxId);\n void state;\n void vpsIp;\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 repairReachability(h): Promise<{ changed: boolean; detail?: string }> {\n // Re-sync the per-box firewall to the host's CURRENT egress IP, but only\n // when it actually changed — the host laptop moved networks and the\n // firewall is now blocking us. Called by the CLI ONLY on a connection-\n // establishment failure (`recover`, the initial attach connect), never on a\n // mid-session drop. A `0.0.0.0/0` firewall (explicit dynamic-IP opt-in) is\n // already open, so it's a no-op.\n const policy: InboundPolicy = h.inbound ?? { mode: 'locked', sources: [] };\n if (policy.mode === 'open') return { changed: false };\n const s = await firewallEgressStatus(h.sandboxId).catch(() => null);\n if (!s || !firewallNeedsSync(s.allowedSources, s.currentEgress)) return { changed: false };\n // Merge the stored whitelist with the refreshed egress so a drift heal\n // never narrows a whitelisted box down to just the host IP.\n const sources = resolveInboundSources(policy, s.currentEgress);\n await syncFirewallSource(client(), s.firewallId, sources);\n return {\n changed: true,\n detail: `firewall updated: SSH now allowed from ${sources.join(', ')} (was ${s.allowedSources.join(', ') || '(no rule)'})`,\n };\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 id = Number.parseInt(h.sandboxId, 10);\n const server = await client().getServer(id);\n if (!server) throw new Error(`hetzner: server ${h.sandboxId} not found`);\n const firewallId = Number.parseInt(server.labels['agentbox.firewall'] ?? '', 10);\n if (!Number.isFinite(firewallId)) {\n throw new Error(`hetzner: no per-box firewall recorded for server ${h.sandboxId}`);\n }\n const hostEgress = policy.mode === 'open' ? null : `${await detectEgressIp({})}/32`;\n const sources = resolveInboundSources(policy, hostEgress);\n await syncFirewallSource(client(), firewallId, sources);\n return { sources };\n },\n\n async startInBoxPortless(h, opts): Promise<void> {\n // Bring up a `portless` proxy *inside the VPS* mirroring the host's\n // mode so `<boxName>.localhost:<P>` resolves to the same content on\n // both sides. The `portless` CLI is baked into the base snapshot by\n // install-box.sh:316. Idempotent — `portless proxy start` exits 0 if a\n // proxy is already running on the port. Best-effort: a failure here\n // just means the in-box symmetric URL won't resolve; the host URL\n // still works.\n //\n // Run as root (vscode has NOPASSWD sudo): portless's :443/:80 TLS\n // proxy self-elevates to root anyway, and its state lands in\n // /root/.portless. A subsequent `portless alias` from vscode would\n // write to /home/vscode/.portless and the proxy wouldn't see it —\n // the two state dirs are disjoint. Using sudo for both keeps them\n // pointed at the same `/root/.portless`.\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 // The TLS mirror serves its own self-signed CA at /root/.portless/ca.pem.\n // `portless proxy start` only trusts it in the system store — not the box\n // user's NSS db, which Chromium / Playwright read — so the VNC browser and\n // Playwright fail with a cert error on `https://<box>.localhost`. Trust it\n // everywhere (system store + vscode NSS db) and point Node at it via\n // NODE_EXTRA_CA_CERTS. Best-effort: the helper never exits non-zero.\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, no\n // SSH-token mint pressure (unlike Daytona). Callers append `-t '<cmd>'`\n // or similar in the `buildAttach` helper.\n return [\n 'ssh',\n ...sshOptArgs(target),\n `${target.user}@${target.host}`,\n ];\n },\n\n async createSnapshot(h, name): Promise<void> {\n const id = Number.parseInt(h.sandboxId, 10);\n const c = client();\n const { image } = await withHetznerRetry(\n { method: 'createImage', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () =>\n c.createImage(id, {\n type: 'snapshot',\n description: name,\n labels: { 'agentbox.role': 'ckpt', 'agentbox.box': h.sandboxId },\n }),\n );\n await pollUntil(\n `image ${String(image.id)} availability`,\n async () => {\n const img = await c.getImage(image.id);\n return img?.status === 'available' ? img : null;\n },\n { deadlineMs: SNAPSHOT_DEADLINE_MS, intervalMs: 3_000, maxIntervalMs: 10_000 },\n );\n },\n\n async deleteSnapshot(name): Promise<void> {\n const c = client();\n const img = await findImageByDescription(c, name);\n if (!img) return;\n try {\n await c.deleteImage(img.id);\n } catch (err) {\n if (err instanceof HetznerApiError && (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 _hetznerTunnels };\n\n","/**\n * Cloud-init `#cloud-config` user-data generators.\n *\n * Two flavors:\n * - **prepare** (`generatePrepareCloudInit`): for the temporary VPS that\n * `prepareHetzner()` 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 '# AgentBox temporary prepare VPS — used by `agentbox prepare --provider hetzner`',\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 // Hetzner's Ubuntu 24.04 stock image enforces a first-login password\n // change for root. With key-based auth that path can't run (no TTY),\n // so sshd refuses with \"Password change required but no TTY available.\"\n // Telling cloud-init to NOT expire passwords + clearing root's expiry\n // via `passwd -d` removes the gate. Belt-and-braces: the chpasswd block\n // covers cloud-init's own users-and-groups run; the runcmd covers the\n // case where the image's pre-baked expiry survives cloud-init.\n 'chpasswd:',\n ' expire: false',\n 'users:',\n ' - name: root',\n ' lock_passwd: false',\n ' ssh_authorized_keys:',\n ` - ${yamlScalar(pubkey)}`,\n 'runcmd:',\n ' - [ passwd, -d, root ]',\n ' - [ chage, -E, \"-1\", -I, \"-1\", -M, \"99999\", root ]',\n ' - [ bash, -lc, \"echo agentbox-prepare-ready\" ]',\n '',\n ].join('\\n');\n}\n\nexport interface ControlPlaneCloudInitOptions {\n /** ed25519/rsa public key string (one line, OpenSSH format) for `root`. */\n sshPubkey: string;\n /** Public git repo to clone the control-plane app from. */\n repoUrl: string;\n /** Branch / tag / sha to check out. */\n repoRef: string;\n}\n\n/**\n * Cloud-init for a control-plane VPS (stock Ubuntu, not the box snapshot).\n * Logs in as `root`, installs Docker + git, and clones the agentbox repo to\n * `/opt/agentbox`. The orchestrator then scp's the secret env + Caddy config\n * and runs `docker compose up` over ssh — secrets never go in user-data (which\n * is readable from cloud metadata).\n */\nexport function controlPlaneCloudInit(opts: ControlPlaneCloudInitOptions): string {\n const pubkey = opts.sshPubkey.trim();\n return [\n '#cloud-config',\n '# AgentBox control-plane VPS — provisioned by `agentbox control-plane setup --deploy hetzner`.',\n 'disable_root: false',\n 'ssh_pwauth: false',\n 'chpasswd:',\n ' expire: false',\n 'users:',\n ' - name: root',\n ' lock_passwd: false',\n ' ssh_authorized_keys:',\n ` - ${yamlScalar(pubkey)}`,\n 'runcmd:',\n ' - [ passwd, -d, root ]',\n ' - [ chage, -E, \"-1\", -I, \"-1\", -M, \"99999\", root ]',\n ' - [ bash, -lc, \"curl -fsSL https://get.docker.com | sh\" ]',\n ' - [ bash, -lc, \"apt-get update && apt-get install -y git\" ]',\n ` - [ bash, -lc, \"git clone --depth 1 --branch ${shArg(opts.repoRef)} ${shArg(opts.repoUrl)} /opt/agentbox || git clone ${shArg(opts.repoUrl)} /opt/agentbox\" ]`,\n '',\n ].join('\\n');\n}\n\n/** Single-quote a value for embedding inside a `bash -lc \"...\"` cloud-init step. */\nfunction shArg(value: string): string {\n // Only used for repo URL/ref (no shell metachars in practice); guard anyway.\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\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 `# 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 // Hetzner'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 Hetzner 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(`hetzner: 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 * Pure Hetzner create preflight — no network. Given a fetched `/server_types`\n * catalog and (optionally) the base image, validate the user's server-type +\n * location choice BEFORE we start creating billable resources (firewall, SSH\n * key, server), and map the late provision errors Hetzner returns into\n * actionable guidance.\n *\n * Kept side-effect-free so it unit-tests against fake catalogs/images. The\n * backend fetches the catalog + image and calls in.\n */\n\nimport { UserFacingError } from '@agentbox/core';\nimport { HetznerApiError, type HetznerImage, type HetznerServerType } from './client.js';\n\nexport interface ServerChoice {\n serverType: string;\n location: string;\n}\n\n/** A non-deprecated x86 type is deprecated iff the `deprecation` object is set. */\nfunction isDeprecated(t: HetznerServerType): boolean {\n return t.deprecated === true || (t.deprecation !== undefined && t.deprecation !== null);\n}\n\n/**\n * Up to `limit` non-deprecated x86 type names from the catalog, cheapest-looking\n * first (the catalog is roughly ordered by size, so preserve its order). Used to\n * suggest alternatives when the user's type is unknown.\n */\nfunction suggestTypes(catalog: HetznerServerType[], limit = 6): string[] {\n return catalog\n .filter((t) => t.architecture === 'x86' && !isDeprecated(t))\n .map((t) => t.name)\n .slice(0, limit);\n}\n\n/** Locations (from `prices[].location`) where a given type is offered. */\nfunction offeredLocations(t: HetznerServerType): string[] {\n const seen = new Set<string>();\n for (const p of t.prices) {\n if (p.location) seen.add(p.location);\n }\n return [...seen];\n}\n\n/**\n * Validate a server-type + location choice against the live catalog and the\n * base image, throwing a `UserFacingError` with a fix on the first problem.\n * Checks, in order: type exists → is x86 (ARM `cax*` snapshots aren't\n * supported) → not deprecated → disk fits the image → location offers the type.\n *\n * `image` is null when the box boots from a Hetzner stock image ref (a plain\n * string like `ubuntu-24.04`, not a numeric snapshot id) — the disk check is\n * skipped in that case since we don't have the image's `disk_size`.\n */\nexport function validateServerChoice(\n choice: ServerChoice,\n catalog: HetznerServerType[],\n image: HetznerImage | null,\n): void {\n const { serverType, location } = choice;\n const type = catalog.find((t) => t.name === serverType);\n\n if (!type) {\n const suggestions = suggestTypes(catalog);\n const hint =\n suggestions.length > 0 ? ` Valid types include: ${suggestions.join(', ')}.` : '';\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" does not exist.${hint}\\n` +\n 'Set one with `--size <type>` or `agentbox config set box.sizeHetzner <type>`.',\n );\n }\n\n if (type.architecture !== 'x86') {\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" is ${type.architecture} (ARM). AgentBox base ` +\n 'snapshots are x86-only, so ARM types (e.g. `cax*`) are not supported.\\n' +\n `Pick an x86 type instead: ${suggestTypes(catalog).join(', ')}.`,\n );\n }\n\n if (isDeprecated(type)) {\n const after = type.deprecation?.unavailable_after;\n const when = after ? ` (unavailable after ${after})` : '';\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" is deprecated${when} and can't be used for new servers.\\n` +\n `Pick a current type instead: ${suggestTypes(catalog).join(', ')}.`,\n );\n }\n\n // Snapshot disk must fit the plan's disk. Skip for stock string refs (image\n // null) — we don't have a disk_size to compare, and Hetzner sizes those itself.\n if (image && typeof image.disk_size === 'number' && type.disk < image.disk_size) {\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" has a ${String(type.disk)} GB disk, but the base ` +\n `snapshot needs at least ${String(image.disk_size)} GB.\\n` +\n 'Choose a larger type (bigger plans have bigger disks).',\n );\n }\n\n const locations = offeredLocations(type);\n if (locations.length > 0 && !locations.includes(location)) {\n throw new UserFacingError(\n `Hetzner server type \"${serverType}\" is not offered in location \"${location}\".\\n` +\n `It is available in: ${locations.join(', ')}.\\n` +\n 'Pick one with `--location <name>` or `agentbox config set box.hetznerLocation <name>`.',\n );\n }\n}\n\n/**\n * Map a Hetzner provision error (from `createServer`) into a friendlier\n * `UserFacingError`, preserving the original message. Non-Hetzner errors and\n * unrecognized codes pass through unchanged so we never hide an unexpected\n * failure. Called around the `createServer` call in the backend.\n */\nexport function mapHetznerProvisionError(err: unknown, choice: ServerChoice): unknown {\n if (!(err instanceof HetznerApiError)) return err;\n const { serverType, location } = choice;\n\n if (err.code === 'resource_limit_exceeded') {\n return new UserFacingError(\n `Hetzner refused to create the server: your account resource limit was exceeded ` +\n `(${err.message}).\\n` +\n 'New Hetzner Cloud accounts start with a low server limit. Request an increase in ' +\n 'the Hetzner Console (Limits page: https://console.hetzner.cloud/ → your project → ' +\n 'Limits), then retry.',\n );\n }\n\n if (err.code === 'resource_unavailable' || err.code === 'placement_error') {\n return new UserFacingError(\n `Hetzner has no capacity for \"${serverType}\" in \"${location}\" right now ` +\n `(${err.message}).\\n` +\n 'Retry, or pick another datacenter with `--location fsn1` / `hel1` / `ash` ' +\n '(or `agentbox config set box.hetznerLocation <name>`).',\n );\n }\n\n return err;\n}\n","/**\n * `agentbox prepare --provider hetzner` — bake the per-org Hetzner base\n * snapshot. Mirrors the user request: \"for `agentbox prepare` (and first\n * time hetzner is used) start a VM and set it up and snapshot as base image\n * (there's no way to start a VPS from an existing dockerfile).\"\n *\n * Flow:\n * 1. Mint an ephemeral SSH keypair under\n * ~/.agentbox/hetzner/prepare-<ts>/.\n * 2. Detect the host's egress IP and create a firewall locked to it,\n * named `agentbox-prepare-<ts>`.\n * 3. Create a temp VPS (Ubuntu 24.04, `cx22` default) with cloud-init\n * injecting the pubkey for `root`.\n * 4. Poll until cloud-init + sshd come up.\n * 5. scp the runtime assets (install script + agentbox-ctl + helpers +\n * baked config files) into /tmp.\n * 6. Run `bash /tmp/agentbox-install.sh` over ssh; stream stdout to the\n * prepare log via the `onLog` callback.\n * 7. `create_image` snapshot of the VPS; poll until `available`.\n * 8. Delete the VPS + firewall.\n * 9. Persist the snapshot id into `~/.agentbox/hetzner-prepared.json`.\n *\n * Failure-mode discipline: each major step is wrapped in try/catch so the\n * temp VPS + firewall are *always* cleaned up on failure (the user must\n * never end up with a forgotten €4/mo VPS due to a prepare error).\n *\n * The user requested noisy logging — every BEGIN/END marker from the\n * install script is forwarded verbatim into the prepare log, plus our own\n * step boundaries from `progress()`.\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 { ensureHetznerCredentials } from './credentials.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport { createPerBoxFirewall, deletePerBoxFirewall, normalizeSourceCidr } from './firewall.js';\nimport { makeHetznerClient } 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 PrepareHetznerOptions {\n name?: string;\n hostWorkspace?: string;\n /** Force re-bake even when `~/.agentbox/hetzner-prepared.json` has a usable base. */\n force?: boolean;\n /** Hetzner location (defaults to `nbg1`). */\n location?: string;\n /** Server type (defaults to `cx22` — 2 vCPU / 4 GB / 40 GB / ~€4/mo). */\n serverType?: string;\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\n * the explicit-open opt-in. Passing a bare IP appends `/32` 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 /** How install-box.sh installs Claude Code (`native` default | `npm`). */\n claudeInstall?: 'native' | 'npm';\n onLog?: (line: string) => void;\n}\n\nexport interface PrepareHetznerResult {\n snapshotName?: string;\n /** Hetzner image id (numeric) — also recorded in hetzner-prepared.json. */\n imageId?: number;\n}\n\n// `cx22` was deprecated by Hetzner in early 2026; `cx23` is the drop-in\n// replacement with the same 2 vCPU / 4 GB / 40 GB shape on x86. Users can\n// still override via `prepareHetzner({serverType: ...})`.\nconst TEMP_SERVER_TYPE_DEFAULT = 'cx23';\nconst TEMP_SERVER_LOCATION_DEFAULT = 'nbg1';\nconst PREPARE_SSH_DEADLINE_MS = 5 * 60_000;\nconst INSTALL_SCRIPT_TIMEOUT_MS = 30 * 60_000;\nconst SNAPSHOT_DEADLINE_MS = 20 * 60_000;\n\n/**\n * Bake the per-org Hetzner base snapshot. Resolves only after the image is\n * `available` and the temp VPS + firewall are gone. Persists `{base.imageId,\n * base.description, base.createdAt, base.installScriptSha256}` into\n * `~/.agentbox/hetzner-prepared.json`.\n */\nexport async function prepareHetzner(\n opts: PrepareHetznerOptions = {},\n): Promise<PrepareHetznerResult> {\n await ensureHetznerCredentials();\n const client = makeHetznerClient();\n const log = opts.onLog ?? (() => {});\n const progress = (step: string) => log(`prepare-hetzner: ${step}`);\n\n // Skip-fast: if a base snapshot is already recorded *and* its image is\n // still on Hetzner *and* the build-context fingerprint hasn't changed *and*\n // --force was not passed, return the existing record.\n const existingState = readPreparedState();\n // Prefer an explicit override; otherwise auto-detect the published-CLI\n // staged runtime tree by inspecting where this module was loaded from.\n const assets = resolveRuntimeAssets({\n cliRuntimeRoot: opts.cliRuntimeRoot ?? findStagedCliRuntimeRoot(),\n repoRoot: opts.repoRoot,\n });\n // Fingerprint = hash of every asset we scp into the prepare VPS. Keyed on\n // logical name (stable across staged-vs-monorepo layouts) so two CLIs with\n // the same staged tree produce the same hash.\n const claudeInstall = opts.claudeInstall ?? 'native';\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 client.getImage(existingState.base.imageId).catch(() => null);\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(\n `recorded base snapshot ${String(existingState.base.imageId)} is gone on Hetzner; rebuilding`,\n );\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 + detect egress IP in parallel.\n progress('minting ephemeral ssh key');\n const key = await mintPrepareKey();\n let firewallId: number | null = null;\n let serverId: number | null = null;\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.\n const stamp = Date.now().toString(36);\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 labels: { 'agentbox.role': 'prepare' },\n });\n firewallId = firewall.id;\n\n // 3. Create temp VPS.\n const serverName = `agentbox-prepare-${stamp}`;\n const cloudInit = generatePrepareCloudInit({ sshPubkey: key.publicKey });\n progress(\n `creating temp VPS ${serverName} (${opts.serverType ?? TEMP_SERVER_TYPE_DEFAULT} / ${opts.location ?? TEMP_SERVER_LOCATION_DEFAULT})`,\n );\n const created = await client.createServer({\n name: serverName,\n server_type: opts.serverType ?? TEMP_SERVER_TYPE_DEFAULT,\n image: 'ubuntu-24.04',\n location: opts.location ?? TEMP_SERVER_LOCATION_DEFAULT,\n user_data: cloudInit,\n firewalls: [{ firewall: firewall.id }],\n labels: { 'agentbox.managed': 'true', 'agentbox.role': 'prepare' },\n start_after_create: true,\n });\n serverId = created.server.id;\n const ip = created.server.public_net.ipv4?.ip;\n if (!ip) {\n throw new Error('hetzner: temp VPS came up without an IPv4 address');\n }\n\n // 4. Wait for sshd.\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(\n `hetzner: ssh on ${ip} did not come up within ${String(PREPARE_SSH_DEADLINE_MS / 1000)}s`,\n );\n }\n progress(\"ssh up — scp'ing runtime assets\");\n\n // 5. scp every asset into /tmp/ **sequentially**. Parallel uploads\n // through 10 fresh ssh connections trip sshd's MaxStartups (10:30:100\n // default) on a freshly-booted VPS — surviving connections look fine\n // but some randomly write 0 bytes to the destination. The sequential\n // form is plenty fast (each file is small, total ~1MB).\n for (const asset of assets) {\n const remote = `/tmp/${asset.remoteBasename}`;\n log(`prepare-hetzner: 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. We trace via `bash -x` and tee the full\n // output to /var/log/agentbox/install.log on the VPS so the trace\n // survives into the snapshot — handy when diagnosing a step that ran\n // (or didn't) deep inside the install. Stream stdout/stderr through\n // `onLog` so `prepare.log` shows the BEGIN/END markers in real time.\n // `set -o pipefail` so the pipe's exit code is bash's, not tee's.\n progress('running install-box.sh on temp VPS (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 // Exit 71 is install-box.sh's dedicated sentinel for \"Claude Code native\n // installer failed after its retries\" — almost always a transient\n // Cloudflare 403 that claude.ai / downloads.claude.ai return to\n // cloud-datacenter egress IPs under load. Surface an actionable message\n // instead of the opaque generic one (stderr is empty here because the\n // install runs `bash -x ... 2>&1 | tee`, merging stderr into stdout).\n if (installRes.exitCode === 71) {\n throw new Error(\n `Claude Code's native installer could not be reached from the Hetzner VPS after 3 retries (~5 min).\\n` +\n `This is a transient Cloudflare 403. It usually clears within a few minutes.\\n\\n` +\n `What to do: wait a moment, then re-run \\`agentbox prepare --provider hetzner --force\\`.\\n` +\n `Full trace: /var/log/agentbox/install.log inside any box made from the resulting snapshot.`,\n );\n }\n throw new Error(\n `install-box.sh failed on temp VPS (exit ${String(installRes.exitCode)})\\n` +\n `Last stderr: ${installRes.stderr.slice(-500) || '(empty)'}\\n` +\n `The full trace was preserved at /var/log/agentbox/install.log inside any box made from the resulting snapshot.`,\n );\n }\n progress('install script complete');\n\n // 6b. Stage host agent static config (~/.claude plugins/skills/settings/\n // _claude.json, ~/.codex config + prompts, ~/.local/share/opencode), scp\n // each tarball, extract into /home/vscode/ as the `vscode` user. Mirrors\n // the Daytona bake step (`Image.addLocalFile` + `Image.runCommands`),\n // adapted for our ssh+scp model. Without this, the in-box claude/codex/\n // opencode boot with no plugins, no skills, no settings, and prompt the\n // user to log in fresh on every box.\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-hetzner: ${w}`);\n if (claudeTar.tarballPath)\n 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-hetzner: ${w}`);\n if (codexTar.tarballPath)\n 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-hetzner: ${w}`);\n if (opencodeTar.tarballPath)\n stagings.push({\n kind: 'opencode',\n tar: opencodeTar,\n dest: '/home/vscode/.local/share/opencode',\n });\n else await opencodeTar.cleanup();\n\n // ~/.agents (cross-agent Agent Skills) — codex reads ~/.agents/skills.\n const agentsTar = await stageAgentsStaticForUpload();\n for (const w of agentsTar.warnings) log(`prepare-hetzner: ${w}`);\n if (agentsTar.tarballPath)\n 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-hetzner: scp ${s.kind} static (${s.tar.tarballPath}) -> ${remote}`);\n await scpUpload(sshTarget, s.tar.tarballPath as string, remote);\n // Extract as vscode so the files land owned by uid 1000. The dir\n // already exists (created by the install script's credential-pivot\n // step) — extract into it, don't replace it.\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, {\n onLine: (line) => log(`[stage:${s.kind}] ${line}`),\n });\n if (r.exitCode !== 0) {\n throw new Error(\n `prepare-hetzner: ${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.\n const description = opts.name ?? `agentbox-base-${stamp}`;\n progress(`creating snapshot '${description}' from VPS ${String(serverId)}`);\n const snap = await client.createImage(serverId, {\n type: 'snapshot',\n description,\n labels: { 'agentbox.role': 'base', 'agentbox.schema': '1' },\n });\n progress(\n `snapshot create requested (image id ${String(snap.image.id)}); polling until available`,\n );\n const ready = await pollUntil(\n `image ${String(snap.image.id)} availability`,\n async () => {\n const img = await client.getImage(snap.image.id);\n if (!img) return null;\n if (img.status === 'available') return img;\n return null;\n },\n {\n deadlineMs: SNAPSHOT_DEADLINE_MS,\n intervalMs: 3_000,\n maxIntervalMs: 10_000,\n onPoll: (l) => log(`prepare-hetzner: ${l}`),\n },\n );\n\n // 8. Persist before tearing down — if the cleanup fails we still know\n // about the new snapshot.\n progress('persisting hetzner-prepared.json');\n const state = readPreparedState();\n const cliStamp = readCliStamp();\n state.base = {\n imageId: ready.id,\n description: ready.description,\n createdAt: new Date().toISOString(),\n contextSha256: contextSha,\n cliVersion: cliStamp.cliVersion,\n cliCommit: cliStamp.cliCommit,\n };\n writePreparedState(state);\n log(`prepare-hetzner: wrote ${preparedStatePath()}`);\n\n // 9. Cleanup: delete server first (cleanly detaches from firewall),\n // then the firewall.\n progress(`deleting temp VPS ${String(serverId)}`);\n await client.deleteServer(serverId);\n serverId = null;\n progress(`deleting per-prepare firewall ${String(firewallId)}`);\n await deletePerBoxFirewall(client, firewallId);\n firewallId = null;\n\n progress(`prepare complete — base snapshot ${String(ready.id)} (${ready.description})`);\n return { snapshotName: ready.description, imageId: ready.id };\n } catch (err) {\n // Failure cleanup — best-effort. Always try to delete the VPS first\n // (it costs €4/mo if left running). Surface the original error in any\n // case.\n if (serverId !== null) {\n log(`prepare-hetzner: cleanup — deleting temp VPS ${String(serverId)} after failure`);\n try {\n await client.deleteServer(serverId);\n } catch (cleanupErr) {\n log(\n `prepare-hetzner: WARN — failed to delete temp VPS ${String(serverId)}; check the Hetzner dashboard manually. ${\n cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)\n }`,\n );\n }\n }\n if (firewallId !== null) {\n log(\n `prepare-hetzner: cleanup — deleting per-prepare firewall ${String(firewallId)} after failure`,\n );\n try {\n await deletePerBoxFirewall(client, firewallId);\n } catch (cleanupErr) {\n log(\n `prepare-hetzner: WARN — failed to delete firewall ${String(firewallId)}; check the Hetzner 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 `daytonaProvider.prepare`.\n */\nexport const prepareHetznerProvider: NonNullable<Provider['prepare']> = (req) =>\n prepareHetzner({\n name: req.name,\n hostWorkspace: req.hostWorkspace ?? process.cwd(),\n force: req.force,\n // Datacenter for the temp bake VPS (defaults to nbg1 when unset). Resolved\n // by the CLI from `--location` / `box.hetznerLocation`.\n location: req.location,\n onLog: req.onLog,\n // Forward the Claude install mode (native | npm). Without this the Hetzner\n // bake always ran the native `curl install.sh`, whose CDN 403s datacenter\n // egress IPs — the `npm` escape hatch (box.claudeInstall / --claude-install\n // npm) never reached the bake. (matches prepareVercelProvider.)\n claudeInstall: req.claudeInstall,\n });\n\n/**\n * First-use gate. If no base snapshot is recorded in\n * `~/.agentbox/hetzner-prepared.json`, throws an actionable error pointing\n * at `agentbox prepare --provider hetzner`.\n *\n * This is called by `backend.provision()` (lazily, from Phase 4 onward) so\n * `agentbox prepare --provider hetzner` itself can run without tripping\n * the gate.\n *\n * Phase 4 will widen this to also re-check the image is still on Hetzner\n * (404 → retrigger prepare prompt). For now it just gates on the local\n * record so the build is honest about the failure mode.\n */\nexport async function ensureHetznerBaseSnapshot(): Promise<void> {\n const state = readPreparedState();\n if (state.base !== undefined) return;\n throw new UserFacingError(\n 'no Hetzner base snapshot found.\\n' +\n 'Run `agentbox prepare --provider hetzner` first (Hetzner 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 Hetzner 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/hetzner/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). Re-exported\n// here so the Hetzner-internal call sites 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', 'hetzner', `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 * Hetzner's per-box ssh dir is un-namespaced (`~/.agentbox/boxes/<id>/ssh/`) —\n * it predates the namespace argument, and moving it would orphan the keys of\n * every already-running box.\n */\nexport {\n SshTunnelManager,\n controlSockPath,\n defaultBoxSshDir,\n type PortForward,\n type SshTunnelOpenOptions,\n} from '@agentbox/sandbox-core';\n","/**\n * Doctor probes + normalized credential status for the hetzner 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 { readHetznerCredStatus } from './credentials.js';\nimport { readPreparedState } from './prepared-state.js';\n\nexport function readCredStatusSummary(): CredStatusSummary {\n return { configured: readHetznerCredStatus().source !== 'none' };\n}\n\nexport async function doctorChecks(): Promise<CheckResult[]> {\n try {\n const cred = readHetznerCredStatus();\n const credRes: CheckResult =\n cred.source === 'none'\n ? {\n label: 'credentials',\n status: 'warn',\n detail: 'HCLOUD_TOKEN not set',\n hint: '`agentbox hetzner 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: `image ${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 hetzner`',\n };\n // Host Portless mints the <box>.localhost alias for the SSH-forwarded port;\n // without it hetzner 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","/**\n * Deploy the AgentBox hosted control plane (the `apps/hub` Next.js +\n * Postgres app) to a fresh Hetzner VPS, reachable over HTTPS at\n * `https://<ipv4>.sslip.io` (sslip.io resolves the host to the IP; Caddy auto-\n * provisions a Let's Encrypt cert — no domain or DNS setup needed).\n *\n * Shape:\n * 1. firewall — SSH from the host egress IP, :80/:443 open (ACME + serving).\n * 2. cloud-init — stock Ubuntu boots, installs Docker + git, clones the repo.\n * 3. over ssh (as root): scp the secret `.env` + a Caddy compose overlay, then\n * `docker compose up -d --build` (Postgres + the app + Caddy, all in-compose).\n * 4. poll `https://<domain>/healthz` until the cert + app are live.\n * Secrets ride scp (per-deploy key), never cloud-init user-data (cloud metadata).\n */\n\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { makeHetznerClient, type HetznerServer } from './client.js';\nimport { controlPlaneCloudInit } from './cloud-init.js';\nimport { detectEgressIp } from './egress-ip.js';\nimport { controlPlaneInboundRules, normalizeSourceCidr } from './firewall.js';\nimport { mintSshKey } from './ssh-key.js';\nimport { scpUpload, sshExec, waitForSsh, type SshTargetArgs } from './ssh-cli.js';\nimport { withHetznerRetry } from './retry.js';\n\nexport interface ControlPlaneHetznerDeployOptions {\n /** Contents of `control-plane.env` — GITHUB_APP_ID / _PRIVATE_KEY / ADMIN_TOKEN. */\n envContent: string;\n /** Override the public hostname (default `<ipv4>.sslip.io`). */\n domain?: string;\n /** Public git repo cloned on the VPS (default the agentbox repo). */\n repoUrl?: string;\n /** Branch / tag / sha to deploy (default `main`). */\n repoRef?: string;\n serverType?: string;\n location?: string;\n serverImage?: string;\n onLog?: (line: string) => void;\n}\n\nexport interface ControlPlaneHetznerDeployResult {\n url: string;\n serverId: number;\n ip: string;\n domain: string;\n firewallId: number;\n sshKeyDir: string;\n}\n\nconst REMOTE_APP_DIR = '/opt/agentbox/apps/hub';\n\nfunction caddyfile(domain: string): string {\n // Caddy auto-provisions a Let's Encrypt cert for the site address and reverse-\n // proxies to the Next app on the compose network (the app listens on :3000).\n return `${domain} {\\n\\treverse_proxy app:3000\\n}\\n`;\n}\n\nconst CADDY_COMPOSE = `services:\n caddy:\n image: caddy:2.8\n restart: unless-stopped\n ports:\n - '80:80'\n - '443:443'\n volumes:\n - ${REMOTE_APP_DIR}/Caddyfile:/etc/caddy/Caddyfile:ro\n - caddy_data:/data\n - caddy_config:/config\n depends_on:\n - app\nvolumes:\n caddy_data:\n caddy_config:\n`;\n\nasync function serverIpv4(\n client: ReturnType<typeof makeHetznerClient>,\n server: HetznerServer,\n deadlineMs: number,\n): Promise<string> {\n if (server.public_net.ipv4?.ip) return server.public_net.ipv4.ip;\n const stop = Date.now() + deadlineMs;\n while (Date.now() < stop) {\n const s = await client.getServer(server.id);\n if (s?.public_net.ipv4?.ip) return s.public_net.ipv4.ip;\n await new Promise((r) => setTimeout(r, 3_000));\n }\n throw new Error(`server ${String(server.id)} never got a public IPv4`);\n}\n\nasync function pollHealthz(url: string, deadlineMs: number, log: (l: string) => void): Promise<void> {\n const stop = Date.now() + deadlineMs;\n let lastErr = '';\n while (Date.now() < stop) {\n try {\n const res = await fetch(`${url}/healthz`, { signal: AbortSignal.timeout(8000) });\n if (res.ok) return;\n lastErr = `HTTP ${String(res.status)}`;\n } catch (e) {\n lastErr = e instanceof Error ? e.name : String(e);\n }\n log(`waiting for ${url}/healthz (cert + app)… ${lastErr}`);\n await new Promise((r) => setTimeout(r, 6_000));\n }\n throw new Error(`control plane did not become healthy at ${url} (${lastErr})`);\n}\n\nexport async function deployControlPlaneToHetzner(\n opts: ControlPlaneHetznerDeployOptions,\n): Promise<ControlPlaneHetznerDeployResult> {\n const log = opts.onLog ?? (() => {});\n const repoUrl = opts.repoUrl ?? 'https://github.com/madarco/agentbox.git';\n const repoRef = opts.repoRef ?? 'main';\n const client = makeHetznerClient();\n\n const stamp = Date.now().toString(36);\n const name = `agentbox-control-plane-${stamp}`;\n\n log('detecting host egress IP for the firewall…');\n const hostCidr = normalizeSourceCidr(await detectEgressIp());\n\n log('creating the control-plane firewall (:22 host-only, :80/:443 open)…');\n const firewall = await withHetznerRetry(\n { method: 'createFirewall', retryOnAmbiguous: false, attemptTimeoutMs: 60_000 },\n () =>\n client.createFirewall({\n name,\n rules: controlPlaneInboundRules(hostCidr),\n labels: { 'agentbox.managed': 'true', 'agentbox.role': 'control-plane' },\n }),\n );\n\n const keyDir = join(homedir(), '.agentbox', 'control-plane', 'ssh', stamp);\n const key = await mintSshKey(keyDir, `agentbox-control-plane-${stamp}`);\n const knownHosts = join(keyDir, 'known_hosts');\n\n log(`provisioning ${opts.serverType ?? 'cx23'} VPS (cloning ${repoUrl}@${repoRef})…`);\n const { server } = await withHetznerRetry(\n { method: 'createServer', retryOnAmbiguous: false, attemptTimeoutMs: 120_000 },\n () =>\n client.createServer({\n name,\n server_type: opts.serverType ?? 'cx23',\n image: opts.serverImage ?? 'ubuntu-24.04',\n location: opts.location ?? 'nbg1',\n user_data: controlPlaneCloudInit({ sshPubkey: key.publicKey, repoUrl, repoRef }),\n firewalls: [{ firewall: firewall.id }],\n labels: { 'agentbox.managed': 'true', 'agentbox.role': 'control-plane' },\n start_after_create: true,\n }),\n );\n\n const ip = await serverIpv4(client, server, 60_000);\n const domain = opts.domain ?? `${ip}.sslip.io`;\n const url = `https://${domain}`;\n const target: SshTargetArgs = { host: ip, user: 'root', identity: key.privatePath, knownHosts };\n\n log(`VPS ${ip} up; waiting for ssh…`);\n if (!(await waitForSsh(target, 5 * 60_000))) {\n throw new Error(`ssh never came up on ${ip}`);\n }\n log('waiting for cloud-init (Docker + repo clone)…');\n await sshExec(target, 'cloud-init status --wait || true', { timeoutMs: 12 * 60_000, onLine: log });\n const cloned = await sshExec(target, `test -d ${REMOTE_APP_DIR}`);\n if (cloned.exitCode !== 0) {\n throw new Error('repo clone did not complete on the VPS (cloud-init failed)');\n }\n\n // Stage the secret env + Caddy config locally, then scp them up.\n const staging = join(tmpdir(), `agentbox-cp-deploy-${stamp}`);\n await mkdir(staging, { recursive: true });\n try {\n const envLocal = join(staging, 'control-plane.env');\n const caddyLocal = join(staging, 'Caddyfile');\n const composeLocal = join(staging, 'docker-compose.caddy.yml');\n await writeFile(envLocal, opts.envContent, { mode: 0o600 });\n await writeFile(caddyLocal, caddyfile(domain));\n await writeFile(composeLocal, CADDY_COMPOSE);\n log('uploading env + Caddy config…');\n await scpUpload(target, envLocal, `${REMOTE_APP_DIR}/.env`);\n await scpUpload(target, caddyLocal, `${REMOTE_APP_DIR}/Caddyfile`);\n await scpUpload(target, composeLocal, `${REMOTE_APP_DIR}/docker-compose.caddy.yml`);\n } finally {\n await rm(staging, { recursive: true, force: true });\n }\n\n log('building + starting the control plane (docker compose up --build)…');\n const up = await sshExec(\n target,\n `cd ${REMOTE_APP_DIR} && docker compose -f docker-compose.yml -f docker-compose.caddy.yml up -d --build`,\n { timeoutMs: 25 * 60_000, onLine: log },\n );\n if (up.exitCode !== 0) {\n throw new Error(`docker compose up failed (exit ${String(up.exitCode)}): ${up.stderr || up.stdout}`);\n }\n\n log(`provisioned; waiting for HTTPS at ${url} …`);\n await pollHealthz(url, 3 * 60_000, log);\n\n const result: ControlPlaneHetznerDeployResult = {\n url,\n serverId: server.id,\n ip,\n domain,\n firewallId: firewall.id,\n sshKeyDir: keyDir,\n };\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,eAAe;AACxB,SAAS,eAAe;AEFxB,SAAS,iBAAiB;AAE1B,SAAS,WAAAA,gBAAe;AACxB,SAAS,WAAAC,gBAAe;AACxB;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;OACK;AIEP,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,SAAS,WAAAD,gBAA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AG,SAAS,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;EACpD;AAEA,EAAAM,KAAI,yEAAoE;AACxE,QAAM,KAAK,MAAM;IACf;IACA,MAAM,cAAc;IACpB,EAAE,WAAW,KAAK,KAAQ,QAAQA,KAAI;EACxC;AACA,MAAI,GAAG,aAAa,GAAG;AACrB,UAAM,IAAI,MAAM,kCAAkC,OAAO,GAAG,QAAQ,CAAC,MAAM,GAAG,UAAU,GAAG,MAAM,EAAE;EACrG;AAEA,EAAAA,KAAI,qCAAqC,GAAG,SAAI;AAChD,QAAM,YAAY,KAAK,IAAI,KAAQA,IAAG;AAEtC,QAAM,SAA0C;IAC9C;IACA,UAAU,OAAO;IACjB;IACA;IACA,YAAY,SAAS;IACrB,WAAW;EACb;AACA,SAAO;AACT;AV3LA,IAAM,gBAAgB,oBAAoB,gBAAgB;EACxD,kBAAkB,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG;AAClD,CAAC;AAEM,IAAM,kBAA4B;EACvC,GAAG;EACH,SAAS;EACT,iBAAiB,MAAM,kCAAkC;AAC3D;AAGO,IAAM,iBAAiC;EAC5C,UAAU;EACV,SAAS;EACT,mBAAmB;EACnB,gBAAgB;EAChB,gBAAgB;EAChB,4BAA4B,CAAC,kBAAkB,kCAAkC,aAAa;EAC9F;AACF;","names":["homedir","resolve","existsSync","opts","client","resolve","homedir","log","raceTimeout","existsSync","existsSync","join","dirname","resolve","mkdir","rm","homedir","join","resolve","dirname","client","log","UserFacingError","SNAPSHOT_DEADLINE_MS","existsSync"]}
|