@madarco/agentbox 0.28.1 → 0.29.0
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 +124 -0
- package/dist/_cloud-attach-HKRHYCY7.js +30 -0
- package/dist/{chunk-JNC7MCWJ.js → chunk-3INUZQTR.js} +10 -10
- package/dist/chunk-3INUZQTR.js.map +1 -0
- package/dist/{chunk-4PR3KJ5X.js → chunk-6PIGTR4D.js} +20 -20
- package/dist/{chunk-NHVGKFVY.js → chunk-7LNXTPEE.js} +340 -22
- package/dist/chunk-7LNXTPEE.js.map +1 -0
- package/dist/{chunk-WB6S4W7O.js → chunk-7Q6BG5AN.js} +2413 -1012
- package/dist/chunk-7Q6BG5AN.js.map +1 -0
- package/dist/{chunk-BUMKBUXS.js → chunk-7QU6XENE.js} +3 -3
- package/dist/chunk-BWE2I5QG.js +17 -0
- package/dist/chunk-BWE2I5QG.js.map +1 -0
- package/dist/{chunk-7ABO7OIF.js → chunk-CO2I3CQI.js} +4 -4
- package/dist/{chunk-OUF3YTQO.js → chunk-DBXCFLAR.js} +14 -17
- package/dist/chunk-DBXCFLAR.js.map +1 -0
- package/dist/{chunk-74VIUGY6.js → chunk-DYETLPUT.js} +6 -9
- package/dist/chunk-DYETLPUT.js.map +1 -0
- package/dist/{chunk-HYXCH4GA.js → chunk-EFVTQ7YB.js} +7 -7
- package/dist/{chunk-46NNZMZT.js → chunk-EPFXLXCW.js} +372 -72
- package/dist/chunk-EPFXLXCW.js.map +1 -0
- package/dist/chunk-GWKGSXDC.js +71 -0
- package/dist/chunk-GWKGSXDC.js.map +1 -0
- package/dist/{chunk-CKD3PRON.js → chunk-GWYD7YBK.js} +12 -9
- package/dist/{chunk-CKD3PRON.js.map → chunk-GWYD7YBK.js.map} +1 -1
- package/dist/{chunk-NHTRTST5.js → chunk-HNWZO2XU.js} +38 -15
- package/dist/chunk-HNWZO2XU.js.map +1 -0
- package/dist/{chunk-EVT2SNF2.js → chunk-HO2ACZES.js} +3 -3
- package/dist/{chunk-V5NWSLWD.js → chunk-HP4L45LW.js} +14 -14
- package/dist/{chunk-B4DAH2F2.js → chunk-LHOKRCNF.js} +3 -3
- package/dist/{chunk-G3H2L3O2.js → chunk-MNDKP4VS.js} +23 -3
- package/dist/chunk-MNDKP4VS.js.map +1 -0
- package/dist/{chunk-JDSYMTMS.js → chunk-NAT2H7J4.js} +110 -66
- package/dist/chunk-NAT2H7J4.js.map +1 -0
- package/dist/{chunk-KFLGXE3R.js → chunk-NGERWFSA.js} +133 -22
- package/dist/chunk-NGERWFSA.js.map +1 -0
- package/dist/{chunk-GFOWBXV7.js → chunk-OKLEPEWZ.js} +460 -253
- package/dist/chunk-OKLEPEWZ.js.map +1 -0
- package/dist/{chunk-YI4GHC2E.js → chunk-QU5BI2HC.js} +12 -15
- package/dist/chunk-QU5BI2HC.js.map +1 -0
- package/dist/{chunk-BWM56FKY.js → chunk-RQURMAPA.js} +11 -11
- package/dist/{chunk-FPMRFMVK.js → chunk-RZCLRWNY.js} +9 -9
- package/dist/{chunk-JQLOGVZK.js → chunk-THUST2QK.js} +85 -21
- package/dist/chunk-THUST2QK.js.map +1 -0
- package/dist/{chunk-OXKW4GWD.js → chunk-UPVP6YGJ.js} +4 -70
- package/dist/chunk-UPVP6YGJ.js.map +1 -0
- package/dist/{chunk-7RSE7ESY.js → chunk-VVNXQ4XS.js} +27 -18
- package/dist/chunk-VVNXQ4XS.js.map +1 -0
- package/dist/{chunk-FGQFVUMH.js → chunk-VY54AX4T.js} +3 -3
- package/dist/{chunk-OUWVN2F2.js → chunk-WGNI24H2.js} +16 -13
- package/dist/chunk-WGNI24H2.js.map +1 -0
- package/dist/{chunk-PSA6GADQ.js → chunk-WHFCJBMO.js} +14 -1
- package/dist/chunk-WHFCJBMO.js.map +1 -0
- package/dist/{chunk-KJ5TCYNI.js → chunk-WHJYOO5H.js} +7 -6
- package/dist/chunk-WHJYOO5H.js.map +1 -0
- package/dist/cloud-backends.js +5 -5
- package/dist/{cloud-poller-SUNA6ZQC-7M5LJHHE.js → cloud-poller-QJRZXB4W-LJ2BRB3L.js} +2 -2
- package/dist/{control-plane-5R7PYRQ6.js → control-plane-UKKYXHIQ.js} +19 -18
- package/dist/cp-hub-upload-BM2OLTOS.js +81 -0
- package/dist/cp-hub-upload-BM2OLTOS.js.map +1 -0
- package/dist/{custody-client-PNCC2HBJ.js → custody-client-NPXJ46TB.js} +5 -4
- package/dist/{deploy-hetzner-SSGSXAKA.js → deploy-hetzner-Y3ILCDRF.js} +10 -10
- package/dist/{dist-RN6JOAG4.js → dist-5OGQ3CJQ.js} +81 -45
- package/dist/{dist-5OR4QTQW.js → dist-7B3VCLZI.js} +9 -9
- package/dist/{dist-EPFS5PRI.js → dist-A5ZEIVAW.js} +10 -10
- package/dist/{dist-6PYXFREL.js → dist-DOEGENNW.js} +61 -16
- package/dist/dist-DOEGENNW.js.map +1 -0
- package/dist/{dist-XQLKK7H3.js → dist-EOGD7KD6.js} +54 -28
- package/dist/dist-EOGD7KD6.js.map +1 -0
- package/dist/{dist-XATN4ZIR.js → dist-FBM2WS5S.js} +22 -4
- package/dist/{dist-POILUDVJ.js → dist-MUTFY7FA.js} +9 -9
- package/dist/{dist-ZNQZHTUN.js → dist-SMDXLPZO.js} +35 -6
- package/dist/{dist-M4O5MU5K.js → dist-VTLQKZ2E.js} +8 -8
- package/dist/{dist-SN2TCRZ5.js → dist-ZJIJHCZB.js} +9 -9
- package/dist/{dist-K5M4HKG7.js → dist-ZNYS7CVF.js} +21 -9
- package/dist/host-reach-drainer-ZJU2STQQ.js +9 -0
- package/dist/hub-Q4VOF4WN.js +37 -0
- package/dist/{hub-adopt-I44VGSBL.js → hub-adopt-OA336ZXZ.js} +8 -8
- package/dist/{hub-api-client-WJPBXZAZ.js → hub-api-client-5U6WOTZ3.js} +2 -2
- package/dist/{hub-docker-target-REEEWUG2.js → hub-docker-target-JKFCABK4.js} +16 -16
- package/dist/index.js +1321 -882
- package/dist/index.js.map +1 -1
- package/dist/prepare-GFWWKWGF.js +41 -0
- package/dist/prepared-custody-KU4PDVBT.js +36 -0
- package/dist/{prepared-state-PV3GUBHO-MF56HWMZ.js → prepared-state-LNQ7DYSU-AR5RMXAO.js} +4 -3
- package/dist/{publish-credentials-BPHUO5VL.js → publish-credentials-3SQXX45P.js} +11 -11
- package/dist/registry-AFKV3EO2.js +18 -0
- package/dist/relay-QH6OEY2V.js +20 -0
- package/dist/relay-QH6OEY2V.js.map +1 -0
- package/dist/{remote-docker-share-RX5ARK45.js → remote-docker-share-RMS6IB5X.js} +11 -11
- package/dist/remote-docker-share-RMS6IB5X.js.map +1 -0
- package/dist/tool-grant-push-T6DRBY3W.js +90 -0
- package/dist/tool-grant-push-T6DRBY3W.js.map +1 -0
- package/package.json +1 -2
- package/runtime/_shared/agentbox-tool-shim +21 -0
- package/runtime/_shared/ctl.cjs +6757 -5299
- package/runtime/_shared/gh-shim +103 -228
- package/runtime/digitalocean/agentbox-tool-shim +21 -0
- package/runtime/digitalocean/ctl.cjs +6757 -5299
- package/runtime/digitalocean/gh-shim +103 -228
- package/runtime/digitalocean/scripts/install-box.sh +9 -15
- package/runtime/docker/Dockerfile.box +8 -18
- package/runtime/docker/packages/ctl/dist/bin.cjs +6757 -5299
- package/runtime/docker/packages/sandbox-docker/scripts/agentbox-tool-shim +21 -0
- package/runtime/docker/packages/sandbox-docker/scripts/gh-shim +103 -228
- package/runtime/e2b/agentbox-tool-shim +21 -0
- package/runtime/e2b/ctl.cjs +6757 -5299
- package/runtime/e2b/gh-shim +103 -228
- package/runtime/e2b/scripts/build-template.sh +5 -9
- package/runtime/hetzner/agentbox-tool-shim +21 -0
- package/runtime/hetzner/ctl.cjs +6757 -5299
- package/runtime/hetzner/gh-shim +103 -228
- package/runtime/hetzner/scripts/install-box.sh +9 -15
- package/runtime/hub/apps/hub/.next/BUILD_ID +1 -1
- package/runtime/hub/apps/hub/.next/app-path-routes-manifest.json +2 -0
- package/runtime/hub/apps/hub/.next/build-manifest.json +3 -3
- package/runtime/hub/apps/hub/.next/routes-manifest.json +16 -0
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js +5 -5
- package/runtime/hub/apps/hub/.next/server/app/(auth)/api/auth/[...all]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/[id]/answer/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/approvals/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/[action]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/agent/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/agent/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/branches/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/checkpoint/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/[op]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/git/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/logs/route.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/logs/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/open/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/rename/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/restart/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/services/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/[id]/vnc/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/boxes/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/checkpoints/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/checkpoints/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/[...path]/route.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/[...path]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/blob/[...path]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/custody/blob/[...path]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/health/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/bake/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/[alias]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/hosts/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/login-code/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/logs/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/[id]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/jobs/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/open-targets/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/branches/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/seed/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/[id]/seed/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/projects/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/credentials/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/[id]/prepare/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/providers/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/prune/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/system/route.js +2 -2
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/api/v1/system/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/approvals/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/page.js +1 -1
- 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)/boxes/[id]/vnc/route/app-paths-manifest.json +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route/build-manifest.json +9 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route/server-reference-manifest.json +4 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js +8 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js.map +5 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route.js.nft.json +1 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/boxes/[id]/vnc/route_client-reference-manifest.js +3 -0
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/custody/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/projects/[id]/page.js +1 -1
- 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)/settings/page.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/(dashboard)/system/page.js +1 -1
- package/runtime/hub/apps/hub/.next/server/app/(dashboard)/system/page.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js +4 -4
- package/runtime/hub/apps/hub/.next/server/app/[...path]/route.js.nft.json +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.html +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/runtime/hub/apps/hub/.next/server/app-paths-manifest.json +2 -0
- package/runtime/hub/apps/hub/.next/server/chunks/044u_hub__next-internal_server_app_(dashboard)_boxes_[id]_vnc_route_actions_1cy1392.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/1jcg_server_app_(dashboard)_api_v1_boxes_[id]_vnc_route_actions_10y_e83.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/{[externals]__1nj4awx._.js → [externals]__02a249v._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__00f9v4p._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__01nppdu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__02f8rwr._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__068_052._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__06ma5m4._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__07kp2fu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1yi-2wa._.js → [root-of-the-server]__08u01ud._.js} +3 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__098bkh3._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1hxo1tv._.js → [root-of-the-server]__09hbkgm._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__09tmbom._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0_3m9sf._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0aotdzg._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0bn6-pu._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0cpt9f9._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0d1lmiq._.js +15 -15
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0dom248._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0f0bb7o._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0gb04bp._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0glplq7._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0xrdbh9._.js → [root-of-the-server]__0gxfyol._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0hsb2ak._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0joqm8t._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0jp-895._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1leda2s._.js → [root-of-the-server]__0jpqg_t._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__17bhgkz._.js → [root-of-the-server]__0lgnu00._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0lsv9-6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0pzgufc._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qfv7z6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0qlr61y._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0s8srqi._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0urn9j5._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0vb8mk2._.js +4 -0
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__17w5eaa._.js → [root-of-the-server]__0x27ifo._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0y7rvy1._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0zsgjre._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1-bqa8a._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__11uspjg._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0zvr6ul._.js → [root-of-the-server]__15tgdh6._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1ek7nxv._.js → [root-of-the-server]__16bz_kz._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1w7jw4q._.js → [root-of-the-server]__18tehjj._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1ds8g0e._.js → [root-of-the-server]__1_hzv4s._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0cgpsh8._.js → [root-of-the-server]__1b5f5h4._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__10-aihp._.js → [root-of-the-server]__1dv80yf._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1eanlxn._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__16lcb2d._.js → [root-of-the-server]__1fc-nvn._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1h4iahl._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0f-c-eh._.js → [root-of-the-server]__1j0vnh3._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1lgrtx6._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1unqgd7._.js → [root-of-the-server]__1lz7931._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1oclxlx._.js → [root-of-the-server]__1n3u6-5._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1qky5cd._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1r2quye._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1rb_nc5._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0cv16py._.js → [root-of-the-server]__1spr8ss._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1t_juqb._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0t8kwy3._.js → [root-of-the-server]__1tct9rj._.js} +3 -3
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0gfa1jg._.js → [root-of-the-server]__1tjtt06._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__09cigc7._.js → [root-of-the-server]__1whjno0._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1wn4-iv._.js +3 -0
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__1x6zxrf._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__0tyixgg._.js → [root-of-the-server]__1xfxc6i._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/{[root-of-the-server]__1m1_gm_._.js → [root-of-the-server]__1xqcvi4._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__207d30i._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_07icdxf._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0907rw0._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0adm87k._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0g01mkg._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0l_klgd._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0lfm81x._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0tbg83f._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0tms_au._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_0zhli27._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_10yfoq5._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_12uhpbp._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_17a9v8y._.js +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/_1c7x9ee._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_1n-c443._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_1y80vfg._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/_214_q-1._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/apps_hub_app_(dashboard)_api_v1_lib_openapi_ts_1yokmzt._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/{packages_relay_dist_0eg7ay1._.js → packages_relay_dist_0p8dnf4._.js} +4 -4
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/{[root-of-the-server]__1plrs94._.js → [root-of-the-server]__0-c5j6l._.js} +2 -2
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_0r2xlss._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/_19vy9ni._.js +2 -2
- 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)_settings_page_tsx_0hv6n82._.js +1 -1
- package/runtime/hub/apps/hub/.next/server/chunks/ssr/{packages_relay_dist_1z9j3g0._.js → packages_relay_dist_0sap-2l._.js} +4 -4
- package/runtime/hub/apps/hub/.next/server/functions-config-manifest.json +3 -1
- package/runtime/hub/apps/hub/.next/server/middleware-build-manifest.js +3 -3
- package/runtime/hub/apps/hub/.next/server/middleware.js +1 -1
- package/runtime/hub/apps/hub/.next/server/pages/500.html +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/{328ny-3zs_h7m.js → 0jefm3re1-2jv.js} +1 -1
- package/runtime/hub/apps/hub/.next/static/chunks/{30h8mz040b5-l.js → 3u4odx1_-dy6b.js} +1 -1
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/boxes/[id]/vnc/route.ts +45 -0
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/openapi.ts +45 -1
- package/runtime/hub/apps/hub/app/(dashboard)/api/v1/lib/validate.ts +14 -3
- package/runtime/hub/apps/hub/app/(dashboard)/boxes/[id]/vnc/route.ts +58 -0
- package/runtime/hub/apps/hub/app/(dashboard)/boxes/components/access.tsx +26 -9
- package/runtime/hub/apps/hub/app/(dashboard)/settings/components/provider-actions.tsx +34 -26
- package/runtime/hub/apps/hub/{auth-JMVHQKWY.js → auth-V7KPRWPS.js} +2 -2
- package/runtime/hub/apps/hub/{auth-config-5IFRWOK4.js → auth-config-B3Y3BT2I.js} +2 -2
- package/runtime/hub/apps/hub/{chunk-VKOCY6SX.js → chunk-3AD3MYNV.js} +49 -14
- package/runtime/hub/apps/hub/{chunk-KTVETF3F.js → chunk-3ZDBZYOY.js} +11 -8
- package/runtime/hub/apps/hub/{chunk-LPYK2354.js → chunk-5ABFGGPT.js} +339 -21
- package/runtime/hub/apps/hub/{chunk-UMPTTQBE.js → chunk-GBYD2ODL.js} +458 -251
- package/runtime/hub/apps/hub/{chunk-5TM7XXLT.js → chunk-H5SUXDZA.js} +2833 -1277
- package/runtime/hub/apps/hub/{chunk-QU3FFGJY.js → chunk-UQ5XNPOF.js} +11 -14
- package/runtime/hub/apps/hub/{chunk-3LAHFDJF.js → chunk-VWQNSZGI.js} +22 -2
- package/runtime/hub/apps/hub/{chunk-EZUK53CC.js → chunk-WHGY7HOC.js} +85 -21
- package/runtime/hub/apps/hub/{chunk-D33EV4YZ.js → chunk-ZP4RYI4U.js} +1 -1
- package/runtime/hub/apps/hub/{cloud-poller-SUNA6ZQC-VSKVMYHL.js → cloud-poller-QJRZXB4W-G7ECKNKQ.js} +1 -1
- package/runtime/hub/apps/hub/{dist-ELZHBQEM.js → dist-37EKQ6RZ.js} +11 -11
- package/runtime/hub/apps/hub/{dist-D265LCAN.js → dist-CGH7PEMZ.js} +21 -3
- package/runtime/hub/apps/hub/{dist-SYWTB6RD.js → dist-CMVSARW5.js} +15 -18
- package/runtime/hub/apps/hub/{dist-5HTJSOHS.js → dist-EGXZRZH2.js} +19 -7
- package/runtime/hub/apps/hub/{dist-YK5FFPXZ.js → dist-EOGGFZZS.js} +62 -20
- package/runtime/hub/apps/hub/{dist-E2FTSTCY.js → dist-LJBHOO3K.js} +34 -5
- package/runtime/hub/apps/hub/{dist-N3E5YAYY.js → dist-R77W6WJ5.js} +53 -26
- package/runtime/hub/apps/hub/{dist-JVEDVVVG.js → dist-TH2JZYZY.js} +7 -7
- package/runtime/hub/apps/hub/{dist-2YP57GMB.js → dist-XPRGHQH2.js} +13 -13
- package/runtime/hub/apps/hub/{dist-NKCXH5DW.js → dist-Z2Y5F7AF.js} +6 -6
- package/runtime/hub/apps/hub/docker-compose.yml +1 -0
- package/runtime/hub/apps/hub/{hub-token-MDOBY7MZ.js → hub-token-DDJ5Z6RS.js} +2 -2
- package/runtime/hub/apps/hub/{hub-worker-UFFLF37F.js → hub-worker-DXVMUQWF.js} +16 -16
- package/runtime/hub/apps/hub/lib/boxes/backend-types.ts +11 -0
- package/runtime/hub/apps/hub/lib/boxes/types.ts +43 -0
- package/runtime/hub/apps/hub/lib/boxes/vnc-link.ts +51 -0
- package/runtime/hub/apps/hub/lib/hub-backend.ts +127 -54
- package/runtime/hub/apps/hub/lib/hub-worker.ts +4 -4
- package/runtime/hub/apps/hub/lib/provider-importers.ts +66 -1
- package/runtime/hub/apps/hub/{prepared-state-PV3GUBHO-PPRQDYFR.js → prepared-state-LNQ7DYSU-ABC2EQVI.js} +3 -2
- package/runtime/hub/apps/hub/server.js +130 -72
- package/runtime/hub/apps/hub/server.ts +18 -0
- package/runtime/hub/apps/hub/test/vnc-link.test.ts +61 -0
- package/runtime/hub/apps/hub/tsconfig.tsbuildinfo +1 -1
- package/runtime/hub-deploy/docker-compose.yml +1 -0
- package/runtime/relay/bin.cjs +16623 -14688
- package/runtime/vercel/agentbox-tool-shim +21 -0
- package/runtime/vercel/ctl.cjs +6757 -5299
- package/runtime/vercel/gh-shim +103 -228
- package/runtime/vercel/scripts/provision.sh +5 -9
- package/share/host-skills/agentbox-info/SKILL.md +24 -14
- package/dist/_cloud-attach-Y5HIQ373.js +0 -28
- package/dist/chunk-46NNZMZT.js.map +0 -1
- package/dist/chunk-74VIUGY6.js.map +0 -1
- package/dist/chunk-7RSE7ESY.js.map +0 -1
- package/dist/chunk-G3H2L3O2.js.map +0 -1
- package/dist/chunk-GFOWBXV7.js.map +0 -1
- package/dist/chunk-JDSYMTMS.js.map +0 -1
- package/dist/chunk-JNC7MCWJ.js.map +0 -1
- package/dist/chunk-JQLOGVZK.js.map +0 -1
- package/dist/chunk-KFLGXE3R.js.map +0 -1
- package/dist/chunk-KJ5TCYNI.js.map +0 -1
- package/dist/chunk-NHTRTST5.js.map +0 -1
- package/dist/chunk-NHVGKFVY.js.map +0 -1
- package/dist/chunk-OUF3YTQO.js.map +0 -1
- package/dist/chunk-OUWVN2F2.js.map +0 -1
- package/dist/chunk-OXKW4GWD.js.map +0 -1
- package/dist/chunk-PSA6GADQ.js.map +0 -1
- package/dist/chunk-WB6S4W7O.js.map +0 -1
- package/dist/chunk-YI4GHC2E.js.map +0 -1
- package/dist/dist-6PYXFREL.js.map +0 -1
- package/dist/dist-XQLKK7H3.js.map +0 -1
- package/dist/hub-MJ7O4WXW.js +0 -36
- package/dist/prepare-V4U5HVJU.js +0 -40
- package/dist/prepared-custody-QIXW7MJM.js +0 -35
- package/dist/relay-DRDELF6B.js +0 -20
- package/runtime/_shared/linear-shim +0 -181
- package/runtime/_shared/ntn-shim +0 -95
- package/runtime/digitalocean/linear-shim +0 -181
- package/runtime/digitalocean/ntn-shim +0 -95
- package/runtime/docker/packages/sandbox-docker/scripts/linear-shim +0 -181
- package/runtime/docker/packages/sandbox-docker/scripts/ntn-shim +0 -95
- package/runtime/e2b/linear-shim +0 -181
- package/runtime/e2b/ntn-shim +0 -95
- package/runtime/hetzner/linear-shim +0 -181
- package/runtime/hetzner/ntn-shim +0 -95
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__039tc0m._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0c_3x8u._.js +0 -3
- package/runtime/hub/apps/hub/.next/server/chunks/[root-of-the-server]__0ty7ew1._.js +0 -3
- package/runtime/vercel/linear-shim +0 -181
- package/runtime/vercel/ntn-shim +0 -95
- /package/dist/{_cloud-attach-Y5HIQ373.js.map → _cloud-attach-HKRHYCY7.js.map} +0 -0
- /package/dist/{chunk-4PR3KJ5X.js.map → chunk-6PIGTR4D.js.map} +0 -0
- /package/dist/{chunk-BUMKBUXS.js.map → chunk-7QU6XENE.js.map} +0 -0
- /package/dist/{chunk-7ABO7OIF.js.map → chunk-CO2I3CQI.js.map} +0 -0
- /package/dist/{chunk-HYXCH4GA.js.map → chunk-EFVTQ7YB.js.map} +0 -0
- /package/dist/{chunk-EVT2SNF2.js.map → chunk-HO2ACZES.js.map} +0 -0
- /package/dist/{chunk-V5NWSLWD.js.map → chunk-HP4L45LW.js.map} +0 -0
- /package/dist/{chunk-B4DAH2F2.js.map → chunk-LHOKRCNF.js.map} +0 -0
- /package/dist/{chunk-BWM56FKY.js.map → chunk-RQURMAPA.js.map} +0 -0
- /package/dist/{chunk-FPMRFMVK.js.map → chunk-RZCLRWNY.js.map} +0 -0
- /package/dist/{chunk-FGQFVUMH.js.map → chunk-VY54AX4T.js.map} +0 -0
- /package/dist/{cloud-poller-SUNA6ZQC-7M5LJHHE.js.map → cloud-poller-QJRZXB4W-LJ2BRB3L.js.map} +0 -0
- /package/dist/{control-plane-5R7PYRQ6.js.map → control-plane-UKKYXHIQ.js.map} +0 -0
- /package/dist/{custody-client-PNCC2HBJ.js.map → custody-client-NPXJ46TB.js.map} +0 -0
- /package/dist/{deploy-hetzner-SSGSXAKA.js.map → deploy-hetzner-Y3ILCDRF.js.map} +0 -0
- /package/dist/{dist-5OR4QTQW.js.map → dist-5OGQ3CJQ.js.map} +0 -0
- /package/dist/{dist-EPFS5PRI.js.map → dist-7B3VCLZI.js.map} +0 -0
- /package/dist/{dist-K5M4HKG7.js.map → dist-A5ZEIVAW.js.map} +0 -0
- /package/dist/{dist-M4O5MU5K.js.map → dist-FBM2WS5S.js.map} +0 -0
- /package/dist/{dist-POILUDVJ.js.map → dist-MUTFY7FA.js.map} +0 -0
- /package/dist/{dist-RN6JOAG4.js.map → dist-SMDXLPZO.js.map} +0 -0
- /package/dist/{dist-SN2TCRZ5.js.map → dist-VTLQKZ2E.js.map} +0 -0
- /package/dist/{dist-XATN4ZIR.js.map → dist-ZJIJHCZB.js.map} +0 -0
- /package/dist/{dist-ZNQZHTUN.js.map → dist-ZNYS7CVF.js.map} +0 -0
- /package/dist/{hub-MJ7O4WXW.js.map → host-reach-drainer-ZJU2STQQ.js.map} +0 -0
- /package/dist/{hub-adopt-I44VGSBL.js.map → hub-Q4VOF4WN.js.map} +0 -0
- /package/dist/{hub-api-client-WJPBXZAZ.js.map → hub-adopt-OA336ZXZ.js.map} +0 -0
- /package/dist/{prepare-V4U5HVJU.js.map → hub-api-client-5U6WOTZ3.js.map} +0 -0
- /package/dist/{hub-docker-target-REEEWUG2.js.map → hub-docker-target-JKFCABK4.js.map} +0 -0
- /package/dist/{prepared-custody-QIXW7MJM.js.map → prepare-GFWWKWGF.js.map} +0 -0
- /package/dist/{prepared-state-PV3GUBHO-MF56HWMZ.js.map → prepared-custody-KU4PDVBT.js.map} +0 -0
- /package/dist/{relay-DRDELF6B.js.map → prepared-state-LNQ7DYSU-AR5RMXAO.js.map} +0 -0
- /package/dist/{publish-credentials-BPHUO5VL.js.map → publish-credentials-3SQXX45P.js.map} +0 -0
- /package/dist/{remote-docker-share-RX5ARK45.js.map → registry-AFKV3EO2.js.map} +0 -0
- /package/runtime/hub/apps/hub/.next/static/{z7_2bKU93xE7GwllL1Duv → XIx10ozuCZRzwSsiCF_5t}/_buildManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{z7_2bKU93xE7GwllL1Duv → XIx10ozuCZRzwSsiCF_5t}/_clientMiddlewareManifest.js +0 -0
- /package/runtime/hub/apps/hub/.next/static/{z7_2bKU93xE7GwllL1Duv → XIx10ozuCZRzwSsiCF_5t}/_ssgManifest.js +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../packages/relay/src/types.ts","../../../packages/relay/src/registry.ts","../../../packages/relay/src/status-store.ts","../../../packages/relay/src/store/memory-store.ts","../../../packages/relay/src/prompts.ts","../../../packages/relay/src/permission.ts","../../../packages/relay/src/worktree.ts","../../../packages/relay/src/git-pat.ts","../../../packages/relay/src/lease.ts","../../../packages/relay/src/store/store-rpc.ts","../../../packages/relay/src/store/store-rpc-routes.ts","../../../packages/relay/src/custody/store.ts","../../../packages/relay/src/custody/routes.ts","../../../packages/relay/src/remote-boxes.ts","../../../packages/relay/src/store/write-through-store.ts","../../../packages/relay/src/github-app.ts","../../../packages/relay/src/queue.ts","../../../packages/relay/src/create-worker.ts","../../../packages/relay/src/core/handler.ts","../../../packages/relay/src/store/schema.ts","../../../packages/relay/src/store/postgres-store.ts","../../../packages/relay/src/store/sqlite-store.ts","../../../packages/relay/src/store/index.ts","../../../packages/relay/src/custody/fs-store.ts","../../../packages/relay/src/server.ts","../../../packages/relay/src/host-actions.ts","../../../packages/relay/src/gh.ts","../../../packages/relay/src/host-initiated.ts","../../../packages/relay/src/cp-rpc.ts","../../../packages/relay/src/integrations.ts","../../../packages/relay/src/safe-transfer.ts","../../../packages/relay/src/host-action-queue.ts","../../../packages/relay/src/hub-notifier.ts","../../../packages/relay/src/notices.ts","../../../packages/relay/src/admin-gate.ts","../../../packages/relay/src/job-log-tail.ts","../../../packages/relay/src/credentials-fanout.ts","../../../packages/relay/src/autopause.ts","../../../packages/relay/src/cloud-keepalive.ts","../../../packages/relay/src/retention.ts","../../../packages/relay/src/daemon.ts","../../../packages/integrations/src/connectors/linear.ts","../../../packages/integrations/src/connectors/notion.ts","../../../packages/integrations/src/registry.ts","../../../packages/relay/src/registration-to-record.ts","../../../packages/relay/src/store/remote-store.ts"],"sourcesContent":["// DownloadKind's canonical decision home is `@agentbox/core`'s sync/files.ts;\n// imported here so DownloadRpcParams below can reference it, re-exported below\n// so existing `./types.js` importers stay unchanged.\nimport type { DownloadKind } from '@agentbox/core';\n\nexport const DEFAULT_RELAY_PORT = 8787;\n/**\n * In-box relay port — distinct from {@link DEFAULT_RELAY_PORT} so a nested\n * agentbox run (developing agentbox inside a box) can bind its own host\n * relay on 8787 inside the outer box without colliding with the in-box\n * supervisor's relay. ctl always binds this port — as a real `mode: 'box'`\n * relay in cloud sandboxes, or a transparent forwarder to the host relay in\n * docker boxes. Override with `AGENTBOX_BOX_RELAY_PORT`.\n */\nexport const DEFAULT_BOX_RELAY_PORT = 8788;\nexport const RELAY_CONTAINER_NAME = 'agentbox-relay';\nexport const RELAY_NETWORK_NAME = 'agentbox-net';\nexport const RELAY_IMAGE_REF = 'agentbox/relay:dev';\nexport const RELAY_EVENT_RING_SIZE = 1000;\n\nexport type BoxKind = 'docker' | 'cloud';\n\nexport interface BoxRegistration {\n boxId: string;\n token: string;\n name: string;\n /** ISO-8601 time the relay received this registration. */\n registeredAt: string;\n /**\n * Which sandbox backend the box runs on. Drives whether the host relay\n * spawns a `CloudBoxPoller` for it. Absent on legacy registrations →\n * treated as 'docker'.\n */\n kind?: BoxKind;\n /**\n * For `kind === 'cloud'`: which cloud backend the executor must resolve\n * (e.g. 'daytona'). The host action executor lazy-imports\n * `@agentbox/sandbox-{backend}` to drive the in-sandbox channel.\n */\n backend?: string;\n /**\n * For `kind === 'cloud'`: the provider-native sandbox id (e.g. the Hetzner\n * server id). The per-box SSH key material lives on disk keyed by this id\n * (`~/.agentbox/boxes/<sandboxId>/ssh/`), so a PC that adopts a hub-created\n * box (`agentbox hub pull`) writes the downloaded keys under the same id, and\n * a reap can locate the box's custody `boxes/<sandboxId>/` subtree. Absent for\n * providers that mint no keypair (e2b/vercel) and legacy registrations.\n */\n sandboxId?: string;\n /** Docker container name; the relay needs it to `docker pause` an idle box. */\n containerName?: string;\n /** ISO-8601 box-creation time (BoxRecord.createdAt); used as a tie-break in auto-pause ordering. */\n createdAt?: string;\n /**\n * 1-based per-project box index (`agentbox list`'s `N` column). When set,\n * the relay writes status.json under `~/.agentbox/boxes/<id>-<n>-<mnemonic>/`\n * to match the host's `boxDirSegment` helper. Absent for legacy\n * (pre-feature) boxes; absent registrations fall back to `<id>-<mnemonic>`.\n */\n projectIndex?: number;\n /**\n * Container-path → host-worktree-dir mapping the host uses to resolve\n * git.pull/git.push RPCs. Empty when the box has no git repos.\n */\n worktrees?: BoxWorktree[];\n /**\n * Preview URL of the in-sandbox relay's `/bridge/*` surface. Set by cloud\n * registrations; the host's `CloudBoxPoller` long-polls it for status +\n * queued host-only RPCs.\n */\n previewUrl?: string;\n /**\n * Provider-proxy token for `previewUrl` (e.g. Daytona's\n * `x-daytona-preview-token`). The host poller attaches it as a header so\n * Daytona's preview proxy lets the request reach the in-sandbox relay.\n */\n previewToken?: string;\n /**\n * Bearer secret authenticating the host poller to `/bridge/*` on the\n * in-sandbox relay. Distinct from `token` (which the in-box agent sees)\n * so a compromised agent can't impersonate the host.\n */\n bridgeToken?: string;\n /**\n * When true, host-action confirm prompts for this box (git push, cp,\n * gh writes, checkpoint, browser.open) resolve to `y` without a human/orchestrator\n * answering. Set at registration from `box.autoApproveHostActions`. Off by\n * default; every auto-approval still emits a `host-action-auto-approved`\n * relay event so the bypass is auditable.\n */\n autoApproveHostActions?: boolean;\n /**\n * Mirrors `box.autoApproveSafeHostActions` (default true). When not `false`,\n * the SAFE subset of host actions (open PR, PR/review comments,\n * sanctioned-branch push, contained non-secret file copy/download, CI rerun,\n * checkpoint, integration writes) auto-resolves without a prompt — each\n * still emits a `host-action-auto-approved` event. Absent → enabled.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * The box repo's origin remote URL (any git URL shape). The hosted control\n * plane resolves owner/repo from THIS registered value when leasing a\n * GitHub-App token (never from box-supplied RPC params). Absent for boxes\n * without a git origin.\n */\n originUrl?: string;\n /**\n * Public IP/host of the box's VM for direct-SSH providers (hetzner,\n * digitalocean). Lets a PC adopting this box (`agentbox hub adopt`)\n * reconstruct the `BoxRecord.ssh` target without asking the provider API.\n * Absent for SDK-reached providers (e2b/vercel/daytona) and legacy rows.\n */\n publicHost?: string;\n /** Resolved image/snapshot ref the box booted from (mirrors `CloudBoxFields.image`). */\n image?: string;\n /** In-box WebProxy port (mirrors `CloudBoxFields.webPort`), for `url` reconstruction. */\n webPort?: number;\n /** Agent the box was created for ('claude' | 'codex' | 'opencode') → `BoxRecord.lastAgent`. */\n agent?: string;\n /**\n * Custody `projects/<slug>` key of the box's project (owner__repo). Links a\n * registration to its seed material and secrets without re-deriving the slug\n * from `originUrl` on every consumer.\n */\n projectSlug?: string;\n}\n\nexport interface BoxWorktree {\n /** Path inside the container (e.g. /workspace, /workspace/app). */\n containerPath: string;\n /**\n * Absolute host path of the main repo whose `.git/` is shared with the\n * container. `git push/fetch` RPCs run with `git -C <hostMainRepo>` — the\n * worktree's working tree lives inside the container's writable layer, but\n * refs/objects are in this shared `.git/`, so push from the main repo dir\n * sees the in-container commits.\n */\n hostMainRepo: string;\n /** Branch the in-container worktree was created on (`agentbox/<box-name>`). */\n branch: string;\n /**\n * Last branch the HOST sanctioned for this box (create-time `branch`, updated\n * by host `agentbox git checkout`/`branch`/`pull <branch>`). The push gate\n * auto-approves only a scratch branch or this value; absent → treated as\n * `branch`.\n */\n sanctionedBranch?: string;\n}\n\nexport interface RelayEvent {\n /** Monotonic per-relay-process id, useful for `since=` polling. */\n id: number;\n /** Box id that posted the event. */\n boxId: string;\n /** Free-form event type, e.g. 'service-state', 'task-state', 'notify'. */\n type: string;\n /** ISO-8601 timestamp the relay assigned on receipt. */\n receivedAt: string;\n /** ISO-8601 client-supplied timestamp, if any. */\n ts?: string;\n /** Arbitrary JSON payload. */\n payload?: unknown;\n}\n\nexport interface PostEventBody {\n type: string;\n ts?: string;\n payload?: unknown;\n}\n\nexport interface PostRpcBody {\n method: string;\n params?: unknown;\n}\n\nexport interface RegisterBoxBody {\n boxId: string;\n token: string;\n name: string;\n /** Sandbox backend kind. Defaults to 'docker' when absent (legacy). */\n kind?: BoxKind;\n /** For cloud boxes: which backend (e.g. 'daytona'). Drives executor lazy-import. */\n backend?: string;\n /** For cloud boxes: provider-native sandbox id (SSH-key + custody dir key). */\n sandboxId?: string;\n containerName?: string;\n createdAt?: string;\n /**\n * 1-based per-project box index. Optional — additive; older boxes and\n * legacy (pre-feature) records register without it and the status path\n * falls back to `<id>-<mnemonic>`.\n */\n projectIndex?: number;\n worktrees?: BoxWorktree[];\n /** Required when `kind === 'cloud'`: in-sandbox relay's /bridge URL. */\n previewUrl?: string;\n /** When the cloud provider's proxy needs a token (Daytona) — attached as a header. */\n previewToken?: string;\n /** Required when `kind === 'cloud'`: bearer for /bridge/* auth. */\n bridgeToken?: string;\n /**\n * Mirrors `box.autoApproveHostActions`: when true, host-action confirm\n * prompts auto-resolve to `y` (audited via a relay event).\n */\n autoApproveHostActions?: boolean;\n /** Mirrors `box.autoApproveSafeHostActions` (default true; absent → enabled). */\n autoApproveSafeHostActions?: boolean;\n /** The box repo's origin remote URL (for GitHub-App lease repo resolution). */\n originUrl?: string;\n /** Public VM IP/host for direct-SSH providers (PC adoption). */\n publicHost?: string;\n /** Resolved image/snapshot ref the box booted from. */\n image?: string;\n /** In-box WebProxy port. */\n webPort?: number;\n /** Agent the box was created for. */\n agent?: string;\n /** Custody `projects/<slug>` key of the box's project. */\n projectSlug?: string;\n}\n\n/**\n * A host-only RPC the in-sandbox relay (box mode) parked while waiting for\n * the host poller to drain, execute on the host, and post back a result.\n * Equivalent of an in-flight `/rpc` call queued through the bridge.\n */\nexport interface HostAction {\n /** Server-generated uuid; the host poller echoes it back in the result. */\n id: string;\n /** Box that initiated the in-sandbox `/rpc`. */\n boxId: string;\n /** Original `/rpc` method (e.g. 'git.push', 'cp.toHost'). */\n method: string;\n /** Original `/rpc` params payload, opaque to the queue. */\n params: unknown;\n /** ISO-8601 enqueue time. */\n createdAt: string;\n}\n\nexport interface HostActionResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Response shape for `GET /bridge/poll`. */\nexport interface BridgePollResponse {\n /** Newly-queued host actions the poller hasn't drained yet. */\n actions: HostAction[];\n /** Events appended since `?since=<id>`. */\n events: RelayEvent[];\n /** Latest box-status snapshot, when one has been pushed. */\n status: unknown | null;\n /** Highest event id seen — the poller's next `?since=`. */\n cursor: number;\n}\n\n/** Body of `POST /bridge/action-result`. */\nexport interface BridgeActionResultBody {\n id: string;\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n// GitRpcParams's canonical wire-type home is `@agentbox/core`'s sync/git-refs.ts\n// (shared with the in-box ctl); re-exported here so `./types.js` importers stay unchanged.\nexport type { GitRpcParams } from '@agentbox/core';\n\nexport interface GitRpcResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface CheckpointRpcParams {\n /** Checkpoint name; defaults host-side to `<box-name>-<next>`. */\n name?: string;\n /** Flatten lower+upper into one tree instead of a layered delta. */\n merged?: boolean;\n /** Mark the new checkpoint as the project default. */\n setDefault?: boolean;\n /**\n * If a checkpoint with the same name exists, rm it (manifest + image)\n * before capturing. Makes the call safe to retry — useful when the\n * agent's harness lost the previous invocation's stdout and can't tell\n * whether it succeeded.\n */\n replace?: boolean;\n}\n\n/**\n * First-cut prompt UX is a y/N confirmation in the host wrapper's footer.\n * `select` / `text` are reserved for a follow-up that grows the footer to\n * two rows; keeping the kind in the wire from day one means the host\n * wrapper can ignore unknown kinds gracefully when an older box hits a\n * newer relay (and vice-versa).\n */\nexport type PromptKind = 'confirm';\n\nexport interface PromptContext {\n /** Short label, e.g. \"git push\" or \"cp toHost: /workspace/x -> ~/dl/x\". */\n command?: string;\n /** Container path of the calling cwd, when known. */\n cwd?: string;\n /** Full argv; wrapper truncates for the footer. */\n argv?: string[];\n}\n\n/**\n * The shape pushed over SSE on `event: prompt-ask`. Also the shape the\n * relay-internal `askPrompt()` helper produces. Not a /rpc method — the\n * relay generates these itself when it is about to take a host-side\n * action; the in-box ctl never asks for prompts directly.\n */\nexport interface PromptAskEvent {\n /** Relay-generated UUIDv4 (the wrapper echoes it back in the answer). */\n id: string;\n kind: PromptKind;\n /** Primary question; wrapper truncates to footer width. */\n message: string;\n /** Optional second-line context; wrapper may show or skip. */\n detail?: string;\n /** Default when the user just hits Enter; default 'n' so y/N is the safe shape. */\n defaultAnswer?: 'y' | 'n';\n context?: PromptContext;\n}\n\n/** Body of `POST /admin/prompts/answer`. */\nexport interface PromptAnswerBody {\n id: string;\n answer: 'y' | 'n';\n /** Set when the user dismissed the prompt (Esc / Ctrl-c); treated as 'n'. */\n cancelled?: boolean;\n}\n\n/**\n * Notice kinds. `checkpoint` is the first — a box is transiently frozen\n * while a checkpoint is captured (`docker commit` pauses the container).\n * Kept open-ended like {@link PromptKind} so an older wrapper degrades\n * gracefully (renders the message) when a newer relay sends a new kind.\n */\nexport type NoticeKind = 'checkpoint';\n\n/**\n * The shape pushed over SSE on `event: notice-set`. Unlike a prompt, a\n * notice is purely informational — there is no answer and the box's RPC\n * is not blocked on it. The host wrapper renders it as an animated footer\n * line so the user knows the box is busy, not stuck. Cleared by a\n * `notice-clear` event carrying `{ id }`.\n */\nexport interface BoxNoticeEvent {\n /** Relay-generated UUIDv4. */\n id: string;\n kind: NoticeKind;\n /** Warning text; the wrapper truncates to footer width. */\n message: string;\n}\n\n/** Body of `POST /admin/notices/set`; the response is `{ id }`. */\nexport interface SetNoticeBody {\n boxId: string;\n kind: NoticeKind;\n message: string;\n /** Auto-expiry backstop in ms; defaults relay-side. */\n ttlMs?: number;\n}\n\n/** Body of `POST /admin/notices/clear`. */\nexport interface ClearNoticeBody {\n boxId: string;\n id: string;\n}\n\nexport interface CpRpcParams {\n /**\n * Source path(s): box paths for `cp.toHost`, host paths for `cp.fromHost`.\n * The host CLI side is what carries the `<box>:` prefix when re-shelled.\n */\n sources?: string[];\n /** Destination path: host path for `cp.toHost`, box path for `cp.fromHost`. */\n dest?: string;\n /**\n * Legacy single-source wire shape (older in-box `agentbox-ctl` baked into a\n * box image before multi-source support). The relay normalizes these into\n * `sources`/`dest`. `boxPath` is the container path; `hostPath` the host path\n * (dst for toHost, src for fromHost).\n */\n boxPath?: string;\n hostPath?: string;\n /** Defaults true; relay always uses `docker exec tar` (recursive). */\n recursive?: boolean;\n /** tar glob patterns / bare dir names to exclude, forwarded to `agentbox cp --exclude`. */\n exclude?: string[];\n /** false → forward `--no-default-excludes` (keep heavy dirs the host CLI drops). */\n defaultExcludes?: boolean;\n /** true → forward `--yes` (copy past the host's size limit). */\n yes?: boolean;\n}\n\nexport interface BrowserOpenRpcParams {\n /** Absolute http(s) URL to open in the host's default browser. */\n url: string;\n}\n\nexport type { DownloadKind };\n\nexport interface DownloadRpcParams {\n kind: DownloadKind;\n /**\n * Host destination override. Reserved — the v1 relay ignores it and uses\n * the host CLI's defaults (`box.workspacePath`, or `~/.claude`). Kept in\n * the wire so a later upgrade can land without bumping the type.\n */\n hostPath?: string;\n /** Reserved for per-kind flags (e.g. workspace: includeNodeModules). */\n options?: Record<string, unknown>;\n}\n","import type { BoxRegistration, RelayEvent } from './types.js';\nimport { RELAY_EVENT_RING_SIZE } from './types.js';\n\nexport class BoxRegistry {\n private readonly map = new Map<string, BoxRegistration>();\n\n register(reg: BoxRegistration): void {\n this.map.set(reg.boxId, reg);\n }\n\n forget(boxId: string): boolean {\n return this.map.delete(boxId);\n }\n\n /** Returns the registration whose token matches, or null. */\n authenticate(token: string): BoxRegistration | null {\n if (token.length === 0) return null;\n for (const reg of this.map.values()) {\n if (reg.token === token) return reg;\n }\n return null;\n }\n\n get(boxId: string): BoxRegistration | undefined {\n return this.map.get(boxId);\n }\n\n list(): BoxRegistration[] {\n return [...this.map.values()];\n }\n\n size(): number {\n return this.map.size;\n }\n}\n\nexport class EventBuffer {\n private readonly buf: RelayEvent[] = [];\n private nextId = 1;\n constructor(private readonly capacity: number = RELAY_EVENT_RING_SIZE) {}\n\n append(input: Omit<RelayEvent, 'id' | 'receivedAt'>): RelayEvent {\n const ev: RelayEvent = {\n id: this.nextId++,\n receivedAt: new Date().toISOString(),\n ...input,\n };\n this.buf.push(ev);\n if (this.buf.length > this.capacity) this.buf.shift();\n return ev;\n }\n\n /** Returns events with id > since. If `box` is given, filters to that box. */\n since(since: number, box?: string): RelayEvent[] {\n const out: RelayEvent[] = [];\n for (const ev of this.buf) {\n if (ev.id <= since) continue;\n if (box && ev.boxId !== box) continue;\n out.push(ev);\n }\n return out;\n }\n\n all(): RelayEvent[] {\n return this.buf.slice();\n }\n\n size(): number {\n return this.buf.length;\n }\n}\n","import { mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * A box status snapshot as received from the in-box daemon. The relay treats\n * it structurally (it has no dep on `@agentbox/ctl`); the rich type lives in\n * `@agentbox/ctl` (`BoxStatus`) and is what the host CLI parses back.\n */\nexport type BoxStatusSnapshot = Record<string, unknown>;\n\n/**\n * Mirrors `sanitizeMnemonic` in @agentbox/config — duplicated here so the relay\n * stays dep-free. Two source-of-truth files; the schema-drift-style guarantee\n * is that boxes only land in `<id>-<mnemonic>/` if both impls agree.\n */\nfunction sanitizeMnemonic(raw: string): string {\n return (\n raw\n .toLowerCase()\n .replace(/-/g, '_')\n .replace(/[^a-z0-9_]+/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_+|_+$/g, '')\n .slice(0, 32) || 'unnamed'\n );\n}\n\n/**\n * Mirrors `boxRunDirFor` / `boxDirSegment` in @agentbox/sandbox-docker — kept\n * in sync by hand. When `projectIndex` (`agentbox list`'s `N`) is set the\n * segment is `<id>-<n>-<mnemonic>` so directories sort cleanly within a\n * project; legacy (pre-feature) boxes register without it and fall back to\n * the original `<id>-<mnemonic>` shape.\n */\nfunction boxRunDirFor(boxId: string, name: string, projectIndex?: number): string {\n const mnemonic = sanitizeMnemonic(name);\n const segment =\n typeof projectIndex === 'number' && Number.isFinite(projectIndex) && projectIndex > 0\n ? `${boxId}-${String(projectIndex)}-${mnemonic}`\n : `${boxId}-${mnemonic}`;\n return join(homedir(), '.agentbox', 'boxes', segment);\n}\n\nfunction boxStatusPathFor(boxId: string, name: string, projectIndex?: number): string {\n return join(boxRunDirFor(boxId, name, projectIndex), 'status.json');\n}\n\n/**\n * Structural guard: a valid box-status payload is an object with `schema === 1`\n * and a non-empty `boxId` string. The relay persists it verbatim; the host\n * reader does the strict typing.\n */\nexport function isValidBoxStatus(payload: unknown): payload is BoxStatusSnapshot {\n if (typeof payload !== 'object' || payload === null) return false;\n const o = payload as Record<string, unknown>;\n return o.schema === 1 && typeof o.boxId === 'string' && o.boxId.length > 0;\n}\n\n/**\n * In-memory latest-status map plus a durable per-box file at\n * `~/.agentbox/boxes/<id>/status.json`. The relay is a single process so it is\n * the single writer; the atomic tmp+rename means the host CLI never reads a\n * torn file. The on-disk copy is what makes status survive box pause/stop,\n * relay restart, and host reboot.\n */\nexport class BoxStatusStore {\n private readonly map = new Map<string, BoxStatusSnapshot>();\n\n get(boxId: string): BoxStatusSnapshot | undefined {\n return this.map.get(boxId);\n }\n\n /**\n * Update the in-memory entry and best-effort persist it to disk. `name` is\n * the box's user-facing name (from the registry); `projectIndex` is the\n * 1-based per-project `N`. Together they form the on-disk dir\n * `~/.agentbox/boxes/<id>-<n>-<mnemonic>/status.json` (or\n * `<id>-<mnemonic>/` if N is absent — legacy boxes).\n */\n async set(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n this.map.set(boxId, status);\n const target = boxStatusPathFor(boxId, name, projectIndex);\n const tmp = `${target}.${String(process.pid)}.tmp`;\n try {\n await mkdir(boxRunDirFor(boxId, name, projectIndex), { recursive: true });\n await writeFile(tmp, JSON.stringify(status), 'utf8');\n await rename(tmp, target);\n } catch {\n await rm(tmp, { force: true }).catch(() => {});\n }\n }\n\n /** Drop the in-memory entry (the on-disk file is wiped with the box dir). */\n delete(boxId: string): void {\n this.map.delete(boxId);\n }\n\n /** Every box's latest snapshot in one pass (backs `Store.listStatuses`). */\n list(): Array<{ boxId: string; status: BoxStatusSnapshot }> {\n return [...this.map.entries()].map(([boxId, status]) => ({ boxId, status }));\n }\n}\n","import { BoxRegistry, EventBuffer } from '../registry.js';\nimport { BoxStatusStore } from '../status-store.js';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\nexport interface MemoryStoreParts {\n registry?: BoxRegistry;\n events?: EventBuffer;\n statusStore?: BoxStatusStore;\n}\n\n/**\n * In-memory {@link Store} — the laptop loopback relay default and the test\n * default. It wraps the original `BoxRegistry` / `EventBuffer` /\n * `BoxStatusStore` instances verbatim, so it is behaviorally identical to the\n * pre-seam relay (status still persists to `~/.agentbox/boxes/<id>/status.json`\n * via `BoxStatusStore.set`). The wrapped instances are exposed so the relay\n * handle can keep handing them to the autopause / queue loops and the unit\n * tests, which read them synchronously.\n */\nexport class MemoryStore implements Store {\n readonly registry: BoxRegistry;\n readonly events: EventBuffer;\n readonly statusStore: BoxStatusStore;\n private readonly prompts = new Map<string, PromptRow>();\n private readonly createJobs = new Map<string, CreateJobRow>();\n\n constructor(parts: MemoryStoreParts = {}) {\n this.registry = parts.registry ?? new BoxRegistry();\n this.events = parts.events ?? new EventBuffer();\n this.statusStore = parts.statusStore ?? new BoxStatusStore();\n }\n\n registerBox(reg: BoxRegistration): Promise<void> {\n this.registry.register(reg);\n return Promise.resolve();\n }\n\n getBox(boxId: string): Promise<BoxRegistration | undefined> {\n return Promise.resolve(this.registry.get(boxId));\n }\n\n authenticateBox(token: string): Promise<BoxRegistration | null> {\n return Promise.resolve(this.registry.authenticate(token));\n }\n\n listBoxes(): Promise<BoxRegistration[]> {\n return Promise.resolve(this.registry.list());\n }\n\n forgetBox(boxId: string): Promise<boolean> {\n return Promise.resolve(this.registry.forget(boxId));\n }\n\n countBoxes(): Promise<number> {\n return Promise.resolve(this.registry.size());\n }\n\n appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n return Promise.resolve(this.events.append(input));\n }\n\n listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n return Promise.resolve(this.events.since(since, boxId));\n }\n\n countEvents(): Promise<number> {\n return Promise.resolve(this.events.size());\n }\n\n setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n return this.statusStore.set(boxId, name, projectIndex, status);\n }\n\n getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n return Promise.resolve(this.statusStore.get(boxId));\n }\n\n deleteStatus(boxId: string): Promise<void> {\n this.statusStore.delete(boxId);\n return Promise.resolve();\n }\n\n listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n return Promise.resolve(this.statusStore.list());\n }\n\n createPrompt(row: PromptRow): Promise<void> {\n this.prompts.set(row.id, { ...row });\n return Promise.resolve();\n }\n\n getPrompt(promptId: string): Promise<PromptRow | null> {\n const row = this.prompts.get(promptId);\n return Promise.resolve(row ? { ...row } : null);\n }\n\n answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const row = this.prompts.get(promptId);\n if (!row || row.status !== 'pending') return Promise.resolve(false);\n row.status = 'answered';\n row.answer = answer;\n row.cancelled = cancelled;\n return Promise.resolve(true);\n }\n\n listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const out: PromptRow[] = [];\n for (const row of this.prompts.values()) {\n if (row.boxId === boxId && row.status === 'pending') out.push({ ...row });\n }\n return Promise.resolve(out);\n }\n\n setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n const row = this.prompts.get(promptId);\n if (row) row.result = result;\n return Promise.resolve();\n }\n\n enqueueCreateJob(job: CreateJobRow): Promise<void> {\n this.createJobs.set(job.id, { ...job });\n return Promise.resolve();\n }\n\n getCreateJob(id: string): Promise<CreateJobRow | null> {\n const job = this.createJobs.get(id);\n return Promise.resolve(job ? { ...job } : null);\n }\n\n listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n const wanted = opts?.status;\n const rows = [...this.createJobs.values()]\n .filter((j) => !wanted || wanted.includes(j.status))\n .sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n .map((j) => ({ ...j }));\n return Promise.resolve(opts?.limit ? rows.slice(0, opts.limit) : rows);\n }\n\n claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n // Oldest queued first; single-process so no real concurrency to guard.\n const queued = [...this.createJobs.values()]\n .filter((j) => j.status === 'queued')\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n const job = queued[0];\n if (!job) return Promise.resolve(null);\n job.status = 'running';\n job.claimedBy = workerId;\n job.startedAt = new Date().toISOString();\n return Promise.resolve({ ...job });\n }\n\n completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n const job = this.createJobs.get(id);\n if (job) {\n job.status = status;\n job.result = result;\n job.finishedAt = new Date().toISOString();\n }\n return Promise.resolve();\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { ServerResponse } from 'node:http';\nimport type { PromptAnswerBody, PromptAskEvent } from './types.js';\n\n/**\n * Resolution shape passed back through `askPrompt`'s Promise. Mirrors the\n * shape the wrapper POSTs to `/admin/prompts/answer` minus the id (the\n * caller already knows it).\n */\nexport interface PromptResolution {\n answer: 'y' | 'n';\n cancelled?: boolean;\n}\n\ninterface PendingPromptEntry {\n ev: PromptAskEvent;\n boxId: string;\n resolve: (r: PromptResolution) => void;\n createdAt: string;\n}\n\n/**\n * In-memory pending prompts map. The relay's host-action handlers (git push,\n * cp.*, download.*) put a pending entry here and await the Promise; the\n * wrapper's POST to `/admin/prompts/answer` resolves it. Entries live for\n * however long the user takes — per the design we block indefinitely until\n * a wrapper attaches and answers.\n */\n/**\n * Per-box auto-approve policy, wired by the relay server once the registry +\n * event buffer are available. `shouldAutoApprove` reflects the box's\n * `autoApproveHostActions` registration flag; `audit` records the bypass to\n * the relay event ring buffer so it stays observable. Lives on\n * {@link PendingPrompts} because that instance is already threaded into every\n * `askPrompt` call site (host + cloud), so no handler signatures change.\n */\nexport interface AutoApprovePolicy {\n shouldAutoApprove(boxId: string): boolean;\n audit(boxId: string, params: Omit<PromptAskEvent, 'id'>, reason?: string): void;\n}\n\n/** A pending approval, flattened for listing across all boxes (hub UI). */\nexport interface PendingApproval {\n id: string;\n boxId: string;\n ev: PromptAskEvent;\n createdAt: string;\n}\n\nexport class PendingPrompts {\n private readonly entries = new Map<string, PendingPromptEntry>();\n private autoApprove: AutoApprovePolicy | null = null;\n private onChange: (() => void) | null = null;\n\n /** Install the per-box auto-approve policy (relay server, once at startup). */\n setAutoApprovePolicy(policy: AutoApprovePolicy): void {\n this.autoApprove = policy;\n }\n\n /**\n * Install a change hook fired whenever the pending set is mutated (add /\n * resolve). Wired by the relay server to the hub notifier so the embedded UI\n * pushes an update to connected browsers.\n */\n setOnChange(fn: () => void): void {\n this.onChange = fn;\n }\n\n /**\n * True when this box opted into `box.autoApproveHostActions`. Records the\n * bypass to the audit sink as a side effect so the caller short-circuits\n * with a trail. Returns false when no policy is installed.\n */\n consumeAutoApprove(boxId: string, params: Omit<PromptAskEvent, 'id'>): boolean {\n if (!this.autoApprove || !this.autoApprove.shouldAutoApprove(boxId)) return false;\n this.autoApprove.audit(boxId, params);\n return true;\n }\n\n /**\n * Record a *safe-subset* auto-approval (opening a PR, a contained file copy,\n * a sanctioned-branch push, …) to the audit sink WITHOUT the blanket\n * `autoApproveHostActions` opt-in. The handler already decided the action is\n * safe under `box.autoApproveSafeHostActions`; this just leaves the same\n * `host-action-auto-approved` trail a full opt-in would, tagged with `reason`.\n * No-op when no policy is installed (e.g. the stateless poll plane).\n */\n noteAutoApprove(boxId: string, params: Omit<PromptAskEvent, 'id'>, reason: string): void {\n this.autoApprove?.audit(boxId, params, reason);\n }\n\n add(boxId: string, ev: PromptAskEvent): Promise<PromptResolution> {\n return new Promise<PromptResolution>((resolve) => {\n this.entries.set(ev.id, {\n ev,\n boxId,\n resolve,\n createdAt: new Date().toISOString(),\n });\n this.onChange?.();\n });\n }\n\n /**\n * Idempotent: returns true if a pending entry was found + resolved, false\n * otherwise. The /admin/prompts/answer handler uses the bool to decide\n * 204 vs 404 — the wrapper treats both as \"we're done.\"\n */\n resolve(id: string, answer: 'y' | 'n', cancelled?: boolean): boolean {\n const entry = this.entries.get(id);\n if (!entry) return false;\n this.entries.delete(id);\n entry.resolve({ answer, cancelled });\n this.onChange?.();\n return true;\n }\n\n /**\n * Snapshot of all pending prompts for a given box; used to flush the\n * backlog to a newly-attached SSE subscriber.\n */\n forBox(boxId: string): PromptAskEvent[] {\n const out: PromptAskEvent[] = [];\n for (const entry of this.entries.values()) {\n if (entry.boxId === boxId) out.push(entry.ev);\n }\n return out;\n }\n\n /**\n * Snapshot of every pending prompt across all boxes, with its boxId and\n * enqueue time — the hub's Approvals view lists these.\n */\n all(): PendingApproval[] {\n const out: PendingApproval[] = [];\n for (const entry of this.entries.values()) {\n out.push({ id: entry.ev.id, boxId: entry.boxId, ev: entry.ev, createdAt: entry.createdAt });\n }\n return out;\n }\n\n /** boxId that owns a pending prompt id, or null when unknown. */\n boxFor(id: string): string | null {\n const entry = this.entries.get(id);\n return entry ? entry.boxId : null;\n }\n\n size(): number {\n return this.entries.size;\n }\n}\n\n/** A callback subscriber to a box's prompt/notice broadcasts. */\nexport type PromptListener = (event: string, data: unknown) => void;\n\n/**\n * Tracks the set of host-side wrappers currently subscribed per box. Two kinds\n * of subscriber exist:\n * - raw `ServerResponse` SSE writers — the relay's own `/admin/prompts/stream`\n * route (in-process on the same server).\n * - callback `PromptListener`s — the hub's `/api/v1` prompt stream, which is a\n * Next route that can't hold the relay's `ServerResponse` directly and\n * receives the same events via a callback instead.\n *\n * `broadcast` writes to both so the user can answer from whichever attached\n * window (footer or web-driven stream) they happen to be in.\n */\nexport class PromptSubscribers {\n private readonly byBox = new Map<string, Set<ServerResponse>>();\n private readonly listenersByBox = new Map<string, Set<PromptListener>>();\n private durableFloor = 0;\n\n add(boxId: string, res: ServerResponse): void {\n let set = this.byBox.get(boxId);\n if (!set) {\n set = new Set();\n this.byBox.set(boxId, set);\n }\n set.add(res);\n }\n\n remove(boxId: string, res: ServerResponse): void {\n const set = this.byBox.get(boxId);\n if (!set) return;\n set.delete(res);\n if (set.size === 0) this.byBox.delete(boxId);\n }\n\n /**\n * Register a callback subscriber for a box; returns an unsubscribe. Used by\n * the hub's `/api/v1` prompt-stream route (a Next route, reached via a\n * globalThis seam) so its stream gets the same `prompt-ask`/`prompt-resolved`/\n * `notice-*` events the footer's admin stream does.\n */\n addListener(boxId: string, fn: PromptListener): () => void {\n let set = this.listenersByBox.get(boxId);\n if (!set) {\n set = new Set();\n this.listenersByBox.set(boxId, set);\n }\n set.add(fn);\n return () => {\n const s = this.listenersByBox.get(boxId);\n if (!s) return;\n s.delete(fn);\n if (s.size === 0) this.listenersByBox.delete(boxId);\n };\n }\n\n forBox(boxId: string): ServerResponse[] {\n const set = this.byBox.get(boxId);\n return set ? Array.from(set) : [];\n }\n\n /**\n * Set a process-wide floor added to every box's {@link count}. This is how the\n * always-on hub declares itself the *durable subscriber*: when the floor is 1,\n * a pending prompt is always answerable (the web UI + `/api/v1/approvals/:id/\n * answer` never go away), so a host-action gate (e.g. git.push) parks the\n * prompt instead of auto-denying when no wrapper is attached. Gated to the\n * control-box profile by the caller — a plain local hub keeps floor 0 (the\n * user is present; an unattended local box shouldn't wedge on a blocked push).\n */\n setDurableFloor(n: number): void {\n this.durableFloor = Math.max(0, n);\n }\n\n /**\n * How many subscribers a box has: raw SSE writers + callback listeners + the\n * durable floor. The host-action no-subscriber gate reads this to decide\n * whether a confirm can be surfaced-and-answered (park) or must fall back to\n * its `*_NO_SUB` policy (auto-deny by default). Counting listeners is\n * load-bearing: the footer moved from a `ServerResponse` on `/admin/prompts/\n * stream` to a callback on the `/api/v1` stream, so a `forBox().length` check\n * would no longer see an attached footer and would silently auto-deny.\n */\n count(boxId: string): number {\n const responses = this.byBox.get(boxId)?.size ?? 0;\n const listeners = this.listenersByBox.get(boxId)?.size ?? 0;\n return responses + listeners + this.durableFloor;\n }\n\n /**\n * Fire-and-forget broadcast to both SSE writers and callback listeners. Writes\n * that fail (closed socket) are swallowed — the route's `close` handler already\n * deregisters the dead subscriber; a throwing listener is isolated the same way.\n */\n broadcast(boxId: string, event: string, data: unknown): void {\n const set = this.byBox.get(boxId);\n if (set) {\n const payload = `event: ${event}\\ndata: ${JSON.stringify(data)}\\n\\n`;\n for (const res of set) {\n try {\n res.write(payload);\n } catch {\n /* dead socket; close handler will deregister */\n }\n }\n }\n const listeners = this.listenersByBox.get(boxId);\n if (listeners) {\n for (const fn of listeners) {\n try {\n fn(event, data);\n } catch {\n /* an errant listener must not take the broadcast (or its peers) down */\n }\n }\n }\n }\n}\n\n/**\n * Internal API used by handleGitRpc / handleCpRpc / handleDownloadRpc and the\n * `browser.open` host-mirror offer. Generates a UUID, adds a pending entry,\n * broadcasts the SSE event, and awaits the answer. Respects\n * `process.env.AGENTBOX_PROMPT === 'off'` — auto-accepts without broadcasting\n * (useful for headless scripts and tests) — and the per-box\n * `box.autoApproveHostActions` policy (auto-accepts with an audit event).\n *\n * `opts.ttlMs` makes the prompt auto-expire: if no answer arrives in time it\n * resolves to its `defaultAnswer` (cancelled) and a `prompt-resolved` event is\n * broadcast so attached wrappers clear it. Used for optional, non-blocking\n * prompts that must not linger when nobody answers; omit it for the\n * block-until-answered prompts that gate a paused in-box RPC.\n */\nexport async function askPrompt(\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n boxId: string,\n params: Omit<PromptAskEvent, 'id'>,\n opts?: { ttlMs?: number },\n): Promise<PromptResolution> {\n if (process.env.AGENTBOX_PROMPT === 'off') {\n return { answer: 'y' };\n }\n // Per-box opt-in: `box.autoApproveHostActions` resolves the confirm to 'y'\n // without surfacing a prompt, but records an audit event (inside\n // consumeAutoApprove) so the bypass is never silent.\n if (prompts.consumeAutoApprove(boxId, params)) {\n return { answer: 'y' };\n }\n const ev: PromptAskEvent = { id: randomUUID(), ...params };\n const promise = prompts.add(boxId, ev);\n subscribers.broadcast(boxId, 'prompt-ask', ev);\n if (opts?.ttlMs !== undefined && opts.ttlMs > 0) {\n const timer = setTimeout(() => {\n if (prompts.resolve(ev.id, params.defaultAnswer ?? 'n', true)) {\n subscribers.broadcast(boxId, 'prompt-resolved', { id: ev.id });\n }\n }, opts.ttlMs);\n if (typeof timer.unref === 'function') timer.unref();\n void promise.then(() => {\n clearTimeout(timer);\n });\n }\n return promise;\n}\n\n/** Helper for the answer body — used by the relay server to validate. */\nexport function isPromptAnswerBody(v: unknown): v is PromptAnswerBody {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n if (typeof o.id !== 'string' || o.id.length === 0) return false;\n if (o.answer !== 'y' && o.answer !== 'n') return false;\n if (o.cancelled !== undefined && typeof o.cancelled !== 'boolean') return false;\n return true;\n}\n","import { randomUUID } from 'node:crypto';\nimport { askPrompt, type PendingPrompts, type PromptSubscribers } from './prompts.js';\nimport type { Store } from './store/store.js';\nimport type { PromptAskEvent } from './types.js';\n\n/**\n * How the relay obtains host-action approval:\n * - 'block' — the laptop loopback relay (a long-lived process): the `/rpc`\n * handler blocks on an in-process `PendingPrompts` Promise until the human\n * answers (today's behavior, unchanged).\n * - 'poll' — the hosted control plane (serverless / stateless per request):\n * the gate parks a prompt row in the Store and returns immediately; `/rpc`\n * replies `202 {promptId}` and the box polls `/rpc/status/:id` for the\n * verdict + result.\n */\nexport type PromptMode = 'block' | 'poll';\n\nexport type ApprovalGate =\n | { kind: 'allow' }\n | { kind: 'deny' }\n | { kind: 'pending'; promptId: string };\n\nexport interface GateDeps {\n mode: PromptMode;\n store: Store;\n /** Required for block mode (the in-process blocking wait). */\n prompts?: PendingPrompts;\n /** Optional: SSE fan-out to an attached human dashboard. Absent on the stateless plane. */\n subscribers?: PromptSubscribers;\n}\n\n/**\n * Decide whether a host action may proceed. The caller has already cleared the\n * fast paths that never prompt at all (agentbox/* branch, valid host-initiated\n * token, read-only op). `promptParams` is the confirm to show the human;\n * `method`/`params` are persisted on the poll-mode row so the approved action\n * can be re-dispatched when the box polls.\n *\n * - 'block': returns allow/deny once the human answers (or AGENTBOX_PROMPT=off\n * / autoApprove resolves it). Behaviorally identical to the pre-poll relay.\n * - 'poll': returns allow when no human is needed (AGENTBOX_PROMPT=off /\n * autoApprove, audited), else parks a pending row and returns its promptId.\n */\nexport async function gateApproval(\n deps: GateDeps,\n boxId: string,\n method: string,\n params: unknown,\n promptParams: Omit<PromptAskEvent, 'id'>,\n): Promise<ApprovalGate> {\n if (deps.mode === 'block') {\n // askPrompt handles AGENTBOX_PROMPT=off + autoApprove (with audit) + the\n // blocking wait, exactly as before. Block mode requires in-process state.\n if (!deps.prompts || !deps.subscribers) return { kind: 'deny' };\n const verdict = await askPrompt(deps.prompts, deps.subscribers, boxId, promptParams);\n return verdict.answer === 'y' && !verdict.cancelled ? { kind: 'allow' } : { kind: 'deny' };\n }\n // poll mode: store-based fast paths (works on the stateless hosted plane, no\n // in-process registry/prompts), then park a row the box will poll for.\n if (process.env.AGENTBOX_PROMPT === 'off') return { kind: 'allow' };\n const box = await deps.store.getBox(boxId);\n if (box?.autoApproveHostActions) {\n // Audited bypass — still observable in the event feed.\n await deps.store.appendEvent({\n boxId,\n type: 'host-action-auto-approved',\n payload: {\n command: promptParams.context?.command,\n argv: promptParams.context?.argv,\n message: promptParams.message,\n },\n });\n return { kind: 'allow' };\n }\n const promptId = randomUUID();\n const ev: PromptAskEvent = { id: promptId, ...promptParams };\n await deps.store.createPrompt({\n id: promptId,\n boxId,\n ev,\n method,\n params,\n status: 'pending',\n createdAt: new Date().toISOString(),\n });\n // Best-effort SSE for an attached human dashboard (no-op when none / on the\n // stateless plane); the box itself never relies on SSE — it polls /rpc/status.\n deps.subscribers?.broadcast(boxId, 'prompt-ask', ev);\n return { kind: 'pending', promptId };\n}\n","import { existsSync } from 'node:fs';\nimport type { BoxRegistration, BoxWorktree } from './types.js';\n\n/**\n * Resolve `containerPath` (a path inside the box) to the registered worktree\n * whose `hostMainRepo` + `branch` the relay should act on. `/workspace` maps to\n * the root repo; `/workspace/<sub>` maps to a nested repo when registered\n * (longest prefix wins). Pure — shared by the node relay (server.ts) and the\n * hosted-plane handler (core/handler.ts).\n */\nexport function resolveWorktree(reg: BoxRegistration, containerPath: string): BoxWorktree | null {\n const trees = reg.worktrees ?? [];\n if (trees.length === 0) return null;\n const exact = trees.find((w) => w.containerPath === containerPath);\n if (exact) return exact;\n const prefixMatches = trees\n .filter(\n (w) => containerPath === w.containerPath || containerPath.startsWith(w.containerPath + '/'),\n )\n .sort((a, b) => b.containerPath.length - a.containerPath.length);\n return prefixMatches[0] ?? trees.find((w) => w.containerPath === '/workspace') ?? null;\n}\n\n/**\n * Reject host-side git RPCs against a worktree with no usable host repo. A box\n * created by the control-box worker registers its `hostMainRepo` as the\n * create-time seed clone — a temp dir deleted after create — so `git -C <that>`\n * would fail cryptically. Returns an actionable error string for such a\n * worktree, or `null` when the host repo exists. Pure aside from the fs check,\n * so it is unit-testable with a real/fake directory.\n */\nexport function hostRepoUnavailableReason(\n worktree: BoxWorktree,\n boxId: string,\n op: string,\n): string | null {\n if (worktree.hostMainRepo.length > 0 && existsSync(worktree.hostMainRepo)) return null;\n return (\n `host-side ${op} is unavailable for box ${boxId}: its host repo ` +\n `(${worktree.hostMainRepo || '<unset>'}) does not exist on this host. ` +\n `Boxes created by the control-box worker have no host working copy — ` +\n `push from inside the box (leased) or adopt the box on this host first.`\n );\n}\n","/**\n * Pure GitHub remote-URL helpers: parse a remote, rewrite it to carry a token\n * over HTTPS, and derive the `gh --repo` slug. Shared by the control plane's\n * GitHub-App token leasing (`lease.ts`) and the cloud git.push path.\n */\n\n/**\n * Parse any GitHub remote URL (scp-like `git@host:owner/repo`, `ssh://…`, or\n * `https://…`, with or without embedded creds) into `{ host, path }`. Throws on\n * an unrecognized shape.\n */\nexport function parseGitRemote(origin: string): { host: string; path: string } {\n const trimmed = origin.trim();\n if (trimmed.length === 0) throw new Error('empty git remote URL');\n\n // URL form first: scheme://[user@]host[:port]/path. Matching this before the\n // scp branch avoids misreading `https://github.com/...` as scp `https:...`.\n const urlForm = /^[a-z][a-z0-9+.-]*:\\/\\/(?:[^@/]+@)?([^/:]+)(?::\\d+)?\\/(.+)$/i.exec(trimmed);\n const scpForm = /^(?:[^@/]+@)?([^/:]+):(.+)$/.exec(trimmed);\n let host: string;\n let path: string;\n if (urlForm) {\n host = urlForm[1]!;\n path = urlForm[2]!;\n } else if (scpForm && !/^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed)) {\n host = scpForm[1]!;\n path = scpForm[2]!;\n } else {\n throw new Error(`unrecognized git remote URL: ${origin}`);\n }\n return { host, path: path.replace(/^\\/+/, '') };\n}\n\n/**\n * Rewrite any GitHub remote URL into an HTTPS URL carrying the PAT as\n * `x-access-token`. Throws on an unrecognized shape.\n */\nexport function toAuthedHttpsUrl(origin: string, token: string): string {\n const { host, path } = parseGitRemote(origin);\n return `https://x-access-token:${token}@${host}/${path}`;\n}\n\n/**\n * Rewrite any GitHub remote URL to plain HTTPS, dropping embedded credentials.\n *\n * For a machine that authenticates git through a credential helper rather than\n * an SSH key — the hub in `hub.gitAuth=gh` mode — an scp-form\n * `git@github.com:owner/repo` origin is unusable: ssh fails at host-key\n * verification (no `known_hosts` entry) before it ever reaches auth, so the\n * helper never gets a say. Same URL over HTTPS is exactly what the helper\n * covers.\n */\nexport function toHttpsUrl(origin: string): string {\n const { host, path } = parseGitRemote(origin);\n return `https://${host}/${path}`;\n}\n\n/**\n * The `[HOST/]OWNER/REPO` slug `gh --repo` expects, derived from a remote URL.\n * github.com is implicit (just `OWNER/REPO`); enterprise hosts are prefixed.\n */\nexport function repoSlugFromRemote(origin: string): string {\n const { host, path } = parseGitRemote(origin);\n const repo = path.replace(/\\.git$/, '');\n return host.toLowerCase() === 'github.com' ? repo : `${host}/${repo}`;\n}\n","import { parseGitRemote, repoSlugFromRemote, toAuthedHttpsUrl } from './git-pat.js';\nimport type { GitHubAppLeaser } from './github-app.js';\nimport type { BoxRegistration, GitRpcResult } from './types.js';\n\n/**\n * Mint a repo-scoped GitHub-App installation token for a box and package it as\n * a `{exitCode,stdout,stderr}` result whose `stdout` is the lease JSON\n * (`{ token, expiresAt, remoteUrl, repo }`). Shared by the node relay\n * (server.ts) and the hosted-plane handler (core/handler.ts).\n *\n * The repo is resolved from the box's REGISTERED origin URL — never from\n * box-supplied params — so a box can only ever lease a token for its own repo.\n */\nexport async function leaseTokenResult(\n leaser: GitHubAppLeaser | null,\n reg: BoxRegistration,\n): Promise<GitRpcResult> {\n if (!leaser) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'git.lease-token: no GitHub App configured on this relay\\n',\n };\n }\n const origin = reg.originUrl;\n if (!origin) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `git.lease-token: box ${reg.boxId} has no registered origin URL\\n`,\n };\n }\n let owner = '';\n let repo = '';\n let slug = '';\n try {\n const { path } = parseGitRemote(origin);\n const [o, r] = path.replace(/\\.git$/, '').split('/');\n owner = o ?? '';\n repo = r ?? '';\n slug = repoSlugFromRemote(origin);\n } catch {\n return { exitCode: 65, stdout: '', stderr: `git.lease-token: unrecognized origin ${origin}\\n` };\n }\n if (!owner || !repo) {\n return {\n exitCode: 65,\n stdout: '',\n stderr: `git.lease-token: cannot derive owner/repo from ${origin}\\n`,\n };\n }\n try {\n const leased = await leaser.leaseRepoToken(owner, repo);\n const payload = {\n token: leased.token,\n expiresAt: leased.expiresAt,\n remoteUrl: toAuthedHttpsUrl(origin, leased.token),\n repo: slug,\n };\n return { exitCode: 0, stdout: JSON.stringify(payload), stderr: '' };\n } catch (err) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `git.lease-token: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n}\n","import type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { PromptRow, Store } from './store.js';\n\n/**\n * A tiny RPC envelope over the {@link Store} interface, so a federated laptop\n * relay can back its state with a remote (hosted) Store over HTTP. The hosted\n * plane exposes `POST /admin/store` (admin-gated) and applies the op via\n * {@link applyStoreOp}; {@link RemoteStore} is the client that posts these.\n *\n * Generic-but-typed: a single switch keeps the dispatch type-safe (no `any`)\n * and the method names are an explicit allow-list — the endpoint can never\n * invoke an arbitrary property of the store object.\n */\nexport interface StoreRpcRequest {\n method: string;\n args: unknown[];\n}\n\nexport interface StoreRpcResponse {\n /** Method return value (already JSON-safe — every Store method returns plain data). */\n result: unknown;\n}\n\n/** True when `method` is a dispatchable Store op. */\nexport function isStoreRpcMethod(method: string): boolean {\n return STORE_RPC_METHODS.has(method);\n}\n\nconst STORE_RPC_METHODS = new Set<string>([\n 'registerBox',\n 'getBox',\n 'authenticateBox',\n 'listBoxes',\n 'forgetBox',\n 'countBoxes',\n 'appendEvent',\n 'listEvents',\n 'countEvents',\n 'setStatus',\n 'getStatus',\n 'deleteStatus',\n 'listStatuses',\n 'createPrompt',\n 'getPrompt',\n 'answerPrompt',\n 'listPendingPrompts',\n 'setPromptResult',\n]);\n\n/** Apply a store op by name with typed argument coercion. Throws on unknown method. */\nexport function applyStoreOp(store: Store, method: string, args: unknown[]): Promise<unknown> {\n switch (method) {\n case 'registerBox':\n return store.registerBox(args[0] as BoxRegistration);\n case 'getBox':\n return store.getBox(args[0] as string);\n case 'authenticateBox':\n return store.authenticateBox(args[0] as string);\n case 'listBoxes':\n return store.listBoxes();\n case 'forgetBox':\n return store.forgetBox(args[0] as string);\n case 'countBoxes':\n return store.countBoxes();\n case 'appendEvent':\n return store.appendEvent(args[0] as Omit<RelayEvent, 'id' | 'receivedAt'>);\n case 'listEvents':\n return store.listEvents(args[0] as number, args[1] as string | undefined);\n case 'countEvents':\n return store.countEvents();\n case 'setStatus':\n return store.setStatus(\n args[0] as string,\n args[1] as string,\n args[2] as number | undefined,\n args[3] as BoxStatusSnapshot,\n );\n case 'getStatus':\n return store.getStatus(args[0] as string);\n case 'deleteStatus':\n return store.deleteStatus(args[0] as string);\n case 'listStatuses':\n return store.listStatuses();\n case 'createPrompt':\n return store.createPrompt(args[0] as PromptRow);\n case 'getPrompt':\n return store.getPrompt(args[0] as string);\n case 'answerPrompt':\n return store.answerPrompt(\n args[0] as string,\n args[1] as 'y' | 'n',\n args[2] as boolean | undefined,\n );\n case 'listPendingPrompts':\n return store.listPendingPrompts(args[0] as string);\n case 'setPromptResult':\n return store.setPromptResult(args[0] as string, args[1] as GitRpcResult);\n default:\n throw new Error(`unknown store op: ${method}`);\n }\n}\n","/**\n * The `/admin/store` generic-Store RPC surface, as a framework-agnostic\n * dispatcher mounted by BOTH relay front-ends: the hosted-plane handler\n * (`core/handler.ts`, Next/Vercel) and the relay daemon (`server.ts`, node:http\n * — what the control box actually runs). One implementation, one gate, both\n * profiles, so a PC's {@link RemoteStore} works against the control box exactly\n * as against the hosted plane.\n *\n * Like custody / remote-boxes, the **admin bearer is the only proof** — never\n * loopback (the control box sits behind Caddy on the same host, so every proxied\n * request looks loopback). Missing admin token → 503 (not configured); wrong\n * token → 401. The method name is an explicit allow-list ({@link isStoreRpcMethod}),\n * so the endpoint can never invoke an arbitrary property of the store object.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\nimport type { Store } from './store.js';\nimport { applyStoreOp, isStoreRpcMethod, type StoreRpcRequest } from './store-rpc.js';\n\n/** Structurally identical to `RelayResponse` in `core/handler.ts` (kept local to avoid a cycle). */\nexport interface StoreRpcRouteResponse {\n status: number;\n body?: unknown;\n}\n\nexport interface StoreRpcRouteRequest {\n method: string;\n /** URL pathname, e.g. `/admin/store`. */\n path: string;\n /** Bearer token as presented ('' when absent). */\n bearer: string;\n /** Raw request body ('' for GET). */\n bodyText: string;\n}\n\nexport interface StoreRpcRouteDeps {\n store: Store;\n /** Admin bearer. Empty/absent → not configured (503). */\n adminToken?: string;\n log?: (line: string) => void;\n}\n\nexport const STORE_RPC_PATH = '/admin/store';\n\n/** True when `path` addresses the generic-Store RPC surface. */\nexport function isStoreRpcPath(path: string): boolean {\n return path === STORE_RPC_PATH;\n}\n\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\nfunction parseJson<T>(text: string): T | null {\n if (text.length === 0) return null;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Dispatch one `/admin/store` request. Returns `null` when `req.path` is not the\n * store-RPC path, so a host router falls through to its own routes unchanged.\n */\nexport async function handleStoreRpcRequest(\n req: StoreRpcRouteRequest,\n deps: StoreRpcRouteDeps,\n): Promise<StoreRpcRouteResponse | null> {\n if (!isStoreRpcPath(req.path)) return null;\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'control plane not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n if (req.method !== 'POST') {\n return { status: 405, body: { error: 'method not allowed' } };\n }\n const body = parseJson<StoreRpcRequest>(req.bodyText);\n if (!body || typeof body.method !== 'string' || !Array.isArray(body.args)) {\n return { status: 400, body: { error: 'expected {method, args}' } };\n }\n if (!isStoreRpcMethod(body.method)) {\n return { status: 400, body: { error: `unknown store op: ${body.method}` } };\n }\n const result = await applyStoreOp(deps.store, body.method, body.args);\n return { status: 200, body: { result: result ?? null } };\n}\n","/**\n * Custody — the control box's copy of what a box needs but the box may not\n * mint for itself: agent login credentials, per-project secrets/envs, and the\n * per-box SSH key material a host minted. The PC stays the source of truth\n * (roadmap §4, \"custody + reach\"); this is the copy the always-on hub holds so\n * a box created from either side is usable from both.\n *\n * The seam is deliberately **path-and-bytes shaped** — no file handles, no\n * streams, no directory semantics leaking through — so the filesystem backend\n * can be swapped for a blob store (key = path, `sha256` = object metadata)\n * without touching a caller. Payloads are small by construction (credentials,\n * `.env` files, SSH keys); the relay's 1 MiB body cap is the ceiling.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { Readable } from 'node:stream';\n\n/**\n * Top-level custody scopes. Anything else is rejected by {@link normalizeCustodyPath}.\n * `prepared` holds each provider's bake record (`<provider>-prepared.json`), so a\n * base baked on either side is visible to both.\n */\nexport const CUSTODY_SCOPES = ['agents', 'projects', 'boxes', 'prepared'] as const;\nexport type CustodyScope = (typeof CUSTODY_SCOPES)[number];\n\n/** Agent ids valid under `agents/` — mirrors `AgentId` in @agentbox/sandbox-core. */\nconst AGENT_IDS = ['claude', 'codex', 'opencode'] as const;\n\n/** Metadata for one stored entry. `sha256` is the ONLY change signal (never `updatedAt`). */\nexport interface CustodyEntry {\n /** Custody-relative path, e.g. `agents/claude/.credentials.json`. */\n path: string;\n size: number;\n /** Hex sha256 of the stored bytes. */\n sha256: string;\n /** POSIX mode of the stored value (filesystem backend: 0o600). */\n mode: number;\n /** ISO timestamp of the last *write*. Informational — hash-skipped puts leave it alone. */\n updatedAt: string;\n}\n\n/** {@link CustodyStore.put} result. `changed: false` means the bytes were already there. */\nexport interface CustodyPutResult extends CustodyEntry {\n changed: boolean;\n}\n\nexport interface CustodyStore {\n /**\n * Store `data` at `path`. Content-addressed skip: when the stored bytes\n * already hash to the same digest, nothing is written and `changed` is false.\n */\n put(path: string, data: Buffer): Promise<CustodyPutResult>;\n /** Fetch bytes + metadata, or null when absent. */\n get(path: string): Promise<{ entry: CustodyEntry; data: Buffer } | null>;\n /** Metadata only (the value never leaves the store). */\n stat(path: string): Promise<CustodyEntry | null>;\n /** The manifest: every entry whose path starts with `prefix` (all entries when omitted). */\n list(prefix?: string): Promise<CustodyEntry[]>;\n /** Remove one entry. Returns false when it wasn't there. */\n delete(path: string): Promise<boolean>;\n\n /**\n * Streaming counterparts of {@link put} / {@link get}, for payloads too large\n * to hold in memory twice.\n *\n * The rest of this seam is deliberately path-and-bytes shaped, and for\n * credentials / `.env` / SSH keys — all small by construction — that is the\n * right contract. A project's `carry:` material breaks the assumption: it is\n * whatever the user asked to be copied into their box, bounded only by\n * `box.cpMaxBytes` (100 MiB). Buffering that as base64 inside a JSON envelope\n * costs roughly six times the payload in peak memory on both ends, which a\n * 4 GB control box does not have to spare.\n *\n * So this pair is the explicit escape hatch rather than a replacement:\n * `put`/`get` stay the simple API, these carry the big objects.\n */\n putStream(path: string, body: Readable, opts?: { maxBytes?: number }): Promise<CustodyPutResult>;\n /**\n * Stream bytes out. Returns the metadata plus a readable, or null when absent.\n * The caller MUST consume or destroy `data`.\n */\n getStream(path: string): Promise<{ entry: CustodyEntry; data: Readable } | null>;\n}\n\n/** Thrown by {@link CustodyStore.putStream} when the body exceeds `maxBytes`. */\nexport class CustodyTooLargeError extends Error {\n constructor(readonly maxBytes: number) {\n super(`payload exceeds the custody blob cap of ${String(maxBytes)} bytes`);\n this.name = 'CustodyTooLargeError';\n }\n}\n\n/** A rejected custody path (bad scope, traversal, illegal segment). Handlers map this to 400. */\nexport class CustodyPathError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CustodyPathError';\n }\n}\n\nconst SEGMENT_RE = /^[A-Za-z0-9._-]+$/;\nconst MAX_SEGMENTS = 6;\nconst MAX_PATH_LENGTH = 256;\n\n/** Hex sha256 of `data` — the store's change signal and the CLI's skip check. */\nexport function custodyDigest(data: Buffer): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\n/**\n * Validate + canonicalize a custody path. Fail-closed: every segment must be a\n * plain name (`.`/`..` and separators rejected, so no traversal can escape the\n * root even before the backend resolves it), the first segment must be a known\n * scope, and `agents/` accepts only the three known agent ids.\n */\nexport function normalizeCustodyPath(raw: string): string {\n const trimmed = raw.replace(/^\\/+/, '').replace(/\\/+$/, '');\n if (trimmed.length === 0) throw new CustodyPathError('empty custody path');\n if (trimmed.length > MAX_PATH_LENGTH) {\n throw new CustodyPathError(`custody path too long (max ${String(MAX_PATH_LENGTH)} chars)`);\n }\n const segments = trimmed.split('/');\n if (segments.length < 2) {\n throw new CustodyPathError(`custody path needs a scope and a name: '${raw}'`);\n }\n if (segments.length > MAX_SEGMENTS) {\n throw new CustodyPathError(`custody path too deep (max ${String(MAX_SEGMENTS)} segments)`);\n }\n for (const seg of segments) {\n if (seg === '.' || seg === '..' || !SEGMENT_RE.test(seg)) {\n throw new CustodyPathError(`illegal custody path segment: '${seg}'`);\n }\n }\n const scope = segments[0] as CustodyScope;\n if (!CUSTODY_SCOPES.includes(scope)) {\n throw new CustodyPathError(\n `unknown custody scope '${scope}' (expected ${CUSTODY_SCOPES.join(' | ')})`,\n );\n }\n if (scope === 'agents' && !(AGENT_IDS as readonly string[]).includes(segments[1]!)) {\n throw new CustodyPathError(\n `unknown agent '${segments[1]!}' (expected ${AGENT_IDS.join(' | ')})`,\n );\n }\n return segments.join('/');\n}\n\n/**\n * Validate a manifest prefix. Looser than a full path (a bare scope like\n * `agents` or a partial `boxes/abc` is legal) but the same anti-traversal rules\n * apply, so a listing can never walk out of the root.\n */\nexport function normalizeCustodyPrefix(raw: string): string {\n const trimmed = raw.replace(/^\\/+/, '').replace(/\\/+$/, '');\n if (trimmed.length === 0) return '';\n if (trimmed.length > MAX_PATH_LENGTH) {\n throw new CustodyPathError(`custody prefix too long (max ${String(MAX_PATH_LENGTH)} chars)`);\n }\n const segments = trimmed.split('/');\n if (segments.length > MAX_SEGMENTS) {\n throw new CustodyPathError(`custody prefix too deep (max ${String(MAX_SEGMENTS)} segments)`);\n }\n for (const seg of segments) {\n if (seg === '.' || seg === '..' || !SEGMENT_RE.test(seg)) {\n throw new CustodyPathError(`illegal custody prefix segment: '${seg}'`);\n }\n }\n if (!CUSTODY_SCOPES.includes(segments[0] as CustodyScope)) {\n throw new CustodyPathError(\n `unknown custody scope '${segments[0]!}' (expected ${CUSTODY_SCOPES.join(' | ')})`,\n );\n }\n return segments.join('/');\n}\n","/**\n * The custody HTTP surface, as a framework-agnostic dispatcher mounted by BOTH\n * relay front-ends: the hosted-plane handler (`core/handler.ts`, Next) and the\n * relay daemon (`server.ts`, node:http — what the control box actually runs).\n * One implementation, one gate, both profiles.\n *\n * Gating is the caller's job with one hard rule, enforced here rather than by\n * each host router: **the admin bearer is the only proof**. `server.ts` treats\n * loopback as admin, but on the control box the hub sits behind Caddy on the\n * same host, so every proxied request looks loopback — accepting that here\n * would publish the credential store. Missing admin token or missing custody\n * store → 503 (not configured); wrong token → 401.\n *\n * Values never appear in a log line: only path, size, and the changed flag.\n */\n\nimport { timingSafeEqual } from 'node:crypto';\nimport type { Readable } from 'node:stream';\nimport {\n CustodyPathError,\n CustodyTooLargeError,\n normalizeCustodyPath,\n normalizeCustodyPrefix,\n type CustodyEntry,\n type CustodyStore,\n} from './store.js';\n\n/** Structurally identical to `RelayResponse` in `core/handler.ts` (kept local to avoid a cycle). */\nexport interface CustodyResponse {\n status: number;\n body?: unknown;\n}\n\nexport interface CustodyRequest {\n method: string;\n /** URL pathname, e.g. `/admin/custody/agents/claude/.credentials.json`. */\n path: string;\n query: URLSearchParams;\n /** Bearer token as presented ('' when absent). */\n bearer: string;\n /** Raw request body ('' for GET/DELETE). */\n bodyText: string;\n}\n\nexport interface CustodyRouteDeps {\n /** Wired by the control box / hub. Absent → custody is not enabled here (503). */\n custody?: CustodyStore | null;\n /** Admin bearer. Empty/absent → custody is not configured (503). */\n adminToken?: string;\n log?: (line: string) => void;\n}\n\nexport const CUSTODY_PATH_PREFIX = '/admin/custody';\n\n/** True when `path` addresses the custody surface (so a router can dispatch it here). */\nexport function isCustodyPath(path: string): boolean {\n return path === CUSTODY_PATH_PREFIX || path.startsWith(`${CUSTODY_PATH_PREFIX}/`);\n}\n\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\n/**\n * Dispatch one custody request. Returns `null` when `req.path` is not a custody\n * path, so a host router can fall through to its own routes unchanged.\n */\nexport async function handleCustodyRequest(\n req: CustodyRequest,\n deps: CustodyRouteDeps,\n): Promise<CustodyResponse | null> {\n if (!isCustodyPath(req.path)) return null;\n const log = deps.log ?? (() => {});\n\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'custody not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n const store = deps.custody;\n if (!store) {\n return { status: 503, body: { error: 'custody store not enabled on this relay' } };\n }\n\n try {\n if (req.path === CUSTODY_PATH_PREFIX) {\n if (req.method !== 'GET') return { status: 405, body: { error: 'method not allowed' } };\n const rawPrefix = req.query.get('prefix');\n const prefix = rawPrefix ? normalizeCustodyPrefix(rawPrefix) : undefined;\n const entries = await store.list(prefix);\n return { status: 200, body: { entries } };\n }\n\n const path = normalizeCustodyPath(\n decodeURIComponent(req.path.slice(`${CUSTODY_PATH_PREFIX}/`.length)),\n );\n\n if (req.method === 'PUT') {\n let parsed: { data?: unknown };\n try {\n parsed = JSON.parse(req.bodyText.length === 0 ? '{}' : req.bodyText) as { data?: unknown };\n } catch {\n return { status: 400, body: { error: 'expected JSON {data: <base64>}' } };\n }\n if (typeof parsed.data !== 'string') {\n return { status: 400, body: { error: 'expected {data: <base64>}' } };\n }\n const buf = Buffer.from(parsed.data, 'base64');\n // base64 decoding is lenient (it drops junk rather than throwing), so\n // round-trip it: a value that doesn't re-encode identically was not\n // base64 and would be stored silently truncated.\n if (buf.toString('base64') !== parsed.data.replace(/\\s+/g, '')) {\n return { status: 400, body: { error: 'data is not valid base64' } };\n }\n const result = await store.put(path, buf);\n log(\n `custody put ${path} (${String(result.size)} bytes, ${result.changed ? 'changed' : 'unchanged'})`,\n );\n return { status: 200, body: result };\n }\n\n if (req.method === 'GET') {\n const found = await store.get(path);\n if (!found) return { status: 404, body: { error: 'no such custody entry' } };\n log(`custody get ${path} (${String(found.entry.size)} bytes)`);\n return { status: 200, body: { ...found.entry, data: found.data.toString('base64') } };\n }\n\n if (req.method === 'DELETE') {\n const hit = await store.delete(path);\n if (!hit) return { status: 404, body: { error: 'no such custody entry' } };\n log(`custody delete ${path}`);\n return { status: 204 };\n }\n\n return { status: 405, body: { error: 'method not allowed' } };\n } catch (err) {\n if (err instanceof CustodyPathError) return { status: 400, body: { error: err.message } };\n const msg = err instanceof Error ? err.message : String(err);\n log(`custody error: ${msg}`);\n return { status: 500, body: { error: `custody: ${msg}` } };\n }\n}\n\n/**\n * The BLOB surface: the same store, addressed the same way, but moving raw\n * `application/octet-stream` bytes instead of base64 inside a JSON envelope.\n *\n * Deliberately a second endpoint rather than a content-type branch on the first.\n * The JSON API is the easy, general-purpose one — a curl and a base64 is all any\n * consumer needs for a credential or a `.env`, and it stays exactly as it was.\n * This one is the advanced path for objects big enough that buffering them twice\n * matters: a project's `carry:` material can run to `box.cpMaxBytes` (100 MiB),\n * where the JSON envelope costs ~6x the payload in peak memory across both ends.\n *\n * Keeping them separate also means there is no wire to break: an older hub\n * simply 404s this prefix, which a client can detect and report precisely.\n */\nexport const CUSTODY_BLOB_PATH_PREFIX = '/admin/custody-blob';\n\n/** True when `path` addresses the blob surface. Disjoint from {@link isCustodyPath}. */\nexport function isCustodyBlobPath(path: string): boolean {\n return path.startsWith(`${CUSTODY_BLOB_PATH_PREFIX}/`);\n}\n\nexport interface CustodyBlobRequest {\n method: string;\n /** URL pathname, e.g. `/admin/custody-blob/projects/acme__web/seed/carry.tar.gz`. */\n path: string;\n bearer: string;\n /** Request body for PUT. Absent for GET/DELETE. */\n body?: Readable;\n /** Cap enforced while streaming (`relay.custodyMaxBlobBytes`). */\n maxBytes?: number;\n}\n\n/**\n * A blob response. `stream` is set only for a successful GET, and the caller\n * owns piping it; everything else is a small JSON `body` exactly like the JSON\n * surface, so error handling is identical on both.\n */\nexport interface CustodyBlobResponse {\n status: number;\n body?: unknown;\n stream?: Readable;\n /** Metadata for a GET, so the host router can set content-length / digest headers. */\n entry?: CustodyEntry;\n}\n\nexport async function handleCustodyBlobRequest(\n req: CustodyBlobRequest,\n deps: CustodyRouteDeps,\n): Promise<CustodyBlobResponse | null> {\n if (!isCustodyBlobPath(req.path)) return null;\n const log = deps.log ?? (() => {});\n\n // Same gate as the JSON surface, for the same reason: on the control box every\n // proxied request looks loopback, so the admin bearer is the only proof.\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'custody not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n const store = deps.custody;\n if (!store) {\n return { status: 503, body: { error: 'custody store not enabled on this relay' } };\n }\n\n try {\n const path = normalizeCustodyPath(\n decodeURIComponent(req.path.slice(`${CUSTODY_BLOB_PATH_PREFIX}/`.length)),\n );\n\n if (req.method === 'PUT') {\n if (!req.body) return { status: 400, body: { error: 'expected a request body' } };\n const result = await store.putStream(path, req.body, { maxBytes: req.maxBytes });\n log(\n `custody blob put ${path} (${String(result.size)} bytes, ${result.changed ? 'changed' : 'unchanged'})`,\n );\n return { status: 200, body: result };\n }\n\n if (req.method === 'GET') {\n const found = await store.getStream(path);\n if (!found) return { status: 404, body: { error: 'no such custody entry' } };\n log(`custody blob get ${path} (${String(found.entry.size)} bytes)`);\n return { status: 200, stream: found.data, entry: found.entry };\n }\n\n return { status: 405, body: { error: 'method not allowed' } };\n } catch (err) {\n if (err instanceof CustodyPathError) return { status: 400, body: { error: err.message } };\n if (err instanceof CustodyTooLargeError) {\n // 413, and the message names the key — an operator hitting this needs to\n // know it is a configured cap, not a broken upload.\n return {\n status: 413,\n body: {\n error: `${err.message}. Raise \\`relay.custodyMaxBlobBytes\\` here and AGENTBOX_CUSTODY_MAX_BLOB_BYTES on the control box.`,\n },\n };\n }\n const msg = err instanceof Error ? err.message : String(err);\n log(`custody blob error: ${msg}`);\n return { status: 500, body: { error: `custody: ${msg}` } };\n }\n}\n","/**\n * The `/remote/boxes` create-queue surface, as a framework-agnostic dispatcher\n * mounted by BOTH relay front-ends: the hosted-plane handler (`core/handler.ts`,\n * Next/Vercel) and the relay daemon (`server.ts`, node:http — what the control\n * box actually runs). One implementation, one gate, both profiles.\n *\n * Like custody, the **admin bearer is the only proof** — never loopback (the\n * control box sits behind Caddy on the same host, so every proxied request looks\n * loopback). Missing admin token → 503 (not configured); wrong token → 401; a\n * store without the create-job queue → 501.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { rm } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { timingSafeEqual } from 'node:crypto';\nimport type { CustodyStore } from './custody/store.js';\nimport type { CreateJobRequest, Store } from './store/store.js';\n\n/** Structurally identical to `RelayResponse` in `core/handler.ts` (kept local to avoid a cycle). */\nexport interface RemoteBoxesResponse {\n status: number;\n body?: unknown;\n}\n\nexport interface RemoteBoxesRequest {\n method: string;\n /** URL pathname, e.g. `/remote/boxes` or `/remote/boxes/<jobId>`. */\n path: string;\n /** Bearer token as presented ('' when absent). */\n bearer: string;\n /** Raw request body ('' for GET). */\n bodyText: string;\n /** Query params, for the log tail's `?offset=`. Absent → treated as empty. */\n query?: URLSearchParams;\n}\n\nexport interface RemoteBoxesDeps {\n store: Store;\n /** Admin bearer. Empty/absent → not configured (503). */\n adminToken?: string;\n /**\n * Providers this plane can CREATE boxes on. `undefined`/empty → all allowed\n * (the full-host control box). A serverless plane sets the SDK-native set.\n */\n createProviders?: string[];\n /**\n * The custody store, if wired. A reap (`DELETE`) also removes the box's\n * `boxes/<sandboxId>/` SSH-key subtree from here so a destroyed box leaves no\n * key material behind. Absent → the reap only clears the registration/status.\n */\n custody?: CustodyStore | null;\n /**\n * Tail of a job's progress log, by byte offset. Wired by the relay daemon\n * (which runs on the same host as the worker writing the file) and omitted by\n * the serverless plane, where there is no such file — absent → 501, and a\n * polling client falls back to status-only progress.\n */\n readJobLog?: (jobId: string, offset: number) => Promise<{ lines: string[]; offset: number }>;\n log?: (line: string) => void;\n}\n\nexport const REMOTE_BOXES_PREFIX = '/remote/boxes';\n\n/**\n * A job id we are willing to hand to a path-building reader.\n *\n * Enforced HERE, at the trust boundary, not only inside the one reader that\n * builds a path today: `readJobLog` is injectable, and a future implementation\n * that forgot the check would inherit a path traversal straight off the URL.\n */\nexport function isSafeJobId(id: string): boolean {\n return id.length > 0 && id.length <= 128 && /^[A-Za-z0-9._-]+$/.test(id);\n}\n\n/** True when `path` addresses the create-queue surface. */\nexport function isRemoteBoxesPath(path: string): boolean {\n return path === REMOTE_BOXES_PREFIX || path.startsWith(`${REMOTE_BOXES_PREFIX}/`);\n}\n\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\nfunction parseJson<T>(text: string): T | null {\n if (text.length === 0) return {} as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\n/**\n * Dispatch one `/remote/boxes` request. Returns `null` when `req.path` is not a\n * create-queue path, so a host router falls through to its own routes unchanged.\n */\nexport async function handleRemoteBoxesRequest(\n req: RemoteBoxesRequest,\n deps: RemoteBoxesDeps,\n): Promise<RemoteBoxesResponse | null> {\n if (!isRemoteBoxesPath(req.path)) return null;\n const log = deps.log ?? (() => {});\n const { store } = deps;\n\n const adminToken = deps.adminToken ?? '';\n if (adminToken.length === 0) {\n return { status: 503, body: { error: 'control plane not configured: admin token unset' } };\n }\n if (!timingSafeEqualStr(req.bearer, adminToken)) {\n return { status: 401, body: { error: 'invalid admin token' } };\n }\n\n if (req.method === 'POST' && req.path === REMOTE_BOXES_PREFIX) {\n if (!store.enqueueCreateJob) {\n return { status: 501, body: { error: 'create-job queue not available on this store' } };\n }\n const body = parseJson<CreateJobRequest>(req.bodyText);\n if (!body || typeof body.repoUrl !== 'string' || typeof body.provider !== 'string') {\n return { status: 400, body: { error: 'expected {repoUrl, provider, branch?, name?, agent?, prompt?}' } };\n }\n const allowed = deps.createProviders;\n if (allowed && allowed.length > 0 && !allowed.includes(body.provider)) {\n return {\n status: 400,\n body: {\n error: `provider '${body.provider}' is not supported by this control plane (allowed: ${allowed.join(', ')})`,\n },\n };\n }\n const id = randomUUID();\n await store.enqueueCreateJob({\n id,\n status: 'queued',\n request: {\n repoUrl: body.repoUrl,\n provider: body.provider,\n branch: body.branch,\n name: body.name,\n agent: body.agent,\n prompt: body.prompt,\n },\n createdAt: new Date().toISOString(),\n });\n log(`enqueued create job ${id} (${body.provider} ${body.repoUrl})`);\n return { status: 202, body: { jobId: id } };\n }\n\n // The queue's own listing. Without it the create queue is addressable only by\n // job id, so a PC that enqueued a background run can't see what else is in\n // flight — `agentbox queue list` would show its local jobs and nothing else.\n if (req.method === 'GET' && req.path === REMOTE_BOXES_PREFIX) {\n if (!store.listCreateJobs) {\n return { status: 501, body: { error: 'create-job queue not available on this store' } };\n }\n const jobs = await store.listCreateJobs({ limit: 100 });\n return { status: 200, body: { jobs } };\n }\n\n // A job's progress log, by byte offset. The worker's per-step lines (clone,\n // seed, the provider's own create output) exist only as a file on the plane\n // that ran the job — without this the PC's `create --via-hub` / `<provider>\n // claude` sits on one static \"running\" line for the minutes a cloud create\n // takes, because the job row carries a status and nothing else.\n if (req.method === 'GET' && req.path.endsWith('/logs')) {\n const id = decodeURIComponent(\n req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length, -'/logs'.length),\n );\n if (id.length === 0) return { status: 404, body: { error: 'no such job' } };\n if (!isSafeJobId(id)) return { status: 400, body: { error: 'invalid job id' } };\n if (!deps.readJobLog) {\n return { status: 501, body: { error: 'job logs not available on this plane' } };\n }\n const offset = Number.parseInt(req.query?.get('offset') ?? '0', 10);\n const tail = await deps.readJobLog(id, Number.isFinite(offset) ? offset : 0);\n return { status: 200, body: tail };\n }\n\n if (req.method === 'GET' && req.path.startsWith(`${REMOTE_BOXES_PREFIX}/`)) {\n if (!store.getCreateJob) {\n return { status: 501, body: { error: 'create-job queue not available on this store' } };\n }\n const id = decodeURIComponent(req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length));\n const job = await store.getCreateJob(id);\n return job ? { status: 200, body: job } : { status: 404, body: { error: 'no such job' } };\n }\n\n // Reap a control-plane box's state from the control box: registration + status\n // + its SSH-key custody subtree. NOT the cloud resource — that teardown needs\n // provider creds + a reconstructed BoxRecord (the hub backend does it when it\n // can). The PC drives this via `hub boxes rm`; the hub UI's Destroy\n // button reaps a Store-registered box the same way.\n if (req.method === 'DELETE' && req.path.startsWith(`${REMOTE_BOXES_PREFIX}/`)) {\n const boxId = decodeURIComponent(req.path.slice(`${REMOTE_BOXES_PREFIX}/`.length));\n if (boxId.length === 0) return { status: 404, body: { error: 'no such box' } };\n const reg = await store.getBox(boxId);\n const existed = await store.forgetBox(boxId);\n await store.deleteStatus(boxId);\n let custodyRemoved = 0;\n if (deps.custody) {\n // Keyed by sandboxId on disk + in custody; fall back to boxId for\n // registrations minted before sandboxId was carried.\n const key = reg?.sandboxId ?? boxId;\n const entries = await deps.custody.list(`boxes/${key}`).catch(() => []);\n for (const e of entries) {\n if (await deps.custody.delete(e.path).catch(() => false)) custodyRemoved += 1;\n }\n }\n // The control box also holds its OWN copy of a box it built: a `state.json`\n // record and the per-box SSH key dir the provider minted. Reaping only the\n // Store left those behind, so a box destroyed from the PC kept showing as\n // `running` in `hub boxes list`, the dashboard and the tray (both read local\n // state first, and a cloud row renders from `cloud.lastState` with no live\n // probe), with its private key still on disk.\n const localRemoved = await reapLocalBoxState(boxId, reg?.sandboxId, log);\n if (!existed && !reg && custodyRemoved === 0 && !localRemoved) {\n return { status: 404, body: { error: 'no such box' } };\n }\n log(\n `reaped box ${boxId} (registration=${String(existed)}, custody=${String(custodyRemoved)}, local=${String(localRemoved)})`,\n );\n return { status: 200, body: { boxId, removed: existed, custodyRemoved, localRemoved } };\n }\n\n return { status: 405, body: { error: 'method not allowed' } };\n}\n\n/**\n * Drop the control box's own record of a box whose cloud resource is already\n * gone: the `state.json` entry and the per-box SSH key dir the provider minted.\n *\n * Scoped to exactly this box's sandbox id — never a sweep. `prune --all`\n * enumerates box dirs by the docker-shaped `<id>-<n>-<mnemonic>` run-dir name,\n * which a VPS provider's sandboxId-keyed dir never matches, so a broad cleanup\n * there would delete a LIVE box's private key.\n *\n * Best-effort and idempotent: this runs on a plain relay too, where there is no\n * local record to remove.\n */\nasync function reapLocalBoxState(\n boxId: string,\n sandboxId: string | undefined,\n log: (line: string) => void,\n): Promise<boolean> {\n let removed = false;\n try {\n const { mutateState, readState, boxSshDirForProvider } = await import('@agentbox/sandbox-core');\n const state = await readState();\n const record = state.boxes.find((b) => b.id === boxId);\n if (record) {\n await mutateState((s) => ({ ...s, boxes: s.boxes.filter((b) => b.id !== boxId) }));\n removed = true;\n const key = record.cloud?.sandboxId ?? sandboxId;\n const provider = record.provider;\n if (key && provider) {\n const sshDir = boxSshDirForProvider(provider, key);\n // `<...>/boxes/<sandboxId>/ssh` — take the box dir, not just the keys.\n if (sshDir) await rm(dirname(sshDir), { recursive: true, force: true }).catch(() => {});\n }\n }\n } catch (err) {\n log(`local reap for ${boxId} failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n return removed;\n}\n","import type { BoxRegistry, EventBuffer } from '../registry.js';\nimport type { BoxStatusSnapshot, BoxStatusStore } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\nexport interface WriteThroughParts {\n registry: BoxRegistry;\n events: EventBuffer;\n statusStore: BoxStatusStore;\n}\n\n/** A durable store that also exposes the optional retention sweeps. */\ninterface StoreWithStatuses extends Store {\n prunePrompts?(beforeIso: string): Promise<number>;\n pruneCreateJobs?(beforeIso: string): Promise<number>;\n}\n\n/**\n * Wraps a durable {@link Store} (SQLite / Postgres) and mirrors every mutating\n * call into the in-process `BoxRegistry` / `EventBuffer` / `BoxStatusStore` the\n * relay handle exposes.\n *\n * Why this exists: the daemon's background loops (autopause, cloud-keepalive,\n * queue) and the hub backend read those concrete instances *synchronously*, not\n * the async `Store`. On the laptop that is fine — `MemoryStore` IS those\n * instances. But a control box injects a durable store, and without this wrapper\n * the handlers would write to SQLite while the instances stay empty, so\n * cloud-keepalive would never see a box and the hub UI would show no status.\n *\n * The durable store stays the source of truth (it survives restarts); the\n * in-memory instances are a within-process cache kept in lock-step by\n * write-through + a one-time {@link hydrate} on boot. The control box runs a\n * single hub process (SQLite single-writer, per phase 1), so no other writer can\n * make the mirror stale. Reads are pure delegation to the durable store.\n */\nexport class WriteThroughStore implements Store {\n private readonly inner: StoreWithStatuses;\n private readonly registry: BoxRegistry;\n private readonly events: EventBuffer;\n private readonly statusStore: BoxStatusStore;\n\n constructor(inner: Store, parts: WriteThroughParts) {\n this.inner = inner;\n this.registry = parts.registry;\n this.events = parts.events;\n this.statusStore = parts.statusStore;\n }\n\n /**\n * Load the durable store's boxes + statuses into the in-memory instances, once\n * at boot, so the loops start against a populated registry after a restart.\n * Events are a ring buffer (ephemeral) and are not hydrated.\n */\n async hydrate(): Promise<void> {\n for (const reg of await this.inner.listBoxes()) this.registry.register(reg);\n for (const { boxId, status } of await this.inner.listStatuses()) {\n const reg = this.registry.get(boxId);\n await this.statusStore.set(boxId, reg?.name ?? boxId, reg?.projectIndex, status);\n }\n }\n\n migrate(): Promise<void> {\n return this.inner.migrate?.() ?? Promise.resolve();\n }\n\n // --- boxes ---\n\n async registerBox(reg: BoxRegistration): Promise<void> {\n await this.inner.registerBox(reg);\n this.registry.register(reg);\n }\n\n getBox(boxId: string): Promise<BoxRegistration | undefined> {\n return this.inner.getBox(boxId);\n }\n\n authenticateBox(token: string): Promise<BoxRegistration | null> {\n return this.inner.authenticateBox(token);\n }\n\n listBoxes(): Promise<BoxRegistration[]> {\n return this.inner.listBoxes();\n }\n\n async forgetBox(boxId: string): Promise<boolean> {\n const existed = await this.inner.forgetBox(boxId);\n this.registry.forget(boxId);\n return existed;\n }\n\n countBoxes(): Promise<number> {\n return this.inner.countBoxes();\n }\n\n // --- events ---\n\n async appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n const ev = await this.inner.appendEvent(input);\n // The mirror ring keeps its own id sequence; the loops only read box/type/ts,\n // never cross-reference the durable id, so the divergence is harmless.\n this.events.append(input);\n return ev;\n }\n\n listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n return this.inner.listEvents(since, boxId);\n }\n\n countEvents(): Promise<number> {\n return this.inner.countEvents();\n }\n\n // --- status ---\n\n async setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n await this.inner.setStatus(boxId, name, projectIndex, status);\n await this.statusStore.set(boxId, name, projectIndex, status);\n }\n\n getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n return this.inner.getStatus(boxId);\n }\n\n async deleteStatus(boxId: string): Promise<void> {\n await this.inner.deleteStatus(boxId);\n this.statusStore.delete(boxId);\n }\n\n listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n return this.inner.listStatuses();\n }\n\n // --- prompt mailbox (pure delegation; no in-memory mirror the loops read) ---\n\n createPrompt(row: PromptRow): Promise<void> {\n return this.inner.createPrompt(row);\n }\n\n getPrompt(promptId: string): Promise<PromptRow | null> {\n return this.inner.getPrompt(promptId);\n }\n\n answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n return this.inner.answerPrompt(promptId, answer, cancelled);\n }\n\n listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n return this.inner.listPendingPrompts(boxId);\n }\n\n setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n return this.inner.setPromptResult(promptId, result);\n }\n\n // --- box-create job queue (pure delegation) ---\n\n enqueueCreateJob(job: CreateJobRow): Promise<void> {\n if (!this.inner.enqueueCreateJob) return Promise.resolve();\n return this.inner.enqueueCreateJob(job);\n }\n\n getCreateJob(id: string): Promise<CreateJobRow | null> {\n return this.inner.getCreateJob?.(id) ?? Promise.resolve(null);\n }\n\n listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n return this.inner.listCreateJobs?.(opts) ?? Promise.resolve([]);\n }\n\n claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n return this.inner.claimNextCreateJob?.(workerId) ?? Promise.resolve(null);\n }\n\n completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n if (!this.inner.completeCreateJob) return Promise.resolve();\n return this.inner.completeCreateJob(id, status, result);\n }\n\n // --- retention (forwarded; blocker B) ---\n\n prunePrompts(beforeIso: string): Promise<number> {\n return this.inner.prunePrompts?.(beforeIso) ?? Promise.resolve(0);\n }\n\n pruneCreateJobs(beforeIso: string): Promise<number> {\n return this.inner.pruneCreateJobs?.(beforeIso) ?? Promise.resolve(0);\n }\n}\n","import { createSign } from 'node:crypto';\n\n/**\n * GitHub App token leasing for the hosted control plane.\n *\n * The control plane holds only the App's private key + id — never a long-lived\n * PAT and never a box's repo. On an approved push it mints a short-lived\n * **installation access token** scoped to the SINGLE box repo (minimal perms)\n * and hands it to the box, which pushes to GitHub directly. GitHub installation\n * tokens always expire in ≤1h and are repo-scoped, so a compromised box yields\n * at most a 1h single-repo credential. The token is never persisted (in-memory\n * cache only; re-minted on a cold start — two cheap API calls).\n *\n * `fetch` (Node 20+) is used directly — no SDK dependency.\n */\n\nexport interface GitHubAppConfig {\n appId: string;\n privateKeyPem: string;\n /** API base; defaults to https://api.github.com (override for GHES). */\n apiBaseUrl?: string;\n}\n\nexport interface LeasedToken {\n token: string;\n /** ISO-8601 expiry as returned by GitHub. */\n expiresAt: string;\n}\n\n/**\n * Load the App config from the environment, or null when not configured.\n * `GITHUB_APP_PRIVATE_KEY` may be a raw PEM or base64-encoded PEM (env-friendly).\n */\nexport function loadGitHubAppConfig(): GitHubAppConfig | null {\n const appId = process.env.GITHUB_APP_ID;\n let key = process.env.GITHUB_APP_PRIVATE_KEY;\n if (!appId || !key) return null;\n if (!key.includes('BEGIN')) {\n try {\n key = Buffer.from(key, 'base64').toString('utf8');\n } catch {\n return null;\n }\n }\n const apiBaseUrl = process.env.GITHUB_API_URL || undefined;\n return { appId, privateKeyPem: key, apiBaseUrl };\n}\n\nfunction b64url(input: string | Buffer): string {\n return Buffer.from(input).toString('base64url');\n}\n\n/**\n * Mint the App JWT (RS256). `exp` is well under GitHub's 10-minute ceiling;\n * `iat` is backdated 60s to tolerate clock skew. Exported for unit testing.\n */\nexport function appJwt(cfg: GitHubAppConfig, nowMs: number = Date.now()): string {\n const now = Math.floor(nowMs / 1000);\n const header = b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }));\n const payload = b64url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: cfg.appId }));\n const signingInput = `${header}.${payload}`;\n const signature = createSign('RSA-SHA256').update(signingInput).sign(cfg.privateKeyPem);\n return `${signingInput}.${b64url(signature)}`;\n}\n\ntype FetchLike = typeof fetch;\n\nexport interface GitHubAppLeaserOptions {\n /** Inject a fetch impl (tests). Defaults to the global fetch. */\n fetchImpl?: FetchLike;\n /** Inject a clock (tests). Defaults to Date.now. */\n now?: () => number;\n}\n\ninterface CacheEntry {\n token: string;\n expiresAt: string;\n expiresAtMs: number;\n}\n\nconst RENEW_BEFORE_MS = 5 * 60 * 1000; // re-mint when <5 min of life remains\n\n/**\n * Leases (and caches) repo-scoped installation tokens. One instance per relay\n * server. The cache key is `owner/repo`; a token is reused until it is within\n * RENEW_BEFORE_MS of expiry.\n */\nexport class GitHubAppLeaser {\n private readonly cfg: GitHubAppConfig;\n private readonly fetchImpl: FetchLike;\n private readonly now: () => number;\n private readonly apiBase: string;\n private readonly cache = new Map<string, CacheEntry>();\n private readonly installationIds = new Map<string, number>();\n\n constructor(cfg: GitHubAppConfig, opts: GitHubAppLeaserOptions = {}) {\n this.cfg = cfg;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n this.now = opts.now ?? Date.now;\n this.apiBase = (cfg.apiBaseUrl ?? 'https://api.github.com').replace(/\\/$/, '');\n }\n\n private headers(jwt: string): Record<string, string> {\n return {\n Authorization: `Bearer ${jwt}`,\n Accept: 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n 'User-Agent': 'agentbox-relay',\n };\n }\n\n /**\n * Resolve the installation id for `owner/repo`, or null when the App is not\n * installed on it (404). Caches positive lookups. Non-404 errors throw.\n */\n private async lookupInstallationId(owner: string, repo: string): Promise<number | null> {\n const key = `${owner}/${repo}`;\n const cached = this.installationIds.get(key);\n if (cached !== undefined) return cached;\n const jwt = appJwt(this.cfg, this.now());\n const res = await this.fetchImpl(`${this.apiBase}/repos/${owner}/${repo}/installation`, {\n headers: this.headers(jwt),\n });\n if (res.status === 404) return null;\n if (!res.ok) {\n throw new Error(`GET installation for ${key} → ${String(res.status)}`);\n }\n const body = (await res.json()) as { id?: number };\n if (typeof body.id !== 'number') throw new Error('installation response missing id');\n this.installationIds.set(key, body.id);\n return body.id;\n }\n\n private async installationId(owner: string, repo: string): Promise<number> {\n const id = await this.lookupInstallationId(owner, repo);\n if (id === null) throw new Error(`GitHub App is not installed on ${owner}/${repo}`);\n return id;\n }\n\n /** Whether the App is installed on `owner/repo` — no token is minted. */\n async isRepoInstalled(owner: string, repo: string): Promise<boolean> {\n return (await this.lookupInstallationId(owner, repo)) !== null;\n }\n\n /**\n * Mint (or return a cached) installation token scoped to the single repo with\n * `contents: write` + `pull_requests: write`. Throws on any GitHub error.\n */\n async leaseRepoToken(owner: string, repo: string): Promise<LeasedToken> {\n const key = `${owner}/${repo}`;\n const cached = this.cache.get(key);\n if (cached && cached.expiresAtMs - this.now() > RENEW_BEFORE_MS) {\n return { token: cached.token, expiresAt: cached.expiresAt };\n }\n const id = await this.installationId(owner, repo);\n const jwt = appJwt(this.cfg, this.now());\n const res = await this.fetchImpl(`${this.apiBase}/app/installations/${String(id)}/access_tokens`, {\n method: 'POST',\n headers: { ...this.headers(jwt), 'Content-Type': 'application/json' },\n body: JSON.stringify({\n repositories: [repo],\n permissions: { contents: 'write', pull_requests: 'write' },\n }),\n });\n if (!res.ok) {\n throw new Error(`failed to mint installation token for ${key} (→ ${String(res.status)})`);\n }\n const body = (await res.json()) as { token?: string; expires_at?: string };\n if (!body.token || !body.expires_at) throw new Error('access_tokens response missing token/expires_at');\n this.cache.set(key, {\n token: body.token,\n expiresAt: body.expires_at,\n expiresAtMs: Date.parse(body.expires_at),\n });\n return { token: body.token, expiresAt: body.expires_at };\n }\n}\n","import { spawn } from 'node:child_process';\nimport { randomBytes } from 'node:crypto';\nimport { mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { closeSync, existsSync, openSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type GitPushMode,\n type UserConfig,\n} from '@agentbox/config';\nimport { readState, STATE_DIR, STATE_FILE } from '@agentbox/sandbox-core';\nimport type { BoxRecord, ResolvedCarryEntry } from '@agentbox/core';\nimport type { BoxRegistry } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\nexport const QUEUE_DIR = join(STATE_DIR, 'queue');\n\n/**\n * Concurrency ceiling for `kind: 'prepare'` (image-bake) jobs, applied **per\n * provider lane** — a separate gate from box creation. Two bakes of the same\n * provider would race on that provider's prepared-state marker and its\n * `box.image<Provider>` pin, so a provider bakes one at a time and a second\n * request for it queues. Different providers share nothing and bake in parallel.\n *\n * The lane key is `job.providerName` verbatim, so a remote-docker `docker:<alias>`\n * bake gets its own lane per host — those run on different machines entirely.\n */\nexport const PREPARE_MAX_CONCURRENT_PER_PROVIDER = 1;\n\nexport type QueueJobStatus = 'queued' | 'running' | 'done' | 'failed' | 'cancelled';\nexport type QueueAgentKind = 'claude-code' | 'codex' | 'opencode';\n\n/**\n * Host-terminal targeting captured on the submitting host when `queue.openIn`\n * is not `none`, carried on the job so the worker can open a fresh terminal\n * onto the box the moment it is ready. The relay treats this as opaque\n * pass-through; the CLI worker (`_run-queued-job`) is what reads and acts on it.\n *\n * The targeting is captured at submit time because the relay daemon is\n * long-lived and idempotent — its own env reflects whatever terminal first\n * started it, not this submit's terminal.\n */\nexport interface QueueJobOpenTerminal {\n host: 'tmux' | 'cmux' | 'herdr' | 'iterm2';\n mode: 'split' | 'window' | 'tab';\n /** Submitting shell's cwd, so the new pane resolves project-scoped refs. */\n cwd: string;\n /** tmux server socket (`$TMUX`) + the pane to split (`$TMUX_PANE`). */\n tmuxSocket?: string;\n tmuxPane?: string;\n /** cmux control socket (`$CMUX_SOCKET_PATH`) + bundled CLI path. */\n cmuxSocket?: string;\n cmuxBundledCli?: string;\n /** Submitting surface + workspace UUIDs (`$CMUX_SURFACE_ID` /\n * `$CMUX_WORKSPACE_ID`), so the worker can split the original pane (or, failing\n * that, the parent workspace) instead of opening a new top-level workspace. */\n cmuxSurfaceId?: string;\n cmuxWorkspaceId?: string;\n /** Herdr session socket (`$HERDR_SOCKET_PATH`) + submitting pane/workspace ids\n * (`$HERDR_PANE_ID` / `$HERDR_WORKSPACE_ID`), so the worker can split the\n * original pane / add a tab in the parent workspace. */\n herdrSocket?: string;\n herdrPaneId?: string;\n herdrWorkspaceId?: string;\n}\n\n/** On-disk job manifest. Read/written under `~/.agentbox/queue/<id>.json`. */\nexport interface QueueJob {\n id: string;\n /**\n * What the worker does with this job. `create` (default when absent) builds a\n * box. `prepare` bakes a provider's base image — it produces an artifact, not\n * a box, so it is excluded from the box/working concurrency gates and never\n * surfaces as a box in the dashboard. Prepare jobs carry `prepare` (not the\n * agent/create fields, which hold inert placeholders).\n */\n kind?: 'create' | 'prepare';\n agent: QueueAgentKind;\n status: QueueJobStatus;\n /** Friendly box name the worker should create the box under. */\n boxName: string;\n providerName: string;\n /** Original initial-prompt text the user passed via `-i`. */\n prompt: string;\n /** Extra argv tokens passed after `--`. */\n agentArgs: string[];\n /**\n * \"Just create the box, don't start an agent\" (like `agentbox create`). When\n * true the worker builds the box and stops — no agent session, no prompt.\n * `agent` still holds a value (required by the type) but is ignored.\n */\n noAgent?: boolean;\n /**\n * Seed the agent's first turn with the setup-wizard prompt (generate\n * `agentbox.yaml`) — set by the hub when the project has no `agentbox.yaml`\n * and no default snapshot. Inert when `noAgent` (no agent to run it).\n */\n setupWizard?: boolean;\n /**\n * A FOREGROUND create (an interactive `agentbox create` a human is watching),\n * as opposed to a background `-i` run. The scheduler starts foreground jobs in\n * their own lane, ungated by `queue.maxConcurrent` — that gate bounds background\n * fan-out, and making an interactive command sit `queued` behind unrelated `-i`\n * jobs would be a worse regression than the inline path it replaces. Its box\n * still counts in the running total once live (honest occupancy); it is just\n * never blocked. See {@link selectNextRunnableForeground}.\n */\n foreground?: boolean;\n /** Workspace + create-time options the worker reconstructs from. */\n createOpts: QueueJobCreateOpts;\n /** Per-job concurrency ceiling (--max-running override, else the global). */\n maxConcurrent: number;\n /**\n * Per-job working-agent ceiling (--max-working override, else the global\n * `queue.maxWorking`). Only consulted when the working-agent gate is active\n * (`queue.maxWorking > 0`). Absent → use the global.\n */\n maxWorking?: number;\n /**\n * Box id the worker created for this job, written back to the manifest as\n * soon as `createBox` returns (before the agent session starts). Lets the\n * working-agent counter join a `running` manifest to its live box status and\n * avoid double-counting the in-flight startup slot once the box registers.\n */\n boxId?: string;\n /**\n * Host-terminal targeting for `queue.openIn`. Set at submit time when the\n * submitting shell ran inside a supported terminal; absent → open nothing.\n */\n openTerminal?: QueueJobOpenTerminal;\n createdAt: string;\n startedAt?: string;\n finishedAt?: string;\n /** Per-job log file path the worker writes to. */\n logPath: string;\n /** PID of the running worker. */\n pid?: number;\n /** Free-form context attached on terminal status flips. */\n reason?: string;\n /** Exit code of the worker process (only set on done/failed). */\n exitCode?: number;\n /**\n * Interactive Claude re-login sub-state. Set by the worker when it detects an\n * expired/dead Claude login during create and drives a browser re-login in a\n * throwaway docker container (job stays `running` meanwhile). The hub API/UI\n * read `phase`/`url`/`error` to surface the flow; the code endpoint writes\n * `code` back, which the worker consumes and clears. Absent for the normal\n * (creds-OK) path.\n */\n login?: QueueJobLogin;\n /** Bake options for a `kind: 'prepare'` job (see {@link QueueJobPrepare}). */\n prepare?: QueueJobPrepare;\n}\n\n/**\n * Claude re-login sub-state carried on a create job. Written **only by the create\n * worker** (worker → UI): `phase`/`url`/`error`/`lastError`. The reverse channel\n * (the pasted OAuth code, UI → worker) rides a separate file — see\n * {@link queueLoginCodePath} — so the two sides never read-modify-write the same\n * object and can't lose each other's updates.\n */\nexport interface QueueJobLogin {\n required: boolean;\n phase: 'starting' | 'awaiting-code' | 'exchanging' | 'done' | 'error';\n /** OAuth approval URL the user must open; present from `awaiting-code` onward. */\n url?: string;\n /** Terminal failure reason (with `phase: 'error'`). */\n error?: string;\n /** A recoverable note (e.g. a rejected code) — the flow stays usable. */\n lastError?: string;\n}\n\n/**\n * Options for a `kind: 'prepare'` job: bake a provider's base image. The worker\n * (`_run-queued-prepare`) passes these into `provider.prepare`, filling any that\n * are absent from the hub's own effective config, and streams progress to the\n * job log. These are the bake INPUTS (not routing) — the CLI's `--build` /\n * `--size` / `--location` / `--name` flags ride here so one route serves every\n * bake shape.\n */\nexport interface QueueJobPrepare {\n /** Rebuild even if the base image/snapshot already exists. */\n force?: boolean;\n /** Bake-time Claude install method (falls back to the effective config). */\n claudeInstall?: 'native' | 'npm';\n /** Force a local docker build instead of pulling the registry base (`--build`). */\n build?: boolean;\n /** Bake-time VM size for the fixed-resource providers (daytona `cpu-mem-disk`, e2b `cpu-mem`). */\n size?: string;\n /** Bake datacenter / region (hetzner / digitalocean / daytona). */\n location?: string;\n /** Snapshot name (daytona; defaults to `agentbox-base-<timestamp>` when absent). */\n name?: string;\n}\n\n/**\n * Minimal subset of CLI create flags the queued worker needs to reconstruct\n * the box. Kept narrow on purpose: anything that only changes interactive\n * attach behavior is irrelevant for the background path.\n */\nexport interface QueueJobCreateOpts {\n workspace: string;\n name?: string;\n hostSnapshot?: boolean;\n snapshot?: string;\n /** Base ref the box's per-box `agentbox/<name>` branch forks from (branch / tag\n * / SHA). Absent → the host's HEAD. Mirrors the CLI's `--from-branch`. */\n fromBranch?: string;\n image?: string;\n withPlaywright?: boolean;\n withEnv?: boolean;\n vnc?: boolean;\n /** `--no-resync` → false; resync the box with the host on (checkpoint) create. */\n resync?: boolean;\n sharedDockerCache?: boolean;\n portless?: boolean;\n sessionName?: string;\n /** Per-box override of `<agent>.dangerouslySkipPermissions` (`--no-...`). */\n dangerouslySkipPermissions?: boolean;\n memory?: string;\n cpus?: string;\n pidsLimit?: string;\n disk?: string;\n /**\n * carry: entries the submitter resolved + approved on the host (the same gate\n * the foreground create runs). Plain host-path metadata — serialized into the\n * job and applied by the worker, which reads the host files at create time.\n */\n carry?: ResolvedCarryEntry[];\n // ── Fields the foreground `agentbox create` conversion carries so the queue\n // worker builds the same box the old inline path did (audit: every create\n // flag has a home; a dropped one is an invisible capability regression). ──\n /** `--build` / `--no-pull`: force a local docker base build (→ allowPull:false). */\n build?: boolean;\n /** `box.imageRegistry`: GHCR ref the base is pulled from (docker + daytona). */\n imageRegistry?: string;\n /** `--with-env` / wizard picks: gitignore-bypassing env/config files to copy in. */\n envFiles?: string[];\n /** `--no-credential-sync` → false: the in-box refreshed-token fan-out watcher. */\n credentialSync?: boolean;\n /** `--bundle-depth`: cap commits in the cloud-seed git bundle (0 = full). */\n bundleDepth?: number;\n /** `-b`/`--use-branch`: reuse an existing branch instead of forking agentbox/<name>. */\n useBranch?: string;\n /** `git.pushMode` (`--dangerously-with-credentials` → 'direct'); cloud only. */\n gitPushMode?: GitPushMode;\n /** `--size`: VM size for cloud providers (hetzner type / daytona cpu-mem-disk / vercel vCPU). */\n size?: string;\n /** `--location`: datacenter/region (hetzner / digitalocean). */\n location?: string;\n /** `--inbound`: VPS firewall access policy (locked | open | CIDR list). */\n inbound?: string;\n /** `--remote-host`: SSH destination whose docker engine runs a remote-docker box. */\n remoteHost?: string;\n}\n\nexport interface QueueConfig {\n enabled: boolean;\n maxConcurrent: number;\n /** Max concurrently-working agents before `-i` jobs queue. 0 = disabled (use the running-box gate). */\n maxWorking: number;\n /** Debounce: ms an agent must stay non-working before it frees its working slot. */\n idleGraceMs: number;\n}\n\n/**\n * Global+built-in queue config (mirrors `loadAutopauseConfig`): re-read every\n * tick so `agentbox config set --global queue.*` takes effect without a relay\n * restart. Project/workspace layers are intentionally ignored — the relay is\n * host-wide.\n */\nexport async function loadQueueConfig(): Promise<QueueConfig> {\n const d = BUILT_IN_DEFAULTS.queue;\n let global: Partial<UserConfig> = {};\n try {\n global = parseUserConfig(await readFile(GLOBAL_CONFIG_FILE, 'utf8'), GLOBAL_CONFIG_FILE);\n } catch {\n // ENOENT / parse error → built-in defaults.\n }\n const q = global.queue ?? {};\n return {\n enabled: q.enabled ?? d.enabled,\n maxConcurrent: q.maxConcurrent ?? d.maxConcurrent,\n maxWorking: q.maxWorking ?? d.maxWorking,\n idleGraceMs: (q.idleGraceSeconds ?? d.idleGraceSeconds) * 1_000,\n };\n}\n\n/**\n * Atomically write a job manifest. Writes to a sibling `.tmp` file then renames\n * — readers never see a half-written JSON file. Idempotent: missing queue dir\n * is created as needed.\n */\nexport async function writeJob(job: QueueJob): Promise<void> {\n await mkdir(QUEUE_DIR, { recursive: true });\n const final = join(QUEUE_DIR, `${job.id}.json`);\n const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, JSON.stringify(job, null, 2) + '\\n', 'utf8');\n await rename(tmp, final);\n}\n\nexport interface EnqueueQueueJobInput {\n agent: QueueAgentKind;\n boxName: string;\n providerName: string;\n prompt: string;\n agentArgs: string[];\n createOpts: QueueJobCreateOpts;\n /**\n * \"Just create the box, don't start an agent\" (like `agentbox create`). The\n * worker runs createBox() then stops — no agent session. `agent` is still\n * required by the type but is ignored by the worker when this is set.\n */\n noAgent?: boolean;\n /** Seed the setup-wizard prompt as the agent's first turn (hub create path). */\n setupWizard?: boolean;\n /** A FOREGROUND create — starts in the ungated lane (see {@link QueueJob.foreground}). */\n foreground?: boolean;\n /** Per-invocation override of queue.maxConcurrent. */\n maxRunningOverride?: number;\n /** Per-invocation override of queue.maxWorking. */\n maxWorkingOverride?: number;\n /** Host-terminal targeting captured at submit time (CLI `queue.openIn`). */\n openTerminal?: QueueJobOpenTerminal;\n}\n\nexport interface EnqueueQueueJobResult {\n job: QueueJob;\n /** Cross-provider running count at the time of enqueue (informational). */\n runningCount: number;\n /** Effective ceiling used for the job (override or global). */\n maxConcurrent: number;\n}\n\n/**\n * Build a queued-job manifest and write it to `~/.agentbox/queue/<id>.json`.\n * Pure + transport-free: it does NOT ensure a relay is running and does NOT\n * poke the scheduler — callers do that (the CLI via `POST /admin/queue/enqueue`\n * after `ensureRelay`; the embedded hub via its in-process queue poke). Kept in\n * `@agentbox/relay` so both the CLI `submitQueueJob` wrapper and the hub backend\n * share one manifest-builder without the hub importing `apps/cli`. The scheduler\n * (`startQueueLoop`) picks the manifest up on its next tick regardless.\n */\nexport async function enqueueQueueJob(input: EnqueueQueueJobInput): Promise<EnqueueQueueJobResult> {\n const cfg = await loadQueueConfig();\n const ceiling =\n typeof input.maxRunningOverride === 'number' && input.maxRunningOverride > 0\n ? input.maxRunningOverride\n : cfg.maxConcurrent;\n const maxWorking =\n typeof input.maxWorkingOverride === 'number' && input.maxWorkingOverride > 0\n ? input.maxWorkingOverride\n : undefined;\n\n const id = randomBytes(9).toString('hex');\n const job: QueueJob = {\n id,\n agent: input.agent,\n status: 'queued',\n boxName: input.boxName,\n providerName: input.providerName,\n prompt: input.prompt,\n agentArgs: input.agentArgs,\n ...(input.noAgent ? { noAgent: true } : {}),\n ...(input.setupWizard ? { setupWizard: true } : {}),\n ...(input.foreground ? { foreground: true } : {}),\n createOpts: input.createOpts,\n maxConcurrent: ceiling,\n ...(maxWorking !== undefined ? { maxWorking } : {}),\n ...(input.openTerminal !== undefined ? { openTerminal: input.openTerminal } : {}),\n createdAt: new Date().toISOString(),\n logPath: queueLogPath(id),\n };\n await writeJob(job);\n\n let runningCount = 0;\n try {\n runningCount = await defaultCountRunningBoxes();\n } catch {\n runningCount = 0;\n }\n\n return { job, runningCount, maxConcurrent: ceiling };\n}\n\nexport interface EnqueuePrepareJobInput {\n /** Provider to bake (docker | daytona | hetzner | vercel | e2b | plugin). */\n providerName: string;\n /** Rebuild even if the base already exists. */\n force?: boolean;\n /** Bake-time Claude install method (else the effective config decides). */\n claudeInstall?: 'native' | 'npm';\n /** Force a local docker build instead of pulling the registry base (`--build`). */\n build?: boolean;\n /** Bake-time VM size (else the effective config's `box.size<Provider>` decides). */\n size?: string;\n /** Bake datacenter / region (else the provider's `box.<...>Location/Region` decides). */\n location?: string;\n /** Snapshot name (daytona; the provider defaults it when absent). */\n name?: string;\n /** Host dir used for config resolution; the worker defaults it if absent. */\n workspace?: string;\n}\n\n/**\n * Build a `kind: 'prepare'` manifest and write it to the queue. Like\n * {@link enqueueQueueJob} this is transport-free — the caller pokes the\n * scheduler. The agent/create fields carry inert placeholders (the prepare\n * worker only reads `providerName` + `prepare`); the job is scheduled in its\n * provider's own lane (see {@link PREPARE_MAX_CONCURRENT_PER_PROVIDER}) and never\n * surfaces as a box.\n */\nexport async function enqueuePrepareJob(input: EnqueuePrepareJobInput): Promise<{ job: QueueJob }> {\n const id = randomBytes(9).toString('hex');\n const prepare: QueueJobPrepare = {\n ...(input.force ? { force: true } : {}),\n ...(input.claudeInstall ? { claudeInstall: input.claudeInstall } : {}),\n ...(input.build ? { build: true } : {}),\n ...(input.size ? { size: input.size } : {}),\n ...(input.location ? { location: input.location } : {}),\n ...(input.name ? { name: input.name } : {}),\n };\n const job: QueueJob = {\n id,\n kind: 'prepare',\n agent: 'claude-code', // placeholder — ignored for prepare\n status: 'queued',\n boxName: '',\n providerName: input.providerName,\n prompt: '',\n agentArgs: [],\n createOpts: { workspace: input.workspace ?? process.cwd() },\n prepare,\n maxConcurrent: PREPARE_MAX_CONCURRENT_PER_PROVIDER,\n createdAt: new Date().toISOString(),\n logPath: queueLogPath(id),\n };\n await writeJob(job);\n return { job };\n}\n\n/** Read a single job manifest by id. Returns null when missing. */\nexport async function readJob(id: string): Promise<QueueJob | null> {\n try {\n const raw = await readFile(join(QUEUE_DIR, `${id}.json`), 'utf8');\n return JSON.parse(raw) as QueueJob;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n}\n\n/** Best-effort delete of a job manifest. ENOENT is not an error. */\nexport async function deleteJob(id: string): Promise<void> {\n try {\n await unlink(join(QUEUE_DIR, `${id}.json`));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;\n }\n}\n\n/**\n * Read every job manifest in the queue dir. Skips temp files (atomic-rename\n * leftovers) and entries that fail to parse — the loop must never crash on a\n * malformed file. Sorted by `createdAt` ascending for FIFO selection.\n */\nexport async function loadQueue(): Promise<QueueJob[]> {\n let entries: string[];\n try {\n entries = await readdir(QUEUE_DIR);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: QueueJob[] = [];\n for (const name of entries) {\n if (!name.endsWith('.json')) continue;\n try {\n const raw = await readFile(join(QUEUE_DIR, name), 'utf8');\n out.push(JSON.parse(raw) as QueueJob);\n } catch {\n // skip malformed — surfaced via tick log if it stays put\n }\n }\n out.sort((a, b) => (a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : 0));\n return out;\n}\n\n/**\n * Pure selector: pick the oldest queued job that can start given the current\n * cross-provider running count. Per-job `maxConcurrent` ceiling wins (a job\n * with `--max-running 3` starts even when the global cap is 1). Returns null\n * when nothing can start right now.\n */\nexport function selectNextRunnable(jobs: QueueJob[], runningCount: number): QueueJob | null {\n // jobs is FIFO by createdAt already (loadQueue sorts).\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue; // prepare has its own lane\n if (j.foreground) continue; // foreground has its own lane (ungated)\n if (runningCount < j.maxConcurrent) return j;\n }\n return null;\n}\n\n/**\n * Pure selector for the FOREGROUND lane: the oldest queued foreground create.\n * Ungated — a foreground create is an interactive command a human is watching\n * (inherently one per terminal), so it must never sit `queued` behind background\n * `-i` jobs that happen to fill `queue.maxConcurrent`. Independent of the box and\n * working gates, exactly like {@link selectNextRunnablePrepare}. Its box counts\n * toward the running total once live (honest occupancy) but is never blocked.\n */\nexport function selectNextRunnableForeground(jobs: QueueJob[]): QueueJob | null {\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue;\n if (!j.foreground) continue;\n return j;\n }\n return null;\n}\n\n/**\n * Count running prepare jobs per provider lane (keyed by `providerName`). Dead\n * workers are skipped so a crashed bake doesn't wedge its provider's lane.\n */\nexport function countRunningPrepareJobsByProvider(jobs: QueueJob[]): Map<string, number> {\n const byProvider = new Map<string, number>();\n for (const j of jobs) {\n if (j.kind !== 'prepare') continue;\n if (j.status !== 'running') continue;\n if (typeof j.pid === 'number' && !processAlive(j.pid)) continue;\n byProvider.set(j.providerName, (byProvider.get(j.providerName) ?? 0) + 1);\n }\n return byProvider;\n}\n\n/**\n * Pure selector for the prepare (image-bake) lane: the oldest queued prepare job\n * whose provider lane is under {@link PREPARE_MAX_CONCURRENT_PER_PROVIDER}. A job\n * whose lane is busy is skipped, not blocking — so a queued e2b bake starts while\n * a docker bake runs. Independent of the box gates.\n */\nexport function selectNextRunnablePrepare(\n jobs: QueueJob[],\n runningByProvider: Map<string, number>,\n): QueueJob | null {\n for (const j of jobs) {\n if (j.kind !== 'prepare') continue;\n if (j.status !== 'queued') continue;\n const running = runningByProvider.get(j.providerName) ?? 0;\n if (running >= PREPARE_MAX_CONCURRENT_PER_PROVIDER) continue;\n return j;\n }\n return null;\n}\n\n// ---- working-agent gate ---------------------------------------------------\n//\n// When `queue.maxWorking > 0` the scheduler caps the number of *working*\n// (quota-consuming) agents instead of running boxes. The signal is each box's\n// live activity state in the relay's BoxStatusStore (fed for docker and cloud\n// alike). A box that has finished thinking and is waiting for the user no\n// longer occupies a slot, so the next queued job starts — without pausing the\n// finished box.\n\n/** Activity union the working gate reasons about (mirrors @agentbox/ctl's `ClaudeActivityState`). */\nexport type WorkingAgentState =\n | 'working'\n | 'idle'\n | 'waiting'\n | 'end-plan'\n | 'question'\n | 'compacting'\n | 'error'\n | 'unknown';\n\nconst WORKING_AGENT_STATES: readonly WorkingAgentState[] = [\n 'working',\n 'idle',\n 'waiting',\n 'end-plan',\n 'question',\n 'compacting',\n 'error',\n 'unknown',\n];\n\nfunction isWorkingAgentState(v: unknown): v is WorkingAgentState {\n return typeof v === 'string' && (WORKING_AGENT_STATES as readonly string[]).includes(v);\n}\n\n/**\n * Boot window during which a freshly-created box (agent not yet reporting a\n * state) still counts as occupying a slot. Must exceed worst-case box\n * create + session launch before the first `working` hook fires, or a burst\n * of queued jobs would over-start before any reports working. Internal\n * constant, not user-tunable (it's a correctness guard, not a preference).\n */\nexport const STARTUP_GRACE_MS = 90_000;\n\n/** One box's facts the pure working-slot predicate reasons about. No I/O, no clock. */\nexport interface WorkingSlotEntry {\n /** boxId (registered box) — for logging/debug only. */\n key: string;\n /** Most-recent active-agent state across claude/codex/opencode, or null when no snapshot. */\n agentState: WorkingAgentState | null;\n /** ms since that agent's `updatedAt` (now - updatedAt), or null. */\n sinceUpdateMs: number | null;\n /** ms since the box was created (now - box.createdAt), or null. */\n sinceCreateMs: number | null;\n}\n\n/**\n * Pure predicate: does this box occupy a working slot right now?\n * - working/compacting → yes (actively consuming quota)\n * - unknown/no-snapshot, booting → yes while within {@link STARTUP_GRACE_MS}\n * - idle/waiting/end-plan/question→ yes only while within the debounce window\n * (`now - updatedAt < idleGraceMs`); this absorbs brief idle flaps between\n * turns so a slot isn't freed-then-reclaimed in a thrash.\n * - error, or anything past its window → no (slot frees).\n */\nexport function occupiesWorkingSlot(e: WorkingSlotEntry, idleGraceMs: number): boolean {\n if (e.agentState === 'working' || e.agentState === 'compacting') return true;\n if (\n (e.agentState === null || e.agentState === 'unknown') &&\n e.sinceCreateMs !== null &&\n e.sinceCreateMs < STARTUP_GRACE_MS\n ) {\n return true;\n }\n if (\n (e.agentState === 'idle' ||\n e.agentState === 'waiting' ||\n e.agentState === 'end-plan' ||\n e.agentState === 'question') &&\n e.sinceUpdateMs !== null &&\n e.sinceUpdateMs < idleGraceMs\n ) {\n return true;\n }\n return false;\n}\n\nexport function countWorkingSlots(entries: WorkingSlotEntry[], idleGraceMs: number): number {\n return entries.reduce((n, e) => (occupiesWorkingSlot(e, idleGraceMs) ? n + 1 : n), 0);\n}\n\n/**\n * Pure selector mirroring {@link selectNextRunnable} but for the working-agent\n * gate: pick the oldest queued job whose effective working ceiling (per-job\n * `maxWorking`, else the global) is above the current working count.\n */\nexport function selectNextRunnableByWorking(\n jobs: QueueJob[],\n workingCount: number,\n globalMaxWorking: number,\n): QueueJob | null {\n for (const j of jobs) {\n if (j.status !== 'queued') continue;\n if (j.kind === 'prepare') continue; // prepare has its own lane\n if (j.foreground) continue; // foreground has its own lane (ungated)\n const ceil =\n typeof j.maxWorking === 'number' && j.maxWorking > 0 ? j.maxWorking : globalMaxWorking;\n if (workingCount < ceil) return j;\n }\n return null;\n}\n\n/**\n * Pick the active agent's state from a box-status snapshot. `claude` is always\n * present (codex/opencode are additive), so prefer whichever agent reports a\n * quota-consuming state, else the most-recently-updated one. Returns nulls\n * when no snapshot / no recognizable state.\n */\nexport function readActiveAgent(snap: Record<string, unknown> | undefined): {\n state: WorkingAgentState | null;\n updatedAt: string | null;\n} {\n if (!snap || typeof snap !== 'object') return { state: null, updatedAt: null };\n const candidates: Array<{ state: WorkingAgentState; updatedAt: string | null }> = [];\n for (const key of ['claude', 'codex', 'opencode']) {\n const sub = (snap as Record<string, unknown>)[key];\n if (!sub || typeof sub !== 'object') continue;\n const o = sub as Record<string, unknown>;\n if (!isWorkingAgentState(o.state)) continue;\n candidates.push({\n state: o.state,\n updatedAt: typeof o.updatedAt === 'string' ? o.updatedAt : null,\n });\n }\n if (candidates.length === 0) return { state: null, updatedAt: null };\n const active = candidates.find((c) => c.state === 'working' || c.state === 'compacting');\n if (active) return active;\n candidates.sort((a, b) => parseTime(b.updatedAt) - parseTime(a.updatedAt));\n return candidates[0]!;\n}\n\nfunction parseTime(iso: string | null): number {\n if (!iso) return 0;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? 0 : t;\n}\n\nfunction msSince(iso: string | null | undefined): number | null {\n if (!iso) return null;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : Date.now() - t;\n}\n\nexport type RunningCountFn = () => Promise<number>;\nexport type CountWorkingFn = (idleGraceMs: number) => Promise<number>;\n\nexport interface QueueLoopDeps {\n log: (line: string) => void;\n /** Injectable; defaults to global-config loader. */\n loadConfig?: () => Promise<QueueConfig>;\n /** Injectable; defaults to docker inspect + cloud-as-running (see {@link defaultCountRunningBoxes}). */\n countRunning?: RunningCountFn;\n /**\n * Injectable working-agent counter (used when `queue.maxWorking > 0`).\n * Defaults to {@link defaultCountWorkingBoxes} over `registry` + `statusStore`.\n */\n countWorking?: CountWorkingFn;\n /** The relay's box registry; required (with `statusStore`) for the working gate. */\n registry?: Pick<BoxRegistry, 'list'>;\n /** The relay's box-status store; required (with `registry`) for the working gate. */\n statusStore?: Pick<BoxStatusStore, 'get'>;\n /** Injectable; defaults to `spawn detached node <cliEntry> _run-queued-job <id>`. */\n spawnWorker?: (job: QueueJob) => Promise<number | null>;\n /** Hook invoked when a manifest's status flips. Tests inject to assert. */\n onStatusChange?: (job: QueueJob) => void;\n intervalMs?: number;\n}\n\nexport interface QueueLoopHandle {\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 2_000;\n\n/**\n * Periodic queue scheduler. Runs alongside the autopause loop in the host\n * relay: every tick, count running boxes, pick the oldest startable queued\n * job, atomically flip it to `running`, then spawn the worker. Worker\n * crash/reboot recovery: on relay start, any `running` manifest whose PID\n * is no longer alive gets flipped to `failed` (the slot is recouped\n * automatically because we count live provider state, not manifests).\n */\nexport function startQueueLoop(deps: QueueLoopDeps): QueueLoopHandle {\n const loadConfig = deps.loadConfig ?? loadQueueConfig;\n const countRunning = deps.countRunning ?? defaultCountRunningBoxes;\n const spawnWorker = deps.spawnWorker ?? defaultSpawnWorker;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { log, onStatusChange } = deps;\n\n const countWorking: CountWorkingFn | null =\n deps.countWorking ??\n (deps.registry && deps.statusStore\n ? (idleGraceMs) => defaultCountWorkingBoxes(deps.registry!, deps.statusStore!, idleGraceMs)\n : null);\n\n let ticking = false;\n let stopped = false;\n let warnedNoWorkingDeps = false;\n let lastSweepAt = 0;\n let inFlight: Promise<void> = recoverOrphanedWorkers(log, onStatusChange).catch((err) => {\n log(`queue: orphan recovery failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n // NOTE: `cfg.enabled` gates only the BACKGROUND box/working lane below (it\n // bounds background `-i` fan-out). The foreground lane (an interactive\n // `agentbox create`, which now enqueues through the hub) and the prepare\n // lane must run regardless — a disabled background queue must not wedge an\n // interactive create at `queued`. Hygiene (sweep/recover) also runs always.\n\n // Throttled hygiene sweep of stale terminal manifests (runs regardless of\n // whether anything is queued, so a finished burst gets cleaned up).\n const now = Date.now();\n if (now - lastSweepAt >= SWEEP_INTERVAL_MS) {\n lastSweepAt = now;\n await sweepTerminalJobs(log, now).catch((err) => {\n log(`queue: sweep failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n }\n\n // Flip jobs whose worker died mid-flight to `failed`. Must run before the\n // no-queued-work early return below, or a dead worker with nothing else\n // queued is never noticed — which is precisely the case that leaves a UI\n // progress card waiting on a job that will never finish.\n await recoverOrphanedWorkers(log, onStatusChange, true).catch((err) => {\n log(`queue: orphan reap failed: ${err instanceof Error ? err.message : String(err)}`);\n });\n\n const jobs = await loadQueue();\n const hasQueued = jobs.some((j) => j.status === 'queued');\n if (!hasQueued) return;\n\n // Working-agent gate when `queue.maxWorking > 0` and the relay wired in\n // its registry + status store; otherwise the legacy running-box gate.\n let gateByWorking = cfg.maxWorking > 0;\n if (gateByWorking && !countWorking) {\n gateByWorking = false;\n if (!warnedNoWorkingDeps) {\n warnedNoWorkingDeps = true;\n log('queue: maxWorking set but registry/statusStore not wired; using running-box gate');\n }\n }\n\n // Start as many slots as we can in one tick — picking one per tick would\n // mean a 2s lag per job after a slot frees, which adds up when a burst\n // of jobs queues against a freshly-cleared pool. Gated by `cfg.enabled`:\n // when the background queue is off, this lane starts nothing (the foreground\n // + prepare lanes below still run).\n while (!stopped && cfg.enabled) {\n let occupancy: number;\n let next: QueueJob | null;\n if (gateByWorking && countWorking) {\n occupancy = await countWorking(cfg.idleGraceMs);\n const fresh = await loadQueue();\n next = selectNextRunnableByWorking(fresh, occupancy, cfg.maxWorking);\n } else {\n occupancy = await countRunning();\n const fresh = await loadQueue();\n next = selectNextRunnable(fresh, occupancy);\n }\n if (!next) break;\n // Atomic claim: re-read to make sure no other process already started\n // it (the relay is the only writer of status: running, but a\n // future-second-relay scenario would clobber here without this read).\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n const ceil = gateByWorking\n ? typeof updated.maxWorking === 'number' && updated.maxWorking > 0\n ? updated.maxWorking\n : cfg.maxWorking\n : updated.maxConcurrent;\n log(\n `queue: started job ${updated.id} (${updated.agent}) as pid ${String(pid)}; ${gateByWorking ? 'working' : 'running'} ${String(occupancy + 1)}/${String(ceil)}`,\n );\n } else {\n log(`queue: started job ${updated.id} (${updated.agent}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for job ${updated.id} failed: ${msg}`);\n }\n }\n\n // Foreground lane — an interactive `agentbox create` a human is watching.\n // Ungated by `queue.maxConcurrent` (that gate bounds background `-i` fan-out);\n // a foreground create must start immediately, not sit `queued` behind unrelated\n // background jobs. Start every queued foreground create this tick — there is\n // inherently one per terminal, and each was launched by a present human.\n while (!stopped) {\n const fresh = await loadQueue();\n const next = selectNextRunnableForeground(fresh);\n if (!next) break;\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n log(\n `queue: started foreground job ${updated.id} (${updated.agent}) as pid ${String(pid)}`,\n );\n } else {\n log(`queue: started foreground job ${updated.id} (${updated.agent}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for foreground job ${updated.id} failed: ${msg}`);\n }\n }\n\n // Prepare (image-bake) lanes — independent of the box/working gates. A bake\n // produces an artifact, not a box, so it neither counts against nor is\n // blocked by running boxes. One lane per provider: the recount below sees\n // the job just claimed, so a single tick starts at most one bake per\n // provider and as many providers as have queued work.\n while (!stopped) {\n const fresh = await loadQueue();\n const runningByProvider = countRunningPrepareJobsByProvider(fresh);\n const next = selectNextRunnablePrepare(fresh, runningByProvider);\n if (!next) break;\n const current = await readJob(next.id);\n if (!current || current.status !== 'queued') continue;\n const updated: QueueJob = {\n ...current,\n status: 'running',\n startedAt: new Date().toISOString(),\n };\n await writeJob(updated);\n onStatusChange?.(updated);\n try {\n const pid = await spawnWorker(updated);\n if (typeof pid === 'number') {\n const withPid: QueueJob = { ...updated, pid };\n await writeJob(withPid);\n onStatusChange?.(withPid);\n log(\n `queue: started prepare job ${updated.id} (${updated.providerName}) as pid ${String(pid)}; ${updated.providerName} lane ${String((runningByProvider.get(updated.providerName) ?? 0) + 1)}/${String(PREPARE_MAX_CONCURRENT_PER_PROVIDER)}`,\n );\n } else {\n log(`queue: started prepare job ${updated.id} (${updated.providerName}); pid unknown`);\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const failed: QueueJob = {\n ...updated,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: `worker-spawn-failed: ${msg}`,\n };\n await writeJob(failed);\n onStatusChange?.(failed);\n log(`queue: spawn for prepare job ${updated.id} failed: ${msg}`);\n }\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n log(`queue: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n /** Inject manual ticks (after enqueue HTTP). Caller is fire-and-forget. */\n function poke(): void {\n if (stopped) return;\n inFlight = tick();\n }\n\n // Expose poke on the handle in addition to stop, so the HTTP enqueue route\n // can trigger an immediate scheduling pass without waiting for the timer.\n const handle: QueueLoopHandle & { poke: () => void } = {\n poke,\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return handle;\n}\n\n/**\n * Scrub `running` manifests whose PID is no longer alive — usually after a\n * host reboot or a relay crash mid-flight. The slot is recouped automatically\n * because `countRunning` reads live provider state, but the manifest must be\n * advanced or `agentbox queue list` keeps lying about what's in progress.\n *\n * `requirePid` distinguishes the two callers:\n * - startup (`false`): a `running` manifest with no PID at all was orphaned by a\n * relay that died between marking the job running and recording the PID. There\n * is no worker to wait for, so fail it.\n * - every tick (`true`): only reap a PID we know is dead. A `running` job whose\n * PID isn't written *yet* is in the spawn window of the current tick — reaping\n * that would kill jobs as they start.\n *\n * Running this per-tick is what makes a worker that dies mid-flight visible. It\n * used to run only at startup, so a crashed worker left the job `running`\n * forever: no terminal status, no SSE `end`, and a UI progress card that waits\n * on a job that is never coming back.\n */\nasync function recoverOrphanedWorkers(\n log: (line: string) => void,\n onChange?: (job: QueueJob) => void,\n requirePid = false,\n): Promise<void> {\n const jobs = await loadQueue();\n for (const j of jobs) {\n if (j.status !== 'running') continue;\n if (typeof j.pid === 'number' ? processAlive(j.pid) : requirePid) continue;\n const failed: QueueJob = {\n ...j,\n status: 'failed',\n finishedAt: new Date().toISOString(),\n reason: 'worker-died',\n };\n await writeJob(failed);\n onChange?.(failed);\n log(`queue: recovered orphan job ${j.id} (pid ${String(j.pid ?? '?')} not alive) -> failed`);\n }\n}\n\n/** Terminal job manifests older than this are swept so `queue list` and the\n * scheduler don't accumulate unbounded done/failed/cancelled entries (they\n * never gate concurrency, but they pollute listings and were never cleaned). */\nexport const TERMINAL_RETENTION_MS = 60 * 60 * 1_000;\nconst SWEEP_INTERVAL_MS = 60 * 1_000;\nconst TERMINAL_STATUSES: readonly QueueJobStatus[] = ['done', 'failed', 'cancelled'];\n\n/**\n * Delete terminal (done/failed/cancelled) job manifests whose terminal flip is\n * older than {@link TERMINAL_RETENTION_MS}. Recent terminal jobs are kept so\n * `agentbox queue list` still shows just-finished history. Best-effort: a\n * delete failure is logged-by-omission and retried next sweep.\n */\nasync function sweepTerminalJobs(log: (line: string) => void, now: number): Promise<void> {\n const jobs = await loadQueue();\n let swept = 0;\n for (const j of jobs) {\n if (!TERMINAL_STATUSES.includes(j.status)) continue;\n const since = Date.parse(j.finishedAt ?? j.createdAt);\n if (Number.isNaN(since) || now - since < TERMINAL_RETENTION_MS) continue;\n await deleteJob(j.id);\n swept += 1;\n }\n if (swept > 0) log(`queue: swept ${String(swept)} stale terminal manifest(s)`);\n}\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Count concurrently *working* agents for the working-agent gate. Computed\n * fresh each call from in-memory relay state (no docker shell-out, no cache):\n * - one {@link WorkingSlotEntry} per registered box, from its live status\n * snapshot (`statusStore`) and creation time (`registry`), scored by\n * {@link occupiesWorkingSlot};\n * - plus each `running` queue job whose box hasn't registered yet (in-flight\n * create), so a burst can't over-start before the first box reports. A job\n * whose `boxId` is already in the registry is counted via its box entry\n * (no double count); a job whose worker PID is dead is skipped (the box,\n * if it exists, is counted via the registry).\n */\nexport async function defaultCountWorkingBoxes(\n registry: Pick<BoxRegistry, 'list'>,\n statusStore: Pick<BoxStatusStore, 'get'>,\n idleGraceMs: number,\n): Promise<number> {\n const boxes = registry.list();\n const registeredIds = new Set(boxes.map((b) => b.boxId));\n const entries: WorkingSlotEntry[] = boxes.map((b) => {\n const active = readActiveAgent(statusStore.get(b.boxId));\n return {\n key: b.boxId,\n agentState: active.state,\n sinceUpdateMs: msSince(active.updatedAt),\n sinceCreateMs: msSince(b.createdAt),\n };\n });\n const count = countWorkingSlots(entries, idleGraceMs);\n\n let jobs: QueueJob[];\n try {\n jobs = await loadQueue();\n } catch {\n return count;\n }\n return count + countInFlightCreateJobs(jobs, registeredIds);\n}\n\n/**\n * Count `running` queue jobs whose box isn't yet accounted for elsewhere — an\n * in-flight create that occupies a concurrency slot before its box exists.\n * Shared by both gates: the caller passes the set of box ids it already counted\n * (relay registry ids for the working gate, state.json ids for the running\n * gate), so a job is added only while its box is invisible to that source. A\n * job whose worker pid is dead is skipped (its box, if any, is counted directly;\n * the orphan-recovery sweep flips the stale manifest to `failed`).\n */\nexport function countInFlightCreateJobs(jobs: QueueJob[], accountedBoxIds: Set<string>): number {\n let n = 0;\n for (const j of jobs) {\n if (j.kind === 'prepare') continue; // a bake is not a box\n if (j.status !== 'running') continue;\n if (j.boxId && accountedBoxIds.has(j.boxId)) continue; // counted via its box\n if (typeof j.pid === 'number' && !processAlive(j.pid)) continue; // dead worker\n n += 1;\n }\n return n;\n}\n\nconst RUNNING_COUNT_CACHE_MS = 3_000;\nlet boxStateCache: { boxCount: number; stateIds: Set<string>; expiresAt: number } | null = null;\n\n/**\n * Cross-provider count of boxes whose runtime state is `running`, plus the\n * in-flight queue jobs whose box isn't in `state.json` yet.\n *\n * The box-state portion reads `~/.agentbox/state.json`, then per-provider:\n * - docker: `docker inspect --format {{.State.Status}}` shell-out (cheap).\n * - non-docker (daytona/hetzner/…): counted as running. Cloud providers\n * don't expose a cheap synchronous probe; the autopause/queue loops would\n * pay an SDK round-trip per box per tick otherwise. Tracked as a v1\n * limitation: a paused cloud box still counts against the slot cap until\n * it's destroyed. Acceptable because cloud pause is rare today.\n * That portion is cached for 3s so multiple slot decisions in one tick share it.\n *\n * The in-flight term is recomputed every call (a cheap `loadQueue` fs read), NOT\n * cached: a job the scheduler just flipped to `running` hasn't created its box\n * yet (~25s on cloud, image pull on docker), so it's absent from `state.json`.\n * Without counting it, the per-tick \"start as many as fit\" loop would re-select\n * the same free slot for the next job and over-start past `--max-running`.\n */\nexport async function defaultCountRunningBoxes(): Promise<number> {\n const { boxCount, stateIds } = await cachedBoxState();\n let jobs: QueueJob[];\n try {\n jobs = await loadQueue();\n } catch {\n return boxCount;\n }\n return boxCount + countInFlightCreateJobs(jobs, stateIds);\n}\n\nasync function cachedBoxState(): Promise<{ boxCount: number; stateIds: Set<string> }> {\n const now = Date.now();\n if (boxStateCache && boxStateCache.expiresAt > now) {\n return { boxCount: boxStateCache.boxCount, stateIds: boxStateCache.stateIds };\n }\n const fresh = await uncachedBoxStateCount();\n boxStateCache = { ...fresh, expiresAt: now + RUNNING_COUNT_CACHE_MS };\n return fresh;\n}\n\n/** Running-box count from `state.json` plus the set of those boxes' ids (for\n * in-flight-job dedup). Read errors / no boxes → zero and an empty set. */\nasync function uncachedBoxStateCount(): Promise<{ boxCount: number; stateIds: Set<string> }> {\n let boxes: BoxRecord[];\n try {\n boxes = (await readState(STATE_FILE)).boxes;\n } catch {\n return { boxCount: 0, stateIds: new Set() };\n }\n const stateIds = new Set(boxes.map((b) => b.id));\n if (boxes.length === 0) return { boxCount: 0, stateIds };\n\n let boxCount = 0;\n const dockerBoxes: BoxRecord[] = [];\n for (const b of boxes) {\n const provider = b.provider ?? 'docker';\n if (provider === 'docker') {\n dockerBoxes.push(b);\n } else {\n // Optimistic: count cloud boxes as running. See note on\n // {@link defaultCountRunningBoxes} for why.\n boxCount += 1;\n }\n }\n if (dockerBoxes.length > 0) {\n const states = await Promise.all(dockerBoxes.map((b) => inspectDockerState(b.container)));\n for (const s of states) {\n if (s === 'running') boxCount += 1;\n }\n }\n return { boxCount, stateIds };\n}\n\nfunction inspectDockerState(containerName: string): Promise<'running' | 'other'> {\n return new Promise<'running' | 'other'>((resolveP) => {\n const child = spawn('docker', ['inspect', '--format', '{{.State.Status}}', containerName], {\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let out = '';\n let settled = false;\n const finish = (state: 'running' | 'other'): void => {\n if (settled) return;\n settled = true;\n resolveP(state);\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish('other');\n }, 10_000);\n child.stdout?.on('data', (c: Buffer) => {\n out += c.toString('utf8');\n });\n child.on('error', () => {\n clearTimeout(timer);\n finish('other');\n });\n child.on('close', () => {\n clearTimeout(timer);\n finish(out.trim() === 'running' ? 'running' : 'other');\n });\n });\n}\n\n/**\n * Default worker spawner: detached `node <cliEntry> _run-queued-job <id>`,\n * with stdout/stderr appended to the job's `logPath`. The CLI entry is set by\n * `ensureRelay` via `AGENTBOX_CLI_ENTRY` (the same hook checkpoint/cp/download\n * RPCs already use). Returns the worker PID, or null when the spawn produced\n * no PID (treated as a soft failure — the loop's catch turns it into a\n * `failed` manifest).\n */\nasync function defaultSpawnWorker(job: QueueJob): Promise<number | null> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry || !existsSync(entry)) {\n throw new Error(\n `AGENTBOX_CLI_ENTRY not set or missing (${String(entry)}); cannot spawn queue worker`,\n );\n }\n await mkdir(join(STATE_DIR, 'logs'), { recursive: true });\n const fd = openSync(job.logPath, 'a');\n // A prepare (image-bake) job runs a different worker; both stream to logPath.\n const command = job.kind === 'prepare' ? '_run-queued-prepare' : '_run-queued-job';\n // Pin an explicit cwd. Without one the worker inherits the daemon's, and this\n // daemon is long-lived while its own directory is not: `npm install -g` (what\n // `self-update` runs) replaces the package tree, so a relay/hub that keeps\n // running across an update sits in a deleted directory. The child then dies on\n // `process.cwd()` at startup — `ENOENT: uv_cwd` — before any of our code runs,\n // which reads as a create that hangs with a Node stack trace for a status line.\n // STATE_DIR is ours and always exists; the worker takes its workspace from the\n // job manifest, never from cwd.\n const child = spawn(process.execPath, [entry, command, job.id], {\n detached: true,\n stdio: ['ignore', fd, fd],\n env: process.env,\n cwd: STATE_DIR,\n });\n child.unref();\n // The fd stays open in the child; close our own copy.\n try {\n closeSync(fd);\n } catch {\n /* the child still holds its own fd */\n }\n return typeof child.pid === 'number' ? child.pid : null;\n}\n\n/** Re-export the path for callers (CLI submit helper, tests). */\nexport const QUEUE_LOGS_DIR = join(STATE_DIR, 'logs');\n\n/** Build the per-job log path. Kept here so submit + worker agree on layout. */\nexport function queueLogPath(id: string): string {\n return join(QUEUE_LOGS_DIR, `queue-${id}.log`);\n}\n\n/**\n * The UI → worker channel for a Claude re-login code: a dedicated file next to\n * the manifest. Only the hub writes it ({@link writeQueueLoginCode}); only the\n * worker reads+consumes it ({@link takeQueueLoginCode}). Keeping it out of the\n * job manifest avoids a cross-process read-modify-write race with the worker's\n * `login` (phase/url) writes.\n */\nexport function queueLoginCodePath(id: string): string {\n return join(QUEUE_DIR, `${id}.login-code`);\n}\n\n/** Hub side: deliver the pasted OAuth approval code to a job, written atomically. */\nexport async function writeQueueLoginCode(id: string, code: string): Promise<void> {\n await mkdir(QUEUE_DIR, { recursive: true });\n const final = queueLoginCodePath(id);\n const tmp = `${final}.tmp.${String(process.pid)}.${String(Date.now())}`;\n await writeFile(tmp, code.trim(), { mode: 0o600 });\n await rename(tmp, final);\n}\n\n/** Worker side: read + consume the pending code (deleting it); null when none. */\nexport async function takeQueueLoginCode(id: string): Promise<string | null> {\n try {\n const code = (await readFile(queueLoginCodePath(id), 'utf8')).trim();\n await unlink(queueLoginCodePath(id)).catch(() => {});\n return code.length > 0 ? code : null;\n } catch {\n return null;\n }\n}\n\n/** Wait briefly for a file to appear (queue manifest after enqueue HTTP). */\nexport async function waitForFile(path: string, timeoutMs = 1_000): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (existsSync(path)) return true;\n await delay(25);\n }\n return existsSync(path);\n}\n","import type { CreateJobRequest, Store } from './store/store.js';\n\n/**\n * A resolved `carry:` entry, spelled structurally so the relay core stays free\n * of a dependency on @agentbox/core's `ResolvedCarryEntry`. The provider on the\n * other end takes the real type; this is only a pass-through.\n */\nexport interface CarryEntryLike {\n rawSrc: string;\n rawDest: string;\n absSrc: string;\n absDest: string;\n kind: 'file' | 'dir';\n optional: boolean;\n mode?: number;\n user?: number;\n exclude?: string[];\n replaceEnvs?: boolean;\n replace?: unknown[];\n symlinkInfo?: 'safe' | 'outside-home';\n}\n\n/**\n * The actual box-creation step, injected by the deploy target. On a self-host\n * worker / Vercel cron this provisions a cloud box and seeds its workspace by\n * cloning `request.repoUrl` with a leased GitHub-App token (origin-clone — no\n * host bundle). Kept injectable so the worker loop is unit-testable without a\n * live cloud, and so the heavy provider wiring lives outside the relay core.\n */\nexport type CreateBoxFn = (\n request: CreateJobRequest,\n jobId: string,\n) => Promise<{ boxId: string; agentStartError?: string }>;\n\n/**\n * Side-effecting steps a {@link makeControlPlaneCreateBox} needs, all injected\n * so the orchestration is unit-testable without a cloud or GitHub. The worker\n * (laptop `hub worker`, or the resident hub worker) clones the repo\n * LOCALLY with a leased GitHub-App token and hands the fresh checkout to the\n * normal, tested `provider.create()` as the workspace — origin-clone seeding\n * without touching the host-coupled create flow.\n */\nexport interface CreateBoxDeps {\n /** Mint an authed HTTPS remote URL for the repo (App lease → x-access-token URL). */\n leaseRemoteUrl(repoUrl: string): Promise<string>;\n /**\n * Clone `authedUrl` into `dest` (checking out `branch` when given), then scrub\n * the remote back to the bare `repoUrl`.\n */\n cloneRepo(authedUrl: string, repoUrl: string, dest: string, branch?: string): Promise<void>;\n /**\n * Provision the cloud box from the local checkout. Returns the new box id, and\n * `agentStartError` when the box was created but starting the agent in-box\n * failed (a background `-i` run) — the caller fails the job WITH the box id so\n * the box is preserved for adopt/attach.\n */\n createBox(opts: {\n workspacePath: string;\n name: string | undefined;\n /** Approved `carry:` entries, staged locally by {@link CreateBoxDeps.fetchSeedMaterial}. */\n carry?: CarryEntryLike[];\n /**\n * The repo this checkout came from. `workspacePath` is a per-job temp clone\n * the worker deletes on the way out, so it is the only durable identity the\n * box has — used to name the box after the repo rather than after that\n * directory.\n */\n repoUrl: string;\n provider: string;\n /**\n * Agent the box is being created for. Registered on the control plane so a\n * PC adopting this box knows which agent to relaunch. When `prompt` is set\n * the worker also STARTS this agent detached in the box.\n */\n agent?: string;\n /** Seed prompt for a background `-i` run — present ⇒ start the agent in-box. */\n prompt?: string;\n /** Fully-processed agent args (post-`--`, incl. skip-permissions). */\n agentArgs?: string[];\n /** Start the agent in-box even with no `prompt` (a hub web-UI create). */\n startAgent?: boolean;\n /** Box-shaping flags the CLI resolved (snapshot/image/withEnv/...); see CreateJobRequestOpts. */\n opts?: CreateJobRequest['opts'];\n onLog?: (line: string) => void;\n }): Promise<{ id: string; agentStartError?: string }>;\n /** Make a per-job temp dir path. */\n tmpDir(jobId: string): string;\n /** Remove the temp checkout (best-effort). */\n cleanup(dir: string): Promise<void>;\n /**\n * Overlay the project's custody seed material (untracked files + env/secrets\n * a PC pushed) onto the fresh checkout at `dest`. A clone can only ever carry\n * committed state, so without this a hub-created box is missing exactly the\n * local files that make the project runnable.\n *\n * Optional and best-effort: a worker with no custody store (or a project that\n * was never pushed) simply creates the box from the bare clone, as before.\n * Returns what it applied, for the job log.\n */\n fetchSeedMaterial?(\n repoUrl: string,\n dest: string,\n ): Promise<{\n files: number;\n capturedAt?: string;\n repoHeadSha?: string;\n /**\n * Approved `carry:` entries staged on this machine, with `absSrc` pointing\n * at the staging dir. Passed straight to {@link CreateBoxDeps.createBox} so\n * the provider applies them exactly as it does for a local create.\n */\n carry?: CarryEntryLike[];\n } | null>;\n log?: (line: string) => void;\n /**\n * Per-job logger, preferred over {@link log} when present. The hub web UI\n * streams a create's progress from a per-job log file, so a job driven from\n * there needs its lines addressable by job id rather than interleaved into one\n * worker-wide log.\n */\n logFor?(jobId: string): (line: string) => void;\n}\n\n/** Runs `git <args>` with optional extra env + timeout; rejects on non-zero. */\nexport type CloneRepoRunGit = (\n args: string[],\n env?: Record<string, string>,\n timeoutMs?: number,\n) => Promise<void>;\n\n/** The GitHub/GitLab-convention LFS API endpoint for a clone URL: `<repo>.git/info/lfs`. */\nfunction lfsEndpointFor(cloneUrl: string): string {\n return `${cloneUrl.replace(/\\.git$/, '')}.git/info/lfs`;\n}\n\n/**\n * Clone `authedUrl` into `dest` robustly against **git-LFS**. A worker (control\n * box / laptop) clones with a leased token, and LFS reuses that token over HTTPS\n * (the standard CI path — verified). But the worker's git environment can resolve\n * an *SSH* LFS batch endpoint — e.g. a `git@github.com: insteadOf` rewrite (the\n * git-identity seeding configures such rewrites) makes git-lfs try SSH — and then\n * it hard-fails the create at the smudge step (`ssh_askpass ... Host key\n * verification failed`). To make the LFS fetch deterministic over HTTPS:\n * 1. clone with `GIT_LFS_SKIP_SMUDGE=1` — the checkout comes down with LFS\n * **pointer files**, so the clone can't fail on LFS transport at all;\n * 2. `git lfs pull` with `lfs.url` FORCED to the authed HTTPS endpoint — the\n * embedded `x-access-token:<token>@` userinfo both authenticates the fetch\n * AND dodges an `https://github.com/ → ssh` insteadOf rewrite (that prefix no\n * longer matches once the userinfo is present), so the real bytes come down\n * over HTTPS. Best-effort + non-interactive + timed: a token that genuinely\n * can't read LFS is left as pointers with a log line, not a failed create;\n * 3. scrub the leased token from `origin` (leave the box on the bare repo URL).\n *\n * Shared by both worker impls (`apps/hub` resident worker, `apps/cli control-plane\n * worker`) via an injected git-runner so it stays runtime-agnostic.\n */\nexport async function cloneRepoWithLfs(\n runGit: CloneRepoRunGit,\n authedUrl: string,\n repoUrl: string,\n dest: string,\n branch?: string,\n log: (line: string) => void = () => {},\n): Promise<void> {\n await runGit(\n branch ? ['clone', '--branch', branch, authedUrl, dest] : ['clone', authedUrl, dest],\n {\n GIT_LFS_SKIP_SMUDGE: '1',\n },\n );\n // Fetch the real LFS bytes over the forced HTTPS endpoint (best-effort). A repo\n // with no LFS makes this a fast no-op. `-c lfs.url` overrides remote/insteadOf\n // resolution; the token is passed on the argv (ephemeral), never written to the\n // box's config — origin is scrubbed to the bare URL below regardless.\n try {\n await runGit(\n ['-C', dest, '-c', `lfs.url=${lfsEndpointFor(authedUrl)}`, 'lfs', 'pull'],\n {\n GIT_TERMINAL_PROMPT: '0',\n GIT_SSH_COMMAND: 'ssh -o BatchMode=yes -o StrictHostKeyChecking=no',\n },\n 120_000,\n );\n } catch (err) {\n log(\n `git-lfs objects left as pointers (fetch failed): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n await runGit(['-C', dest, 'remote', 'set-url', 'origin', repoUrl]);\n}\n\n/**\n * Build a {@link CreateBoxFn} from injected side-effecting steps: lease a push\n * token, clone the repo locally, provision the box from that checkout, clean up.\n */\nexport function makeControlPlaneCreateBox(deps: CreateBoxDeps): CreateBoxFn {\n return async (request, jobId) => {\n const log = deps.logFor?.(jobId) ?? deps.log ?? (() => {});\n const dir = deps.tmpDir(jobId);\n try {\n log(`leasing a push token for ${request.repoUrl}`);\n const authedUrl = await deps.leaseRemoteUrl(request.repoUrl);\n log(`cloning ${request.repoUrl}${request.branch ? `@${request.branch}` : ''} into ${dir}`);\n await deps.cloneRepo(authedUrl, request.repoUrl, dir, request.branch);\n let carry: CarryEntryLike[] | undefined;\n if (deps.fetchSeedMaterial) {\n try {\n const seed = await deps.fetchSeedMaterial(request.repoUrl, dir);\n carry = seed?.carry?.length ? seed.carry : undefined;\n if (seed && seed.files > 0) {\n // Report what the seed was captured from: it can lag the branch tip\n // (the PC pushes it on create), and a surprising box is much easier\n // to explain when the job log says how old its local files are.\n const from = [\n seed.repoHeadSha ? `at ${seed.repoHeadSha.slice(0, 8)}` : null,\n seed.capturedAt ? `captured ${seed.capturedAt}` : null,\n ]\n .filter(Boolean)\n .join(', ');\n log(\n `applied ${String(seed.files)} seed file(s) from custody${from ? ` (${from})` : ''}`,\n );\n }\n } catch (err) {\n // Untracked/env material is a convenience: the box is still usable\n // without it, so say so and carry on rather than failing a create the\n // user is waiting on. `carry:` is NOT in that category — those paths\n // were shown to the user and approved, so applyProjectSeed throws for\n // them and that throw must not be swallowed here.\n // Matched by NAME, not by message prefix: a tar/fs failure while\n // unpacking approved entries throws a generic error, and swallowing it\n // would build the box without those files — the exact bug the loud\n // path exists to prevent. `applyProjectSeed` wraps every carry failure\n // in `CarrySeedError` so this test can't miss one.\n if (err instanceof Error && err.name === 'CarrySeedError') throw err;\n const msg = err instanceof Error ? err.message : String(err);\n log(`seed material unavailable (continuing with a bare clone): ${msg}`);\n }\n }\n log(`provisioning ${request.provider} box from the clone`);\n const box = await deps.createBox({\n workspacePath: dir,\n name: request.name,\n repoUrl: request.repoUrl,\n provider: request.provider,\n ...(carry ? { carry } : {}),\n // Carry the job's agent through to the box record + its plane\n // registration, so an adopting PC relaunches the right agent instead of\n // guessing. Without this a hub-created box adopts with no `lastAgent`.\n agent: request.agent,\n // A background `-i` run seeds a prompt: the worker starts the agent\n // in-box with these. Absent ⇒ a \"cold\" create (create --via-hub /\n // foreground) that the PC attaches later.\n prompt: request.prompt,\n agentArgs: request.agentArgs,\n startAgent: request.startAgent,\n // Box-shaping flags the CLI resolved, so a control-box create isn't built\n // with defaults where the user asked for a snapshot / image / env / etc.\n opts: request.opts,\n onLog: log,\n });\n log(`created box ${box.id}`);\n return { boxId: box.id, agentStartError: box.agentStartError };\n } finally {\n await deps.cleanup(dir);\n }\n };\n}\n\n/**\n * Claim + run ONE queued create job. Returns the processed job id, or null when\n * the queue is empty (or the store has no create-job support). A throwing\n * `createBox` marks the job failed (never throws out of here).\n */\nexport async function drainOneCreateJob(\n store: Store,\n createBox: CreateBoxFn,\n workerId: string,\n): Promise<string | null> {\n if (!store.claimNextCreateJob || !store.completeCreateJob) return null;\n const job = await store.claimNextCreateJob(workerId);\n if (!job) return null;\n try {\n const { boxId, agentStartError } = await createBox(job.request, job.id);\n // The box was created; if starting the agent in-box failed, fail the job but\n // keep the box id so it's adoptable/attachable (the user re-logins + retries).\n if (agentStartError) {\n await store.completeCreateJob(job.id, 'failed', { boxId, error: agentStartError });\n } else {\n await store.completeCreateJob(job.id, 'done', { boxId });\n }\n } catch (err) {\n await store.completeCreateJob(job.id, 'failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n return job.id;\n}\n\n/**\n * Drain queued create jobs until the queue is empty or `max` is hit. Used by\n * the self-host worker loop and a Vercel cron tick. Returns the count processed.\n */\nexport async function drainCreateJobs(\n store: Store,\n createBox: CreateBoxFn,\n workerId: string,\n max = 10,\n): Promise<number> {\n let processed = 0;\n while (processed < max) {\n const id = await drainOneCreateJob(store, createBox, workerId);\n if (!id) break;\n processed++;\n }\n return processed;\n}\n","import { timingSafeEqual } from 'node:crypto';\nimport type { GitHubAppLeaser } from '../github-app.js';\nimport { leaseTokenResult } from '../lease.js';\nimport { gateApproval } from '../permission.js';\nimport { isValidBoxStatus } from '../status-store.js';\nimport type { Store } from '../store/store.js';\nimport { handleStoreRpcRequest } from '../store/store-rpc-routes.js';\nimport { resolveWorktree } from '../worktree.js';\nimport { handleCustodyRequest, type CustodyRouteDeps } from '../custody/routes.js';\nimport { handleRemoteBoxesRequest } from '../remote-boxes.js';\nimport type { CustodyStore } from '../custody/store.js';\nimport { isScratchBranch } from '@agentbox/core';\nimport type {\n BoxRegistration,\n GitRpcParams,\n PostEventBody,\n PostRpcBody,\n RegisterBoxBody,\n} from '../types.js';\n\n/**\n * Framework-agnostic request/response dispatch for the HOSTED control plane\n * (the Next.js app on Vercel / self-host). It reuses the relay's shared\n * primitives — the {@link Store}, {@link gateApproval}, the GitHub-App leaser —\n * but is decoupled from node:http and from host execution: it never runs git\n * locally (no worktree on the hosted plane) and obtains approvals via the poll\n * mailbox, never by blocking. The long-lived laptop relay keeps using\n * `server.ts` (node:http, host execution, SSE); they share the same core\n * building blocks but not this handler.\n *\n * Host-local RPCs (cp/download/checkpoint, and the docker-style git.push/fetch)\n * are intentionally rejected here — they require a host, which the plane has\n * none of. Cloud boxes push via `git.lease-token` instead.\n */\nexport interface GenericRequest {\n method: string;\n /** URL pathname, e.g. \"/rpc\" or \"/rpc/status/<id>\". */\n path: string;\n query: URLSearchParams;\n /** The Bearer token, already extracted ('' when absent). */\n bearer: string;\n /** Raw request body (already read by the adapter; '' for GET). */\n bodyText: string;\n}\n\nexport interface RelayResponse {\n status: number;\n /** JSON-serializable body (omitted → empty response). */\n body?: unknown;\n}\n\nexport interface ControlPlaneDeps {\n store: Store;\n /** GitHub-App leaser for `git.lease-token`; null → leasing returns a clear error. */\n leaser: GitHubAppLeaser | null;\n /** Admin bearer gating `/admin/*` + `/remote/*`. Required (fail-closed). */\n adminToken: string;\n /**\n * Providers this plane can CREATE boxes on (gates `POST /remote/boxes`).\n * `undefined`/empty → all providers allowed. A serverless plane (Vercel, no\n * worker) sets this to the SDK-native set so it cleanly refuses providers\n * whose `create()` needs host execution (e.g. hetzner).\n */\n createProviders?: string[];\n /**\n * Custody store (agent creds / project secrets / box SSH keys). Absent →\n * `/admin/custody/*` fail-closes with 503. See `../custody/routes.ts`.\n */\n custody?: CustodyStore | null;\n log?: (line: string) => void;\n}\n\nfunction ok(body: unknown, status = 200): RelayResponse {\n return { status, body };\n}\nfunction err(status: number, error: string): RelayResponse {\n return { status, body: { error } };\n}\nfunction timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\nfunction parseJson<T>(text: string): T | null {\n if (text.length === 0) return {} as T;\n try {\n return JSON.parse(text) as T;\n } catch {\n return null;\n }\n}\n\nconst HOST_LOCAL_METHODS = new Set([\n 'git.push',\n 'git.fetch',\n 'cp.toHost',\n 'cp.fromHost',\n 'download.workspace',\n 'download.env',\n 'download.config',\n 'download.claude',\n 'checkpoint.create',\n]);\n\n/**\n * Dispatch one control-plane request. The hosted plane's gating is fixed:\n * `/admin/*` and `/remote/*` always require the admin bearer (never loopback),\n * and approvals are always poll-mode.\n */\nexport async function handleRelayRequest(\n req: GenericRequest,\n deps: ControlPlaneDeps,\n): Promise<RelayResponse> {\n const { store, leaser } = deps;\n const log = deps.log ?? (() => {});\n\n if (deps.adminToken.length === 0) {\n // Fail closed — a hosted plane with no admin token must never serve /admin/*.\n // 503 (not 500): a deploy that hasn't had its secrets set yet is \"not ready\",\n // not crashed. healthz is handled before this in the Web adapter (lib/plane.ts).\n return err(503, 'control plane not configured: admin token unset');\n }\n\n if (req.method === 'GET' && req.path === '/healthz') {\n return ok({\n ok: true,\n boxes: await store.countBoxes(),\n events: await store.countEvents(),\n controlPlane: true,\n });\n }\n\n const isAdmin = req.path.startsWith('/admin/') || req.path.startsWith('/remote/');\n if (isAdmin && !timingSafeEqualStr(req.bearer, deps.adminToken)) {\n return err(401, 'invalid admin token');\n }\n\n const custodyDeps: CustodyRouteDeps = { custody: deps.custody, adminToken: deps.adminToken, log };\n const custody = await handleCustodyRequest(req, custodyDeps);\n if (custody) return custody.body === undefined ? { status: custody.status } : ok(custody.body, custody.status);\n\n // --- box endpoints (per-box bearer) ---\n if (req.method === 'POST' && req.path === '/events') {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const body = parseJson<PostEventBody>(req.bodyText);\n if (!body || typeof body.type !== 'string' || body.type.length === 0) {\n return err(400, 'missing \"type\" string');\n }\n if (body.type === 'box-status') {\n if (!isValidBoxStatus(body.payload)) return err(400, 'invalid box-status payload');\n await store.setStatus(reg.boxId, reg.name, reg.projectIndex, body.payload);\n return ok({ ok: true }, 202);\n }\n const ev = await store.appendEvent({\n boxId: reg.boxId,\n type: body.type,\n ts: typeof body.ts === 'string' ? body.ts : undefined,\n payload: body.payload,\n });\n return ok({ id: ev.id }, 202);\n }\n\n if (req.method === 'POST' && req.path === '/rpc') {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const body = parseJson<PostRpcBody>(req.bodyText);\n if (!body || typeof body.method !== 'string' || body.method.length === 0) {\n return err(400, 'missing \"method\" string');\n }\n log(`rpc box=${reg.boxId} method=${body.method}`);\n return dispatchRpc(reg, body.method, body.params, deps);\n }\n\n if (req.method === 'GET' && req.path.startsWith('/rpc/status/')) {\n const reg = await store.authenticateBox(req.bearer);\n if (!reg) return err(401, 'unknown box token');\n const promptId = decodeURIComponent(req.path.slice('/rpc/status/'.length));\n const row = await store.getPrompt(promptId);\n if (!row || row.boxId !== reg.boxId) return err(404, 'no such prompt');\n if (row.status === 'pending') return ok({ status: 'pending' });\n if (row.answer !== 'y' || row.cancelled) {\n return ok({ status: 'done', result: { exitCode: 10, stdout: '', stderr: 'denied by user\\n' } });\n }\n const cached = row.result;\n const result = cached ?? (await runApproved(reg, row.method, leaser));\n if (!cached) await store.setPromptResult(promptId, result);\n return ok({ status: 'done', result });\n }\n\n // --- admin endpoints (admin bearer, checked above) ---\n if (req.method === 'POST' && req.path === '/admin/register-box') {\n const body = parseJson<RegisterBoxBody>(req.bodyText);\n if (!body || !body.boxId || !body.token || typeof body.name !== 'string') {\n return err(400, 'expected {boxId, token, name}');\n }\n const reg: BoxRegistration = {\n boxId: body.boxId,\n token: body.token,\n name: body.name,\n kind: body.kind === 'cloud' ? 'cloud' : 'docker',\n backend: body.backend || undefined,\n sandboxId: body.sandboxId || undefined,\n registeredAt: new Date().toISOString(),\n containerName: body.containerName || undefined,\n createdAt: body.createdAt || undefined,\n projectIndex:\n typeof body.projectIndex === 'number' && body.projectIndex > 0\n ? Math.trunc(body.projectIndex)\n : undefined,\n worktrees: Array.isArray(body.worktrees) ? body.worktrees : undefined,\n previewUrl: body.previewUrl || undefined,\n previewToken: body.previewToken || undefined,\n bridgeToken: body.bridgeToken || undefined,\n autoApproveHostActions: body.autoApproveHostActions === true,\n autoApproveSafeHostActions: body.autoApproveSafeHostActions !== false,\n originUrl: body.originUrl || undefined,\n };\n await store.registerBox(reg);\n log(`registered ${reg.kind ?? 'docker'} box ${reg.boxId} (${reg.name})`);\n return ok(null, 204);\n }\n\n if (req.method === 'POST' && req.path === '/admin/forget-box') {\n const body = parseJson<{ boxId?: string }>(req.bodyText);\n if (!body?.boxId) return err(400, 'expected {boxId}');\n await store.forgetBox(body.boxId);\n await store.deleteStatus(body.boxId);\n return ok(null, 204);\n }\n\n if (req.method === 'GET' && req.path === '/admin/box-status') {\n const box = req.query.get('box') ?? '';\n const status = box ? await store.getStatus(box) : undefined;\n return status ? ok(status) : err(404, 'no status for box');\n }\n\n if (req.method === 'GET' && req.path === '/admin/events') {\n const since = Number.parseInt(req.query.get('since') ?? '0', 10) || 0;\n const box = req.query.get('box') ?? undefined;\n return ok({ events: await store.listEvents(since, box ?? undefined) });\n }\n\n if (req.method === 'GET' && req.path === '/admin/app/repo-installed') {\n // Whether the GitHub App is installed on owner/repo — lets a CLI without a\n // local App key (a laptop pointed at this plane) decide whether to prompt\n // the user to authorize the repo. No token is minted.\n if (!leaser) return err(503, 'no GitHub App configured on this control plane');\n const owner = req.query.get('owner') ?? '';\n const repo = req.query.get('repo') ?? '';\n if (!owner || !repo) return err(400, 'missing owner/repo query params');\n try {\n return ok({ installed: await leaser.isRepoInstalled(owner, repo) });\n } catch (e) {\n return err(502, `installation check failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n if (req.method === 'GET' && req.path === '/admin/registry') {\n const redacted = (await store.listBoxes()).map((r) => ({\n boxId: r.boxId,\n name: r.name,\n kind: r.kind,\n registeredAt: r.registeredAt,\n projectIndex: r.projectIndex,\n originUrl: r.originUrl,\n }));\n return ok({ boxes: redacted });\n }\n\n if (req.method === 'GET' && req.path === '/admin/prompts') {\n const boxId = req.query.get('boxId') ?? '';\n if (boxId.length === 0) return err(400, 'missing boxId query param');\n const pending = (await store.listPendingPrompts(boxId)).map((r) => r.ev);\n return ok({ prompts: pending });\n }\n\n if (req.method === 'POST' && req.path === '/admin/prompts/answer') {\n const body = parseJson<{ id?: string; answer?: string; cancelled?: boolean }>(req.bodyText);\n if (!body?.id || (body.answer !== 'y' && body.answer !== 'n')) {\n return err(400, 'expected {id, answer:\"y\"|\"n\", cancelled?}');\n }\n const hit = await store.answerPrompt(body.id, body.answer, body.cancelled);\n return hit ? ok(null, 204) : err(404, 'no pending prompt with that id');\n }\n\n // Generic Store RPC for a federated laptop relay's RemoteStore — a shared\n // dispatcher mounted in both this hosted-plane handler and the relay daemon\n // (`server.ts`), so a PC's RemoteStore works against the control box and the\n // Vercel plane identically.\n const storeRpc = await handleStoreRpcRequest(req, { store, adminToken: deps.adminToken, log });\n if (storeRpc) {\n return storeRpc.body === undefined ? { status: storeRpc.status } : ok(storeRpc.body, storeRpc.status);\n }\n\n // Create-queue surface (`/remote/boxes`) — a shared dispatcher mounted in both\n // this hosted-plane handler and the relay daemon (`server.ts`), so the control\n // box and the Vercel plane serve identical enqueue/status semantics.\n const remote = await handleRemoteBoxesRequest(req, {\n store,\n adminToken: deps.adminToken,\n createProviders: deps.createProviders,\n custody: deps.custody,\n log,\n });\n if (remote) return remote.body === undefined ? { status: remote.status } : ok(remote.body, remote.status);\n\n return err(404, 'not found');\n}\n\nasync function dispatchRpc(\n reg: BoxRegistration,\n method: string,\n params: unknown,\n deps: ControlPlaneDeps,\n): Promise<RelayResponse> {\n if (method === 'git.lease-token') {\n const p = params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, p?.path ?? '/workspace');\n // Lease-token grants a *repo-scoped* push token — the box can then push any\n // branch with it, so (unlike the relay-driven git.push, where the relay\n // picks the exact branch) the sanctioned-branch auto-approve does NOT apply\n // here. Only the box's own scratch branch bypasses; everything else parks\n // for a human.\n const isAgentboxBranch = isScratchBranch(worktree?.branch);\n if (!isAgentboxBranch) {\n const gate = await gateApproval({ mode: 'poll', store: deps.store }, reg.boxId, method, params, {\n kind: 'confirm',\n message: `Allow box ${reg.name} to lease a push token for ${reg.originUrl ?? 'its repo'}?`,\n detail: `branch ${worktree?.branch ?? '(unregistered)'}`,\n defaultAnswer: 'n',\n context: { command: 'git lease-token', cwd: p?.path },\n });\n if (gate.kind === 'pending') return ok({ status: 'pending', promptId: gate.promptId }, 202);\n if (gate.kind === 'deny') {\n return ok({ exitCode: 10, stdout: '', stderr: 'denied by user\\n' }, 500);\n }\n }\n const result = await leaseTokenResult(deps.leaser, reg);\n return ok(result, result.exitCode === 0 ? 200 : 500);\n }\n\n if (method === 'browser.open') {\n // The box already opened it locally; just record the event (no host mirror).\n const p = params as { url?: unknown } | undefined;\n if (typeof p?.url === 'string') {\n await deps.store.appendEvent({ boxId: reg.boxId, type: 'browser-open', payload: { url: p.url } });\n }\n return ok({ exitCode: 0, stdout: '', stderr: '' });\n }\n\n if (HOST_LOCAL_METHODS.has(method)) {\n return ok(\n {\n exitCode: 64,\n stdout: '',\n stderr: `${method}: not available on the hosted control plane (no host). Cloud boxes push via git.lease-token.\\n`,\n },\n 501,\n );\n }\n\n return ok({ error: 'rpc method not implemented', method }, 501);\n}\n\n/** Execute a poll-approved action on the hosted plane. Only leasing is parkable here. */\nasync function runApproved(\n reg: BoxRegistration,\n method: string,\n leaser: GitHubAppLeaser | null,\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n if (method === 'git.lease-token') return leaseTokenResult(leaser, reg);\n return { exitCode: 64, stdout: '', stderr: `relay: no approved-action executor for ${method}\\n` };\n}\n","import * as pg from 'drizzle-orm/pg-core';\nimport * as sq from 'drizzle-orm/sqlite-core';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, PromptAskEvent, RelayEvent } from '../types.js';\nimport type { CreateJobRow, PromptRow } from './store.js';\n\n/**\n * The relay core's persisted schema, in both dialects.\n *\n * Drizzle types a table (and therefore every query) to its dialect, so `pg-core`\n * and `sqlite-core` each need their own table objects — but the *logical* schema\n * is one: identical table names, identical column names, identical JSON payloads.\n * Only the physical types differ (jsonb/timestamptz/bigint-identity vs\n * text-json/text-ISO/integer-autoincrement), which is what lets the existing\n * Postgres tables stay byte-compatible with what the hand-written SQL created.\n *\n * Timestamps are written as JS-side values in both dialects rather than leaning\n * on a `now()` default, so the read mappers below are shared: they normalize\n * `Date | string` to ISO-8601 whichever driver produced the row.\n *\n * DDL lives here too (see PG_SCHEMA_SQL / SQLITE_SCHEMA_SQL). Drizzle only emits\n * DDL through drizzle-kit migration folders, and a folder of .sql files does not\n * survive tsup bundling into relay's `bin.cjs` or the hub's standalone build — so\n * the boot-time `CREATE TABLE IF NOT EXISTS` stays literal SQL, colocated with\n * the schema it must match. Every *query* is drizzle-built.\n */\n\n// --- postgres ---\n\nexport const pgBoxes = pg.pgTable('boxes', {\n boxId: pg.text('box_id').primaryKey(),\n token: pg.text('token').notNull(),\n originUrl: pg.text('origin_url'),\n data: pg.jsonb('data').$type<BoxRegistration>().notNull(),\n registeredAt: pg.timestamp('registered_at', { withTimezone: true }).notNull(),\n});\n\nexport const pgEvents = pg.pgTable('events', {\n id: pg.bigint('id', { mode: 'number' }).generatedAlwaysAsIdentity().primaryKey(),\n boxId: pg.text('box_id').notNull(),\n type: pg.text('type').notNull(),\n ts: pg.text('ts'),\n payload: pg.jsonb('payload'),\n receivedAt: pg.timestamp('received_at', { withTimezone: true }).notNull(),\n});\n\nexport const pgBoxStatus = pg.pgTable('box_status', {\n boxId: pg.text('box_id').primaryKey(),\n name: pg.text('name'),\n projectIndex: pg.integer('project_index'),\n status: pg.jsonb('status').$type<BoxStatusSnapshot>().notNull(),\n updatedAt: pg.timestamp('updated_at', { withTimezone: true }).notNull(),\n});\n\nexport const pgPrompts = pg.pgTable('prompts', {\n id: pg.text('id').primaryKey(),\n boxId: pg.text('box_id').notNull(),\n ev: pg.jsonb('ev').$type<PromptAskEvent>().notNull(),\n method: pg.text('method').notNull(),\n params: pg.jsonb('params'),\n status: pg.text('status').$type<PromptRow['status']>().notNull(),\n answer: pg.text('answer').$type<'y' | 'n'>(),\n cancelled: pg.boolean('cancelled'),\n result: pg.jsonb('result').$type<GitRpcResult>(),\n createdAt: pg.timestamp('created_at', { withTimezone: true }).notNull(),\n expiresAt: pg.timestamp('expires_at', { withTimezone: true }),\n});\n\nexport const pgCreateJobs = pg.pgTable('create_jobs', {\n id: pg.text('id').primaryKey(),\n status: pg.text('status').$type<CreateJobRow['status']>().notNull(),\n request: pg.jsonb('request').$type<CreateJobRow['request']>().notNull(),\n result: pg.jsonb('result').$type<NonNullable<CreateJobRow['result']>>(),\n claimedBy: pg.text('claimed_by'),\n createdAt: pg.timestamp('created_at', { withTimezone: true }).notNull(),\n startedAt: pg.timestamp('started_at', { withTimezone: true }),\n finishedAt: pg.timestamp('finished_at', { withTimezone: true }),\n});\n\n/** Idempotent DDL for the Postgres tables. Unchanged from the pre-drizzle store. */\nexport const PG_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS boxes (\n box_id text PRIMARY KEY,\n token text NOT NULL,\n origin_url text,\n data jsonb NOT NULL,\n registered_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);\n\nCREATE TABLE IF NOT EXISTS events (\n id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n box_id text NOT NULL,\n type text NOT NULL,\n ts text,\n payload jsonb,\n received_at timestamptz NOT NULL DEFAULT now()\n);\nCREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);\n\nCREATE TABLE IF NOT EXISTS box_status (\n box_id text PRIMARY KEY,\n name text,\n project_index int,\n status jsonb NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n id text PRIMARY KEY,\n box_id text NOT NULL,\n ev jsonb NOT NULL,\n method text NOT NULL,\n params jsonb,\n status text NOT NULL DEFAULT 'pending',\n answer text,\n cancelled boolean,\n result jsonb,\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz\n);\nCREATE INDEX IF NOT EXISTS prompts_box_pending_idx ON prompts (box_id) WHERE status = 'pending';\n\nCREATE TABLE IF NOT EXISTS create_jobs (\n id text PRIMARY KEY,\n status text NOT NULL DEFAULT 'queued',\n request jsonb NOT NULL,\n result jsonb,\n claimed_by text,\n created_at timestamptz NOT NULL DEFAULT now(),\n started_at timestamptz,\n finished_at timestamptz\n);\nCREATE INDEX IF NOT EXISTS create_jobs_queued_idx ON create_jobs (created_at) WHERE status = 'queued';\n`;\n\n// --- sqlite ---\n\nexport const sqliteBoxes = sq.sqliteTable(\n 'boxes',\n {\n boxId: sq.text('box_id').primaryKey(),\n token: sq.text('token').notNull(),\n originUrl: sq.text('origin_url'),\n data: sq.text('data', { mode: 'json' }).$type<BoxRegistration>().notNull(),\n registeredAt: sq.text('registered_at').notNull(),\n },\n (t) => [sq.index('boxes_token_idx').on(t.token)],\n);\n\nexport const sqliteEvents = sq.sqliteTable(\n 'events',\n {\n id: sq.integer('id').primaryKey({ autoIncrement: true }),\n boxId: sq.text('box_id').notNull(),\n type: sq.text('type').notNull(),\n ts: sq.text('ts'),\n payload: sq.text('payload', { mode: 'json' }),\n receivedAt: sq.text('received_at').notNull(),\n },\n (t) => [sq.index('events_box_idx').on(t.boxId, t.id)],\n);\n\nexport const sqliteBoxStatus = sq.sqliteTable('box_status', {\n boxId: sq.text('box_id').primaryKey(),\n name: sq.text('name'),\n projectIndex: sq.integer('project_index'),\n status: sq.text('status', { mode: 'json' }).$type<BoxStatusSnapshot>().notNull(),\n updatedAt: sq.text('updated_at').notNull(),\n});\n\nexport const sqlitePrompts = sq.sqliteTable(\n 'prompts',\n {\n id: sq.text('id').primaryKey(),\n boxId: sq.text('box_id').notNull(),\n ev: sq.text('ev', { mode: 'json' }).$type<PromptAskEvent>().notNull(),\n method: sq.text('method').notNull(),\n params: sq.text('params', { mode: 'json' }),\n status: sq.text('status').$type<PromptRow['status']>().notNull(),\n answer: sq.text('answer').$type<'y' | 'n'>(),\n cancelled: sq.integer('cancelled', { mode: 'boolean' }),\n result: sq.text('result', { mode: 'json' }).$type<GitRpcResult>(),\n createdAt: sq.text('created_at').notNull(),\n expiresAt: sq.text('expires_at'),\n },\n (t) => [sq.index('prompts_box_status_idx').on(t.boxId, t.status)],\n);\n\nexport const sqliteCreateJobs = sq.sqliteTable(\n 'create_jobs',\n {\n id: sq.text('id').primaryKey(),\n status: sq.text('status').$type<CreateJobRow['status']>().notNull(),\n request: sq.text('request', { mode: 'json' }).$type<CreateJobRow['request']>().notNull(),\n result: sq.text('result', { mode: 'json' }).$type<NonNullable<CreateJobRow['result']>>(),\n claimedBy: sq.text('claimed_by'),\n createdAt: sq.text('created_at').notNull(),\n startedAt: sq.text('started_at'),\n finishedAt: sq.text('finished_at'),\n },\n (t) => [sq.index('create_jobs_status_idx').on(t.status, t.createdAt)],\n);\n\n/** Idempotent DDL for the SQLite tables (mirror of {@link PG_SCHEMA_SQL}). */\nexport const SQLITE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS boxes (\n box_id text PRIMARY KEY,\n token text NOT NULL,\n origin_url text,\n data text NOT NULL,\n registered_at text NOT NULL\n);\nCREATE INDEX IF NOT EXISTS boxes_token_idx ON boxes (token);\n\nCREATE TABLE IF NOT EXISTS events (\n id integer PRIMARY KEY AUTOINCREMENT,\n box_id text NOT NULL,\n type text NOT NULL,\n ts text,\n payload text,\n received_at text NOT NULL\n);\nCREATE INDEX IF NOT EXISTS events_box_idx ON events (box_id, id);\n\nCREATE TABLE IF NOT EXISTS box_status (\n box_id text PRIMARY KEY,\n name text,\n project_index integer,\n status text NOT NULL,\n updated_at text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS prompts (\n id text PRIMARY KEY,\n box_id text NOT NULL,\n ev text NOT NULL,\n method text NOT NULL,\n params text,\n status text NOT NULL DEFAULT 'pending',\n answer text,\n cancelled integer,\n result text,\n created_at text NOT NULL,\n expires_at text\n);\nCREATE INDEX IF NOT EXISTS prompts_box_status_idx ON prompts (box_id, status);\n\nCREATE TABLE IF NOT EXISTS create_jobs (\n id text PRIMARY KEY,\n status text NOT NULL DEFAULT 'queued',\n request text NOT NULL,\n result text,\n claimed_by text,\n created_at text NOT NULL,\n started_at text,\n finished_at text\n);\nCREATE INDEX IF NOT EXISTS create_jobs_status_idx ON create_jobs (status, created_at);\n`;\n\n// --- shared row mappers (either dialect) ---\n\n/** A timestamp column as returned by pg (Date) or sqlite (ISO text). */\nexport type DbTimestamp = Date | string;\n\nexport function toIso(value: DbTimestamp): string {\n return value instanceof Date ? value.toISOString() : new Date(value).toISOString();\n}\n\nexport function toIsoOrUndefined(value: DbTimestamp | null): string | undefined {\n return value === null ? undefined : toIso(value);\n}\n\nexport interface EventRow {\n id: number;\n boxId: string;\n type: string;\n ts: string | null;\n payload: unknown;\n receivedAt: DbTimestamp;\n}\n\nexport function rowToEvent(r: EventRow): RelayEvent {\n return {\n id: Number(r.id),\n boxId: r.boxId,\n type: r.type,\n ts: r.ts ?? undefined,\n payload: r.payload ?? undefined,\n receivedAt: toIso(r.receivedAt),\n };\n}\n\nexport interface PromptDbRow {\n id: string;\n boxId: string;\n ev: PromptAskEvent;\n method: string;\n params: unknown;\n status: PromptRow['status'];\n answer: 'y' | 'n' | null;\n cancelled: boolean | null;\n result: GitRpcResult | null;\n createdAt: DbTimestamp;\n expiresAt: DbTimestamp | null;\n}\n\nexport function rowToPrompt(r: PromptDbRow): PromptRow {\n return {\n id: r.id,\n boxId: r.boxId,\n ev: r.ev,\n method: r.method,\n params: r.params ?? undefined,\n status: r.status,\n answer: r.answer ?? undefined,\n cancelled: r.cancelled ?? undefined,\n result: r.result ?? undefined,\n createdAt: toIso(r.createdAt),\n expiresAt: toIsoOrUndefined(r.expiresAt),\n };\n}\n\nexport interface CreateJobDbRow {\n id: string;\n status: CreateJobRow['status'];\n request: CreateJobRow['request'];\n result: NonNullable<CreateJobRow['result']> | null;\n claimedBy: string | null;\n createdAt: DbTimestamp;\n startedAt: DbTimestamp | null;\n finishedAt: DbTimestamp | null;\n}\n\nexport function rowToJob(r: CreateJobDbRow): CreateJobRow {\n return {\n id: r.id,\n status: r.status,\n request: r.request,\n result: r.result ?? undefined,\n claimedBy: r.claimedBy ?? undefined,\n createdAt: toIso(r.createdAt),\n startedAt: toIsoOrUndefined(r.startedAt),\n finishedAt: toIsoOrUndefined(r.finishedAt),\n };\n}\n","import { and, asc, desc, eq, gt, inArray, isNotNull, lt, lte, or } from 'drizzle-orm';\nimport type { NodePgDatabase } from 'drizzle-orm/node-postgres';\nimport type { Pool } from 'pg';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport { RELAY_EVENT_RING_SIZE } from '../types.js';\nimport {\n PG_SCHEMA_SQL,\n pgBoxStatus,\n pgBoxes,\n pgCreateJobs,\n pgEvents,\n pgPrompts,\n rowToEvent,\n rowToJob,\n rowToPrompt,\n} from './schema.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\n/**\n * Postgres-backed {@link Store} for the hosted control plane (Vercel-managed\n * Postgres, Neon, or a self-hosted Postgres beside the app). Queries are built\n * with drizzle over the shared schema in `./schema.ts` — the same schema the\n * SQLite store uses, so the two dialects cannot drift.\n *\n * `pg` (and drizzle's `node-postgres` driver, which statically imports it) is\n * loaded via a lazy dynamic import so the laptop relay / CLI bundle — which only\n * ever uses {@link MemoryStore} — never pulls it in (mirrors how host-actions.ts\n * lazy-loads the cloud SDKs; `pg` is in the relay tsup `external` list).\n */\n\nconst DEFAULT_EVENT_CAP = RELAY_EVENT_RING_SIZE;\n\nexport interface PostgresStoreOptions {\n /** Postgres connection string (e.g. `process.env.POSTGRES_URL`). */\n connectionString?: string;\n /** Inject a pre-built pool (tests / a shared app pool). Takes precedence over connectionString. */\n pool?: Pool;\n /**\n * Global event-row cap, mirroring the in-memory ring. Newest N kept by id;\n * older rows trimmed on append. 0 disables trimming. Default 1000.\n */\n eventCap?: number;\n}\n\nexport class PostgresStore implements Store {\n private readonly eventCap: number;\n private readonly connectionString?: string;\n private readonly injectedPool?: Pool;\n private poolPromise: Promise<Pool> | null = null;\n private dbPromise: Promise<NodePgDatabase> | null = null;\n\n constructor(opts: PostgresStoreOptions = {}) {\n this.connectionString = opts.connectionString;\n this.injectedPool = opts.pool;\n this.eventCap = opts.eventCap ?? DEFAULT_EVENT_CAP;\n }\n\n /** Lazily build (or reuse) the pg Pool. `pg` is imported on first use only. */\n private pool(): Promise<Pool> {\n if (this.injectedPool) return Promise.resolve(this.injectedPool);\n this.poolPromise ??= import('pg').then(\n ({ default: pg }) => new pg.Pool({ connectionString: this.connectionString }),\n );\n return this.poolPromise;\n }\n\n private db(): Promise<NodePgDatabase> {\n this.dbPromise ??= (async () => {\n const pool = await this.pool();\n const { drizzle } = await import('drizzle-orm/node-postgres');\n return drizzle(pool);\n })();\n return this.dbPromise;\n }\n\n /** Create the tables if absent. Call once on boot (idempotent). */\n async migrate(): Promise<void> {\n const pool = await this.pool();\n await pool.query(PG_SCHEMA_SQL);\n }\n\n /** Release the pool (tests / graceful shutdown). No-op for an injected pool. */\n async close(): Promise<void> {\n if (this.injectedPool) return;\n if (this.poolPromise) {\n const pool = await this.poolPromise;\n await pool.end();\n this.poolPromise = null;\n this.dbPromise = null;\n }\n }\n\n // --- boxes ---\n\n async registerBox(reg: BoxRegistration): Promise<void> {\n const db = await this.db();\n await db\n .insert(pgBoxes)\n .values({\n boxId: reg.boxId,\n token: reg.token,\n originUrl: reg.originUrl ?? null,\n data: reg,\n registeredAt: new Date(reg.registeredAt),\n })\n .onConflictDoUpdate({\n target: pgBoxes.boxId,\n set: { token: reg.token, originUrl: reg.originUrl ?? null, data: reg },\n });\n }\n\n async getBox(boxId: string): Promise<BoxRegistration | undefined> {\n const db = await this.db();\n const rows = await db.select({ data: pgBoxes.data }).from(pgBoxes).where(eq(pgBoxes.boxId, boxId));\n return rows[0]?.data;\n }\n\n async authenticateBox(token: string): Promise<BoxRegistration | null> {\n if (token.length === 0) return null;\n const db = await this.db();\n const rows = await db\n .select({ data: pgBoxes.data })\n .from(pgBoxes)\n .where(eq(pgBoxes.token, token))\n .limit(1);\n return rows[0]?.data ?? null;\n }\n\n async listBoxes(): Promise<BoxRegistration[]> {\n const db = await this.db();\n const rows = await db.select({ data: pgBoxes.data }).from(pgBoxes).orderBy(asc(pgBoxes.registeredAt));\n return rows.map((r) => r.data);\n }\n\n async forgetBox(boxId: string): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .delete(pgBoxes)\n .where(eq(pgBoxes.boxId, boxId))\n .returning({ boxId: pgBoxes.boxId });\n return rows.length > 0;\n }\n\n async countBoxes(): Promise<number> {\n const db = await this.db();\n return db.$count(pgBoxes);\n }\n\n // --- events ---\n\n async appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n const db = await this.db();\n const rows = await db\n .insert(pgEvents)\n .values({\n boxId: input.boxId,\n type: input.type,\n ts: input.ts ?? null,\n payload: input.payload ?? null,\n receivedAt: new Date(),\n })\n .returning({ id: pgEvents.id, receivedAt: pgEvents.receivedAt });\n const row = rows[0]!;\n if (this.eventCap > 0) {\n // Keep only the newest `eventCap` rows by id, matching the in-memory ring.\n await db.delete(pgEvents).where(lte(pgEvents.id, row.id - this.eventCap));\n }\n return {\n id: row.id,\n boxId: input.boxId,\n type: input.type,\n ts: input.ts,\n payload: input.payload,\n receivedAt: row.receivedAt.toISOString(),\n };\n }\n\n async listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n const db = await this.db();\n const where =\n boxId === undefined\n ? gt(pgEvents.id, since)\n : and(gt(pgEvents.id, since), eq(pgEvents.boxId, boxId));\n const rows = await db.select().from(pgEvents).where(where).orderBy(asc(pgEvents.id));\n return rows.map(rowToEvent);\n }\n\n async countEvents(): Promise<number> {\n const db = await this.db();\n return db.$count(pgEvents);\n }\n\n // --- status ---\n\n async setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n const db = await this.db();\n const updatedAt = new Date();\n await db\n .insert(pgBoxStatus)\n .values({ boxId, name, projectIndex: projectIndex ?? null, status, updatedAt })\n .onConflictDoUpdate({\n target: pgBoxStatus.boxId,\n set: { name, projectIndex: projectIndex ?? null, status, updatedAt },\n });\n }\n\n async getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n const db = await this.db();\n const rows = await db\n .select({ status: pgBoxStatus.status })\n .from(pgBoxStatus)\n .where(eq(pgBoxStatus.boxId, boxId));\n return rows[0]?.status;\n }\n\n async deleteStatus(boxId: string): Promise<void> {\n const db = await this.db();\n await db.delete(pgBoxStatus).where(eq(pgBoxStatus.boxId, boxId));\n }\n\n /**\n * All box status snapshots in one query (avoids N+1 over listBoxes +\n * per-box getStatus). Used by the hosted hub UI to render every box's live\n * status. Not on the Store interface — only the hosted stores need it.\n */\n async listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n const db = await this.db();\n return db.select({ boxId: pgBoxStatus.boxId, status: pgBoxStatus.status }).from(pgBoxStatus);\n }\n\n // --- prompt mailbox ---\n\n async createPrompt(row: PromptRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(pgPrompts)\n .values({\n id: row.id,\n boxId: row.boxId,\n ev: row.ev,\n method: row.method,\n params: row.params ?? null,\n status: row.status,\n answer: row.answer ?? null,\n cancelled: row.cancelled ?? null,\n result: row.result ?? null,\n createdAt: new Date(row.createdAt),\n expiresAt: row.expiresAt ? new Date(row.expiresAt) : null,\n })\n .onConflictDoNothing({ target: pgPrompts.id });\n }\n\n async getPrompt(promptId: string): Promise<PromptRow | null> {\n const db = await this.db();\n const rows = await db.select().from(pgPrompts).where(eq(pgPrompts.id, promptId));\n return rows[0] ? rowToPrompt(rows[0]) : null;\n }\n\n async answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .update(pgPrompts)\n .set({ status: 'answered', answer, cancelled: cancelled ?? null })\n .where(and(eq(pgPrompts.id, promptId), eq(pgPrompts.status, 'pending')))\n .returning({ id: pgPrompts.id });\n return rows.length > 0;\n }\n\n async listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const db = await this.db();\n const rows = await db\n .select()\n .from(pgPrompts)\n .where(and(eq(pgPrompts.boxId, boxId), eq(pgPrompts.status, 'pending')))\n .orderBy(asc(pgPrompts.createdAt));\n return rows.map(rowToPrompt);\n }\n\n async setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n const db = await this.db();\n await db.update(pgPrompts).set({ result }).where(eq(pgPrompts.id, promptId));\n }\n\n // --- box-create job queue ---\n\n async enqueueCreateJob(job: CreateJobRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(pgCreateJobs)\n .values({\n id: job.id,\n status: job.status,\n request: job.request,\n result: job.result ?? null,\n claimedBy: job.claimedBy ?? null,\n createdAt: new Date(job.createdAt),\n startedAt: job.startedAt ? new Date(job.startedAt) : null,\n finishedAt: job.finishedAt ? new Date(job.finishedAt) : null,\n })\n .onConflictDoNothing({ target: pgCreateJobs.id });\n }\n\n async getCreateJob(id: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n const rows = await db.select().from(pgCreateJobs).where(eq(pgCreateJobs.id, id));\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n const db = await this.db();\n const base = db.select().from(pgCreateJobs);\n const filtered = opts?.status?.length\n ? base.where(inArray(pgCreateJobs.status, opts.status))\n : base;\n const rows = await filtered.orderBy(desc(pgCreateJobs.createdAt)).limit(opts?.limit ?? 100);\n return rows.map(rowToJob);\n }\n\n async claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n // Atomic claim: lock the oldest queued row, skip ones a sibling worker holds.\n const oldestQueued = db\n .select({ id: pgCreateJobs.id })\n .from(pgCreateJobs)\n .where(eq(pgCreateJobs.status, 'queued'))\n .orderBy(asc(pgCreateJobs.createdAt))\n .limit(1)\n .for('update', { skipLocked: true });\n const rows = await db\n .update(pgCreateJobs)\n .set({ status: 'running', claimedBy: workerId, startedAt: new Date() })\n .where(inArray(pgCreateJobs.id, oldestQueued))\n .returning();\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n const db = await this.db();\n await db\n .update(pgCreateJobs)\n .set({ status, result, finishedAt: new Date() })\n .where(eq(pgCreateJobs.id, id));\n }\n\n // --- retention (timestamptz columns compare against a Date) ---\n\n async prunePrompts(beforeIso: string): Promise<number> {\n const db = await this.db();\n const before = new Date(beforeIso);\n const rows = await db\n .delete(pgPrompts)\n .where(\n or(\n and(eq(pgPrompts.status, 'answered'), lt(pgPrompts.createdAt, before)),\n and(isNotNull(pgPrompts.expiresAt), lt(pgPrompts.expiresAt, before)),\n ),\n )\n .returning({ id: pgPrompts.id });\n return rows.length;\n }\n\n async pruneCreateJobs(beforeIso: string): Promise<number> {\n const db = await this.db();\n const before = new Date(beforeIso);\n const rows = await db\n .delete(pgCreateJobs)\n .where(\n and(\n inArray(pgCreateJobs.status, ['done', 'failed']),\n isNotNull(pgCreateJobs.finishedAt),\n lt(pgCreateJobs.finishedAt, before),\n ),\n )\n .returning({ id: pgCreateJobs.id });\n return rows.length;\n }\n}\n","import { mkdirSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport { STATE_DIR } from '@agentbox/config';\nimport { and, asc, desc, eq, gt, inArray, isNotNull, lt, lte, or } from 'drizzle-orm';\nimport type { SqliteRemoteDatabase } from 'drizzle-orm/sqlite-proxy';\nimport type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport { RELAY_EVENT_RING_SIZE } from '../types.js';\nimport {\n SQLITE_SCHEMA_SQL,\n rowToEvent,\n rowToJob,\n rowToPrompt,\n sqliteBoxStatus,\n sqliteBoxes,\n sqliteCreateJobs,\n sqliteEvents,\n sqlitePrompts,\n} from './schema.js';\nimport type { CreateJobRow, PromptRow, Store } from './store.js';\n\n/**\n * SQLite-backed {@link Store} — the control box's default (a single always-on\n * process on a small VPS has no reason to run a Postgres container).\n *\n * Driver: `node:sqlite`'s `DatabaseSync` behind drizzle's `sqlite-proxy`\n * (bring-your-own-executor) driver. drizzle ships no `node:sqlite` driver, and\n * its `better-sqlite3` one would add a native dependency; `sqlite-proxy` gets the\n * same typed query builder over the exact driver the hub's better-auth already\n * uses (`~/.agentbox/hub/auth.db`), with no native build step. The executor\n * callback below is the whole adapter.\n *\n * `node:sqlite` (and the drizzle driver) are lazy dynamic imports so the laptop\n * CLI bundle never touches them, and so a Node < 22.5 host only fails if it\n * actually asks for a SQLite store.\n *\n * Concurrency: SQLite is single-writer. WAL + a busy timeout make concurrent\n * readers fine, but the design consequence (recorded in the plan) is that the\n * create worker must run in the hub *process*, not as a second container on the\n * same file.\n */\n\nconst DEFAULT_EVENT_CAP = RELAY_EVENT_RING_SIZE;\n\n/** Default DB path — sibling of the hub's better-auth `auth.db`. */\nexport const DEFAULT_SQLITE_STORE_PATH = join(STATE_DIR, 'hub', 'store.db');\n\n/** `node:sqlite` landed in 22.5 (the repo's engines floor is 20.10). */\nconst MIN_NODE_SQLITE = [22, 5] as const;\n\nexport interface SqliteStoreOptions {\n /** DB file path, or ':memory:' (tests). Default `~/.agentbox/hub/store.db`. */\n path?: string;\n /** Global event-row cap, mirroring the in-memory ring. 0 disables trimming. Default 1000. */\n eventCap?: number;\n}\n\n/** The subset of `node:sqlite`'s DatabaseSync this store drives. */\ninterface SqliteDatabase {\n exec(sql: string): void;\n prepare(sql: string): SqliteStatement;\n close(): void;\n}\ninterface SqliteStatement {\n run(...params: unknown[]): unknown;\n all(...params: unknown[]): unknown[];\n setReturnArrays?: (enabled: boolean) => void;\n}\n\n/**\n * Load `node:sqlite` without any bundler seeing the specifier.\n *\n * It is a *prefix-only* builtin, so it is absent from `module.builtinModules` —\n * and vite 5 / vite-node decide \"is this a builtin?\" from that list, strip the\n * `node:`, and then try to load a package called `sqlite` from disk. A plain\n * `await import('node:sqlite')` therefore breaks every vitest run that touches\n * this store. Going through `createRequire` keeps the load a runtime concern of\n * Node's own resolver, which is the only one that gets this right.\n */\nfunction loadNodeSqlite(): typeof import('node:sqlite') {\n const require = createRequire(import.meta.url);\n return require('node:sqlite') as typeof import('node:sqlite');\n}\n\nfunction assertNodeSupportsSqlite(): void {\n const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);\n const ok = major > MIN_NODE_SQLITE[0] || (major === MIN_NODE_SQLITE[0] && minor >= MIN_NODE_SQLITE[1]);\n if (!ok) {\n throw new Error(\n `the SQLite store needs Node >= ${MIN_NODE_SQLITE[0]}.${MIN_NODE_SQLITE[1]} for node:sqlite (running ${process.versions.node}). ` +\n 'Upgrade Node, or point the hub at a Postgres store (POSTGRES_URL).',\n );\n }\n}\n\nexport class SqliteStore implements Store {\n private readonly path: string;\n private readonly eventCap: number;\n private raw: SqliteDatabase | null = null;\n private dbPromise: Promise<SqliteRemoteDatabase> | null = null;\n\n constructor(opts: SqliteStoreOptions = {}) {\n this.path = opts.path ?? DEFAULT_SQLITE_STORE_PATH;\n this.eventCap = opts.eventCap ?? DEFAULT_EVENT_CAP;\n }\n\n /**\n * Open the DB (creating the file + tables if absent) and wrap it in drizzle.\n * Lazy + memoized: the schema is always applied before the first query, so\n * callers never have to sequence `migrate()` themselves.\n */\n private db(): Promise<SqliteRemoteDatabase> {\n this.dbPromise ??= (async () => {\n assertNodeSupportsSqlite();\n const { DatabaseSync } = loadNodeSqlite();\n const { drizzle } = await import('drizzle-orm/sqlite-proxy');\n if (this.path !== ':memory:') mkdirSync(dirname(this.path), { recursive: true });\n const raw = new DatabaseSync(this.path) as unknown as SqliteDatabase;\n // WAL keeps readers off the writer's back; busy_timeout turns a concurrent\n // write into a short wait instead of an immediate SQLITE_BUSY throw.\n raw.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;');\n raw.exec(SQLITE_SCHEMA_SQL);\n this.raw = raw;\n return drizzle(async (sql, params, method) => {\n const stmt = raw.prepare(sql);\n if (method === 'run') {\n stmt.run(...params);\n return { rows: [] };\n }\n // drizzle maps result columns positionally, so rows must be arrays.\n // node:sqlite grew setReturnArrays after 22.5 — fall back to key order\n // (our queries are single-table, so no duplicate-column collapse).\n let rows: unknown[][];\n if (typeof stmt.setReturnArrays === 'function') {\n stmt.setReturnArrays(true);\n rows = stmt.all(...params) as unknown[][];\n } else {\n rows = (stmt.all(...params) as Record<string, unknown>[]).map((r) => Object.values(r));\n }\n return method === 'get' ? { rows: rows[0] ?? [] } : { rows };\n });\n })();\n return this.dbPromise;\n }\n\n /** Open + apply the schema. Idempotent; `db()` does it lazily anyway. */\n async migrate(): Promise<void> {\n await this.db();\n }\n\n /** Close the underlying handle (tests / graceful shutdown). */\n async close(): Promise<void> {\n if (this.dbPromise) await this.dbPromise.catch(() => undefined);\n this.raw?.close();\n this.raw = null;\n this.dbPromise = null;\n }\n\n // --- boxes ---\n\n async registerBox(reg: BoxRegistration): Promise<void> {\n const db = await this.db();\n await db\n .insert(sqliteBoxes)\n .values({\n boxId: reg.boxId,\n token: reg.token,\n originUrl: reg.originUrl ?? null,\n data: reg,\n registeredAt: reg.registeredAt,\n })\n .onConflictDoUpdate({\n target: sqliteBoxes.boxId,\n set: { token: reg.token, originUrl: reg.originUrl ?? null, data: reg },\n });\n }\n\n async getBox(boxId: string): Promise<BoxRegistration | undefined> {\n const db = await this.db();\n const rows = await db\n .select({ data: sqliteBoxes.data })\n .from(sqliteBoxes)\n .where(eq(sqliteBoxes.boxId, boxId));\n return rows[0]?.data;\n }\n\n async authenticateBox(token: string): Promise<BoxRegistration | null> {\n if (token.length === 0) return null;\n const db = await this.db();\n const rows = await db\n .select({ data: sqliteBoxes.data })\n .from(sqliteBoxes)\n .where(eq(sqliteBoxes.token, token))\n .limit(1);\n return rows[0]?.data ?? null;\n }\n\n async listBoxes(): Promise<BoxRegistration[]> {\n const db = await this.db();\n const rows = await db\n .select({ data: sqliteBoxes.data })\n .from(sqliteBoxes)\n .orderBy(asc(sqliteBoxes.registeredAt));\n return rows.map((r) => r.data);\n }\n\n async forgetBox(boxId: string): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .delete(sqliteBoxes)\n .where(eq(sqliteBoxes.boxId, boxId))\n .returning({ boxId: sqliteBoxes.boxId });\n return rows.length > 0;\n }\n\n async countBoxes(): Promise<number> {\n const db = await this.db();\n return db.$count(sqliteBoxes);\n }\n\n // --- events ---\n\n async appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n const db = await this.db();\n const receivedAt = new Date().toISOString();\n const rows = await db\n .insert(sqliteEvents)\n .values({\n boxId: input.boxId,\n type: input.type,\n ts: input.ts ?? null,\n payload: input.payload ?? null,\n receivedAt,\n })\n .returning({ id: sqliteEvents.id });\n const id = rows[0]!.id;\n if (this.eventCap > 0) {\n // Keep only the newest `eventCap` rows by id, matching the in-memory ring.\n await db.delete(sqliteEvents).where(lte(sqliteEvents.id, id - this.eventCap));\n }\n return {\n id,\n boxId: input.boxId,\n type: input.type,\n ts: input.ts,\n payload: input.payload,\n receivedAt,\n };\n }\n\n async listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n const db = await this.db();\n const where =\n boxId === undefined\n ? gt(sqliteEvents.id, since)\n : and(gt(sqliteEvents.id, since), eq(sqliteEvents.boxId, boxId));\n const rows = await db.select().from(sqliteEvents).where(where).orderBy(asc(sqliteEvents.id));\n return rows.map(rowToEvent);\n }\n\n async countEvents(): Promise<number> {\n const db = await this.db();\n return db.$count(sqliteEvents);\n }\n\n // --- status ---\n\n async setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n const db = await this.db();\n const updatedAt = new Date().toISOString();\n await db\n .insert(sqliteBoxStatus)\n .values({ boxId, name, projectIndex: projectIndex ?? null, status, updatedAt })\n .onConflictDoUpdate({\n target: sqliteBoxStatus.boxId,\n set: { name, projectIndex: projectIndex ?? null, status, updatedAt },\n });\n }\n\n async getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n const db = await this.db();\n const rows = await db\n .select({ status: sqliteBoxStatus.status })\n .from(sqliteBoxStatus)\n .where(eq(sqliteBoxStatus.boxId, boxId));\n return rows[0]?.status;\n }\n\n async deleteStatus(boxId: string): Promise<void> {\n const db = await this.db();\n await db.delete(sqliteBoxStatus).where(eq(sqliteBoxStatus.boxId, boxId));\n }\n\n /** All box status snapshots in one query (see PostgresStore.listStatuses). */\n async listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n const db = await this.db();\n return db\n .select({ boxId: sqliteBoxStatus.boxId, status: sqliteBoxStatus.status })\n .from(sqliteBoxStatus);\n }\n\n // --- prompt mailbox ---\n\n async createPrompt(row: PromptRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(sqlitePrompts)\n .values({\n id: row.id,\n boxId: row.boxId,\n ev: row.ev,\n method: row.method,\n params: row.params ?? null,\n status: row.status,\n answer: row.answer ?? null,\n cancelled: row.cancelled ?? null,\n result: row.result ?? null,\n createdAt: row.createdAt,\n expiresAt: row.expiresAt ?? null,\n })\n .onConflictDoNothing({ target: sqlitePrompts.id });\n }\n\n async getPrompt(promptId: string): Promise<PromptRow | null> {\n const db = await this.db();\n const rows = await db.select().from(sqlitePrompts).where(eq(sqlitePrompts.id, promptId));\n return rows[0] ? rowToPrompt(rows[0]) : null;\n }\n\n async answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n const db = await this.db();\n const rows = await db\n .update(sqlitePrompts)\n .set({ status: 'answered', answer, cancelled: cancelled ?? null })\n .where(and(eq(sqlitePrompts.id, promptId), eq(sqlitePrompts.status, 'pending')))\n .returning({ id: sqlitePrompts.id });\n return rows.length > 0;\n }\n\n async listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n const db = await this.db();\n const rows = await db\n .select()\n .from(sqlitePrompts)\n .where(and(eq(sqlitePrompts.boxId, boxId), eq(sqlitePrompts.status, 'pending')))\n .orderBy(asc(sqlitePrompts.createdAt));\n return rows.map(rowToPrompt);\n }\n\n async setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n const db = await this.db();\n await db.update(sqlitePrompts).set({ result }).where(eq(sqlitePrompts.id, promptId));\n }\n\n // --- box-create job queue ---\n\n async enqueueCreateJob(job: CreateJobRow): Promise<void> {\n const db = await this.db();\n await db\n .insert(sqliteCreateJobs)\n .values({\n id: job.id,\n status: job.status,\n request: job.request,\n result: job.result ?? null,\n claimedBy: job.claimedBy ?? null,\n createdAt: job.createdAt,\n startedAt: job.startedAt ?? null,\n finishedAt: job.finishedAt ?? null,\n })\n .onConflictDoNothing({ target: sqliteCreateJobs.id });\n }\n\n async getCreateJob(id: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n const rows = await db.select().from(sqliteCreateJobs).where(eq(sqliteCreateJobs.id, id));\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async listCreateJobs(opts?: {\n limit?: number;\n status?: Array<CreateJobRow['status']>;\n }): Promise<CreateJobRow[]> {\n const db = await this.db();\n const base = db.select().from(sqliteCreateJobs);\n const filtered = opts?.status?.length\n ? base.where(inArray(sqliteCreateJobs.status, opts.status))\n : base;\n const rows = await filtered\n .orderBy(desc(sqliteCreateJobs.createdAt))\n .limit(opts?.limit ?? 100);\n return rows.map(rowToJob);\n }\n\n async claimNextCreateJob(workerId: string): Promise<CreateJobRow | null> {\n const db = await this.db();\n // No SKIP LOCKED in SQLite — but the claim is one statement, and node:sqlite\n // executes it synchronously, so no second claimer can interleave between the\n // subquery and the update. The `status = 'queued'` guard is belt-and-braces.\n const oldestQueued = db\n .select({ id: sqliteCreateJobs.id })\n .from(sqliteCreateJobs)\n .where(eq(sqliteCreateJobs.status, 'queued'))\n .orderBy(asc(sqliteCreateJobs.createdAt))\n .limit(1);\n const rows = await db\n .update(sqliteCreateJobs)\n .set({ status: 'running', claimedBy: workerId, startedAt: new Date().toISOString() })\n .where(\n and(inArray(sqliteCreateJobs.id, oldestQueued), eq(sqliteCreateJobs.status, 'queued')),\n )\n .returning();\n return rows[0] ? rowToJob(rows[0]) : null;\n }\n\n async completeCreateJob(\n id: string,\n status: 'done' | 'failed',\n result: { boxId?: string; error?: string },\n ): Promise<void> {\n const db = await this.db();\n await db\n .update(sqliteCreateJobs)\n .set({ status, result, finishedAt: new Date().toISOString() })\n .where(eq(sqliteCreateJobs.id, id));\n }\n\n // --- retention (ISO strings compare lexicographically, matching the columns) ---\n\n async prunePrompts(beforeIso: string): Promise<number> {\n const db = await this.db();\n const rows = await db\n .delete(sqlitePrompts)\n .where(\n or(\n and(eq(sqlitePrompts.status, 'answered'), lt(sqlitePrompts.createdAt, beforeIso)),\n and(isNotNull(sqlitePrompts.expiresAt), lt(sqlitePrompts.expiresAt, beforeIso)),\n ),\n )\n .returning({ id: sqlitePrompts.id });\n return rows.length;\n }\n\n async pruneCreateJobs(beforeIso: string): Promise<number> {\n const db = await this.db();\n const rows = await db\n .delete(sqliteCreateJobs)\n .where(\n and(\n inArray(sqliteCreateJobs.status, ['done', 'failed']),\n isNotNull(sqliteCreateJobs.finishedAt),\n lt(sqliteCreateJobs.finishedAt, beforeIso),\n ),\n )\n .returning({ id: sqliteCreateJobs.id });\n return rows.length;\n }\n}\n","import { MemoryStore } from './memory-store.js';\nimport { PostgresStore } from './postgres-store.js';\nimport { SqliteStore } from './sqlite-store.js';\nimport type { Store } from './store.js';\n\nexport type { Store } from './store.js';\nexport { MemoryStore, type MemoryStoreParts } from './memory-store.js';\nexport { PostgresStore, type PostgresStoreOptions } from './postgres-store.js';\nexport { SqliteStore, type SqliteStoreOptions, DEFAULT_SQLITE_STORE_PATH } from './sqlite-store.js';\nexport { WriteThroughStore, type WriteThroughParts } from './write-through-store.js';\nexport { PG_SCHEMA_SQL, SQLITE_SCHEMA_SQL } from './schema.js';\n\n/**\n * Resolve a {@link Store} from a spec string. Used by the deploy adapters:\n * - undefined / 'memory' → in-memory (laptop relay, tests).\n * - 'postgres://…' / 'postgresql://…' → Postgres (hosted control plane).\n * - 'sqlite:<path>' / a bare path → SQLite (the control box default).\n * A federated laptop relay builds its RemoteStore directly (Phase 4b), not here.\n */\nexport function makeStore(spec?: string): Store {\n if (!spec || spec === 'memory') return new MemoryStore();\n if (spec.startsWith('postgres://') || spec.startsWith('postgresql://')) {\n return new PostgresStore({ connectionString: spec });\n }\n if (spec.startsWith('sqlite:')) {\n // Accept sqlite:/abs/path, sqlite:relative.db and sqlite://./file.db alike.\n const path = spec.slice('sqlite:'.length).replace(/^\\/\\//, '');\n if (!path) throw new Error(`store spec has no path: ${spec}`);\n return new SqliteStore({ path });\n }\n // A bare path (absolute, relative, or ':memory:') is a SQLite file.\n if (spec === ':memory:' || spec.startsWith('/') || spec.startsWith('.') || spec.endsWith('.db')) {\n return new SqliteStore({ path: spec });\n }\n throw new Error(`unknown store spec: ${spec}`);\n}\n","/**\n * Filesystem-backed {@link CustodyStore} — phase 2's backend: plain files under\n * `~/.agentbox/hub/custody/`, `0700` dirs / `0600` files. No sidecar manifest:\n * digests are computed from the bytes on read, so the manifest can never drift\n * from what is actually stored.\n *\n * `put`/`get` read the whole value into memory, which is right for what custody\n * was built to hold (credentials / `.env` / SSH keys — kilobytes). A project's\n * `carry:` material is the exception, so `putStream`/`getStream` pipe instead;\n * see the seam docs on {@link CustodyStore.putStream}.\n */\n\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { pipeline } from 'node:stream/promises';\nimport { Transform, type Readable } from 'node:stream';\nimport { STATE_DIR } from '@agentbox/config';\nimport {\n custodyDigest,\n CustodyTooLargeError,\n normalizeCustodyPath,\n normalizeCustodyPrefix,\n type CustodyEntry,\n type CustodyPutResult,\n type CustodyStore,\n} from './store.js';\n\n/** Where the control box keeps custody — sibling of `store.db` / `auth.db`. */\nexport const DEFAULT_CUSTODY_DIR = join(STATE_DIR, 'hub', 'custody');\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\nexport interface FsCustodyStoreOptions {\n /** Custody root. Defaults to {@link DEFAULT_CUSTODY_DIR}. */\n root?: string;\n}\n\nexport class FsCustodyStore implements CustodyStore {\n readonly root: string;\n\n constructor(opts: FsCustodyStoreOptions = {}) {\n this.root = opts.root ?? DEFAULT_CUSTODY_DIR;\n }\n\n async put(path: string, data: Buffer): Promise<CustodyPutResult> {\n const rel = normalizeCustodyPath(path);\n const abs = join(this.root, rel);\n const sha256 = custodyDigest(data);\n\n const existing = await this.readEntry(rel);\n if (existing && existing.entry.sha256 === sha256) {\n // Content-addressed skip: identical bytes are already stored, so the file\n // (and its mtime) is left untouched — an unchanged re-push is a no-op.\n return { ...existing.entry, changed: false };\n }\n\n await mkdir(dirname(abs), { recursive: true, mode: DIR_MODE });\n // Atomic: a reader (or a crash) never observes a half-written credential.\n const tmp = `${abs}.${randomBytes(6).toString('hex')}.tmp`;\n try {\n await writeFile(tmp, data, { mode: FILE_MODE });\n await chmod(tmp, FILE_MODE);\n await rename(tmp, abs);\n } catch (err) {\n await rm(tmp, { force: true });\n throw err;\n }\n const st = await stat(abs);\n return {\n path: rel,\n size: data.length,\n sha256,\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n changed: true,\n };\n }\n\n async get(path: string): Promise<{ entry: CustodyEntry; data: Buffer } | null> {\n return this.readEntry(normalizeCustodyPath(path));\n }\n\n async stat(path: string): Promise<CustodyEntry | null> {\n const found = await this.readEntry(normalizeCustodyPath(path));\n return found ? found.entry : null;\n }\n\n async list(prefix?: string): Promise<CustodyEntry[]> {\n const rel = prefix === undefined ? '' : normalizeCustodyPrefix(prefix);\n const entries: CustodyEntry[] = [];\n for (const found of await this.walk(this.root)) {\n // Prefix match on path segments — `agents/cl` must not match `agents/claude`.\n if (rel.length > 0 && found !== rel && !found.startsWith(`${rel}/`)) continue;\n const e = await this.readEntry(found);\n if (e) entries.push(e.entry);\n }\n entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n return entries;\n }\n\n async delete(path: string): Promise<boolean> {\n const rel = normalizeCustodyPath(path);\n const abs = join(this.root, rel);\n try {\n await rm(abs);\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false;\n throw err;\n }\n }\n\n async putStream(\n path: string,\n body: Readable,\n opts: { maxBytes?: number } = {},\n ): Promise<CustodyPutResult> {\n const rel = normalizeCustodyPath(path);\n const abs = join(this.root, rel);\n await mkdir(dirname(abs), { recursive: true, mode: DIR_MODE });\n const tmp = `${abs}.${randomBytes(6).toString('hex')}.tmp`;\n\n const hash = createHash('sha256');\n let size = 0;\n // Cap while streaming, not after: the point of this path is never to hold\n // the whole payload, so an over-cap body must be cut off mid-flight rather\n // than measured once it has already landed.\n const meter = new Transform({\n transform(chunk: Buffer, _enc, cb) {\n size += chunk.length;\n if (opts.maxBytes !== undefined && size > opts.maxBytes) {\n cb(new CustodyTooLargeError(opts.maxBytes));\n return;\n }\n hash.update(chunk);\n cb(null, chunk);\n },\n });\n\n try {\n await pipeline(body, meter, createWriteStream(tmp, { mode: FILE_MODE }));\n } catch (err) {\n await rm(tmp, { force: true });\n throw err;\n }\n\n const sha256 = hash.digest('hex');\n const existing = await this.readEntryMeta(rel);\n if (existing && existing.sha256 === sha256) {\n // Same content-addressed skip `put` makes. The bytes still crossed the\n // wire (a stream can't be hashed before it arrives), but the stored file\n // and its mtime are left alone — the client's manifest pre-check is what\n // avoids the transfer itself.\n await rm(tmp, { force: true });\n return { ...existing, changed: false };\n }\n\n try {\n await chmod(tmp, FILE_MODE);\n await rename(tmp, abs);\n } catch (err) {\n await rm(tmp, { force: true });\n throw err;\n }\n const st = await stat(abs);\n return {\n path: rel,\n size,\n sha256,\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n changed: true,\n };\n }\n\n async getStream(path: string): Promise<{ entry: CustodyEntry; data: Readable } | null> {\n const rel = normalizeCustodyPath(path);\n const entry = await this.readEntryMeta(rel);\n if (!entry) return null;\n return { entry, data: createReadStream(join(this.root, rel)) };\n }\n\n /**\n * Metadata without holding the value. Digest still comes from the bytes (no\n * sidecar to drift), but they are hashed in a streaming pass and discarded,\n * so a 100 MiB entry costs a buffer's worth of memory rather than 100 MiB.\n */\n private async readEntryMeta(rel: string): Promise<CustodyEntry | null> {\n const abs = join(this.root, rel);\n try {\n const st = await stat(abs);\n if (!st.isFile()) return null;\n const hash = createHash('sha256');\n await pipeline(\n createReadStream(abs),\n new Transform({\n transform(chunk: Buffer, _enc, cb) {\n hash.update(chunk);\n cb();\n },\n }),\n );\n return {\n path: rel,\n size: st.size,\n sha256: hash.digest('hex'),\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n };\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;\n throw err;\n }\n }\n\n private async readEntry(rel: string): Promise<{ entry: CustodyEntry; data: Buffer } | null> {\n const abs = join(this.root, rel);\n try {\n const [data, st] = await Promise.all([readFile(abs), stat(abs)]);\n return {\n entry: {\n path: rel,\n size: data.length,\n sha256: custodyDigest(data),\n mode: st.mode & 0o777,\n updatedAt: st.mtime.toISOString(),\n },\n data,\n };\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'EISDIR') return null;\n throw err;\n }\n }\n\n /** Custody-relative paths of every regular file under `dir` (tmp files skipped). */\n private async walk(dir: string): Promise<string[]> {\n let dirents;\n try {\n dirents = await readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw err;\n }\n const out: string[] = [];\n for (const d of dirents) {\n const abs = join(dir, d.name);\n if (d.isDirectory()) {\n out.push(...(await this.walk(abs)));\n } else if (d.isFile() && !d.name.endsWith('.tmp')) {\n out.push(relative(this.root, abs).split(sep).join('/'));\n }\n }\n return out;\n }\n}\n","import { spawn } from 'node:child_process';\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport {\n boxCarriedHostPaths,\n boxWorkspacePath,\n executeCloudAction,\n refreshCloudPreviewUrl,\n resolveHostPath,\n} from './host-actions.js';\nimport { canAutoApproveTransfer } from './safe-transfer.js';\nimport { HostActionQueue } from './host-action-queue.js';\nimport { HubNotifier } from './hub-notifier.js';\nimport { BoxNotices } from './notices.js';\nimport { hostOpenCommand } from '@agentbox/sandbox-core';\nimport {\n isSanctionedPushBranch,\n isScratchBranch,\n landRefspec,\n parseDownloadKind,\n resolveLandDest,\n resolveRemote,\n sanitizeGitArgs,\n upstreamRef,\n} from '@agentbox/core';\nimport { getConnector } from '@agentbox/integrations';\nimport {\n assertGhReady,\n checkoutGuards,\n GH_API_ENDPOINT_REFUSAL,\n GH_PR_READ_ONLY_OPS,\n GH_PR_SAFE_AUTO_APPROVE_OPS,\n GH_RUN_READ_ONLY_OPS,\n injectPrCreateHead,\n isAllowedGhApiEndpoint,\n refuseGhApiCall,\n isGhPrOp,\n isGhRunOp,\n PR_CREATE_NO_HEAD_REFUSAL,\n prCreateHasExplicitHead,\n prCreateNeedsHead,\n ghRunContext,\n refuseCheckoutByDefault,\n refuseMergeBypass,\n runHostGh,\n type GhApiRpcParams,\n type GhPrOp,\n type GhPrRpcParams,\n type GhRunOp,\n type GhRunRpcParams,\n} from './gh.js';\nimport { hashRpcParams, HostInitiatedTokens } from './host-initiated.js';\nimport {\n assertIntegrationReady,\n makeIntegrationOpRefusal,\n parseIntegrationMethod,\n refuseIfIntegrationDisabled,\n refuseIntegrationCall,\n runHostIntegration,\n type IntegrationRpcParams,\n} from './integrations.js';\nimport { GitHubAppLeaser, loadGitHubAppConfig, type GitHubAppConfig } from './github-app.js';\nimport { leaseTokenResult } from './lease.js';\nimport { gateApproval, type GateDeps, type PromptMode } from './permission.js';\nimport { resolveWorktree, hostRepoUnavailableReason } from './worktree.js';\nimport { adminGateAllows } from './admin-gate.js';\nimport {\n handleCustodyBlobRequest,\n handleCustodyRequest,\n isCustodyBlobPath,\n} from './custody/routes.js';\nimport { handleRemoteBoxesRequest, isRemoteBoxesPath } from './remote-boxes.js';\nimport { readCreateJobLog } from './job-log-tail.js';\nimport { handleStoreRpcRequest, isStoreRpcPath } from './store/store-rpc-routes.js';\nimport type { CustodyStore } from './custody/store.js';\nimport { askPrompt, isPromptAnswerBody, PendingPrompts, PromptSubscribers } from './prompts.js';\nimport { BoxRegistry, EventBuffer } from './registry.js';\nimport { CREDENTIALS_UPDATED_EVENT, CredentialsFanout } from './credentials-fanout.js';\nimport { BoxStatusStore, isValidBoxStatus } from './status-store.js';\nimport { MemoryStore } from './store/memory-store.js';\nimport { WriteThroughStore } from './store/write-through-store.js';\nimport type { Store } from './store/store.js';\nimport { DEFAULT_BOX_RELAY_PORT } from './types.js';\nimport { buildCpArgv, cpFlags, normalizeCpParams } from './cp-rpc.js';\nimport type {\n BoxRegistration,\n BoxWorktree,\n BridgeActionResultBody,\n BridgePollResponse,\n BrowserOpenRpcParams,\n CheckpointRpcParams,\n ClearNoticeBody,\n CpRpcParams,\n DownloadKind,\n DownloadRpcParams,\n GitRpcParams,\n GitRpcResult,\n HostAction,\n PostEventBody,\n PostRpcBody,\n PromptAnswerBody,\n RegisterBoxBody,\n RelayEvent,\n SetNoticeBody,\n} from './types.js';\n\nexport type RelayMode = 'host' | 'box';\n\nexport interface RelayServerOptions {\n port: number;\n /** Bind address; defaults to '0.0.0.0' so containers can reach the relay across the local docker network OR the Daytona preview proxy can hit the in-sandbox box-mode relay. */\n host?: string;\n logger?: (line: string) => void;\n /**\n * 'host' (default): host relay process; executes host-only RPCs locally\n * via `spawn` and serves `/admin/*` to the CLI / wrapper.\n * 'box': in-sandbox relay; host-only RPCs enqueue on a `HostActionQueue`\n * for the host poller to drain via `/bridge/*`.\n */\n mode?: RelayMode;\n /**\n * Required when `mode === 'box'`: bearer for the box-only `/bridge/*`\n * routes. Distinct from per-box `BoxRegistration.token` so a compromised\n * in-box agent cannot impersonate the host poller.\n */\n bridgeToken?: string;\n /**\n * Persisted-state backend. Defaults to an in-memory store wrapping the\n * relay's historical in-memory structures (the laptop relay + tests). A\n * hosted control plane injects a Postgres-backed store; a federated laptop\n * relay injects a RemoteStore. See `./store/store.ts`.\n */\n store?: Store;\n /**\n * How host-action approvals are obtained. Defaults to 'block' (the\n * long-lived laptop relay blocks on a human). The stateless hosted plane\n * uses 'poll' via its own handler, not this server. See `./permission.ts`.\n */\n promptMode?: PromptMode;\n /**\n * GitHub App config for `git.lease-token` (the hosted plane mints repo-scoped\n * installation tokens and leases them to boxes). Defaults to\n * {@link loadGitHubAppConfig} (`GITHUB_APP_ID` + `GITHUB_APP_PRIVATE_KEY`).\n * Null/absent → `git.lease-token` returns a clear \"not configured\" error.\n */\n githubApp?: GitHubAppConfig | null;\n /**\n * Custody store (agent creds / project secrets / box SSH keys). Absent → the\n * `/admin/custody/*` routes are not served here. The control box (hetzner\n * profile) wires an {@link FsCustodyStore}. See `./custody/routes.ts`.\n */\n custody?: CustodyStore | null;\n /**\n * Per-request body cap for custody PUTs (`relay.custodyMaxBodyBytes`).\n * Defaults to 32 MiB — big enough for a project's untracked-files seed tar,\n * and scoped to custody so the 1 MiB control-plane cap still governs every\n * other route.\n */\n custodyMaxBodyBytes?: number;\n /**\n * Cap for the streaming blob surface (`relay.custodyMaxBlobBytes`). Defaults\n * to 100 MiB to match `box.cpMaxBytes`, so a `carry:` entry the CLI accepted\n * at resolve time can actually be stored — the two caps disagreeing is what\n * let an approved 25.7 MiB file be promised to the user and then dropped.\n * Enforced mid-stream, so an over-cap body is cut off rather than landed.\n */\n custodyMaxBlobBytes?: number;\n /**\n * Admin bearer that gates `/admin/custody/*` (the ONLY proof accepted — the\n * loopback bypass that covers the other `/admin/*` routes does not apply to\n * custody, since a control box behind Caddy makes every request look\n * loopback). Required for custody to serve; other admin routes are unaffected.\n */\n adminToken?: string;\n /**\n * Optional delegate for requests that matched no relay route (e.g. Next's\n * `getRequestHandler()`). Invoked at the top-level 404 fallthrough, so every\n * relay route still matches first and the UI can never shadow `/admin`,\n * `/rpc`, etc. Lets the hub serve Next on the relay's own port.\n */\n uiHandler?: (req: IncomingMessage, res: ServerResponse) => void;\n}\n\nexport interface RelayServerHandle {\n server: Server;\n /** The persisted-state backend the handlers use (memory by default). */\n store: Store;\n registry: BoxRegistry;\n events: EventBuffer;\n statusStore: BoxStatusStore;\n prompts: PendingPrompts;\n subscribers: PromptSubscribers;\n notices: BoxNotices;\n /** Fan-out for the embedded hub UI's SSE route (pending-approval changes). */\n hubNotifier: HubNotifier;\n /** The custody store, when wired (control box). Used by the hub backend's reap. */\n custody?: CustodyStore | null;\n /** Present only in `mode === 'box'`: the parking lot for host-only RPCs. */\n hostActions?: HostActionQueue;\n url: string;\n /**\n * Wire a \"kick the queue scheduler now\" callback. Called by\n * `POST /admin/queue/enqueue` so a freshly-submitted background job doesn't\n * wait up to one tick for the relay to notice the new manifest.\n * No-op until set; the queue still picks the job up via the periodic tick.\n */\n setQueuePoke: (fn: () => void) => void;\n /**\n * Kick the queue scheduler in-process (same effect as `POST\n * /admin/queue/enqueue`, without a loopback round-trip). Used by the embedded\n * hub after it enqueues a create job via `enqueueQueueJob`. No-op until\n * `setQueuePoke` has wired the scheduler.\n */\n pokeQueue: () => void;\n close: () => Promise<void>;\n}\n\n/** Event type whose payload is a durable BoxStatus snapshot (persisted, not ringed). */\nconst BOX_STATUS_EVENT = 'box-status';\n\nconst MAX_BODY_BYTES = 1024 * 1024; // 1 MiB hard cap; relay is for control-plane traffic, not payloads.\n/**\n * Per-request cap for custody PUTs only. Custody carries project seed material\n * (an untracked-files tarball) as base64 JSON, which the 1 MiB control-plane cap\n * is far too small for — but raising {@link MAX_BODY_BYTES} would hand the same\n * budget to `/rpc` and `/events`, which have no business with payloads. Override\n * with `relay.custodyMaxBodyBytes`.\n */\nconst DEFAULT_CUSTODY_MAX_BODY_BYTES = 32 * 1024 * 1024; // 32 MiB\n/** Matches `box.cpMaxBytes` — see the `custodyMaxBlobBytes` option doc. */\nconst DEFAULT_CUSTODY_MAX_BLOB_BYTES = 100 * 1024 * 1024; // 100 MiB\nconst GIT_RPC_TIMEOUT_MS = 120_000; // git push/pull can be slow on big repos.\nconst CHECKPOINT_RPC_TIMEOUT_MS = 600_000; // capturing node_modules/build trees can be slow.\nconst DOWNLOAD_RPC_TIMEOUT_MS = 600_000; // claude/workspace pulls over rsync can take minutes.\nconst CP_RPC_TIMEOUT_MS = 300_000; // single-file/dir cp; tar pipe through docker exec.\nconst BROWSER_OPEN_RPC_TIMEOUT_MS = 15_000; // `open` hands off to the browser and returns at once.\nconst BROWSER_OPEN_PROMPT_TTL_MS = 25_000; // the \"open on host too?\" offer auto-dismisses if ignored.\nconst SSE_HEARTBEAT_MS = 15_000; // every 15s; wrapper reconnects if it sees no traffic for ~30s.\n\nfunction send(\n res: ServerResponse,\n status: number,\n body: unknown,\n contentType: string = 'application/json',\n): void {\n const text = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);\n res.statusCode = status;\n if (text.length > 0) {\n res.setHeader('Content-Type', contentType);\n res.setHeader('Content-Length', Buffer.byteLength(text).toString());\n res.end(text);\n } else {\n res.end();\n }\n}\n\nasync function readJsonBody<T>(req: IncomingMessage): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let total = 0;\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > MAX_BODY_BYTES) {\n reject(new Error('request body too large'));\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => {\n const text = Buffer.concat(chunks).toString('utf8');\n if (text.length === 0) {\n resolve({} as T);\n return;\n }\n try {\n resolve(JSON.parse(text) as T);\n } catch (err) {\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n });\n req.on('error', reject);\n });\n}\n\nasync function readRawBody(\n req: IncomingMessage,\n maxBytes: number = MAX_BODY_BYTES,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let total = 0;\n const chunks: Buffer[] = [];\n req.on('data', (chunk: Buffer) => {\n total += chunk.length;\n if (total > maxBytes) {\n reject(new Error('request body too large'));\n req.destroy();\n return;\n }\n chunks.push(chunk);\n });\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));\n req.on('error', reject);\n });\n}\n\nfunction bearerToken(req: IncomingMessage): string {\n const raw = req.headers.authorization;\n if (typeof raw !== 'string') return '';\n const m = /^Bearer\\s+(.+)$/i.exec(raw.trim());\n return m ? m[1]!.trim() : '';\n}\n\nfunction isLoopbackAddress(addr: string | undefined): boolean {\n if (!addr) return false;\n return (\n addr === '127.0.0.1' || addr === '::1' || addr === '::ffff:127.0.0.1' || addr.startsWith('127.')\n );\n}\n\n/**\n * Build the relay HTTP server. Routes:\n * POST /events — bearer auth (box token), appends to ring buffer.\n * POST /rpc — bearer auth; dispatches git.push/fetch, cp.*, download.*, checkpoint.create on the host.\n * POST /admin/register-box — loopback only.\n * POST /admin/forget-box — loopback only.\n * GET /admin/box-status — loopback only; query `box`; latest snapshot.\n * GET /admin/events — loopback only; query `box`, `since`.\n * GET /admin/registry — loopback only; list registered boxes (token redacted).\n * GET /admin/prompts — loopback only; query `boxId`; one-shot list of pending host-action approvals.\n * GET /admin/prompts/stream — loopback only; SSE; pushes prompt-ask/prompt-resolved/notice-set/notice-clear/ping events.\n * POST /admin/prompts/answer — loopback only; resolves a pending prompt by id.\n * POST /admin/host-initiated/mint — loopback only; mints a one-time token scoped to (boxId, method).\n * POST /admin/notices/set — loopback only; sets an informational box notice (returns {id}).\n * POST /admin/notices/clear — loopback only; clears a box notice by id.\n * GET /healthz — liveness + capability probe (no auth); reports {pid, cliEntry}.\n */\nexport function createRelayServer(opts: RelayServerOptions): RelayServerHandle {\n const log = opts.logger ?? (() => {});\n const registry = new BoxRegistry();\n const events = new EventBuffer();\n const statusStore = new BoxStatusStore();\n const prompts = new PendingPrompts();\n const subscribers = new PromptSubscribers();\n const notices = new BoxNotices(subscribers);\n // Fan-out for the embedded hub UI: every change to the pending-approval set\n // pushes a refresh to browsers subscribed on the hub's SSE route. No-op when\n // no hub is attached (the CLI relay bin never subscribes).\n const hubNotifier = new HubNotifier();\n prompts.setOnChange(() => hubNotifier.notify());\n // The persisted-state seam. Defaults to a MemoryStore wrapping the concrete\n // instances above, so the laptop relay + tests behave exactly as before; a\n // hosted control plane injects a Postgres-backed store instead. Handlers go\n // through `store.*`; the concrete instances stay exposed on the handle for\n // the autopause / queue loops (bin.ts) and the unit tests that read them.\n // Persisted-state seam. localhost/tests get a MemoryStore wrapping the concrete\n // instances above (byte-identical to the pre-seam relay). A control box injects\n // a durable store (SQLite/Postgres); wrap it so every write also mirrors into\n // those instances — the daemon's loops + the hub backend read them synchronously\n // and would otherwise see an empty registry/statusStore (Backlog: phase-3\n // blocker A). `startRelayServer` hydrates the mirror from the store on boot.\n const store: Store = opts.store\n ? new WriteThroughStore(opts.store, { registry, events, statusStore })\n : new MemoryStore({ registry, events, statusStore });\n // Per-box `box.autoApproveHostActions`: when a box registered with the flag,\n // host-action confirms resolve to 'y' without a prompt, but every bypass\n // lands in the event ring buffer (visible via `/admin/events`) so it's\n // auditable. Reads the concrete registry/events synchronously (not the async\n // store): `askPrompt` broadcasts to SSE subscribers synchronously, so this\n // gate must stay sync. The MemoryStore wraps these same instances, so the\n // sync policy view and the async store view never diverge on the laptop relay.\n prompts.setAutoApprovePolicy({\n shouldAutoApprove: (boxId) => registry.get(boxId)?.autoApproveHostActions === true,\n audit: (boxId, params, reason) => {\n events.append({\n boxId,\n type: 'host-action-auto-approved',\n payload: {\n command: params.context?.command,\n argv: params.context?.argv,\n message: params.message,\n ...(reason ? { reason } : {}),\n },\n });\n log(\n `auto-approved host action for ${boxId}: ${params.context?.command ?? params.message}` +\n (reason ? ` (${reason})` : ''),\n );\n },\n });\n const hostInitiatedTokens = new HostInitiatedTokens();\n let queuePoke: (() => void) | null = null;\n const host = opts.host ?? '0.0.0.0';\n const mode: RelayMode = opts.mode ?? 'host';\n // Box mode parks host-only RPCs until the host poller answers; host mode\n // executes them inline (the historical behavior).\n const hostActions = mode === 'box' ? new HostActionQueue() : null;\n // Host-mode handler for refreshed agent credentials (newest-wins backup\n // write + debounced `agentbox credentials propagate` spawn). In box mode the\n // event rides the local ring buffer to the bridge instead — the host's\n // poller hands it to this handler on the other side.\n // `custody` is the control box's store — passing it is what lets an accepted\n // token reach custody, so the next hub create seeds a current credential\n // instead of the last one a PC pushed. Absent on a localhost relay (no store).\n const credentialsFanout =\n mode === 'box' ? null : new CredentialsFanout({ log, custody: opts.custody ?? null });\n if (mode === 'box' && (!opts.bridgeToken || opts.bridgeToken.length === 0)) {\n throw new Error(\"relay mode='box' requires a non-empty bridgeToken\");\n }\n const bridgeToken = opts.bridgeToken ?? '';\n // The laptop relay blocks on a human for approvals (today's behavior). The\n // stateless hosted plane uses 'poll' via its own handler, not this server.\n const promptMode: PromptMode = opts.promptMode ?? 'block';\n const gateDeps: GateDeps = { mode: promptMode, store, prompts, subscribers };\n // GitHub App leaser for `git.lease-token` (hosted plane). Off when no App is\n // configured — the laptop relay never needs it (it pushes host-side / cloud\n // boxes reach it via the poller).\n const githubAppConfig = opts.githubApp === undefined ? loadGitHubAppConfig() : opts.githubApp;\n const leaser = githubAppConfig ? new GitHubAppLeaser(githubAppConfig) : null;\n const custody = opts.custody ?? null;\n const custodyAdminToken = opts.adminToken ?? '';\n const custodyMaxBodyBytes =\n typeof opts.custodyMaxBodyBytes === 'number' && opts.custodyMaxBodyBytes > 0\n ? opts.custodyMaxBodyBytes\n : DEFAULT_CUSTODY_MAX_BODY_BYTES;\n const custodyMaxBlobBytes =\n typeof opts.custodyMaxBlobBytes === 'number' && opts.custodyMaxBlobBytes > 0\n ? opts.custodyMaxBlobBytes\n : DEFAULT_CUSTODY_MAX_BLOB_BYTES;\n const uiHandler = opts.uiHandler;\n\n // Host-mode pollers for cloud-tagged boxes; started on /admin/register-box,\n // stopped on /admin/forget-box. Lazy import to keep host-mode startup free\n // of cloud-poller deps until actually needed.\n type CloudPollersModule = typeof import('./cloud-poller.js');\n let pollers: InstanceType<CloudPollersModule['CloudBoxPollers']> | null = null;\n async function getPollers(): Promise<InstanceType<CloudPollersModule['CloudBoxPollers']>> {\n if (!pollers) {\n const mod: CloudPollersModule = await import('./cloud-poller.js');\n pollers = new mod.CloudBoxPollers();\n }\n return pollers;\n }\n\n const server = createServer((req, res) => {\n handle(req, res).catch((err: unknown) => {\n const msg = err instanceof Error ? err.message : String(err);\n log(`relay: handler error: ${msg}`);\n if (!res.headersSent) send(res, 500, { error: 'internal error' });\n else res.end();\n });\n });\n\n async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'relay'}`);\n const route = `${req.method ?? 'GET'} ${url.pathname}`;\n\n if (route === 'GET /healthz') {\n // `cliEntry` and `pid` let the host-side `ensureRelay` distinguish a\n // *capable* relay from one that's merely alive: a relay spawned without\n // AGENTBOX_CLI_ENTRY silently fails every cp/download/checkpoint host\n // action (exit 64) for its whole lifetime. Reporting it here lets the\n // caller reclaim (kill by `pid`) and respawn instead of reusing it.\n send(res, 200, {\n ok: true,\n boxes: await store.countBoxes(),\n events: await store.countEvents(),\n pid: process.pid,\n // True when a Next UI is delegated here (the embedded hub) vs a bare relay.\n // Lets `agentbox hub` distinguish \"a hub already runs\" from \"a lean relay\n // holds the port\" (reclaim + respawn as the hub).\n ui: Boolean(uiHandler),\n cliEntry: Boolean(process.env.AGENTBOX_CLI_ENTRY),\n // The spawning CLI's version/commit (inherited via env at spawn time).\n // `version` lets host-side ensureRelay reclaim a relay left over from a\n // different agentbox version; `commit` is observability-only.\n version: process.env.AGENTBOX_CLI_VERSION || undefined,\n commit: process.env.AGENTBOX_CLI_COMMIT || undefined,\n // The running hub's profile + whether the resident create worker is on.\n // `agentbox hub expose` flips a localhost hub to the `hetzner` profile;\n // reporting it here lets host-side `ensureHub` reclaim a hub running in\n // the wrong mode (a plain localhost hub while deploy.json says exposed),\n // and `hub status` show what is actually running.\n profile: process.env.AGENTBOX_HUB_PROFILE || undefined,\n worker: process.env.AGENTBOX_HUB_WORKER === 'on' ? true : undefined,\n });\n return;\n }\n\n // Bridge routes are the host poller's view into an in-sandbox box-mode\n // relay. They are bearer-authed with the per-relay bridgeToken and\n // exist only when mode === 'box'. No loopback check: the Daytona\n // preview proxy reaches them from non-loopback IPs.\n if (url.pathname.startsWith('/bridge/')) {\n if (mode !== 'box' || !hostActions) {\n send(res, 404, { error: 'bridge routes available only in mode=box' });\n return;\n }\n if (bearerToken(req) !== bridgeToken) {\n send(res, 401, { error: 'invalid bridge token' });\n return;\n }\n if (route === 'GET /bridge/healthz') {\n send(res, 200, { ok: true, queued: hostActions.size(), events: events.size() });\n return;\n }\n if (route === 'GET /bridge/poll') {\n const since = Number.parseInt(url.searchParams.get('since') ?? '0', 10) || 0;\n const newEvents = await store.listEvents(since);\n const lastId = newEvents.length > 0 ? newEvents[newEvents.length - 1]!.id : since;\n const actions = hostActions.drain();\n // A box-mode relay only ever has one registered box (itself). The\n // status snapshot — if any has been pushed — belongs to that box.\n const only = (await store.listBoxes())[0];\n const status = only ? ((await store.getStatus(only.boxId)) ?? null) : null;\n const reply: BridgePollResponse = {\n actions,\n events: newEvents,\n status,\n cursor: lastId,\n };\n send(res, 200, reply);\n return;\n }\n if (route === 'POST /bridge/action-result') {\n const body = await readJsonBody<BridgeActionResultBody>(req);\n if (\n !body ||\n typeof body.id !== 'string' ||\n body.id.length === 0 ||\n typeof body.exitCode !== 'number'\n ) {\n send(res, 400, { error: 'expected {id, exitCode, stdout, stderr}' });\n return;\n }\n const ok = hostActions.resolve(body.id, {\n exitCode: body.exitCode,\n stdout: typeof body.stdout === 'string' ? body.stdout : '',\n stderr: typeof body.stderr === 'string' ? body.stderr : '',\n });\n if (!ok) {\n send(res, 404, { error: 'no parked action with that id' });\n return;\n }\n send(res, 204, null);\n return;\n }\n send(res, 404, { error: 'not found', route });\n return;\n }\n\n // The blob surface must be dispatched BEFORE the JSON one, because it is the\n // only path that does not buffer the body — handing a 100 MiB carry payload\n // to `readRawBody` below is exactly what this route exists to avoid. The\n // request object IS the stream; nothing has consumed it yet.\n if (isCustodyBlobPath(url.pathname)) {\n const blobRes = await handleCustodyBlobRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n bearer: bearerToken(req),\n body: req.method === 'PUT' ? req : undefined,\n maxBytes: custodyMaxBlobBytes,\n },\n { custody, adminToken: custodyAdminToken, log },\n );\n if (blobRes) {\n if (blobRes.stream) {\n res.writeHead(blobRes.status, {\n 'content-type': 'application/octet-stream',\n ...(blobRes.entry ? { 'content-length': String(blobRes.entry.size) } : {}),\n ...(blobRes.entry ? { 'x-agentbox-sha256': blobRes.entry.sha256 } : {}),\n });\n blobRes.stream.pipe(res);\n blobRes.stream.on('error', () => res.destroy());\n } else {\n send(res, blobRes.status, blobRes.body ?? null);\n }\n return;\n }\n }\n\n // Custody (`/admin/custody/*`) is admin-bearer-gated, NOT loopback-gated:\n // on the control box the hub sits behind Caddy on the same host, so every\n // proxied request looks loopback. The shared dispatcher enforces the bearer\n // (and fail-closes with 503 when custody or the admin token is unset), so\n // this must run BEFORE the loopback rejection below.\n if (url.pathname === '/admin/custody' || url.pathname.startsWith('/admin/custody/')) {\n const bodyText =\n req.method === 'PUT' || req.method === 'POST'\n ? await readRawBody(req, custodyMaxBodyBytes)\n : '';\n const custodyRes = await handleCustodyRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n query: url.searchParams,\n bearer: bearerToken(req),\n bodyText,\n },\n { custody, adminToken: custodyAdminToken, log },\n );\n if (custodyRes) {\n send(res, custodyRes.status, custodyRes.body ?? null);\n return;\n }\n }\n\n // Create-queue surface (`/remote/boxes`) — admin-bearer-gated like custody\n // (not loopback: the control box is behind Caddy). The shared dispatcher is\n // the SAME one the Vercel plane's `core/handler.ts` mounts, so the PC can\n // `agentbox create --via-hub` against the control box exactly as against the\n // hosted plane. Runs before the loopback rejection below.\n if (isRemoteBoxesPath(url.pathname)) {\n const bodyText = req.method === 'POST' ? await readRawBody(req) : '';\n const remoteRes = await handleRemoteBoxesRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n bearer: bearerToken(req),\n bodyText,\n query: url.searchParams,\n },\n { store, adminToken: custodyAdminToken, custody, readJobLog: readCreateJobLog, log },\n );\n if (remoteRes) {\n send(res, remoteRes.status, remoteRes.body ?? null);\n return;\n }\n }\n\n // Generic Store RPC (`/admin/store`) — admin-bearer-gated shared dispatcher,\n // the same one `core/handler.ts` mounts, so a PC's RemoteStore reads the\n // control box's registry/status/events over HTTP. Carries its own bearer\n // gate (not loopback: the control box is behind Caddy), so it runs before the\n // loopback rejection below. A laptop relay has no admin token → 503.\n if (isStoreRpcPath(url.pathname)) {\n const bodyText = req.method === 'POST' ? await readRawBody(req) : '';\n const storeRpcRes = await handleStoreRpcRequest(\n {\n method: req.method ?? 'GET',\n path: url.pathname,\n bearer: bearerToken(req),\n bodyText,\n },\n { store, adminToken: custodyAdminToken, log },\n );\n if (storeRpcRes) {\n send(res, storeRpcRes.status, storeRpcRes.body ?? null);\n return;\n }\n }\n\n // Admin endpoints are reachable from loopback, or — on a relay with an\n // admin token configured (the control box) — with that bearer. The relay\n // binds to 0.0.0.0 so containers can reach /events and /rpc via\n // host.docker.internal, but admin operations (register-box, forget-box,\n // list events, etc.) are for the host CLI / an authenticated admin and must\n // not be exposed to boxes. A laptop relay sets no admin token, so its gate\n // stays loopback-only. Any other `/remote/*` is a hosted-plane surface not\n // served by this relay.\n if (url.pathname.startsWith('/admin/') || url.pathname.startsWith('/remote/')) {\n if (url.pathname.startsWith('/remote/')) {\n send(res, 404, { error: 'not found', route });\n return;\n }\n const loopback = isLoopbackAddress(req.socket.remoteAddress);\n if (!adminGateAllows(loopback, bearerToken(req), custodyAdminToken)) {\n send(res, 403, { error: 'admin endpoints are loopback-only' });\n return;\n }\n }\n\n if (route === 'POST /events') {\n const reg = await authBox(req, res);\n if (!reg) return;\n const body = await readJsonBody<PostEventBody>(req);\n if (!body || typeof body.type !== 'string' || body.type.length === 0) {\n send(res, 400, { error: 'missing \"type\" string' });\n return;\n }\n // box-status is durable state, not an event: persist the latest snapshot\n // per box and skip the ring buffer (a 15s heartbeat per box would\n // otherwise evict the useful git/service events from the 1000-cap ring).\n if (body.type === BOX_STATUS_EVENT) {\n if (!isValidBoxStatus(body.payload)) {\n send(res, 400, { error: 'invalid box-status payload' });\n return;\n }\n await store.setStatus(reg.boxId, reg.name, reg.projectIndex, body.payload);\n // Push it to attached wrappers. The durable file only serves a footer on\n // THIS machine; a box owned by a remote hub has no such file on the\n // user's laptop, so the stream is the only way its footer learns the\n // agent activity and the `starting N/M…` service count.\n subscribers.broadcast(reg.boxId, BOX_STATUS_EVENT, body.payload);\n log(`box-status box=${reg.boxId}`);\n send(res, 202, { ok: true });\n return;\n }\n // Refreshed agent credentials: handled out-of-band in host mode — the\n // payload is a secret and must never land in the event ring buffer. In\n // box mode it falls through to the ring so the bridge drains it to the\n // host poller (which routes it to the host relay's handler).\n if (body.type === CREDENTIALS_UPDATED_EVENT && credentialsFanout) {\n const verdict = await credentialsFanout.handle(reg.boxId, body.payload);\n log(\n `credentials-updated box=${reg.boxId} accepted=${String(verdict.accepted)} (${verdict.reason})`,\n );\n send(res, 202, { ok: true, accepted: verdict.accepted });\n return;\n }\n const ev = await store.appendEvent({\n boxId: reg.boxId,\n type: body.type,\n ts: typeof body.ts === 'string' ? body.ts : undefined,\n payload: body.payload,\n });\n log(`event ${String(ev.id)} box=${reg.boxId} type=${body.type}`);\n send(res, 202, { id: ev.id });\n return;\n }\n\n if (route === 'POST /rpc') {\n const reg = await authBox(req, res);\n if (!reg) return;\n const body = await readJsonBody<PostRpcBody>(req);\n if (!body || typeof body.method !== 'string' || body.method.length === 0) {\n send(res, 400, { error: 'missing \"method\" string' });\n return;\n }\n log(`rpc box=${reg.boxId} method=${body.method}`);\n // Box-mode: every host-only RPC (anything except the in-sandbox-local\n // `browser.open` notification) is parked on the HostActionQueue. The\n // host's CloudBoxPoller drains via `/bridge/poll`, executes on the\n // host (with the existing `askPrompt` gate for `git.push`), and POSTs\n // the result back to `/bridge/action-result`, which resolves the\n // awaited Promise here and unblocks the in-box `/rpc` caller.\n if (mode === 'box' && hostActions && body.method !== 'browser.open') {\n const queued = await hostActions.enqueue(reg.boxId, body.method, body.params);\n const status = queued.exitCode === 0 ? 200 : 500;\n send(res, status, queued);\n return;\n }\n if (body.method === 'git.push' || body.method === 'git.fetch') {\n // Cloud box reaching this host-mode relay directly over the forwarder\n // (rather than via the poller): run the cloud bundle pull-back executor,\n // which does its own gating and pushes via the host workspace.\n if (reg.kind === 'cloud') {\n const action: HostAction = {\n id: '',\n boxId: reg.boxId,\n method: body.method,\n params: body.params,\n createdAt: new Date().toISOString(),\n };\n const result = await executeCloudAction(action, {\n backendName: reg.backend ?? '',\n boxId: reg.boxId,\n boxName: reg.name,\n prompts,\n subscribers,\n hostInitiatedTokens,\n autoApproveSafeHostActions: reg.autoApproveSafeHostActions,\n originUrl: reg.originUrl,\n log,\n });\n send(res, result.exitCode === 0 ? 200 : 500, result);\n return;\n }\n // Only `push` mutates the user's remote; fetch is read-only and noisy.\n // Per-box `agentbox/<name>` branches are the box's own scratch branch\n // — pushes to them are the whole point of agentbox, so they bypass\n // the y/N gate. Any other branch still prompts.\n if (body.method === 'git.push') {\n const hostOnlyParams = body.params as GitRpcParams | undefined;\n if (hostOnlyParams?.hostOnly) {\n // Landing the branch in the host's local repo publishes nothing,\n // so the push-confirm gate doesn't apply. Land and return.\n const saveResult = await handleGitSaveToHost(reg, hostOnlyParams);\n send(res, saveResult.exitCode === 0 ? 200 : 500, saveResult);\n return;\n }\n const params = body.params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, params?.path ?? '/workspace');\n // The docker relay always pushes the worktree's host-selected branch\n // (`sanctionedBranch`, falling back to the create-time `branch`) — the\n // in-box agent can't influence which branch is pushed. Key the gate on\n // THAT branch, not the immutable create-time `branch` (which is always\n // `agentbox/*`): after a host `agentbox git checkout main`, the push\n // target is `main`, so it must NOT be treated as a scratch bypass.\n // A scratch target bypasses unconditionally; a non-scratch sanctioned\n // target bypasses only as part of the safe subset (honors\n // `box.autoApproveSafeHostActions`) and leaves an audit trail.\n const dockerPushBranch = worktree?.sanctionedBranch ?? worktree?.branch;\n const isScratch = isScratchBranch(dockerPushBranch);\n const safeApproveOn = reg.autoApproveSafeHostActions !== false;\n // `isSanctionedPushBranch(dockerPushBranch, dockerPushBranch)` is true\n // only for a resolved branch — so a box with no registered worktree\n // (undefined branch) never bypasses and still prompts.\n const isSanctionedNonScratch =\n !isScratch &&\n safeApproveOn &&\n isSanctionedPushBranch(dockerPushBranch, dockerPushBranch);\n const bypassPushGate = isScratch || isSanctionedNonScratch;\n if (isSanctionedNonScratch) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `git push to sanctioned branch ${dockerPushBranch ?? ''} from box ${reg.name}`,\n context: { command: 'git push', cwd: params?.path, argv: params?.args },\n },\n 'safe: sanctioned-branch push',\n );\n }\n // Host-initiated pushes (driven by `agentbox git push <box>`) skip\n // the confirm prompt — but only if the host CLI minted a valid,\n // unexpired, scope-matched, params-hash-bound token via\n // /admin/host-initiated/mint. If a token is *present* but doesn't\n // validate (wrong scope, mutated params, expired, replayed), reject\n // hard: that's an attack signal (the only way to get a token is to\n // mint one host-side, and a legitimate host call always sends what\n // it minted for). Fall through to the prompt only when no token was\n // claimed — that's the normal agent-initiated path.\n const tokenClaimed = typeof params?.hostInitiated === 'string';\n const incomingHash = hashRpcParams(params);\n const hostInitiatedOk =\n !bypassPushGate &&\n tokenClaimed &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, 'git.push', incomingHash);\n if (!bypassPushGate && tokenClaimed && !hostInitiatedOk) {\n send(res, 500, {\n exitCode: 10,\n stdout: '',\n stderr:\n 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n });\n return;\n }\n if (!bypassPushGate && !hostInitiatedOk) {\n const gate = await gateApproval(gateDeps, reg.boxId, 'git.push', body.params, {\n kind: 'confirm',\n message: `Allow git push from box ${reg.name}?`,\n detail: `${resolveRemote(params?.remote)} ${(params?.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: {\n command: 'git push',\n cwd: params?.path,\n argv: params?.args,\n },\n });\n // Poll mode: parked — the box polls /rpc/status/<promptId> for the\n // verdict + result (the push runs there, on approval).\n if (gate.kind === 'pending') {\n send(res, 202, { status: 'pending', promptId: gate.promptId });\n return;\n }\n if (gate.kind === 'deny') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n }\n const result = await handleGitRpc(\n reg,\n body.method,\n body.params as GitRpcParams | undefined,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'git.lease-token') {\n // The hosted-plane equivalent of git.push: instead of the relay pushing,\n // it leases a repo-scoped GitHub-App token and the box pushes directly.\n // Because that token can push ANY branch (the relay doesn't pick the\n // branch here, unlike git.push), the sanctioned-branch auto-approve does\n // NOT apply — only the box's own scratch branch bypasses; others prompt.\n const params = body.params as GitRpcParams | undefined;\n const worktree = resolveWorktree(reg, params?.path ?? '/workspace');\n const isAgentboxBranch = isScratchBranch(worktree?.branch);\n if (!isAgentboxBranch) {\n const gate = await gateApproval(gateDeps, reg.boxId, 'git.lease-token', body.params, {\n kind: 'confirm',\n message: `Allow box ${reg.name} to lease a push token for ${reg.originUrl ?? 'its repo'}?`,\n detail: `branch ${worktree?.branch ?? '(unregistered)'}`,\n defaultAnswer: 'n',\n context: { command: 'git lease-token', cwd: params?.path },\n });\n if (gate.kind === 'pending') {\n send(res, 202, { status: 'pending', promptId: gate.promptId });\n return;\n }\n if (gate.kind === 'deny') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await leaseTokenResult(leaser, reg);\n send(res, result.exitCode === 0 ? 200 : 500, result);\n return;\n }\n if (body.method === 'cp.toHost' || body.method === 'cp.fromHost') {\n const params = body.params as CpRpcParams | undefined;\n let norm: { sources: string[]; dest: string };\n try {\n norm = normalizeCpParams(body.method, params);\n } catch (err) {\n send(res, 400, { error: err instanceof Error ? err.message : String(err) });\n return;\n }\n if (\n params!.exclude !== undefined &&\n (!Array.isArray(params!.exclude) || params!.exclude.some((p) => typeof p !== 'string'))\n ) {\n send(res, 400, { error: 'cp.* exclude must be an array of strings' });\n return;\n }\n const direction = body.method === 'cp.toHost' ? 'box -> host' : 'host -> box';\n // Resolve host paths against THIS box's workspace so a relative path\n // doesn't land under the relay daemon's CWD (whichever project started\n // the relay), and so the consent prompt shows the real destination.\n const workspacePath = await boxWorkspacePath(reg.boxId);\n const {\n argv: cpArgs,\n detail,\n contextArgv,\n } = buildCpArgv({\n method: body.method,\n boxName: reg.name,\n sources: norm.sources,\n dest: norm.dest,\n resolveHost: (p) => resolveHostPath(workspacePath, p),\n flags: cpFlags(params!),\n });\n const detailParts = [detail];\n if (params!.exclude && params!.exclude.length > 0) {\n detailParts.push(`exclude: ${params!.exclude.join(', ')}`);\n }\n if (params!.defaultExcludes === false) detailParts.push('(default excludes off)');\n if (params!.yes) detailParts.push('(over size limit — confirmed)');\n // Auto-approve a transfer that stays inside the box's project folder\n // (box->host: check the dest; host->box: check the sources, keeping\n // secret files behind the prompt). Anything else prompts as before.\n const cpHostPaths =\n body.method === 'cp.toHost'\n ? [resolveHostPath(workspacePath, norm.dest)]\n : norm.sources.map((s) => resolveHostPath(workspacePath, s));\n const cpAuto = await canAutoApproveTransfer({\n enabled: reg.autoApproveSafeHostActions !== false,\n workspacePath,\n hostPaths: cpHostPaths,\n checkSecret: body.method === 'cp.fromHost',\n carried: body.method === 'cp.fromHost' ? await boxCarriedHostPaths(reg.boxId) : undefined,\n });\n if (cpAuto) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `cp (${direction}) on ${reg.name}`,\n detail: detailParts.join('\\n'),\n context: { command: body.method, argv: contextArgv },\n },\n body.method === 'cp.toHost'\n ? 'safe: contained copy to host'\n : 'safe: contained copy from host',\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow cp (${direction}) on ${reg.name}?`,\n detail: detailParts.join('\\n'),\n defaultAnswer: 'n',\n context: {\n command: body.method,\n argv: contextArgv,\n },\n });\n if (verdict.answer !== 'y') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await handleCpRpc(cpArgs, workspacePath);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method.startsWith('gh.pr.')) {\n const op = body.method.slice('gh.pr.'.length);\n if (!isGhPrOp(op)) {\n send(res, 400, { error: `unknown gh.pr.* op: ${op}` });\n return;\n }\n const result = await handleGhPrRpc(\n op,\n reg,\n body.params as GhPrRpcParams | undefined,\n prompts,\n subscribers,\n hostInitiatedTokens,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method.startsWith('gh.run.')) {\n const op = body.method.slice('gh.run.'.length);\n if (!isGhRunOp(op)) {\n send(res, 400, { error: `unknown gh.run.* op: ${op}` });\n return;\n }\n const result = await handleGhRunRpc(\n op,\n reg,\n body.params as GhRunRpcParams | undefined,\n prompts,\n subscribers,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'gh.api') {\n const result = await handleGhApiRpc(reg, body.params as GhApiRpcParams | undefined);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method.startsWith('integration.')) {\n const result = await handleIntegrationRpc(\n body.method,\n reg,\n body.params as IntegrationRpcParams | undefined,\n prompts,\n subscribers,\n hostInitiatedTokens,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'git.clone' || body.method === 'gh.repo.clone') {\n // Clone bundle-ship-back machinery is deferred to a follow-up PR\n // The shim + ctl plumbing is in place so the next iteration only has\n // to land the relay-side host clone + bundle + box transfer.\n send(res, 501, {\n exitCode: 64,\n stdout: '',\n stderr: `${body.method}: not yet implemented for this box. Run \\`gh\\` / \\`git\\` on the host directly for now.\\n`,\n });\n return;\n }\n if (\n body.method === 'download.workspace' ||\n body.method === 'download.env' ||\n body.method === 'download.config' ||\n body.method === 'download.claude'\n ) {\n const params = body.params as DownloadRpcParams | undefined;\n const kind = parseDownloadKind(body.method);\n // `download.workspace` lands under the box's project folder (contained by\n // construction), so it auto-approves under the safe flag. The env/config/\n // claude kinds land in ~/.agentbox / ~/.claude (outside the project) and\n // keep prompting.\n const dlWorkspace = await boxWorkspacePath(reg.boxId);\n const dlAuto =\n kind === 'workspace' &&\n (await canAutoApproveTransfer({\n enabled: reg.autoApproveSafeHostActions !== false,\n workspacePath: dlWorkspace,\n hostPaths: dlWorkspace ? [dlWorkspace] : [],\n checkSecret: false,\n }));\n if (dlAuto) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `download (${kind}) from ${reg.name}`,\n detail: params?.hostPath ?? '(default host location)',\n context: { command: body.method, argv: params?.hostPath ? [params.hostPath] : [] },\n },\n 'safe: contained download',\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow download (${kind}) from ${reg.name}?`,\n detail: params?.hostPath ?? '(default host location)',\n defaultAnswer: 'n',\n context: {\n command: body.method,\n argv: params?.hostPath ? [params.hostPath] : [],\n },\n });\n if (verdict.answer !== 'y') {\n send(res, 500, { exitCode: 10, stdout: '', stderr: 'denied by user\\n' });\n return;\n }\n }\n const result = await handleDownloadRpc(reg, kind);\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'checkpoint.create') {\n const result = await handleCheckpointRpc(\n reg,\n body.params as CheckpointRpcParams | undefined,\n );\n const status = result.exitCode === 0 ? 200 : 500;\n send(res, status, result);\n return;\n }\n if (body.method === 'browser.open') {\n const params = body.params as BrowserOpenRpcParams | undefined;\n const url = typeof params?.url === 'string' ? params.url.trim() : '';\n if (!isOpenableUrl(url)) {\n // The scheme guard keeps a box from handing the host's `open` a\n // file path or app instead of a URL.\n send(res, 400, {\n exitCode: 64,\n stdout: '',\n stderr: 'browser.open: only http/https URLs are allowed\\n',\n });\n return;\n }\n // The box already opened the link in its own browser; this RPC is\n // just a notification. Record the event and answer at once — never\n // block the box on the host user's decision.\n await store.appendEvent({ boxId: reg.boxId, type: 'browser-open', payload: { url } });\n send(res, 200, { exitCode: 0, stdout: '', stderr: '' });\n // Offer to mirror the link to the host browser: a non-blocking,\n // auto-expiring confirm prompt in the footer/dashboard. Skipped under\n // AGENTBOX_PROMPT=off so a headless box can't spray the host with\n // browser tabs via askPrompt's auto-'y'.\n if (process.env.AGENTBOX_PROMPT !== 'off') {\n if (mode === 'box' && hostActions) {\n // Cloud: the in-sandbox relay has no SSE subscribers (the host\n // wrapper attaches to the host relay, not the in-sandbox one).\n // Queue a `browser.open.mirror` host action — the host poller\n // drains it, executes the prompt + open against host\n // subscribers, and resolves the parked entry. We don't await;\n // the host's verdict isn't reported back to the in-box agent\n // and `HostActionQueue.maxAgeMs` GCs the entry if it lingers.\n void hostActions.enqueue(reg.boxId, 'browser.open.mirror', { url });\n } else {\n void askPrompt(\n prompts,\n subscribers,\n reg.boxId,\n {\n kind: 'confirm',\n message: `Open link from box ${reg.name} on the host?`,\n detail: url,\n defaultAnswer: 'n',\n context: { command: 'browser.open', argv: [url] },\n },\n { ttlMs: BROWSER_OPEN_PROMPT_TTL_MS },\n )\n .then((verdict) => {\n if (verdict.answer === 'y' && !verdict.cancelled) {\n void runHostCommand([hostOpenCommand(), url], BROWSER_OPEN_RPC_TIMEOUT_MS);\n }\n })\n .catch(() => {\n /* best-effort */\n });\n }\n }\n return;\n }\n await store.appendEvent({\n boxId: reg.boxId,\n type: 'rpc-unknown',\n payload: { method: body.method },\n });\n send(res, 501, { error: 'rpc method not implemented', method: body.method });\n return;\n }\n\n // Poll-mode verdict + result for a parked approval (see ./permission.ts).\n // The box polls this after a `/rpc` returned `202 {promptId}`:\n // - pending → keep polling\n // - denied/cancelled → exit 10\n // - approved → run the action once, cache the result, return it\n if (req.method === 'GET' && url.pathname.startsWith('/rpc/status/')) {\n const reg = await authBox(req, res);\n if (!reg) return;\n const promptId = decodeURIComponent(url.pathname.slice('/rpc/status/'.length));\n const row = await store.getPrompt(promptId);\n if (!row || row.boxId !== reg.boxId) {\n send(res, 404, { error: 'no such prompt', promptId });\n return;\n }\n if (row.status === 'pending') {\n send(res, 200, { status: 'pending' });\n return;\n }\n if (row.answer !== 'y' || row.cancelled) {\n send(res, 200, {\n status: 'done',\n result: { exitCode: 10, stdout: '', stderr: 'denied by user\\n' },\n });\n return;\n }\n // Approved. Idempotent: a cached result short-circuits re-polls; the box\n // polls sequentially so there is no concurrent first-execute race here.\n const cached = row.result;\n const result = cached ?? (await dispatchApprovedAction(reg, row.method, row.params));\n if (!cached) await store.setPromptResult(promptId, result);\n send(res, 200, { status: 'done', result });\n return;\n }\n\n if (route === 'POST /admin/register-box') {\n const body = await readJsonBody<RegisterBoxBody>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n typeof body.token !== 'string' ||\n typeof body.name !== 'string' ||\n body.boxId.length === 0 ||\n body.token.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, token, name}' });\n return;\n }\n const worktrees = sanitizeWorktrees(body.worktrees);\n // Only accept a finite positive integer; everything else (including the\n // common `undefined` from legacy boxes) drops to `undefined` and the\n // status-store falls back to the `<id>-<mnemonic>` segment shape.\n const projectIndex =\n typeof body.projectIndex === 'number' &&\n Number.isFinite(body.projectIndex) &&\n body.projectIndex > 0\n ? Math.trunc(body.projectIndex)\n : undefined;\n const kind = body.kind === 'cloud' ? 'cloud' : 'docker';\n const reg: BoxRegistration = {\n boxId: body.boxId,\n token: body.token,\n name: body.name,\n kind,\n backend:\n typeof body.backend === 'string' && body.backend.length > 0 ? body.backend : undefined,\n sandboxId:\n typeof body.sandboxId === 'string' && body.sandboxId.length > 0\n ? body.sandboxId\n : undefined,\n registeredAt: new Date().toISOString(),\n containerName:\n typeof body.containerName === 'string' && body.containerName.length > 0\n ? body.containerName\n : undefined,\n createdAt:\n typeof body.createdAt === 'string' && body.createdAt.length > 0\n ? body.createdAt\n : undefined,\n projectIndex,\n worktrees,\n previewUrl:\n typeof body.previewUrl === 'string' && body.previewUrl.length > 0\n ? body.previewUrl\n : undefined,\n previewToken:\n typeof body.previewToken === 'string' && body.previewToken.length > 0\n ? body.previewToken\n : undefined,\n bridgeToken:\n typeof body.bridgeToken === 'string' && body.bridgeToken.length > 0\n ? body.bridgeToken\n : undefined,\n autoApproveHostActions: body.autoApproveHostActions === true,\n // Default on: only an explicit `false` disables the safe subset, so an\n // older wire body without the field stays relaxed.\n autoApproveSafeHostActions: body.autoApproveSafeHostActions !== false,\n originUrl:\n typeof body.originUrl === 'string' && body.originUrl.length > 0\n ? body.originUrl\n : undefined,\n publicHost:\n typeof body.publicHost === 'string' && body.publicHost.length > 0\n ? body.publicHost\n : undefined,\n image: typeof body.image === 'string' && body.image.length > 0 ? body.image : undefined,\n webPort:\n typeof body.webPort === 'number' && Number.isFinite(body.webPort) && body.webPort > 0\n ? Math.trunc(body.webPort)\n : undefined,\n agent: typeof body.agent === 'string' && body.agent.length > 0 ? body.agent : undefined,\n projectSlug:\n typeof body.projectSlug === 'string' && body.projectSlug.length > 0\n ? body.projectSlug\n : undefined,\n };\n await store.registerBox(reg);\n log(\n `registered ${kind} box ${reg.boxId} (${reg.name})` +\n (worktrees && worktrees.length > 0\n ? ` with ${String(worktrees.length)} worktree(s)`\n : ''),\n );\n // Cloud boxes get a host-side poller so the host relay can mirror their\n // status into its BoxStatusStore (and, once the executor is wired,\n // drain queued host-only RPCs and post results back).\n if (kind === 'cloud' && reg.previewUrl && reg.bridgeToken) {\n try {\n const set = await getPollers();\n set.start(reg.boxId, {\n boxId: reg.boxId,\n previewUrl: reg.previewUrl,\n bridgeToken: reg.bridgeToken,\n previewToken: reg.previewToken,\n onEvents: async (evs) => {\n for (const ev of evs) {\n // Credential updates carry a secret blob — route to the\n // fan-out handler, never into the host event ring buffer.\n if (ev.type === CREDENTIALS_UPDATED_EVENT && credentialsFanout) {\n const verdict = await credentialsFanout.handle(reg.boxId, ev.payload);\n log(\n `credentials-updated box=${reg.boxId} accepted=${String(verdict.accepted)} (${verdict.reason})`,\n );\n continue;\n }\n await store.appendEvent({\n boxId: reg.boxId,\n type: ev.type,\n payload: ev.payload,\n ts: ev.ts,\n });\n }\n },\n onStatus: (status) => {\n if (isValidBoxStatus(status)) {\n void store.setStatus(reg.boxId, reg.name, reg.projectIndex, status);\n // Same reason as the direct-POST path above: this is the only\n // status source an attached footer has for a cloud box.\n subscribers.broadcast(reg.boxId, BOX_STATUS_EVENT, status);\n }\n },\n // Drained host-only RPCs (git.push, …) run on the host via the\n // executor and the result is POSTed back to /bridge/action-result.\n // No backend name → no executor; the poller's default respond\n // already returns a \"no executor\" error so the box unblocks.\n onAction: reg.backend\n ? async (action, respond) => {\n try {\n const result = await executeCloudAction(action, {\n backendName: reg.backend!,\n boxId: reg.boxId,\n boxName: reg.name,\n prompts,\n subscribers,\n hostInitiatedTokens,\n autoApproveSafeHostActions: reg.autoApproveSafeHostActions,\n originUrl: reg.originUrl,\n log,\n });\n await respond(result);\n } catch (err) {\n await respond({\n exitCode: 1,\n stdout: '',\n stderr: `host executor failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n });\n }\n }\n : undefined,\n // Self-heal a dead preview transport (hetzner SSH `-L` after a\n // ControlMaster death). The relay strips the `cloud:` prefix\n // the cloud-provider tags onto BoxRecord.container — what the\n // backend's `get(sandboxId)` expects is the bare sandbox id.\n recoverPreviewUrl: reg.backend\n ? async () => refreshCloudPreviewUrl(reg.backend!, reg.boxId, DEFAULT_BOX_RELAY_PORT)\n : undefined,\n logger: log,\n });\n } catch (err) {\n log(\n `failed to start cloud poller for ${reg.boxId}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/forget-box') {\n const body = await readJsonBody<{ boxId?: string }>(req);\n if (!body || typeof body.boxId !== 'string' || body.boxId.length === 0) {\n send(res, 400, { error: 'expected {boxId}' });\n return;\n }\n const existed = await store.forgetBox(body.boxId);\n await store.deleteStatus(body.boxId);\n if (pollers) await pollers.stop(body.boxId);\n log(`forgot box ${body.boxId} (existed=${String(existed)})`);\n send(res, 204, null);\n return;\n }\n\n if (route === 'GET /admin/box-status') {\n const box = url.searchParams.get('box') ?? '';\n const status = box ? await store.getStatus(box) : undefined;\n if (!status) {\n send(res, 404, { error: 'no status for box', box });\n return;\n }\n send(res, 200, status);\n return;\n }\n\n if (route === 'GET /admin/events') {\n const since = Number.parseInt(url.searchParams.get('since') ?? '0', 10) || 0;\n const box = url.searchParams.get('box') ?? undefined;\n const list = await store.listEvents(since, box ?? undefined);\n send(res, 200, { events: list });\n return;\n }\n\n if (route === 'GET /admin/registry') {\n // Redact tokens; callers on the admin path don't need them and we don't\n // want them showing up in logs if someone curls this.\n const redacted = (await store.listBoxes()).map((r) => ({\n boxId: r.boxId,\n name: r.name,\n registeredAt: r.registeredAt,\n containerName: r.containerName,\n createdAt: r.createdAt,\n projectIndex: r.projectIndex,\n worktrees: r.worktrees ?? [],\n }));\n send(res, 200, { boxes: redacted });\n return;\n }\n\n if (route === 'GET /admin/prompts') {\n // One-shot snapshot of pending host-action approvals for a box. The SSE\n // `/stream` variant is for long-lived wrappers; this is for an\n // orchestrator (or `agentbox agent approvals`) that wants to inspect the\n // backlog, answer via /admin/prompts/answer, and move on without holding\n // a stream open. `boxId=` required, same as /stream.\n const boxId = url.searchParams.get('boxId') ?? '';\n if (boxId.length === 0) {\n send(res, 400, { error: 'missing boxId query param' });\n return;\n }\n // Poll mode parks prompts in the store; block mode keeps them in-process.\n const pending =\n promptMode === 'poll'\n ? (await store.listPendingPrompts(boxId)).map((r) => r.ev)\n : prompts.forBox(boxId);\n send(res, 200, { prompts: pending });\n return;\n }\n\n if (route === 'GET /admin/prompts/stream') {\n // Per-box SSE channel. The wrapper (apps/cli/src/wrapped-pty) subscribes\n // and stays connected; we push prompt-ask events on broadcast and a\n // periodic ping so the wrapper can detect a dead socket without traffic.\n // `boxId=` is required so a host with multiple boxes only sees its own\n // box's prompts (the wrapper attaches per-box anyway).\n const boxId = url.searchParams.get('boxId') ?? '';\n if (boxId.length === 0) {\n send(res, 400, { error: 'missing boxId query param' });\n return;\n }\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/event-stream');\n res.setHeader('Cache-Control', 'no-cache');\n res.setHeader('Connection', 'keep-alive');\n // Helps with proxies (e.g. nginx) that would otherwise buffer the\n // chunked response. The relay binds to loopback so this is belt-and-\n // suspenders, but the cost is one extra header.\n res.setHeader('X-Accel-Buffering', 'no');\n if (typeof res.flushHeaders === 'function') res.flushHeaders();\n res.write(': connected\\n\\n');\n subscribers.add(boxId, res);\n // Flush any prompts that arrived while no wrapper was attached — per\n // the design we block indefinitely on the in-box RPC, so a backlog can\n // build up between detach and reattach.\n for (const ev of prompts.forBox(boxId)) {\n res.write(`event: prompt-ask\\ndata: ${JSON.stringify(ev)}\\n\\n`);\n }\n // Then any active notices, so a wrapper attaching mid-checkpoint still\n // sees the in-progress warning (prompts first — they outrank notices).\n for (const ev of notices.forBox(boxId)) {\n res.write(`event: notice-set\\ndata: ${JSON.stringify(ev)}\\n\\n`);\n }\n const heartbeat = setInterval(() => {\n try {\n res.write(`event: ping\\ndata: {\"ts\":\"${new Date().toISOString()}\"}\\n\\n`);\n } catch {\n /* dead socket; close handler below removes */\n }\n }, SSE_HEARTBEAT_MS);\n if (typeof heartbeat.unref === 'function') heartbeat.unref();\n res.on('close', () => {\n clearInterval(heartbeat);\n subscribers.remove(boxId, res);\n });\n return;\n }\n\n if (route === 'POST /admin/prompts/answer') {\n const body = await readJsonBody<PromptAnswerBody>(req);\n if (!isPromptAnswerBody(body)) {\n send(res, 400, { error: 'expected {id, answer:\"y\"|\"n\", cancelled?}' });\n return;\n }\n // Poll mode: the answer lands on the store row; the box's /rpc/status\n // poll picks it up and runs (or denies) the parked action.\n if (promptMode === 'poll') {\n const row = await store.getPrompt(body.id);\n const hit = await store.answerPrompt(body.id, body.answer, body.cancelled);\n if (!hit) {\n send(res, 404, { error: 'no pending prompt with that id' });\n return;\n }\n if (row) subscribers.broadcast(row.boxId, 'prompt-resolved', { id: body.id });\n send(res, 204, null);\n return;\n }\n // Block mode: resolve the in-process pending Promise (the parked /rpc\n // call unblocks and runs/denies inline). Find the owning box first so we\n // can target the prompt-resolved broadcast (other wrappers clear their\n // stale footer).\n const targetBox = prompts.boxFor(body.id);\n const hit = prompts.resolve(body.id, body.answer, body.cancelled);\n if (!hit) {\n // Already answered (idempotent) or never existed.\n send(res, 404, { error: 'no pending prompt with that id' });\n return;\n }\n if (targetBox) {\n subscribers.broadcast(targetBox, 'prompt-resolved', { id: body.id });\n }\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/host-initiated/mint') {\n // Host CLI mints a one-time token before invoking `agentbox-ctl` in a\n // box for a credentialed RPC. The token is scoped to\n // (boxId, method, paramsHash) and consumed on first use.\n // See ./host-initiated.ts for rationale.\n //\n // paramsHash is mandatory in practice — without it a box that\n // harvests the token from agentbox-ctl's /proc/<pid>/cmdline could\n // replay it with mutated args. Accept `null` only for callers that\n // intentionally opt out (none today).\n const body = await readJsonBody<{\n boxId?: string;\n method?: string;\n paramsHash?: string | null;\n ttlMs?: number;\n }>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n body.boxId.length === 0 ||\n typeof body.method !== 'string' ||\n body.method.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, method, paramsHash, ttlMs?}' });\n return;\n }\n // Allow `paramsHash: null` (explicit opt-out) or a hex string.\n let paramsHash: string | null;\n if (body.paramsHash === null || body.paramsHash === undefined) {\n paramsHash = null;\n } else if (typeof body.paramsHash === 'string' && /^[0-9a-f]{64}$/.test(body.paramsHash)) {\n paramsHash = body.paramsHash;\n } else {\n send(res, 400, { error: 'paramsHash must be a 64-hex sha256 string or null' });\n return;\n }\n const ttlMs =\n typeof body.ttlMs === 'number' && Number.isFinite(body.ttlMs) && body.ttlMs > 0\n ? body.ttlMs\n : undefined;\n const token = hostInitiatedTokens.mint(body.boxId, body.method, paramsHash, ttlMs);\n log(\n `host-initiated-mint box=${body.boxId} method=${body.method} paramsBound=${paramsHash !== null}`,\n );\n send(res, 200, { token });\n return;\n }\n\n if (route === 'POST /admin/notices/set') {\n const body = await readJsonBody<SetNoticeBody>(req);\n if (\n !body ||\n typeof body.boxId !== 'string' ||\n body.boxId.length === 0 ||\n typeof body.kind !== 'string' ||\n body.kind.length === 0 ||\n typeof body.message !== 'string' ||\n body.message.length === 0\n ) {\n send(res, 400, { error: 'expected {boxId, kind, message}' });\n return;\n }\n const ttlMs =\n typeof body.ttlMs === 'number' && Number.isFinite(body.ttlMs) && body.ttlMs > 0\n ? body.ttlMs\n : undefined;\n const id = notices.set(body.boxId, body.kind, body.message, ttlMs);\n log(`notice-set box=${body.boxId} kind=${body.kind} id=${id}`);\n send(res, 200, { id });\n return;\n }\n\n if (route === 'POST /admin/queue/enqueue') {\n // The CLI's `submitQueueJob` writes the manifest first, then POSTs here\n // so the relay's scheduler runs immediately instead of waiting for the\n // next periodic tick. Body is informational — the source of truth is\n // the manifest on disk.\n const body = await readJsonBody<{ id?: string }>(req);\n if (!body || typeof body.id !== 'string' || body.id.length === 0) {\n send(res, 400, { error: 'expected {id}' });\n return;\n }\n log(`queue-enqueue id=${body.id}`);\n queuePoke?.();\n send(res, 204, null);\n return;\n }\n\n if (route === 'POST /admin/notices/clear') {\n const body = await readJsonBody<ClearNoticeBody>(req);\n if (!body || typeof body.id !== 'string' || body.id.length === 0) {\n send(res, 400, { error: 'expected {boxId, id}' });\n return;\n }\n notices.clear(body.id);\n log(`notice-clear id=${body.id}`);\n send(res, 204, null);\n return;\n }\n\n if (uiHandler) {\n uiHandler(req, res);\n return;\n }\n send(res, 404, { error: 'not found', route });\n }\n\n /**\n * Run a host action that has already cleared its approval gate (poll mode:\n * the box reached `/rpc/status` after a `y`). No re-gating here. Extended per\n * method as the hosted plane grows.\n */\n async function dispatchApprovedAction(\n reg: BoxRegistration,\n method: string,\n params: unknown,\n ): Promise<GitRpcResult> {\n if (method === 'git.push' || method === 'git.fetch') {\n return handleGitRpc(reg, method, params as GitRpcParams | undefined);\n }\n if (method === 'git.lease-token') {\n return leaseTokenResult(leaser, reg);\n }\n return {\n exitCode: 64,\n stdout: '',\n stderr: `relay: no approved-action executor for ${method}\\n`,\n };\n }\n\n async function authBox(\n req: IncomingMessage,\n res: ServerResponse,\n ): Promise<BoxRegistration | null> {\n const token = bearerToken(req);\n if (token.length === 0) {\n send(res, 401, { error: 'missing bearer token' });\n return null;\n }\n const match = await store.authenticateBox(token);\n if (!match) {\n send(res, 401, { error: 'unknown box token' });\n return null;\n }\n return match;\n }\n\n return {\n server,\n store,\n registry,\n events,\n statusStore,\n prompts,\n subscribers,\n notices,\n hubNotifier,\n custody,\n hostActions: hostActions ?? undefined,\n url: `http://${host}:${String(opts.port)}`,\n setQueuePoke: (fn) => {\n queuePoke = fn;\n },\n pokeQueue: () => {\n queuePoke?.();\n },\n close: async () => {\n if (pollers) await pollers.stopAll();\n await new Promise<void>((resolve, reject) => {\n server.close((err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n },\n };\n}\n\nfunction sanitizeWorktrees(input: BoxWorktree[] | undefined): BoxWorktree[] | undefined {\n if (!Array.isArray(input)) return undefined;\n const out: BoxWorktree[] = [];\n for (const w of input) {\n if (\n w &&\n typeof w.containerPath === 'string' &&\n typeof w.hostMainRepo === 'string' &&\n typeof w.branch === 'string'\n ) {\n out.push({\n containerPath: w.containerPath,\n hostMainRepo: w.hostMainRepo,\n branch: w.branch,\n ...(typeof w.sanctionedBranch === 'string' && w.sanctionedBranch.length > 0\n ? { sanctionedBranch: w.sanctionedBranch }\n : {}),\n });\n }\n }\n return out;\n}\n\n/**\n * git.push --host-only: make the box's branch available in the host's *local*\n * repo without pushing to any remote. Docker boxes commit against the\n * bind-mounted `.git/`, so the box's branch ref already lives in the host repo;\n * we just copy it to the requested destination ref via a self-fetch (which\n * enforces fast-forward and works even though the source branch is checked out\n * in the worktree). When the destination equals the source branch this is a\n * no-op success — the branch is already on the host.\n */\nasync function handleGitSaveToHost(\n reg: BoxRegistration,\n params: GitRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n // Land the branch the box is actually on (its host-sanctioned branch, updated\n // by `agentbox git checkout`), matching what `git.push` publishes — not the\n // stale create-time scratch ref.\n const src = worktree.sanctionedBranch ?? worktree.branch;\n const dest = resolveLandDest(src, params?.as);\n if (dest === src) {\n return {\n exitCode: 0,\n stdout: `branch ${dest} already available in ${worktree.hostMainRepo}\\n`,\n stderr: '',\n };\n }\n const refspec = landRefspec(src, dest, params?.force);\n const result = await runHostCommand(['git', '-C', worktree.hostMainRepo, 'fetch', '.', refspec]);\n if (result.exitCode === 0) {\n return {\n exitCode: 0,\n stdout: `branch ${dest} available in ${worktree.hostMainRepo}\\n${result.stdout}`,\n stderr: result.stderr,\n };\n }\n return result;\n}\n\n/**\n * git.push / git.fetch: run `git -C <hostMainRepo> <op> <remote> <branch>\n * [args]` on the host with the user's creds. The in-container worktree's\n * working tree isn't on the host, so we operate on the shared `.git/` from\n * the main repo dir — refs already point at the in-container commits\n * (committed there against the bind-mounted .git).\n *\n * git.pull is intentionally NOT handled here: a pull merges into the\n * working tree, which lives inside the container. The in-box\n * `agentbox-ctl git pull` calls git.fetch via RPC, then runs a local merge.\n */\nasync function handleGitRpc(\n reg: BoxRegistration,\n method: 'git.push' | 'git.fetch',\n params: GitRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n // A worker-created (hub) box registered its `hostMainRepo` as the create-time\n // seed clone (a temp dir deleted after create), so `git -C <that>` would fail\n // cryptically. Reject fail-closed with a clear message instead.\n const unavailable = hostRepoUnavailableReason(worktree, reg.boxId, method);\n if (unavailable) {\n return { exitCode: 64, stdout: '', stderr: unavailable };\n }\n const op = method === 'git.push' ? 'push' : 'fetch';\n const remote = resolveRemote(params?.remote);\n // Operate on the host-sanctioned branch (updated by `agentbox git checkout`),\n // falling back to the create-time `branch` for records without the field.\n // The agent can't influence this — the relay picks the branch — so pushing\n // it is always host-controlled.\n const pushBranch = worktree.sanctionedBranch ?? worktree.branch;\n const argv = ['git', '-C', worktree.hostMainRepo, op, remote, pushBranch];\n argv.push(...sanitizeGitArgs(params?.args));\n const result = await runHostCommand(argv);\n // After a successful push, mirror what `git push -u` would have left behind:\n // make the branch track `origin/<branch>` so the in-box `git status` /\n // Claude Code's PR badge see an upstream. Skip per-box scratch branches\n // (`agentbox/<name>`) — they're local-only by design. Docker shares .git/\n // with the box, so update-ref of the remote-tracking ref already happened\n // during the push; only the upstream config is missing.\n if (method === 'git.push' && result.exitCode === 0 && !isScratchBranch(pushBranch)) {\n await runHostCommand([\n 'git',\n '-C',\n worktree.hostMainRepo,\n 'branch',\n `--set-upstream-to=${upstreamRef(remote, pushBranch)}`,\n pushBranch,\n ]);\n }\n return result;\n}\n\n/**\n * gh.pr.<op>: shell to the host's `gh` CLI (with the user's gh auth) to drive\n * a PR operation requested from inside the box. Read-only ops (`view`,\n * `list`) bypass the confirm prompt; everything else surfaces an\n * `askPrompt` to the host wrapper before running. `merge` and `checkout`\n * have additional opt-in env guards — see `refuseMergeBypass` and\n * `refuseCheckoutByDefault` in `./gh.ts`.\n *\n * Runs `gh` with `cwd = worktree.hostMainRepo` so `gh` infers the repo from\n * the host repo's `git remote -v`. The box's worktree branch is registered\n * (used to refuse `checkout` against the active per-box branch).\n */\nasync function handleGhPrRpc(\n op: GhPrOp,\n reg: BoxRegistration,\n params: GhPrRpcParams | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n hostInitiatedTokens: HostInitiatedTokens,\n): Promise<GitRpcResult> {\n // Env-only refusals first — cheap, deterministic, no fs/process calls.\n const mergeBypass = refuseMergeBypass(op);\n if (mergeBypass) return mergeBypass;\n const checkoutOptIn = refuseCheckoutByDefault(op);\n if (checkoutOptIn) return checkoutOptIn;\n\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n if (op === 'checkout') {\n // Guard against the host repo checking out onto ANY branch a box currently\n // occupies — its create-time scratch ref AND its host-sanctioned branch\n // (the box's live HEAD after `agentbox git checkout`), either of which the\n // bind-mounted `.git/HEAD` would corrupt.\n const branches = (reg.worktrees ?? []).flatMap((w) =>\n w.sanctionedBranch && w.sanctionedBranch !== w.branch\n ? [w.branch, w.sanctionedBranch]\n : [w.branch],\n );\n const guard = await checkoutGuards(worktree.hostMainRepo, branches);\n if (guard) return guard;\n }\n\n // Host-initiated `gh pr <op>` (from `agentbox git pr <op> <box>`) skips\n // the confirm prompt — but only with a valid scope-matched, params-hash-\n // bound one-time token. If a token is *present* but invalid (mutated\n // params, replayed, etc.) we reject hard — that's an attack signal. Only\n // fall through to the prompt when no token was claimed. The\n // `refuseMergeBypass` / `refuseCheckoutByDefault` guards above still run.\n const tokenClaimedGh = typeof params?.hostInitiated === 'string';\n const incomingHashGh = hashRpcParams(params);\n const hostInitiatedOk =\n !GH_PR_READ_ONLY_OPS.has(op) &&\n tokenClaimedGh &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, `gh.pr.${op}`, incomingHashGh);\n if (!GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGh && !hostInitiatedOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n // Safe subset: open-PR + PR comment auto-approve under the flag (audited);\n // review/close/reopen/merge/checkout keep prompting. A `create` with an\n // EXPLICIT `--head` is excluded — that head could name any branch (e.g.\n // `main`), so it falls back to the prompt; a headless `create` has its head\n // forced to the box's sanctioned branch below, so it stays scoped.\n const ghSafeAuto =\n GH_PR_SAFE_AUTO_APPROVE_OPS.has(op) &&\n reg.autoApproveSafeHostActions !== false &&\n !prCreateHasExplicitHead(op, args);\n if (ghSafeAuto && !hostInitiatedOk) {\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `gh pr ${op} from box ${reg.name}`,\n detail: args.join(' ').slice(0, 200),\n context: { command: `gh pr ${op}`, cwd: containerPath, argv: args },\n },\n `safe: gh pr ${op}`,\n );\n }\n if (!GH_PR_READ_ONLY_OPS.has(op) && !ghSafeAuto && !hostInitiatedOk) {\n const detail = args.join(' ').slice(0, 200);\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow gh pr ${op} from box ${reg.name}?`,\n detail,\n defaultAnswer: 'n',\n context: {\n command: `gh pr ${op}`,\n cwd: containerPath,\n argv: args,\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n\n // Default `--head` to the box's branch for `create` (the host repo cwd isn't\n // on the box branch, so gh can't infer it). Done after token validation —\n // which hashes the incoming `params`, not this post-injection argv.\n // Inject the box's SANCTIONED branch (updated by `agentbox git checkout`),\n // matching what `git.push` publishes — so a headless PR targets the branch\n // the box's work is actually on, not the stale create-time scratch ref.\n const finalArgs = injectPrCreateHead(op, worktree.sanctionedBranch ?? worktree.branch, args);\n // Never let `gh` fall back to the host repo's checked-out branch.\n if (prCreateNeedsHead(op, finalArgs)) return PR_CREATE_NO_HEAD_REFUSAL;\n const prRun = ghRunContext(worktree.hostMainRepo, reg.originUrl, finalArgs);\n return runHostGh(['pr', op, ...prRun.args], prRun.cwd);\n}\n\n/**\n * `gh.run.<op>` (list / view / rerun). Runs `gh run …` in the host main repo\n * so gh infers the GitHub repo from its remotes. `list` / `view` are read-only;\n * `rerun` re-triggers CI and goes through the host confirm prompt. No\n * host-initiated token path — this is an in-box-only surface.\n */\nasync function handleGhRunRpc(\n op: GhRunOp,\n reg: BoxRegistration,\n params: GhRunRpcParams | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n if (!GH_RUN_READ_ONLY_OPS.has(op)) {\n const detail = args.join(' ').slice(0, 200);\n if (reg.autoApproveSafeHostActions !== false) {\n // `gh run rerun` only re-triggers the project's own CI — safe subset.\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `gh run ${op} from box ${reg.name}`,\n detail,\n context: { command: `gh run ${op}`, cwd: containerPath, argv: args },\n },\n `safe: gh run ${op}`,\n );\n } else {\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow gh run ${op} from box ${reg.name}?`,\n detail,\n defaultAnswer: 'n',\n context: { command: `gh run ${op}`, cwd: containerPath, argv: args },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n const runRun = ghRunContext(worktree.hostMainRepo, reg.originUrl, args);\n return runHostGh(['run', op, ...runRun.args], runRun.cwd);\n}\n\n/**\n * `gh.api`: allowlisted REST calls. Runs `gh api <endpoint> …` in the host main\n * repo. The endpoint must match `GH_API_ALLOWED_ENDPOINTS`; `refuseGhApiCall`\n * then enforces the method policy (GET anywhere on the allowlist, POST only on\n * the comment endpoints). No prompt — reads and comment POSTs are both silent.\n */\nasync function handleGhApiRpc(\n reg: BoxRegistration,\n params: GhApiRpcParams | undefined,\n): Promise<GitRpcResult> {\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const endpoint = typeof params?.endpoint === 'string' ? params.endpoint : '';\n if (!isAllowedGhApiEndpoint(endpoint)) return GH_API_ENDPOINT_REFUSAL;\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n const callRefusal = refuseGhApiCall(endpoint, args);\n if (callRefusal) return callRefusal;\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n const apiRun = ghRunContext(worktree.hostMainRepo, undefined, args);\n return runHostGh(['api', endpoint, ...apiRun.args], apiRun.cwd);\n}\n\n/**\n * `integration.<service>.<op>`: generic dispatch for any connector\n * registered in `@agentbox/integrations`. Mirrors the `gh.pr.<op>` flow\n * (worktree resolve → `assertReady` → host-initiated token / askPrompt for\n * writes → shell out). Reads bypass the prompt; writes are always gated.\n * Op-level `refuseCall` (e.g. `notion.api`'s GET-only check) runs after\n * worktree resolve but before any host process is touched.\n *\n * All failures return the same `{exitCode, stdout, stderr}` envelope as\n * `handleGhPrRpc` — including unknown-method/service shapes (exit 64) —\n * so the cloud and docker paths emit identical wire shapes per the\n * \"fix across all providers\" rule.\n */\nasync function handleIntegrationRpc(\n method: string,\n reg: BoxRegistration,\n params: IntegrationRpcParams | undefined,\n prompts: PendingPrompts,\n subscribers: PromptSubscribers,\n hostInitiatedTokens: HostInitiatedTokens,\n): Promise<GitRpcResult> {\n const parsed = parseIntegrationMethod(method);\n if (!parsed) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration method shape: ${method}\\n`,\n };\n }\n const connector = getConnector(parsed.service);\n if (!connector) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration service: ${parsed.service}\\n`,\n };\n }\n const opDesc = connector.ops[parsed.op];\n if (!opDesc) {\n return makeIntegrationOpRefusal(\n parsed.service,\n parsed.op,\n connector.hostBin,\n Object.keys(connector.ops),\n );\n }\n const containerPath = params?.path ?? '/workspace';\n const worktree = resolveWorktree(reg, containerPath);\n if (!worktree) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `no worktree registered for box ${reg.boxId} matching ${containerPath}`,\n };\n }\n const args = Array.isArray(params?.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n const callRefusal = refuseIntegrationCall(opDesc, args);\n if (callRefusal) return callRefusal;\n\n // Layered enablement gate — the in-box shim and ctl both transparently\n // forward to here, so this one check covers every caller. Reads the\n // worktree's project config so a single project can opt in without\n // flipping it globally. Placed after `refuseIntegrationCall` so the\n // ordering matches the cloud handler (`runIntegrationRpc` in\n // host-actions.ts) — keeps the wire envelope identical across providers\n // for the malformed-args-to-disabled-integration edge case. Runs before\n // `assertIntegrationReady`, the prompt, and the host spawn so a disabled\n // integration is never user-visible as a permission prompt.\n const enableRefusal = await refuseIfIntegrationDisabled(parsed.service, worktree.hostMainRepo);\n if (enableRefusal) return enableRefusal;\n\n const ready = await assertIntegrationReady(connector);\n if (ready) return ready;\n\n // Host-initiated calls (from a host CLI mint) skip the prompt — but only\n // with a valid scope-matched, params-hash-bound one-time token. Hard\n // reject a *present-but-invalid* token (attack signal). Only fall through\n // to the prompt when no token was claimed. Reads never need a token.\n if (opDesc.write) {\n if (reg.autoApproveSafeHostActions !== false) {\n // Integration writes hit the connected external service (not the host) —\n // safe subset, audited, no prompt.\n prompts.noteAutoApprove(\n reg.boxId,\n {\n kind: 'confirm',\n message: `${parsed.service} ${parsed.op} from box ${reg.name}`,\n detail: args.join(' ').slice(0, 200),\n context: {\n command: `integration ${parsed.service} ${parsed.op}`,\n cwd: containerPath,\n argv: args,\n },\n },\n `safe: integration ${parsed.service} ${parsed.op}`,\n );\n } else {\n const tokenClaimed = typeof params?.hostInitiated === 'string';\n const incomingHash = hashRpcParams(params);\n const tokenOk =\n tokenClaimed &&\n hostInitiatedTokens.consume(params?.hostInitiated, reg.boxId, method, incomingHash);\n if (tokenClaimed && !tokenOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n if (!tokenOk) {\n const detail = args.join(' ').slice(0, 200);\n const verdict = await askPrompt(prompts, subscribers, reg.boxId, {\n kind: 'confirm',\n message: `Allow ${parsed.service} ${parsed.op} from box ${reg.name}?`,\n detail,\n defaultAnswer: 'n',\n context: {\n command: `integration ${parsed.service} ${parsed.op}`,\n cwd: containerPath,\n argv: args,\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n }\n\n return runHostIntegration(connector, opDesc, args, worktree.hostMainRepo);\n}\n\n/**\n * cp.toHost / cp.fromHost: copy a file/dir between box and host. Shells\n * out to the installed agentbox CLI's `cp` subcommand — that command\n * already knows how to handle the docker exec tar pipe + chown + auto-\n * unpause; duplicating that here would drift. `AGENTBOX_CLI_ENTRY` is set\n * by `ensureRelay` when it spawns this process.\n *\n * Caller (the /rpc route) already gated this with askPrompt and rejected\n * non-'y' answers; we never reach this code without consent.\n */\nasync function handleCpRpc(cpArgs: string[], cwd?: string): Promise<GitRpcResult> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run cp host-side',\n };\n }\n // Re-shell the installed `agentbox cp` (it owns the tar pipe, excludes, the\n // size guard, and provider routing). `cpArgs` is the fully-built argv from\n // buildCpArgv (box side prefixed with `<name>:`, host paths absolute); `cwd`\n // (the box workspace) makes the host CLI's project-config lookup box-correct.\n const argv = [process.execPath, entry, ...cpArgs];\n return runHostCommand(argv, CP_RPC_TIMEOUT_MS, cwd);\n}\n\n/**\n * download.{workspace,env,config,claude}: ask the installed agentbox CLI\n * to pull box contents to the host. Same decoupling rationale as cp — the\n * CLI owns rsync exclude lists, gitignore handling, claude registry\n * merging. The relay passes `-y` so the host CLI doesn't try to prompt\n * (we already did, via the host wrapper, before reaching this handler).\n */\nasync function handleDownloadRpc(reg: BoxRegistration, kind: DownloadKind): Promise<GitRpcResult> {\n // params.hostPath is reserved in the wire shape; the v1 relay ignores it\n // and lets the host CLI use its defaults (box.workspacePath or ~/.claude).\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run download host-side',\n };\n }\n const argv = [process.execPath, entry, 'download'];\n // `workspace` is the default download (no subcommand); the other three\n // are subcommands of `download`.\n if (kind !== 'workspace') argv.push(kind);\n argv.push(reg.name, '-y');\n // Run from the box's host workspace so the host CLI's project-config lookup\n // is box-correct (the destination already defaults to box.workspacePath).\n const cwd = await boxWorkspacePath(reg.boxId);\n return runHostCommand(argv, DOWNLOAD_RPC_TIMEOUT_MS, cwd);\n}\n\n/**\n * Capture a checkpoint host-side by shelling out to the installed agentbox\n * CLI (same decoupling philosophy as `handleGitRpc` spawning `git`). The\n * relay only knows the box id; the CLI resolves the BoxRecord (project root,\n * checkpoint config, snapshot storage) from it. `AGENTBOX_CLI_ENTRY` is set\n * by `ensureRelay` when it spawns this process.\n */\nasync function handleCheckpointRpc(\n reg: BoxRegistration,\n params: CheckpointRpcParams | undefined,\n): Promise<GitRpcResult> {\n const entry = process.env.AGENTBOX_CLI_ENTRY;\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run checkpoint host-side',\n };\n }\n const argv = [process.execPath, entry, 'checkpoint', 'create', reg.boxId];\n if (params?.name) argv.push('--name', params.name);\n if (params?.merged === true) argv.push('--merged');\n if (params?.setDefault === true) argv.push('--set-default');\n if (params?.replace === true) argv.push('--replace');\n return runHostCommand(argv, CHECKPOINT_RPC_TIMEOUT_MS);\n}\n\n/**\n * Guard for the `browser.open` RPC: only absolute http/https URLs may be\n * handed to the host's `open`. Rejecting every other scheme (`file:`,\n * `javascript:`, bare paths) keeps an in-box agent from opening host files\n * or apps under the guise of \"opening a link\".\n */\nexport function isOpenableUrl(value: string): boolean {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return false;\n }\n return url.protocol === 'http:' || url.protocol === 'https:';\n}\n\nfunction runHostCommand(\n argv: string[],\n timeoutMs: number = GIT_RPC_TIMEOUT_MS,\n cwd?: string,\n): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const [cmd, ...rest] = argv;\n if (!cmd) {\n resolve({ exitCode: 64, stdout: '', stderr: 'empty command' });\n return;\n }\n const child = spawn(cmd, rest, {\n env: process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Default to the relay daemon's CWD when unset (legacy behaviour); callers\n // that know the box pass its workspace so relative host paths + project\n // config resolve against the box, not whatever dir launched the relay.\n ...(cwd ? { cwd } : {}),\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n stderr += String(err.message ?? err);\n finish(127);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\nexport async function startRelayServer(opts: RelayServerOptions): Promise<RelayServerHandle> {\n const handle = createRelayServer(opts);\n // Hydrate the in-memory mirror from a durable store before the caller starts\n // the daemon loops, so a control box's registry/statusStore survive a restart\n // (no-op for the MemoryStore laptop path — it has no `hydrate`).\n if (handle.store instanceof WriteThroughStore) await handle.store.hydrate();\n await new Promise<void>((resolve, reject) => {\n handle.server.once('error', reject);\n handle.server.listen(opts.port, opts.host ?? '0.0.0.0', () => {\n handle.server.removeListener('error', reject);\n resolve();\n });\n });\n return handle;\n}\n\nexport type { BoxRegistration, RelayEvent };\n","/**\n * Host-side executor for actions parked by the in-sandbox `box-mode` relay\n * and drained by the `CloudBoxPoller`. This is where the host actually does\n * the work an in-box `agentbox-ctl git push` needs done — with host SSH\n * creds, in the host repo, without ever sending secrets into the box.\n *\n * v0 implements `git.push` and `git.fetch` via the git-bundle pull-back\n * pattern: the in-sandbox `git bundle create` is fetched into a host tmp\n * file, the host repo `git fetch`es the per-box branch from it (always a\n * fast-forward — the per-box branch only ever moves forward), then runs\n * the real `git push origin` / `git fetch origin`. `cp.*`, `download.*`,\n * `checkpoint.create`, `browser.open` are stubbed with a clear \"not yet\n * supported for cloud boxes\" error so the in-box command unblocks instead\n * of hanging. Filling each in is localized to this file.\n */\n\nimport { execa } from 'execa';\nimport { toHttpsUrl } from './git-pat.js';\nimport { existsSync } from 'node:fs';\nimport { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport {\n isResolvedBranch,\n isScratchBranch,\n isSanctionedPushBranch,\n landRefspec,\n parseDownloadKind,\n realpathSafe,\n remoteTrackingRef,\n resolveHostPath,\n resolveLandDest,\n resolveRemote,\n sanitizeGitArgs,\n upstreamRef,\n} from '@agentbox/core';\nimport type { CloudBackend, CloudHandle } from '@agentbox/core';\nimport {\n findBox,\n hostOpenCommand,\n isSupportedApiVersion,\n pluginForProvider,\n readState,\n} from '@agentbox/sandbox-core';\nimport {\n assertGhReady,\n checkoutGuards,\n GH_API_ENDPOINT_REFUSAL,\n GH_PR_READ_ONLY_OPS,\n GH_PR_SAFE_AUTO_APPROVE_OPS,\n GH_RUN_READ_ONLY_OPS,\n injectPrCreateHead,\n isAllowedGhApiEndpoint,\n isGhPrOp,\n isGhRunOp,\n PR_CREATE_NO_HEAD_REFUSAL,\n prCreateHasExplicitHead,\n prCreateNeedsHead,\n refuseCheckoutByDefault,\n refuseGhApiCall,\n refuseMergeBypass,\n ghRunContext,\n runHostGh,\n type GhApiRpcParams,\n type GhPrRpcParams,\n type GhRunRpcParams,\n} from './gh.js';\nimport { hashRpcParams, type HostInitiatedTokens } from './host-initiated.js';\nimport { buildCpArgv, cpFlags, normalizeCpParams, type CpMethod } from './cp-rpc.js';\nimport {\n assertIntegrationReady,\n makeIntegrationOpRefusal,\n parseIntegrationMethod,\n refuseIfIntegrationDisabled,\n refuseIntegrationCall,\n runHostIntegration,\n type IntegrationRpcParams,\n} from './integrations.js';\nimport { askPrompt, type PendingPrompts, type PromptSubscribers } from './prompts.js';\nimport { canAutoApproveTransfer } from './safe-transfer.js';\nimport { getConnector } from '@agentbox/integrations';\nimport type {\n CheckpointRpcParams,\n CpRpcParams,\n DownloadRpcParams,\n GitRpcParams,\n HostAction,\n HostActionResult,\n} from './types.js';\n\nexport interface CloudActionExecutorDeps {\n /** From BoxRegistration.backend (e.g. 'daytona'). */\n backendName: string;\n /** From BoxRegistration.boxId. Used to look up the BoxRecord in ~/.agentbox/state.json. */\n boxId: string;\n /** Friendly box name — used in confirm-prompt messages. Falls back to boxId. */\n boxName?: string;\n /** Host relay's pending-prompts queue, for gating destructive ops like git push. */\n prompts?: PendingPrompts;\n /** Host wrapper SSE subscribers — the prompt UX feeds through them. */\n subscribers?: PromptSubscribers;\n /** Host CLI one-time tokens; presence + scope-match skips the confirm prompt. */\n hostInitiatedTokens?: HostInitiatedTokens;\n /**\n * Mirrors `box.autoApproveSafeHostActions` from the registration (default\n * on). When not `false`, the SAFE subset of host actions auto-resolves; only\n * an explicit `false` restores the always-prompt behavior. Undefined is\n * treated as enabled so callers that don't know the flag stay relaxed.\n */\n autoApproveSafeHostActions?: boolean;\n /**\n * The box's REGISTERED origin URL (`BoxRegistration.originUrl`), used only\n * when this host has no working checkout for the box and `runGitRpc` has to\n * push from a scratch repo (the control-box case — the create worker's clone\n * is a temp dir it deletes).\n *\n * It must come from the registration, never from the box: the box could\n * rewrite its own `origin`, and pushing to an attacker-chosen URL with the\n * host's credential helper attached would hand over the token. Same invariant\n * the lease path states in `lease.ts`.\n */\n originUrl?: string;\n /** Best-effort logger. */\n log?: (line: string) => void;\n}\n\n/**\n * Host-side loader for the built-in cloud backends, injected by whichever\n * bundle owns this relay process.\n *\n * ## Why this is injected rather than imported\n *\n * The relay can't depend on the `@agentbox/sandbox-*` packages: that would\n * close a `sandbox-daytona → sandbox-cloud → sandbox-docker → relay` cycle in\n * the package.json deps. It used to reach them with a computed dynamic import\n * (`'@agentbox/sandbox-' + 'daytona'`) on the theory that esbuild would\n * constant-fold and inline the package. It does not — esbuild never bundles\n * `import(pkg)`, so the specifier stayed a runtime `node_modules` lookup. That\n * works in the pnpm dev tree (workspace symlinks) and fails on every npm\n * install, where the `@agentbox/*` packages are devDependencies bundled into\n * the CLI and therefore absent from `node_modules` entirely.\n *\n * So each bundle that hosts a relay registers a loader built from ITS OWN\n * literal-specifier provider map (the maps are already inlined there):\n * - the CLI's spawned relay bin — `AGENTBOX_CLOUD_BACKENDS` points at\n * `apps/cli/dist/cloud-backends.js`, side-loaded lazily in `bin.ts`.\n * - the hub / control box — `apps/hub/server.ts` registers in-process\n * before starting the daemon.\n *\n * `resolveBackend` returns `null` for anything it doesn't own (plugins,\n * `docker`), so the plugin registry stays the single gated path for external\n * providers.\n */\nexport interface CloudBackendLoader {\n /** Stable marker for logs + the build-time wiring check. */\n id?: string;\n /** Resolve a BUILT-IN backend; `null` means \"not mine — keep looking\". */\n resolveBackend(name: string): Promise<CloudBackend | null>;\n /** The `@agentbox/sandbox-cloud` cp helpers used by the download executor. */\n loadCloudCp(): Promise<CloudCpModule>;\n}\n\nlet cloudBackendLoader: CloudBackendLoader | undefined;\n\n/**\n * Register (or clear, with `undefined`) the host's built-in backend loader.\n * Must run before the relay starts serving — `startCloudKeepaliveLoop` caches a\n * failed resolve per backend name for the process lifetime.\n */\nexport function setCloudBackendLoader(loader: CloudBackendLoader | undefined): void {\n cloudBackendLoader = loader;\n cloudCpModule = undefined;\n}\n\n/**\n * Lazy backend resolver, in precedence order:\n * 1. the injected loader (built-ins, from the host bundle),\n * 2. the legacy bare-specifier import — only resolves in the pnpm dev tree or\n * for a standalone embedder that installed the packages itself,\n * 3. the plugin registry (external providers, imported by absolute path),\n * 4. throw.\n *\n * Built-ins are tried before plugins in both 1 and 2 so a plugin can never\n * shadow a shipped provider name.\n */\nexport async function resolveCloudBackend(name: string): Promise<CloudBackend> {\n if (cloudBackendLoader) {\n const injected = await cloudBackendLoader.resolveBackend(name);\n if (injected) return injected;\n }\n // Legacy fallback. The `'@agentbox/sandbox-' + '<name>'` specifiers stay\n // computed so esbuild leaves them alone instead of trying (and failing) to\n // inline a package the relay doesn't depend on. Reached only when no loader\n // was injected — i.e. the dev tree or a standalone embedder.\n if (name === 'daytona') {\n const pkg = '@agentbox/sandbox-' + 'daytona';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { daytonaBackend: CloudBackend }).daytonaBackend,\n );\n }\n if (name === 'hetzner') {\n const pkg = '@agentbox/sandbox-' + 'hetzner';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { hetznerBackend: CloudBackend }).hetznerBackend,\n );\n }\n if (name === 'vercel') {\n const pkg = '@agentbox/sandbox-' + 'vercel';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { vercelBackend: CloudBackend }).vercelBackend,\n );\n }\n if (name === 'e2b') {\n const pkg = '@agentbox/sandbox-' + 'e2b';\n return loadCloudBackend(\n pkg,\n async () => ((await import(pkg)) as { e2bBackend: CloudBackend }).e2bBackend,\n );\n }\n if (name === 'digitalocean') {\n const pkg = '@agentbox/sandbox-' + 'digitalocean';\n return loadCloudBackend(\n pkg,\n async () =>\n ((await import(pkg)) as { digitaloceanBackend: CloudBackend }).digitaloceanBackend,\n );\n }\n if (name === 'remote-docker') {\n const pkg = '@agentbox/sandbox-' + 'remote-docker';\n return loadCloudBackend(\n pkg,\n async () =>\n ((await import(pkg)) as { remoteDockerBackend: CloudBackend }).remoteDockerBackend,\n );\n }\n // External provider plugins: not bundle-inlined, so resolve from the same\n // `~/.agentbox/plugins.json` registry the CLI writes and `import()` the\n // recorded entry with a TRUE variable specifier. The relay runs on the host\n // (same ~/.agentbox), so the registry + the installed package are reachable.\n const plugin = pluginForProvider(name);\n if (plugin) {\n if (!isSupportedApiVersion(plugin.apiVersion)) {\n throw new Error(\n `relay: plugin '${plugin.packageName}' targets provider SDK v${String(plugin.apiVersion)}, which this AgentBox does not support`,\n );\n }\n return loadCloudBackend(plugin.packageName, async () => {\n const mod = (await import(pathToFileURL(plugin.resolvedEntry).href)) as {\n providerModule?: { provider?: { name?: string }; backend?: CloudBackend };\n providerModules?: { provider?: { name?: string }; backend?: CloudBackend }[];\n };\n const all = mod.providerModules ?? (mod.providerModule ? [mod.providerModule] : []);\n // Strict name match — never fall back to all[0] (wrong-backend hazard).\n const pm = all.find((m) => m.provider?.name === name);\n if (!pm?.backend) {\n throw new Error(`plugin '${plugin.packageName}' exposes no cloud backend for '${name}'`);\n }\n return pm.backend;\n });\n }\n throw new Error(`no host executor for cloud backend '${name}'`);\n}\n\n/**\n * True for \"the module isn't installed\" failures. The `code` check is the\n * durable one: Node's ESM resolver says `Cannot find package 'x' imported from\n * y` (ERR_MODULE_NOT_FOUND) while CJS says `Cannot find module` — matching only\n * the CJS wording let the raw ESM error through untranslated.\n */\nexport function isModuleNotFound(err: unknown): boolean {\n const code = (err as { code?: unknown } | null)?.code;\n if (code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND') return true;\n const msg = err instanceof Error ? err.message : String(err);\n return /cannot find (module|package)|MODULE_NOT_FOUND/i.test(msg);\n}\n\n/**\n * Run a provider's dynamic import, turning a missing-module failure into the\n * actionable \"no loader was injected\" error (other errors propagate unchanged).\n * Shared by every branch of `resolveCloudBackend`'s legacy fallback.\n */\nasync function loadCloudBackend(\n pkg: string,\n load: () => Promise<CloudBackend>,\n): Promise<CloudBackend> {\n try {\n return await load();\n } catch (err) {\n if (isModuleNotFound(err)) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `relay: cannot load '${pkg}' at runtime — no cloud-backend loader was injected and the package is not installed next to @agentbox/relay (the @madarco/agentbox CLI injects one via AGENTBOX_CLOUD_BACKENDS; the hub registers one in-process). Original: ${msg}`,\n );\n }\n throw err;\n }\n}\n\n/**\n * Re-mint the preview URL for a cloud box's `port` after a transport-level\n * failure (the host CloudBoxPoller saw ECONNREFUSED on the local port).\n * Hetzner reopens its SSH ControlMaster + `-L` forward; Daytona's permanent\n * CloudFront alias doesn't need refresh and this returns null.\n *\n * Takes the agentbox `boxId` (the one the relay knows), resolves it to the\n * backend's sandboxId via `~/.agentbox/state.json` the same way\n * `executeCloudAction` does, then asks the backend to refresh.\n *\n * Best-effort: any error during resolve/refresh returns null and the\n * poller stays on the (broken) URL — the next poll will trip the same\n * recovery hook on the next ECONNREFUSED. Throwing here would crash the\n * poller; we'd rather keep retrying.\n */\nexport async function refreshCloudPreviewUrl(\n backendName: string,\n boxId: string,\n port: number,\n): Promise<string | null> {\n try {\n const backend = await resolveCloudBackend(backendName);\n if (!backend.refreshPreviewUrl) return null;\n const lookup = await lookupCloudBox(boxId);\n const handle: CloudHandle = { sandboxId: lookup.cloudSandboxId };\n const url = await backend.refreshPreviewUrl(handle, port);\n return url.url;\n } catch {\n return null;\n }\n}\n\nexport async function executeCloudAction(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const log = deps.log ?? (() => {});\n log(`executing ${action.method} for box ${deps.boxId}`);\n\n if (action.method === 'git.push' || action.method === 'git.fetch') {\n return runGitRpc(action, deps);\n }\n if (action.method === 'cp.toHost' || action.method === 'cp.fromHost') {\n return runCpRpc(action, deps);\n }\n if (\n action.method === 'download.workspace' ||\n action.method === 'download.env' ||\n action.method === 'download.config' ||\n action.method === 'download.claude'\n ) {\n return runDownloadRpc(action, deps);\n }\n if (action.method === 'checkpoint.create') {\n return runCheckpointRpc(action, deps);\n }\n if (action.method === 'browser.open.mirror') {\n return runBrowserOpenMirror(action, deps);\n }\n if (action.method.startsWith('gh.pr.')) {\n return runGhPrRpc(action, deps);\n }\n if (action.method.startsWith('gh.run.')) {\n return runGhRunRpc(action, deps);\n }\n if (action.method === 'gh.api') {\n return runGhApiRpc(action, deps);\n }\n if (action.method.startsWith('integration.')) {\n return runIntegrationRpc(action, deps);\n }\n if (action.method === 'git.clone' || action.method === 'gh.repo.clone') {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${action.method}: not yet implemented for this box. Run \\`gh\\` / \\`git\\` on the host directly for now.\\n`,\n };\n }\n return {\n exitCode: 1,\n stdout: '',\n stderr: `host executor for '${action.method}' is not yet supported for cloud boxes\\n`,\n };\n}\n\n/**\n * Cloud `gh.pr.<op>` executor. Simpler than `runGitRpc` because nothing\n * needs to round-trip into the sandbox — `gh` only needs the host repo\n * (already at the right remote in `lookup.workspacePath`).\n *\n * Mirrors the docker handler's confirmation matrix exactly: `view` / `list`\n * are silent, write ops go through `askPrompt`, `checkout` is opt-in via\n * `AGENTBOX_GH_PR_CHECKOUT=allow`, and `merge` refuses `AGENTBOX_PROMPT=off`\n * bypass unless `AGENTBOX_GH_FORCE=1`. When no SSE subscriber is attached,\n * write-op behavior is gated by `AGENTBOX_GH_NO_SUB` (`deny` default,\n * `allow`, or `prompt`) — same shape as `AGENTBOX_GIT_PUSH_NO_SUB`.\n */\nasync function runGhPrRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const op = action.method.slice('gh.pr.'.length);\n if (!isGhPrOp(op)) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown gh.pr.* op: ${op}\\n`,\n };\n }\n // Env-only refusals first — cheap, deterministic, no fs/process calls.\n const mergeBypass = refuseMergeBypass(op);\n if (mergeBypass) return mergeBypass;\n const checkoutOptIn = refuseCheckoutByDefault(op);\n if (checkoutOptIn) return checkoutOptIn;\n\n const params = (action.params ?? {}) as GhPrRpcParams;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n\n const lookup = await lookupCloudBox(deps.boxId);\n\n if (op === 'checkout') {\n // The cloud host repo isn't bind-mounted by anything; the only \"branch\n // we must not stomp\" concern is the host's own current branch, which is\n // a generic dirty-tree / \"already on this branch\" question gh itself\n // surfaces. We still refuse a dirty tree.\n const guard = await checkoutGuards(lookup.workspacePath, []);\n if (guard) return guard;\n }\n\n // Host-initiated `gh pr <op>` (from `agentbox git pr <op> <box>`) skips\n // the confirm prompt — but only with a valid scope-matched, params-hash-\n // bound one-time token. If a token is *present* but invalid, reject\n // hard: attack signal. Only fall through to the prompt when no token was\n // claimed. Destructive-op env opt-ins above still apply.\n const tokenClaimedGhCloud = typeof params.hostInitiated === 'string';\n const incomingHashGhCloud = hashRpcParams(params);\n const hostInitiatedGhOk =\n !GH_PR_READ_ONLY_OPS.has(op) &&\n tokenClaimedGhCloud &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n `gh.pr.${op}`,\n incomingHashGhCloud,\n ) ??\n false);\n if (!GH_PR_READ_ONLY_OPS.has(op) && tokenClaimedGhCloud && !hostInitiatedGhOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n // Safe subset: opening a PR (relay forces `--head <box-branch>`) and PR\n // comments auto-approve under the flag, audited. merge/checkout/review/close\n // keep prompting.\n // A `create` with an EXPLICIT `--head` is excluded from the safe subset — that\n // head could name any branch (e.g. `main`); it falls back to the prompt. A\n // headless `create` has its head forced to the box's sanctioned branch below.\n const ghSafeAuto =\n GH_PR_SAFE_AUTO_APPROVE_OPS.has(op) &&\n deps.autoApproveSafeHostActions !== false &&\n !prCreateHasExplicitHead(op, args);\n if (ghSafeAuto && !hostInitiatedGhOk) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `gh pr ${op} from cloud box ${deps.boxName ?? deps.boxId}`,\n detail: args.join(' ').slice(0, 200),\n context: { command: `gh pr ${op}`, cwd: params.path, argv: args },\n },\n `safe: gh pr ${op}`,\n );\n }\n if (\n !GH_PR_READ_ONLY_OPS.has(op) &&\n !ghSafeAuto &&\n !hostInitiatedGhOk &&\n deps.prompts &&\n deps.subscribers\n ) {\n const detail = args.join(' ').slice(0, 200);\n const ctx = {\n kind: 'confirm' as const,\n message: `Allow gh pr ${op} from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail,\n defaultAnswer: 'n' as const,\n context: {\n command: `gh pr ${op}`,\n cwd: params.path,\n argv: args,\n },\n };\n const hasSubscriber = deps.subscribers.count(deps.boxId) > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.(`gh.pr.${op} auto-approved (no subscribers, AGENTBOX_GH_NO_SUB=allow)`);\n // fall through\n } else {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx, {\n ttlMs: 5 * 60 * 1000,\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n } else {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx);\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n\n // Default `--head` to the box's branch for `create` (the host repo cwd isn't\n // on the box branch, so gh can't infer it). Probed from the box; a failed\n // probe leaves args unchanged (today's behavior).\n let finalArgs = args;\n const containerPath = params.path ?? '/workspace';\n const needsHeadProbe =\n op === 'create' && !args.some((a) => a === '--head' || a.startsWith('--head='));\n if (needsHeadProbe) {\n const backend = await resolveCloudBackend(deps.backendName);\n const handle: CloudHandle = { sandboxId: lookup.cloudSandboxId };\n const branchProbe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --abbrev-ref HEAD`,\n );\n const branch = branchProbe.exitCode === 0 ? (branchProbe.stdout ?? '').trim() : '';\n // Prefer the host-sanctioned branch so a headless PR targets the box's own\n // work (and matches the safe-auto gate above), not whatever HEAD the agent\n // may have switched to. Fall back to the probed HEAD when unknown.\n finalArgs = injectPrCreateHead(op, lookup.sanctionedBranch ?? branch, finalArgs);\n }\n // Never let `gh` fall back to the host repo's checked-out branch.\n if (prCreateNeedsHead(op, finalArgs)) return PR_CREATE_NO_HEAD_REFUSAL;\n const prRun = ghRunContext(lookup.workspacePath, deps.originUrl, finalArgs);\n return runHostGh(['pr', op, ...prRun.args], prRun.cwd);\n}\n\n/**\n * Cloud-side confirm gate for a write op. Mirrors the prompt / no-subscriber\n * handling in `runGhPrRpc` (`AGENTBOX_GH_NO_SUB` deny/allow/prompt). Returns a\n * ready-to-send denial `HostActionResult` to abort, or `null` to proceed.\n */\nasync function cloudWriteConfirm(\n deps: CloudActionExecutorDeps,\n command: string,\n cwd: string | undefined,\n args: string[],\n): Promise<HostActionResult | null> {\n if (!deps.prompts || !deps.subscribers) return null;\n const ctx = {\n kind: 'confirm' as const,\n message: `Allow ${command} from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail: args.join(' ').slice(0, 200),\n defaultAnswer: 'n' as const,\n context: { command, cwd, argv: args },\n };\n const hasSubscriber = deps.subscribers.count(deps.boxId) > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.(`${command} auto-approved (no subscribers, AGENTBOX_GH_NO_SUB=allow)`);\n return null;\n }\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx, {\n ttlMs: 5 * 60 * 1000,\n });\n return verdict.answer === 'y' ? null : { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, ctx);\n return verdict.answer === 'y' ? null : { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n}\n\n/**\n * Cloud `gh.run.<op>` executor (list / view / rerun). `list` / `view` are\n * silent reads; `rerun` re-triggers CI and goes through `cloudWriteConfirm`.\n */\nasync function runGhRunRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const op = action.method.slice('gh.run.'.length);\n if (!isGhRunOp(op)) {\n return { exitCode: 64, stdout: '', stderr: `unknown gh.run.* op: ${op}\\n` };\n }\n const params = (action.params ?? {}) as GhRunRpcParams;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n const lookup = await lookupCloudBox(deps.boxId);\n if (!GH_RUN_READ_ONLY_OPS.has(op)) {\n if (deps.autoApproveSafeHostActions !== false) {\n // `gh run rerun` only re-triggers the project's own CI — safe subset.\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `gh run ${op} from cloud box ${deps.boxName ?? deps.boxId}`,\n detail: args.join(' ').slice(0, 200),\n context: { command: `gh run ${op}`, cwd: params.path, argv: args },\n },\n `safe: gh run ${op}`,\n );\n } else {\n const denied = await cloudWriteConfirm(deps, `gh run ${op}`, params.path, args);\n if (denied) return denied;\n }\n }\n const runRun = ghRunContext(lookup.workspacePath, deps.originUrl, args);\n return runHostGh(['run', op, ...runRun.args], runRun.cwd);\n}\n\n/**\n * Cloud `gh.api` executor. Read-only, allowlisted endpoints only — same guards\n * as the docker `handleGhApiRpc`. No prompt (matches `gh pr view`).\n */\nasync function runGhApiRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as GhApiRpcParams;\n const endpoint = typeof params.endpoint === 'string' ? params.endpoint : '';\n if (!isAllowedGhApiEndpoint(endpoint)) return GH_API_ENDPOINT_REFUSAL;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n const callRefusal = refuseGhApiCall(endpoint, args);\n if (callRefusal) return callRefusal;\n const ghReady = await assertGhReady();\n if (ghReady) return ghReady;\n const lookup = await lookupCloudBox(deps.boxId);\n const apiRun = ghRunContext(lookup.workspacePath, undefined, args);\n return runHostGh(['api', endpoint, ...apiRun.args], apiRun.cwd);\n}\n\n/**\n * Cloud `integration.<service>.<op>` executor. Mirrors the docker handler\n * exactly — same descriptor lookup, same read/write gating, same host\n * binary invocation. Reuses the gh-pr `cloudWriteConfirm` helper because\n * the no-subscriber fallback (`AGENTBOX_GH_NO_SUB` env knob) covers every\n * gated host action by design.\n */\nasync function runIntegrationRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const parsed = parseIntegrationMethod(action.method);\n if (!parsed) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration method shape: ${action.method}\\n`,\n };\n }\n const connector = getConnector(parsed.service);\n if (!connector) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `unknown integration service: ${parsed.service}\\n`,\n };\n }\n const opDesc = connector.ops[parsed.op];\n if (!opDesc) {\n return makeIntegrationOpRefusal(\n parsed.service,\n parsed.op,\n connector.hostBin,\n Object.keys(connector.ops),\n );\n }\n const params = (action.params ?? {}) as IntegrationRpcParams;\n const args = Array.isArray(params.args)\n ? params.args.filter((a): a is string => typeof a === 'string')\n : [];\n\n const callRefusal = refuseIntegrationCall(opDesc, args);\n if (callRefusal) return callRefusal;\n\n // Cloud boxes don't register worktrees the same way docker boxes do; the\n // closest analogue is `lookupCloudBox`'s `workspacePath` (the host-side\n // path the cloud provider records as the box's project root). Use it to\n // read the layered config and fire the enablement gate — same envelope\n // shape the docker handler returns. Placed after `refuseIntegrationCall`\n // so the structural / op-level checks (which don't need the box record)\n // still short-circuit cleanly on a malformed registry; the gate runs\n // before `assertIntegrationReady`, the prompt, and the host spawn so a\n // disabled integration is never user-visible as a permission prompt.\n const lookup = await lookupCloudBox(deps.boxId);\n const enableRefusal = await refuseIfIntegrationDisabled(parsed.service, lookup.workspacePath);\n if (enableRefusal) return enableRefusal;\n\n const ready = await assertIntegrationReady(connector);\n if (ready) return ready;\n\n if (opDesc.write) {\n if (deps.autoApproveSafeHostActions !== false) {\n // Integration writes go to the connected external service (not the\n // host), so they're in the safe subset — audited, no prompt.\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `integration ${parsed.service} ${parsed.op} from cloud box ${deps.boxName ?? deps.boxId}`,\n detail: args.join(' ').slice(0, 200),\n context: {\n command: `integration ${parsed.service} ${parsed.op}`,\n cwd: params.path,\n argv: args,\n },\n },\n `safe: integration ${parsed.service} ${parsed.op}`,\n );\n } else {\n const tokenClaimed = typeof params.hostInitiated === 'string';\n const incomingHash = hashRpcParams(params);\n const tokenOk =\n tokenClaimed &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n action.method,\n incomingHash,\n ) ??\n false);\n if (tokenClaimed && !tokenOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n if (!tokenOk) {\n const denied = await cloudWriteConfirm(\n deps,\n `integration ${parsed.service} ${parsed.op}`,\n params.path,\n args,\n );\n if (denied) return denied;\n }\n }\n }\n\n return runHostIntegration(connector, opDesc, args, lookup.workspacePath);\n}\n\n/**\n * Mirror an in-box `browser.open` notification on the host. The action runs\n * detached from the box's `/rpc` (the in-box handler responded 200 long\n * before queuing this), so blocking here doesn't tie up an agent — we can\n * happily wait for the host user's verdict with a TTL fallback.\n *\n * On `y` we spawn `open <url>` on the host. Any other verdict (deny / TTL\n * timeout / no subscribers) silently drops the link. Always resolves\n * exit 0 because the box doesn't observe the result.\n */\nasync function runBrowserOpenMirror(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as { url?: string };\n const url = typeof params.url === 'string' ? params.url.trim() : '';\n if (!url || !/^https?:\\/\\//i.test(url)) {\n return { exitCode: 0, stdout: '', stderr: '' };\n }\n if (!deps.prompts || !deps.subscribers) return { exitCode: 0, stdout: '', stderr: '' };\n if (process.env['AGENTBOX_PROMPT'] === 'off') {\n return { exitCode: 0, stdout: '', stderr: '' };\n }\n // 90s TTL matches the docker browser.open behavior closely enough that an\n // attached user has plenty of time to answer without leaving a stale\n // prompt indefinitely.\n const TTL_MS = 90_000;\n try {\n const verdict = await askPrompt(\n deps.prompts,\n deps.subscribers,\n deps.boxId,\n {\n kind: 'confirm',\n message: `Open link from cloud box ${deps.boxName ?? deps.boxId} on the host?`,\n detail: url,\n defaultAnswer: 'n',\n context: { command: 'browser.open', argv: [url] },\n },\n { ttlMs: TTL_MS },\n );\n if (verdict.answer === 'y' && !verdict.cancelled) {\n // Open on the host's default handler (`open` on macOS, `xdg-open` on\n // Linux). Spawn detached so the relay loop isn't blocked; the box never\n // observes the outcome.\n const { spawn } = await import('node:child_process');\n const child = spawn(hostOpenCommand(), [url], { stdio: 'ignore', detached: true });\n child.unref();\n }\n } catch (err) {\n deps.log?.(`browser.open.mirror failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n return { exitCode: 0, stdout: '', stderr: '' };\n}\n\ninterface BoxLookup {\n workspacePath: string;\n cloudSandboxId: string;\n /**\n * Branch the host has sanctioned for this box's pushes (defaults to the\n * create-time `workspaceBranch`). The push gate auto-approves a push only to\n * a scratch branch or this value.\n */\n sanctionedBranch?: string;\n}\n\nasync function lookupCloudBox(boxId: string): Promise<BoxLookup> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok') {\n throw new Error(`box ${boxId} not in ~/.agentbox/state.json`);\n }\n const sid = hit.box.cloud?.sandboxId;\n if (!sid) {\n throw new Error(`box ${boxId} has no cloud.sandboxId — record is malformed`);\n }\n return {\n workspacePath: hit.box.workspacePath,\n cloudSandboxId: sid,\n sanctionedBranch: hit.box.cloud?.sanctionedBranch ?? hit.box.cloud?.workspaceBranch,\n };\n}\n\n/**\n * The box's registered host workspace (the host dir that mirrors `/workspace`),\n * used as the base for resolving relative host paths in `cp`/`download` RPCs.\n * Returns `undefined` when the box isn't in state. Shared by the docker\n * (server.ts) and cloud handlers so a relative host path never silently\n * resolves against the long-lived relay daemon's CWD (which is arbitrary — one\n * relay serves many boxes/projects).\n */\nexport async function boxWorkspacePath(boxId: string): Promise<string | undefined> {\n const state = await readState();\n const hit = findBox(boxId, state);\n return hit.kind === 'ok' ? hit.box.workspacePath : undefined;\n}\n\n/**\n * The realpath'd host source paths this box already approved via its `carry:`\n * block, so the cp auto-approve gate can exempt a secret file that the user\n * already consented to copy in at create time. Best-effort: empty set on any\n * read failure (→ secret files fall back to prompting). Shared by the docker\n * and cloud cp handlers.\n */\nexport async function boxCarriedHostPaths(boxId: string): Promise<Set<string>> {\n const out = new Set<string>();\n try {\n const state = await readState();\n const hit = findBox(boxId, state);\n const entries = hit.kind === 'ok' ? hit.box.carry?.entries : undefined;\n for (const e of entries ?? []) out.add(await realpathSafe(e.src));\n } catch {\n /* best-effort */\n }\n return out;\n}\n\n// resolveHostPath's pure decision moved to `@agentbox/core`'s sync/files.ts.\n// Re-exported here so `server.ts` (and the cp/download call sites below) keep\n// importing it from `./host-actions.js` unchanged.\nexport { resolveHostPath };\n\n/**\n * The `@agentbox/sandbox-cloud` cp helpers the download executor needs. Kept\n * out of the relay bundle for the same dependency-cycle reason as the provider\n * backends — the injected `CloudBackendLoader` supplies them; the computed\n * specifier below is the same dev-tree-only fallback.\n */\nexport interface CloudCpModule {\n pullCloudDirContents(\n backend: CloudBackend,\n handle: CloudHandle,\n boxSrc: string,\n hostDst: string,\n ): Promise<{ finalPath: string }>;\n}\n\nlet cloudCpModule: CloudCpModule | undefined;\nasync function loadCloudCp(): Promise<CloudCpModule> {\n if (cloudCpModule) return cloudCpModule;\n if (cloudBackendLoader) {\n cloudCpModule = await cloudBackendLoader.loadCloudCp();\n return cloudCpModule;\n }\n // Legacy fallback — see resolveCloudBackend.\n const pkg = '@agentbox/sandbox-' + 'cloud';\n try {\n const mod = (await import(pkg)) as CloudCpModule;\n cloudCpModule = mod;\n return mod;\n } catch (err) {\n if (isModuleNotFound(err)) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `relay: cannot load '${pkg}' at runtime — no cloud-backend loader was injected and the package is not installed next to @agentbox/relay (the @madarco/agentbox CLI injects one via AGENTBOX_CLOUD_BACKENDS; the hub registers one in-process). Original: ${msg}`,\n );\n }\n throw err;\n }\n}\n\nasync function runCpRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const method = action.method as CpMethod;\n const params = (action.params ?? {}) as CpRpcParams;\n let norm: { sources: string[]; dest: string };\n try {\n norm = normalizeCpParams(method, params);\n } catch (err) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run cp host-side\\n',\n };\n }\n const direction = method === 'cp.toHost' ? 'box -> host' : 'host -> box';\n // Resolve host paths against THIS box's workspace so a relative path doesn't\n // land under the relay daemon's CWD (which belongs to whichever project\n // started the relay), and so the consent prompt shows the real destination.\n const lookup = await lookupCloudBox(deps.boxId);\n const boxName = deps.boxName ?? deps.boxId;\n const {\n argv: cpArgs,\n detail,\n contextArgv,\n } = buildCpArgv({\n method,\n boxName,\n sources: norm.sources,\n dest: norm.dest,\n resolveHost: (p) => resolveHostPath(lookup.workspacePath, p),\n flags: cpFlags(params),\n });\n // Same askPrompt UX as docker's /rpc handler — keeps the in-box agent from\n // pulling host files / scattering box files without explicit consent. A\n // transfer contained in the box project folder (non-secret for host->box)\n // auto-approves under the safe flag, mirroring the docker handler.\n const cpHostPaths =\n method === 'cp.toHost'\n ? [resolveHostPath(lookup.workspacePath, norm.dest)]\n : norm.sources.map((s) => resolveHostPath(lookup.workspacePath, s));\n const cpAuto = await canAutoApproveTransfer({\n enabled: deps.autoApproveSafeHostActions !== false,\n workspacePath: lookup.workspacePath,\n hostPaths: cpHostPaths,\n checkSecret: method === 'cp.fromHost',\n carried: method === 'cp.fromHost' ? await boxCarriedHostPaths(deps.boxId) : undefined,\n });\n if (cpAuto) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `cp (${direction}) on ${boxName}`,\n detail,\n context: { command: method, argv: contextArgv },\n },\n method === 'cp.toHost' ? 'safe: contained copy to host' : 'safe: contained copy from host',\n );\n } else if (deps.prompts && deps.subscribers) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow cp (${direction}) on ${boxName}?`,\n detail,\n defaultAnswer: 'n',\n context: { command: method, argv: contextArgv },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n // Converge on the docker path: re-shell the installed `agentbox cp`. Its\n // `isCloud` branch routes to the cloud provider's uploadPath/downloadPath, so\n // excludes, the size guard, and provider routing are honored identically to a\n // host-typed `agentbox cp` (the old direct-primitive path silently dropped\n // them). cwd = the box workspace makes project-config lookup box-correct.\n const argv = [process.execPath, entry, ...cpArgs];\n const result = await execa(argv[0]!, argv.slice(1), {\n reject: false,\n cwd: lookup.workspacePath,\n });\n return {\n exitCode: result.exitCode ?? 1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\n/**\n * Capture a checkpoint by shelling out to the installed `agentbox` CLI\n * (same decoupling as the docker handler — the CLI owns checkpoint name\n * allocation, the `--set-default` config write, snapshot store layout, and\n * the cloud-snapshot creation via `provider.checkpoint.create`). The CLI's\n * `checkpoint create` is already provider-aware, so this path works for\n * both backends; we just hand it the box id.\n */\nasync function runCheckpointRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as Partial<CheckpointRpcParams>;\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: 'relay: AGENTBOX_CLI_ENTRY not set; cannot run checkpoint host-side\\n',\n };\n }\n // Vercel checkpoints stop + reboot the box: `sb.snapshot()` powers off the\n // microVM (resume is lazy on the next SDK call). When an interactive wrapper\n // is attached, warn + require confirmation before we yank the box out from\n // under it. Other backends snapshot without stopping (docker `docker commit`,\n // hetzner no-pause, daytona), so they stay prompt-free. No attached wrapper →\n // proceed (a headless caller already knows the box will reboot).\n if (\n deps.backendName === 'vercel' &&\n deps.autoApproveSafeHostActions === false &&\n deps.prompts &&\n deps.subscribers &&\n deps.subscribers.count(deps.boxId) > 0\n ) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Create checkpoint on ${deps.boxName ?? deps.boxId}? The vercel box will stop and reboot.`,\n detail: params.name ? `checkpoint: ${params.name}` : '(auto-named)',\n defaultAnswer: 'n',\n context: { command: 'checkpoint create', argv: params.name ? [params.name] : [] },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'checkpoint denied by user\\n' };\n }\n } else if (\n deps.backendName === 'vercel' &&\n deps.subscribers &&\n deps.subscribers.count(deps.boxId) > 0\n ) {\n // Checkpoint is a safe subset op (the box's own snapshot); audit the\n // reboot-causing auto-approval so it's still visible in the event feed.\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `checkpoint create on ${deps.boxName ?? deps.boxId} (vercel box will stop and reboot)`,\n detail: params.name ? `checkpoint: ${params.name}` : '(auto-named)',\n context: { command: 'checkpoint create', argv: params.name ? [params.name] : [] },\n },\n 'safe: checkpoint create',\n );\n }\n\n const argv = [process.execPath, entry, 'checkpoint', 'create', deps.boxId];\n if (params.name) argv.push('--name', params.name);\n // --merged is docker-image-layer specific (flatten). For cloud snapshots\n // it's a no-op; pass it through anyway so the CLI's docker branch sees it\n // and the cloud branch ignores it cleanly.\n if (params.merged === true) argv.push('--merged');\n if (params.setDefault === true) argv.push('--set-default');\n if (params.replace === true) argv.push('--replace');\n const result = await execa(argv[0]!, argv.slice(1), { reject: false });\n return {\n exitCode: result.exitCode ?? 1,\n stdout: result.stdout ?? '',\n stderr: result.stderr ?? '',\n };\n}\n\nasync function runDownloadRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as Partial<DownloadRpcParams>;\n const kind = parseDownloadKind(action.method);\n // Only `workspace` lands cleanly on cloud today — env/config/claude live in\n // per-agent volumes and aren't routed yet (Phase 6 follow-up; see backlog\n // 2.2). Surface a clear error instead of pretending to succeed.\n if (kind !== 'workspace') {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `download.${kind} is not yet supported for cloud boxes (only download.workspace is)\\n`,\n };\n }\n const lookup = await lookupCloudBox(deps.boxId);\n // params.hostPath is reserved in the wire shape; v1 lands /workspace under\n // box.workspacePath (the host project root), matching docker's default. A\n // relative override resolves against the box workspace, not the relay's CWD.\n const hostDst =\n typeof params.hostPath === 'string' && params.hostPath.length > 0\n ? resolveHostPath(lookup.workspacePath, params.hostPath)\n : lookup.workspacePath;\n // Auto-approve when the destination stays inside the box project folder\n // (the default does); an escaping override still prompts.\n const dlAuto = await canAutoApproveTransfer({\n enabled: deps.autoApproveSafeHostActions !== false,\n workspacePath: lookup.workspacePath,\n hostPaths: [hostDst],\n checkSecret: false,\n });\n if (dlAuto) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `download (${kind}) from ${deps.boxName ?? deps.boxId}`,\n detail: params.hostPath ?? '(default host location)',\n context: { command: action.method, argv: params.hostPath ? [params.hostPath] : [] },\n },\n 'safe: contained download',\n );\n } else if (deps.prompts && deps.subscribers) {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow download (${kind}) from ${deps.boxName ?? deps.boxId}?`,\n detail: params.hostPath ?? '(default host location)',\n defaultAnswer: 'n',\n context: {\n command: action.method,\n argv: params.hostPath ? [params.hostPath] : [],\n },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n const backend = await resolveCloudBackend(deps.backendName);\n const handle: CloudHandle = { sandboxId: lookup.cloudSandboxId };\n const cp = await loadCloudCp();\n try {\n const result = await cp.pullCloudDirContents(backend, handle, '/workspace', hostDst);\n return { exitCode: 0, stdout: `${result.finalPath}\\n`, stderr: '' };\n } catch (err) {\n return {\n exitCode: 1,\n stdout: '',\n stderr: `download failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n}\n\n/**\n * Git RPC executor for cloud boxes. The push direction:\n *\n * 1. In the sandbox, write a bundle of the per-box branch.\n * 2. Download the bundle to the host.\n * 3. Fetch the bundle ref into the host repo (always a fast-forward).\n * 4. Run the real git push from the host repo.\n *\n * Fetch direction is the mirror: host fetches origin, bundles, uploads,\n * sandbox fetches from the bundle, in-box `agentbox-ctl git pull` then\n * does its local merge as today.\n */\n/**\n * Where the host runs its half of a git RPC, and what it pushes to.\n *\n * On a laptop this is the user's real checkout: `dir` is the working copy and\n * `remote` is whatever `origin` resolves to there. On a **control box** there is\n * no checkout at all — the create worker clones into a temp dir and deletes it\n * in a `finally` — so `dir` is a throwaway repo we initialize per call and\n * `remote` is the registered origin URL.\n *\n * A scratch repo is enough because `git bundle create <file> <branch>` is\n * self-contained: it carries the branch's full history with no prerequisites, so\n * unbundling into an empty repo yields a pushable ref. Nothing needs to persist\n * between pushes, which is why the hub keeps no per-project clones.\n */\nexport interface HostGitRepo {\n dir: string;\n /** Explicit push target — a URL for scratch repos, else the caller's remote name. */\n remote: string;\n scratch: boolean;\n cleanup: () => Promise<void>;\n}\n\n/**\n * The push URL a scratch (checkout-less) host repo should use. SSH/scp remotes\n * are rewritten to plain HTTPS; anything already HTTPS — or any URL shape\n * `toHttpsUrl` can't parse — is passed through untouched, so an unusual remote\n * fails at git with its own message instead of here.\n */\nfunction httpsOriginForScratchPush(origin: string): string {\n if (/^https?:\\/\\//i.test(origin)) return origin;\n try {\n return toHttpsUrl(origin);\n } catch {\n return origin;\n }\n}\n\nexport async function resolveHostGitRepo(\n workspacePath: string,\n deps: CloudActionExecutorDeps,\n remoteName: string,\n): Promise<HostGitRepo> {\n if (workspacePath.length > 0 && existsSync(workspacePath)) {\n return {\n dir: workspacePath,\n remote: remoteName,\n scratch: false,\n cleanup: () => Promise.resolve(),\n };\n }\n // No host checkout. Only the REGISTERED origin can be trusted as a push\n // target — see the `originUrl` doc on CloudActionExecutorDeps.\n const rawOrigin = deps.originUrl?.trim() ?? '';\n if (rawOrigin.length === 0) {\n throw new Error(\n `host-side git is unavailable for box ${deps.boxId}: its host repo (${workspacePath || '<unset>'}) does not exist ` +\n `and the box has no registered origin URL to push to. Adopt the box on a host with a checkout, or re-register it.`,\n );\n }\n // A checkout-less host is a control box, which authenticates git through a\n // credential helper (`hub.gitAuth=gh`) or an App token — never an SSH key. An\n // scp-form `git@github.com:owner/repo` origin therefore dies at host-key\n // verification before auth is ever consulted, so rewrite it to the HTTPS URL\n // the helper covers. Mirrors the create worker's clone (`hub-worker.ts`),\n // which has always done this — without it the clone side works and the push\n // side fails for every SSH-origin project.\n const origin = httpsOriginForScratchPush(rawOrigin);\n const dir = await mkdtemp(join(tmpdir(), 'agentbox-git-scratch-'));\n const init = await execa('git', ['-C', dir, 'init', '--quiet'], { reject: false });\n if ((init.exitCode ?? 1) !== 0) {\n await rm(dir, { recursive: true, force: true });\n throw new Error(`could not initialize a scratch git repo: ${init.stderr ?? ''}`);\n }\n return {\n dir,\n remote: origin,\n scratch: true,\n cleanup: () => rm(dir, { recursive: true, force: true }),\n };\n}\n\nasync function runGitRpc(\n action: HostAction,\n deps: CloudActionExecutorDeps,\n): Promise<HostActionResult> {\n const params = (action.params ?? {}) as GitRpcParams;\n const lookup = await lookupCloudBox(deps.boxId);\n const backend = await resolveCloudBackend(deps.backendName);\n const handle = { sandboxId: lookup.cloudSandboxId };\n\n // The in-box ctl sends `params.path = process.cwd()`. When the user runs\n // `agentbox-ctl git push` from anywhere outside /workspace (e.g. $HOME),\n // that path won't be a git repo and `git rev-parse` would fail. Fall back\n // to /workspace whenever the supplied path can't resolve a git dir — the\n // per-box branch only ever lives at /workspace anyway.\n let containerPath = params.path ?? '/workspace';\n if (containerPath !== '/workspace') {\n const probe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --git-dir`,\n );\n if (probe.exitCode !== 0) containerPath = '/workspace';\n }\n\n // 1. Resolve the box's current branch (the per-box `agentbox/<name>`).\n const branchProbe = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} rev-parse --abbrev-ref HEAD`,\n );\n const branch = (branchProbe.stdout ?? '').trim();\n if (branchProbe.exitCode !== 0 || !isResolvedBranch(branch)) {\n return {\n exitCode: branchProbe.exitCode || 1,\n stdout: '',\n stderr: `failed to resolve branch in sandbox ${containerPath}: ${branchProbe.stderr || branch}`,\n };\n }\n\n // Host-only landing: copy the box's branch into the host's *local* repo\n // (no remote push, nothing published). This is the push flow's bundle\n // pull-back steps without the final `git push` — so it skips the confirm\n // gate below entirely. Destination defaults to the box's branch name.\n if (params.hostOnly) {\n // Unlike push/fetch, this one has nowhere to go without a real checkout —\n // its whole purpose is to leave the branch in the host's repo. A scratch\n // repo we delete would be a no-op dressed up as a success.\n if (lookup.workspacePath.length === 0 || !existsSync(lookup.workspacePath)) {\n return {\n exitCode: 64,\n stdout: '',\n stderr:\n `--host-only is unavailable for box ${deps.boxId}: this host has no working copy of the project ` +\n `(${lookup.workspacePath || '<unset>'} does not exist). Boxes created by a control box have no host ` +\n `checkout — push to the remote instead, or adopt the box on a machine that has one.\\n`,\n };\n }\n const dest = resolveLandDest(branch, params.as);\n const stageSave = await mkdtemp(join(tmpdir(), 'agentbox-git-save-'));\n const hostBundleSave = join(stageSave, 'op.bundle');\n const remoteBundleSave = '/tmp/agentbox-rpc-save.bundle';\n try {\n const make = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} bundle create ${shellQuote(remoteBundleSave)} ${shellQuote(branch)}`,\n );\n if (make.exitCode !== 0) {\n return {\n exitCode: make.exitCode,\n stdout: '',\n stderr: `bundle create failed: ${make.stderr || make.stdout}`,\n };\n }\n await backend.downloadFile(handle, remoteBundleSave, hostBundleSave);\n const refspec = landRefspec(branch, dest, params.force);\n const landed = await execa(\n 'git',\n ['-C', lookup.workspacePath, 'fetch', hostBundleSave, refspec],\n { reject: false },\n );\n if ((landed.exitCode ?? 1) !== 0) {\n return {\n exitCode: landed.exitCode ?? 1,\n stdout: landed.stdout ?? '',\n stderr: `host git fetch from bundle failed: ${landed.stderr ?? ''}`,\n };\n }\n return {\n exitCode: 0,\n stdout: `branch ${dest} available in ${lookup.workspacePath}\\n${landed.stdout ?? ''}`,\n stderr: landed.stderr ?? '',\n };\n } finally {\n await rm(stageSave, { recursive: true, force: true });\n await backend.exec(handle, `rm -f ${shellQuote(remoteBundleSave)}`).catch(() => {\n /* best-effort */\n });\n }\n }\n\n // Gate `git.push` (and only `git.push`) behind the same host-side confirm\n // prompt the Docker provider already uses. The wrapper's SSE subscriber on\n // /admin/prompts/stream surfaces it as a footer y/N; `askPrompt` returns\n // auto-`y` when AGENTBOX_PROMPT=off (matches Docker behavior).\n // The gate is bypassed for pushes to a *sanctioned* branch: the box's own\n // `agentbox/<name>` scratch branch (always its job), or the branch the host\n // last put the box on (`sanctionedBranch`). A scratch push bypasses\n // unconditionally; the sanctioned-but-non-scratch bypass is part of the safe\n // subset, so it honors `box.autoApproveSafeHostActions` and leaves an audit\n // trail. An agent that self-switches HEAD to another branch still prompts.\n const isScratch = isScratchBranch(branch);\n const safeApproveOn = deps.autoApproveSafeHostActions !== false;\n const isSanctionedNonScratch =\n !isScratch && safeApproveOn && isSanctionedPushBranch(branch, lookup.sanctionedBranch);\n const bypassPushGate = isScratch || isSanctionedNonScratch;\n if (action.method === 'git.push' && isSanctionedNonScratch) {\n deps.prompts?.noteAutoApprove(\n deps.boxId,\n {\n kind: 'confirm',\n message: `git push to sanctioned branch ${branch} on ${deps.boxName ?? deps.boxId}`,\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n },\n 'safe: sanctioned-branch push',\n );\n }\n // Host-initiated pushes (driven by `agentbox git push <box>`) skip the\n // confirm prompt — but only with a valid scope-matched, params-hash-bound\n // one-time token. If a token is *present* but invalid (mutated args,\n // replayed, expired), reject hard: that's an attack signal. Only fall\n // through to the prompt when no token was claimed.\n const tokenClaimedGit = typeof params.hostInitiated === 'string';\n const incomingHashGit = hashRpcParams(params);\n const hostInitiatedOk =\n !bypassPushGate &&\n tokenClaimedGit &&\n (deps.hostInitiatedTokens?.consume(\n params.hostInitiated,\n deps.boxId,\n 'git.push',\n incomingHashGit,\n ) ??\n false);\n if (action.method === 'git.push' && !bypassPushGate && tokenClaimedGit && !hostInitiatedOk) {\n return {\n exitCode: 10,\n stdout: '',\n stderr: 'host-initiated token rejected: invalid, expired, or bound to different params\\n',\n };\n }\n if (\n action.method === 'git.push' &&\n !bypassPushGate &&\n !hostInitiatedOk &&\n deps.prompts &&\n deps.subscribers\n ) {\n // Cloud-specific fallback: when no SSE subscriber is attached the prompt\n // would block indefinitely (the user has nothing to answer in). Choose\n // up-front whether to auto-deny (default) or auto-approve based on env\n // — same env knob shape as `AGENTBOX_PROMPT`. The decision is bounded\n // by `AGENTBOX_GIT_PUSH_NO_SUB`: 'deny' (default), 'allow', or 'prompt'\n // (block anyway, legacy behavior).\n const hasSubscriber = deps.subscribers.count(deps.boxId) > 0;\n if (!hasSubscriber && process.env['AGENTBOX_PROMPT'] !== 'off') {\n const noSubMode = (process.env['AGENTBOX_GIT_PUSH_NO_SUB'] ?? 'deny').toLowerCase();\n if (noSubMode === 'deny') {\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'denied automatically — no attached wrapper to confirm. Attach `agentbox claude` (or similar) and retry, or set AGENTBOX_GIT_PUSH_NO_SUB=allow.\\n',\n };\n }\n if (noSubMode === 'allow') {\n deps.log?.('git.push auto-approved (no subscribers, AGENTBOX_GIT_PUSH_NO_SUB=allow)');\n // Fall through to the actual push.\n } else {\n // 'prompt' or anything else: legacy blocking behavior with a TTL so\n // a never-attaching user doesn't wedge the executor forever.\n const verdict = await askPrompt(\n deps.prompts,\n deps.subscribers,\n deps.boxId,\n {\n kind: 'confirm',\n message: `Allow git push from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail:\n `${resolveRemote(params.remote)} ${branch} ${(params.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n },\n { ttlMs: 5 * 60 * 1000 },\n );\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n } else {\n const verdict = await askPrompt(deps.prompts, deps.subscribers, deps.boxId, {\n kind: 'confirm',\n message: `Allow git push from cloud box ${deps.boxName ?? deps.boxId}?`,\n detail: `${resolveRemote(params.remote)} ${branch} ${(params.args ?? []).join(' ')}`.trim(),\n defaultAnswer: 'n',\n context: { command: 'git push', cwd: containerPath, argv: params.args },\n });\n if (verdict.answer !== 'y') {\n return { exitCode: 10, stdout: '', stderr: 'denied by user\\n' };\n }\n }\n }\n\n const remoteName = resolveRemote(params.remote);\n let repo: HostGitRepo;\n try {\n repo = await resolveHostGitRepo(lookup.workspacePath, deps, remoteName);\n } catch (err) {\n return {\n exitCode: 64,\n stdout: '',\n stderr: `${err instanceof Error ? err.message : String(err)}\\n`,\n };\n }\n if (repo.scratch) {\n deps.log?.(\n `git.${action.method === 'git.push' ? 'push' : 'fetch'}: no host checkout for box ${deps.boxId}; using a scratch repo against ${repo.remote}`,\n );\n }\n\n const stage = await mkdtemp(join(tmpdir(), 'agentbox-git-rpc-'));\n const hostBundle = join(stage, 'op.bundle');\n const remoteBundle = '/tmp/agentbox-rpc.bundle';\n try {\n if (action.method === 'git.push') {\n // 2a. Bundle the per-box branch inside the sandbox.\n const make = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} bundle create ${shellQuote(remoteBundle)} ${shellQuote(branch)}`,\n );\n if (make.exitCode !== 0) {\n return {\n exitCode: make.exitCode,\n stdout: '',\n stderr: `bundle create failed: ${make.stderr || make.stdout}`,\n };\n }\n // 2b. Download to host tmp.\n await backend.downloadFile(handle, remoteBundle, hostBundle);\n // 3. Fast-forward the host repo's per-box branch ref to the sandbox tip.\n // In a scratch repo this is what materializes the branch at all.\n const fetch = await execa(\n 'git',\n ['-C', repo.dir, 'fetch', hostBundle, `${branch}:${branch}`],\n { reject: false },\n );\n if (fetch.exitCode !== 0) {\n return {\n exitCode: fetch.exitCode ?? 1,\n stdout: fetch.stdout ?? '',\n stderr: `host git fetch from bundle failed: ${fetch.stderr ?? ''}`,\n };\n }\n // 4. Real push. Args are user-controlled (`agentbox-ctl git push --\n // <args>`); pass them through to git on the host. `repo.remote` is the\n // caller's remote name against a real checkout, or the registered origin\n // URL when we're pushing out of a scratch repo (which has no remotes).\n const remote = repo.remote;\n const argv = ['-C', repo.dir, 'push', remote, branch];\n argv.push(...sanitizeGitArgs(params.args));\n const push = await execa('git', argv, { reject: false });\n let pushStderr = push.stderr ?? '';\n // After a successful push, sync the box's view of origin to match what\n // a normal local `git push -u` would have left behind: write the pushed\n // tip into the box's `refs/remotes/origin/<branch>` and set the branch\n // upstream to track it. Without this, Claude Code's PR badge sees no\n // upstream on the branch and doesn't fetch / display the PR. Per-box\n // scratch branches (`agentbox/<name>`) skip the sync — they're\n // local-only by design.\n if ((push.exitCode ?? 1) === 0 && !isScratchBranch(branch)) {\n try {\n const sha = await execa('git', ['-C', repo.dir, 'rev-parse', branch], { reject: false });\n const shaText = (sha.stdout ?? '').trim();\n if (sha.exitCode === 0 && shaText.length > 0) {\n // These are refs INSIDE the box, so they must use the remote NAME —\n // `repo.remote` may be a bare URL when we pushed from a scratch repo.\n const updateRef = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} update-ref ${remoteTrackingRef(remoteName, branch)} ${shellQuote(shaText)}`,\n );\n if (updateRef.exitCode !== 0) {\n pushStderr += `\\nrelay: post-push in-box update-ref ${remoteTrackingRef(remoteName, branch)} failed: ${updateRef.stderr || updateRef.stdout}`;\n }\n const setUpstream = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} branch --set-upstream-to=${upstreamRef(remoteName, branch)} ${shellQuote(branch)}`,\n );\n if (setUpstream.exitCode !== 0) {\n pushStderr += `\\nrelay: post-push in-box --set-upstream-to=${upstreamRef(remoteName, branch)} failed: ${setUpstream.stderr || setUpstream.stdout}`;\n }\n } else {\n pushStderr += `\\nrelay: post-push rev-parse ${branch} failed on host; skipping in-box origin/upstream sync`;\n }\n } catch (err) {\n pushStderr += `\\nrelay: post-push in-box origin/upstream sync threw: ${err instanceof Error ? err.message : String(err)}`;\n }\n }\n return {\n exitCode: push.exitCode ?? 1,\n stdout: push.stdout ?? '',\n stderr: pushStderr,\n };\n }\n // git.fetch: host fetches origin, bundles, uploads, sandbox fetches.\n // A scratch repo has no configured remote, so fetch the registered URL\n // straight into the remote-tracking namespace the bundle step reads back.\n const fetchArgs = repo.scratch\n ? ['-C', repo.dir, 'fetch', repo.remote, '+refs/heads/*:refs/remotes/origin/*', '--tags']\n : ['-C', repo.dir, 'fetch', repo.remote];\n const hostFetch = await execa('git', fetchArgs, { reject: false });\n if (hostFetch.exitCode !== 0) {\n return {\n exitCode: hostFetch.exitCode ?? 1,\n stdout: hostFetch.stdout ?? '',\n stderr: `host git fetch failed: ${hostFetch.stderr ?? ''}`,\n };\n }\n // Bundle origin's remote-tracking refs so the sandbox sees the updates.\n const bundle = await execa('git', ['-C', repo.dir, 'bundle', 'create', hostBundle, `--all`], {\n reject: false,\n });\n if (bundle.exitCode !== 0) {\n return {\n exitCode: bundle.exitCode ?? 1,\n stdout: '',\n stderr: `host git bundle create failed: ${bundle.stderr ?? ''}`,\n };\n }\n await backend.uploadFile(handle, hostBundle, remoteBundle);\n const sandboxFetch = await backend.exec(\n handle,\n `git -C ${shellQuote(containerPath)} fetch ${shellQuote(remoteBundle)} '+refs/heads/*:refs/remotes/origin/*' --tags`,\n );\n return {\n exitCode: sandboxFetch.exitCode,\n stdout: sandboxFetch.stdout,\n stderr: sandboxFetch.stderr,\n };\n } finally {\n await rm(stage, { recursive: true, force: true });\n await repo.cleanup().catch(() => {\n /* best-effort */\n });\n await backend.exec(handle, `rm -f ${shellQuote(remoteBundle)}`).catch(() => {\n /* best-effort */\n });\n }\n}\n\n/** Local helper — sandbox-cloud's `quoteShellArg` would be a cross-package import. */\nfunction shellQuote(arg: string): string {\n if (arg.length === 0) return \"''\";\n if (/^[A-Za-z0-9_@%+=:,./-]+$/.test(arg)) return arg;\n return \"'\" + arg.replace(/'/g, \"'\\\\''\") + \"'\";\n}\n","/**\n * Host-side helpers for the `gh.pr.*` RPCs (PR create / view / list / comment /\n * review / merge / checkout / close / reopen). The relay reuses the host's\n * `gh` install + auth: the in-box agent has no GitHub token, the host does.\n *\n * Same decoupling philosophy as `handleGitRpc`'s direct `git` spawn — we shell\n * out to `gh` with a known `cwd` (the host main repo) so `gh` infers the\n * GitHub repo from `git remote -v` and uses the user's authenticated gh\n * identity. No new credential plumbing inside the box.\n *\n * Lives in its own file so both `server.ts` (docker path) and `host-actions.ts`\n * (cloud path) can share `assertGhReady` + `runHostGh` + the `checkout`\n * guards without creating an import cycle.\n */\n\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { repoSlugFromRemote } from './git-pat.js';\nimport type { GitRpcResult } from './types.js';\n\n/** Whitelisted subset of `gh pr` ops exposed via RPC. Keep in sync with the ctl CLI. */\nexport const GH_PR_OPS = [\n 'create',\n 'view',\n 'list',\n 'diff',\n 'checks',\n 'comment',\n 'review',\n 'merge',\n 'checkout',\n 'close',\n 'reopen',\n] as const;\n\nexport type GhPrOp = (typeof GH_PR_OPS)[number];\n\nexport function isGhPrOp(value: string): value is GhPrOp {\n return (GH_PR_OPS as readonly string[]).includes(value);\n}\n\n/** Read-only ops never trigger the host confirmation prompt. */\nexport const GH_PR_READ_ONLY_OPS: ReadonlySet<GhPrOp> = new Set(['view', 'list', 'diff', 'checks']);\n\n/**\n * `gh pr` write ops that auto-approve under `box.autoApproveSafeHostActions`:\n * opening a PR for the box's branch (the relay forces `--head <box-branch>`, so\n * it can only ever target the box's own work) and commenting on a PR. The more\n * consequential writes (`review`, `close`, `reopen`, and especially `merge` /\n * `checkout`) are deliberately excluded — they keep prompting.\n */\nexport const GH_PR_SAFE_AUTO_APPROVE_OPS: ReadonlySet<GhPrOp> = new Set(['create', 'comment']);\n\n/**\n * Whitelisted subset of `gh run` ops exposed via RPC. `list` / `view` are\n * read-only; `rerun` re-triggers CI (a write — gated by the host confirm\n * prompt). `watch` is deliberately absent: it blocks until the run finishes,\n * which doesn't fit the relay's buffered request/response model (the in-box\n * `gh-shim` rejects it and points users at `gh run view`).\n */\nexport const GH_RUN_OPS = ['list', 'view', 'rerun'] as const;\n\nexport type GhRunOp = (typeof GH_RUN_OPS)[number];\n\nexport function isGhRunOp(value: string): value is GhRunOp {\n return (GH_RUN_OPS as readonly string[]).includes(value);\n}\n\n/** Read-only `gh run` ops never trigger the host confirmation prompt. */\nexport const GH_RUN_READ_ONLY_OPS: ReadonlySet<GhRunOp> = new Set(['list', 'view']);\n\n// The PR review-comment endpoints. GET lists inline review comments; POST adds\n// one (the thing `gh pr comment` can't do). `…/comments/:id/replies` replies to\n// a review comment. The optional trailing `(\\?…)` lets agents embed GET query\n// params in the path (e.g. `…/comments?per_page=50`) rather than via field flags.\nconst PR_REVIEW_COMMENT = /^repos\\/[^/]+\\/[^/]+\\/pulls\\/\\d+\\/comments(\\?.*)?$/;\nconst PR_REVIEW_COMMENT_REPLY = /^repos\\/[^/]+\\/[^/]+\\/pulls\\/\\d+\\/comments\\/\\d+\\/replies(\\?.*)?$/;\n\n/**\n * `gh api` endpoints on which POST (create a comment) is proxied — unprompted,\n * since comments are low-risk. Kept separate from the read allowlist so adding\n * a read-only endpoint there later doesn't widen the POST surface.\n */\nexport const GH_API_WRITE_ALLOWED_ENDPOINTS: readonly RegExp[] = [\n PR_REVIEW_COMMENT,\n PR_REVIEW_COMMENT_REPLY,\n];\n\n/**\n * Allowlist of `gh api` endpoint patterns the relay will proxy at all (the\n * overall gate). Superset of the write-allowed list; meant to grow one\n * deliberate entry at a time. GET is allowed on every entry; POST only on the\n * write-allowed subset (see `refuseGhApiCall`).\n */\nexport const GH_API_ALLOWED_ENDPOINTS: readonly RegExp[] = [...GH_API_WRITE_ALLOWED_ENDPOINTS];\n\n/** True when `endpoint` matches an allowlisted `gh api` pattern (proxied at all). */\nexport function isAllowedGhApiEndpoint(endpoint: string): boolean {\n return GH_API_ALLOWED_ENDPOINTS.some((re) => re.test(normalizeGhApiEndpoint(endpoint)));\n}\n\n/** True when POST is permitted on `endpoint` (the comment endpoints). */\nexport function isWriteAllowedGhApiEndpoint(endpoint: string): boolean {\n return GH_API_WRITE_ALLOWED_ENDPOINTS.some((re) => re.test(normalizeGhApiEndpoint(endpoint)));\n}\n\n/** Strip a leading slash so `/repos/...` and `repos/...` both match. */\nfunction normalizeGhApiEndpoint(endpoint: string): string {\n return endpoint.replace(/^\\/+/, '');\n}\n\n/** Ready-to-send refusal when a `gh api` endpoint isn't on the allowlist. */\nexport const GH_API_ENDPOINT_REFUSAL: GitRpcResult = {\n exitCode: 65,\n stdout: '',\n stderr:\n 'gh api: endpoint not allowlisted. Proxied: GET on ' +\n 'repos/:owner/:repo/pulls/:number/comments (and /:id/replies); POST to those ' +\n 'endpoints to add a review comment.\\n',\n};\n\n/**\n * Endpoint-aware `gh api` policy. Returns a ready-to-send refusal, or `null`\n * when the call may proceed. The caller has already checked the endpoint is on\n * `GH_API_ALLOWED_ENDPOINTS`.\n *\n * - GET → allowed everywhere on the allowlist.\n * - POST → allowed only on the write-allowed comment endpoints (unprompted).\n * - PATCH/PUT/DELETE/etc. → refused.\n * - `--input` → refused: the host `gh` runs with stdin ignored and a box-side\n * file path wouldn't exist on the host, so it can't cross the relay. Agents\n * pass fields via `-f`/`-F`.\n *\n * `gh` uses Go's pflag, which accepts a short flag's value glued on (`-XPOST`,\n * `-fbody=hi`) and the `=` form (`-X=POST`, `--method=POST`) as well as the\n * space-separated form. The box-side shim is the convenience gate; this relay\n * guard is the security boundary for a direct `agentbox-ctl` call, so it\n * recognizes every spelling.\n */\nexport function refuseGhApiCall(endpoint: string, args: string[]): GitRpcResult | null {\n const refuse = (reason: string): GitRpcResult => ({\n exitCode: 65,\n stdout: '',\n stderr: `gh api: ${reason}\\n`,\n });\n\n let explicitMethod: string | null = null;\n let hasFieldFlag = false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i] ?? '';\n // --method / -X with a separately-tokenized value.\n if (arg === '-X' || arg === '--method') {\n explicitMethod = args[i + 1] ?? '';\n i++; // consumed the value\n continue;\n }\n // --method=VALUE / -X=VALUE / -XVALUE (glued short form).\n if (arg.startsWith('--method=')) {\n explicitMethod = arg.slice('--method='.length);\n continue;\n }\n if (arg.startsWith('-X') && arg.length > 2) {\n explicitMethod = arg.slice(2).replace(/^=/, '');\n continue;\n }\n // `--input` (stdin/file body) can't traverse the relay — refuse outright.\n // Its spaced value (if any) is irrelevant; we return before consuming it.\n if (arg === '--input' || arg.startsWith('--input=')) {\n return refuse(\n \"'--input' (stdin/file body) isn't supported through the relay; use -f/-F fields\",\n );\n }\n // Field flags auto-switch gh api to POST. The SPACED forms take the next\n // token as their value, so consume it — otherwise a method-looking value\n // (e.g. `-f -X=GET`, where pflag binds `-X=GET` as `-f`'s value and POSTs)\n // would be misread as a real `--method` next iteration and downgrade the\n // detected method to GET, slipping a POST past a future read-only endpoint.\n if (arg === '-f' || arg === '-F' || arg === '--field' || arg === '--raw-field') {\n hasFieldFlag = true;\n i++; // consume the value token\n continue;\n }\n // Glued field forms carry their value inline (`-fbody=hi`, `--field=…`). No\n // read-only flag starts with -f / -F, so the prefix match is safe.\n if (\n arg.startsWith('-f') ||\n arg.startsWith('-F') ||\n arg.startsWith('--field=') ||\n arg.startsWith('--raw-field=')\n ) {\n hasFieldFlag = true;\n }\n }\n\n const method = (explicitMethod ?? (hasFieldFlag ? 'POST' : 'GET')).toUpperCase();\n if (method === 'GET') return null;\n if (method === 'POST') {\n if (isWriteAllowedGhApiEndpoint(endpoint)) return null;\n return refuse(\n `POST is only proxied to PR review-comment endpoints (repos/:o/:r/pulls/:n/comments[/:id/replies]), not '${endpoint}'`,\n );\n }\n return refuse(\n `method '${method}' is not proxied — only GET, and POST to comment endpoints, are allowed`,\n );\n}\n\n/**\n * Default `gh pr create`'s `--head` to the box's branch so the PR is for the\n * box's work, not whatever the host main repo happens to have checked out\n * (`gh` infers head from the cwd's HEAD, which is the user's own branch — or\n * an untracked one, which aborts with \"you must first push the current branch\n * to a remote, or use the --head flag\"). Only injected for `create`, only when\n * the caller didn't already pass `--head` (or its `-H` shorthand), and only when we resolved a real\n * branch (not empty / detached `HEAD`). The host CLI's `agentbox git pr create`\n * already injects this; the relay covers the in-box `agentbox-ctl git pr` /\n * `gh pr` path, which forwards args verbatim.\n */\nexport function injectPrCreateHead(\n op: GhPrOp,\n branch: string | undefined,\n args: string[],\n): string[] {\n if (op !== 'create') return args;\n if (!branch || branch === 'HEAD') return args;\n if (hasHeadArg(args)) return args;\n return ['--head', branch, ...args];\n}\n\nfunction hasHeadArg(args: string[]): boolean {\n // `gh pr create` accepts `--head`, `--head=<b>`, and the `-H` shorthand in\n // its `-H <b>` / `-H<b>` / `-H=<b>` forms. Recognize all so an explicit head\n // neither gets double-injected nor triggers the no-head refusal.\n return args.some((a) => a === '--head' || a.startsWith('--head=') || a.startsWith('-H'));\n}\n\n/**\n * True when the caller passed an explicit `--head`/`-H` on a `gh pr create`.\n * The safe-subset auto-approve only covers a `create` with NO explicit head:\n * the relay then forces `--head` to the box's sanctioned branch, so the PR can\n * only ever target the box's own work. An explicit head (which could name any\n * branch, e.g. `main`) falls back to the confirm prompt.\n */\nexport function prCreateHasExplicitHead(op: GhPrOp, args: string[]): boolean {\n return op === 'create' && hasHeadArg(args);\n}\n\n/**\n * True when a `gh pr create` would run with no `--head` — i.e. we couldn't\n * resolve the box's branch to inject and the caller didn't pass one. The\n * relay must refuse rather than let `gh` fall back to the host repo's\n * *checked-out* branch, which would open a PR for the wrong branch.\n */\nexport function prCreateNeedsHead(op: GhPrOp, args: string[]): boolean {\n return op === 'create' && !hasHeadArg(args);\n}\n\n/** Ready-to-send refusal for a `create` that has no resolvable `--head`. */\nexport const PR_CREATE_NO_HEAD_REFUSAL: GitRpcResult = {\n exitCode: 65,\n stdout: '',\n stderr:\n 'gh pr create: refusing to run without --head — could not resolve this ' +\n \"box's branch, and falling back to the host repo's checked-out branch \" +\n 'would open a PR for the wrong branch. Ensure the box branch is pushed, ' +\n 'or pass --head <branch> explicitly.\\n',\n};\n\n/** Wire params for every `gh.pr.<op>` method. Mirrors the new ctl command surface. */\nexport interface GhPrRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** Pass-through argv (`--title`, `--body`, `--label`, `--draft`, `--json`, …). */\n args?: string[];\n /**\n * One-time token minted by the host CLI via `/admin/host-initiated/mint`\n * before invoking `agentbox git pr <op> <box>`. Validated against the\n * relay's in-memory store, scoped to `(boxId, method=gh.pr.<op>)`;\n * consumed on match and the confirm prompt is skipped. Boxes cannot mint\n * tokens (admin endpoint is loopback-only). `AGENTBOX_GH_FORCE` /\n * `AGENTBOX_GH_PR_CHECKOUT` opt-ins still apply — destructive guards do\n * not weaken when host-initiated.\n */\n hostInitiated?: string;\n}\n\n/** Wire params for every `gh.run.<op>` method. In-box surface only (no token). */\nexport interface GhRunRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** Pass-through argv (`--json`, `--limit`, `<run-id>`, …). */\n args?: string[];\n}\n\n/** Wire params for the `gh.api` method. Read-only, allowlisted endpoints. */\nexport interface GhApiRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** The REST endpoint, e.g. `repos/:owner/:repo/pulls/:number/comments`. */\n endpoint?: string;\n /** Pass-through argv (`--jq`, `--paginate`, `-H`, …). */\n args?: string[];\n}\n\nconst GH_RPC_TIMEOUT_MS = 120_000;\nconst GH_READY_CACHE_TTL_MS = 60_000;\n\ninterface GhReadyCache {\n /** null on success; a ready-to-send error envelope when gh isn't usable. */\n result: GitRpcResult | null;\n expiresAt: number;\n}\nlet ghReadyCache: GhReadyCache | undefined;\n\n/**\n * Returns `null` when the host has a usable, authenticated `gh`. Otherwise\n * returns a ready-to-send `{ exitCode, stdout, stderr }` envelope describing\n * what's missing. Cached for ~60s so a burst of PR ops doesn't reprobe gh on\n * every call.\n *\n * - `gh` missing → exit 127 (matches Bash's \"command not found\").\n * - `gh` present but `gh auth status` non-zero → exit 4 (gh's own conventional\n * \"not logged in\" exit code).\n *\n * We don't pass `--hostname github.com` to `auth status` — agents pointed at\n * a GitHub Enterprise host should also pass. Any authed host is good enough.\n */\nexport async function assertGhReady(): Promise<GitRpcResult | null> {\n const now = Date.now();\n if (ghReadyCache && ghReadyCache.expiresAt > now) {\n return ghReadyCache.result;\n }\n const result = await probeGh();\n ghReadyCache = { result, expiresAt: now + GH_READY_CACHE_TTL_MS };\n return result;\n}\n\n/** Test-only: clear the readiness cache between cases. */\nexport function _resetGhReadyCacheForTests(): void {\n ghReadyCache = undefined;\n}\n\nasync function probeGh(): Promise<GitRpcResult | null> {\n const version = await runHostGh(['--version'], process.cwd(), 10_000);\n if (version.exitCode === 127 || /ENOENT/.test(version.stderr)) {\n return {\n exitCode: 127,\n stdout: '',\n stderr: 'gh not installed on host (https://cli.github.com)\\n',\n };\n }\n if (version.exitCode !== 0) {\n return {\n exitCode: version.exitCode,\n stdout: '',\n stderr: `gh --version failed: ${version.stderr || version.stdout}`.trimEnd() + '\\n',\n };\n }\n // gh authenticates directly from GH_TOKEN/GITHUB_TOKEN in the environment and\n // ignores any stored `gh auth login`. When a token is supplied that way with\n // no stored login, `gh auth status` would falsely report \"not logged in\" even\n // though every API call succeeds. Treat a present token as authenticated.\n if ((process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? '').length > 0) {\n return null;\n }\n const auth = await runHostGh(['auth', 'status'], process.cwd(), 15_000);\n if (auth.exitCode !== 0) {\n return {\n exitCode: 4,\n stdout: '',\n stderr: 'gh not authenticated on host (run `gh auth login`)\\n',\n };\n }\n return null;\n}\n\n/**\n * Where to run `gh`, and whether it must be told the repo.\n *\n * `gh` infers the repo from its cwd's git remote, so the host checkout is the\n * natural place to run it. A control box has no checkout: passing that path as\n * `cwd` makes the spawn itself fail with a bare `spawn gh ENOENT` (Node reports\n * a missing cwd exactly like a missing binary), which reads as \"gh isn't\n * installed\" and sent us hunting the wrong problem. Fall back to a directory\n * that exists and name the repo explicitly from the registered origin instead.\n */\nexport function ghRunContext(\n workspacePath: string,\n originUrl: string | undefined,\n args: string[],\n): { cwd: string; args: string[] } {\n if (workspacePath.length > 0 && existsSync(workspacePath)) {\n return { cwd: workspacePath, args };\n }\n const origin = originUrl?.trim() ?? '';\n const alreadyScoped = args.some((a) => a === '--repo' || a === '-R' || a.startsWith('--repo='));\n if (origin.length === 0 || alreadyScoped) return { cwd: tmpdir(), args };\n try {\n return { cwd: tmpdir(), args: ['--repo', repoSlugFromRemote(origin), ...args] };\n } catch {\n return { cwd: tmpdir(), args };\n }\n}\n\n/**\n * Spawn `gh` on the host with the given argv inside `cwd`. Returns the\n * standard `{ exitCode, stdout, stderr }` envelope. Self-contained\n * (doesn't call into `server.ts`'s `runHostCommand`) so this module has no\n * import dependency on the server module — keeps the relay's two RPC\n * dispatch paths (docker `/rpc` and cloud `executeCloudAction`) from\n * importing each other.\n */\nexport function runHostGh(\n args: string[],\n cwd: string,\n timeoutMs: number = GH_RPC_TIMEOUT_MS,\n): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn('gh', args, {\n cwd,\n env: process.env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: gh command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n // ENOENT (gh missing) lands here too; surface as exit 127 to match shell semantics.\n const code = (err as NodeJS.ErrnoException).code;\n stderr += String(err.message ?? err);\n finish(code === 'ENOENT' ? 127 : 1);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/**\n * Pre-flight for `gh.pr.checkout`. Refuses when:\n * - the host repo has uncommitted changes (clobbers WIP), or\n * - HEAD is currently any registered per-box branch (`agentbox/<name>`) —\n * the box's bind-mounted `.git/HEAD` would silently flip with the host.\n *\n * Returns a ready-to-send error envelope on refusal, or `null` to proceed.\n */\nexport async function checkoutGuards(\n hostMainRepo: string,\n registeredBranches: readonly string[],\n): Promise<GitRpcResult | null> {\n const status = await runGitProbe(['-C', hostMainRepo, 'status', '--porcelain']);\n if (status.exitCode !== 0) {\n return {\n exitCode: status.exitCode,\n stdout: '',\n stderr:\n `gh pr checkout: failed to inspect host repo: ${status.stderr || status.stdout}`.trimEnd() +\n '\\n',\n };\n }\n if (status.stdout.trim().length > 0) {\n return {\n exitCode: 12,\n stdout: '',\n stderr: `gh pr checkout: ${hostMainRepo} has uncommitted changes; refusing to switch branches\\n`,\n };\n }\n const head = await runGitProbe(['-C', hostMainRepo, 'rev-parse', '--abbrev-ref', 'HEAD']);\n if (head.exitCode !== 0) {\n return {\n exitCode: head.exitCode,\n stdout: '',\n stderr:\n `gh pr checkout: failed to resolve HEAD: ${head.stderr || head.stdout}`.trimEnd() + '\\n',\n };\n }\n const currentBranch = head.stdout.trim();\n if (registeredBranches.includes(currentBranch)) {\n return {\n exitCode: 12,\n stdout: '',\n stderr: `gh pr checkout: ${hostMainRepo} is on registered box branch ${currentBranch}; refusing (would corrupt the bind-mounted box HEAD)\\n`,\n };\n }\n return null;\n}\n\nfunction runGitProbe(args: string[]): Promise<GitRpcResult> {\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn('git', args, { env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout?.on('data', (c: Buffer) => {\n stdout += c.toString('utf8');\n });\n child.stderr?.on('data', (c: Buffer) => {\n stderr += c.toString('utf8');\n });\n child.on('error', (err) => {\n resolve({ exitCode: 127, stdout, stderr: stderr + String(err.message ?? err) });\n });\n child.on('close', (code) => {\n resolve({ exitCode: code ?? -1, stdout, stderr });\n });\n });\n}\n\n/**\n * `merge` is the most destructive op. `AGENTBOX_PROMPT=off` auto-`y`s every\n * other prompt in the relay; for `gh pr merge` we refuse that bypass unless\n * the user opted in via `AGENTBOX_GH_FORCE=1`. Returns a ready-to-send envelope\n * when the bypass should be refused; `null` otherwise.\n */\nexport function refuseMergeBypass(op: GhPrOp): GitRpcResult | null {\n if (op !== 'merge') return null;\n if (process.env['AGENTBOX_PROMPT'] !== 'off') return null;\n if (process.env['AGENTBOX_GH_FORCE'] === '1') return null;\n return {\n exitCode: 10,\n stdout: '',\n stderr:\n 'gh pr merge: AGENTBOX_PROMPT=off bypass requires AGENTBOX_GH_FORCE=1 (merge is irreversible)\\n',\n };\n}\n\n/**\n * `gh pr checkout` is gated behind an explicit opt-in env: it mutates the\n * host main repo's `HEAD`, which the bind-mounted box sees too. Returns a\n * ready-to-send envelope when the op should be refused; `null` otherwise.\n */\nexport function refuseCheckoutByDefault(op: GhPrOp): GitRpcResult | null {\n if (op !== 'checkout') return null;\n if (process.env['AGENTBOX_GH_PR_CHECKOUT'] === 'allow') return null;\n return {\n exitCode: 13,\n stdout: '',\n stderr: 'gh pr checkout: disabled by default; set AGENTBOX_GH_PR_CHECKOUT=allow to enable\\n',\n };\n}\n","/**\n * Host-initiated RPC tokens.\n *\n * `agentbox git <op> <box>` runs on the host but ultimately triggers a\n * credentialed RPC (`git.push`, `gh.pr.<op>`, …) on the host-side relay.\n * Those RPCs normally surface a y/N confirm prompt to the user — the box\n * (and the agent inside it) is untrusted, so every push/PR must be approved.\n *\n * For host-initiated calls, the user has already typed the command on the\n * host, so re-prompting is just friction. But \"host-initiated\" must not be\n * something the box can claim by setting a flag — a malicious agent could\n * trivially abuse that. So instead the host CLI:\n *\n * 1. Computes a `paramsHash` of the exact params it's about to send.\n * 2. Mints a one-time token via the relay's loopback-only admin endpoint\n * `POST /admin/host-initiated/mint`, scoped to `(boxId, method, paramsHash)`.\n * 3. Passes the token to `agentbox-ctl` (via `--host-initiated-token`),\n * which forwards it in `params.hostInitiated` on the RPC.\n * 4. The relay re-hashes the incoming params (excluding `hostInitiated`),\n * compares against the minted hash, and only skips the prompt on a\n * full `(boxId, method, paramsHash)` match. The token is then consumed.\n *\n * Tokens are 32 random bytes (256 bits — collision/guessing safety), expire\n * after ~120s, and are one-shot.\n *\n * Failure-mode policy (enforced at each call site, not here):\n *\n * - `params.hostInitiated` absent → no token claimed; the RPC falls\n * through to the normal askPrompt path (the agent-initiated default).\n * - `params.hostInitiated` present but `consume()` returns false →\n * **reject the RPC outright** (exit code 10). The only way to obtain a\n * token is via the loopback-only mint endpoint; a token that doesn't\n * validate (wrong scope, mutated params, replayed, expired) is an\n * attack signal. Falling through to the prompt would (a) leak that the\n * attacker has a token, (b) bait the user into approving a call they\n * didn't initiate. Hard reject.\n *\n * ## Threat model\n *\n * The mint endpoint is loopback-only, so a box cannot mint its own tokens\n * (boxes see the relay on `host.docker.internal` or via cloud bridges,\n * never 127.0.0.1).\n *\n * The token is delivered to the box via `docker exec --argv agentbox-ctl …\n * --host-initiated-token <tok>`. /proc/<pid>/cmdline is world-readable on\n * Linux, so a malicious in-box process polling /proc COULD harvest the\n * token while agentbox-ctl is running. Without paramsHash binding the\n * attacker could then send their own RPC with the same token but *modified\n * args* (`--force` on push, altered `--title`/`--body` on PR create) and\n * win a race against the legit caller. paramsHash binding closes that gap:\n * the relay rejects any incoming params that don't hash to the minted hash,\n * so harvested tokens are only good for the exact params the host CLI\n * already authorized.\n *\n * Optional `paramsHash === undefined` mode exists for forward compatibility\n * (callers that don't need params binding); the production callers\n * (`agentbox git`) always pass a hash.\n */\n\nimport { createHash, randomBytes } from 'node:crypto';\n\nconst DEFAULT_TTL_MS = 120_000;\n\ninterface TokenRecord {\n boxId: string;\n method: string;\n /**\n * Hex SHA-256 of the canonicalized params the host CLI committed to\n * sending. Verified against the incoming `/rpc` params in `consume()`.\n * `null` means \"no params binding\" — only safe for calls where the\n * params surface is fully host-controlled (none in practice today).\n */\n paramsHash: string | null;\n expiresAt: number;\n}\n\n/**\n * Compute a stable SHA-256 of the JSON params, with keys sorted and the\n * `hostInitiated` field stripped (so the token-bearing call hashes the same\n * as the at-mint-time intended params). Stable hash regardless of key order\n * in the wire payload, regardless of whether `hostInitiated` is set.\n */\nexport function hashRpcParams(params: unknown): string {\n return createHash('sha256').update(canonicalJson(params)).digest('hex');\n}\n\nfunction canonicalJson(v: unknown): string {\n if (v === null) return 'null';\n if (typeof v === 'undefined') return 'null';\n if (typeof v === 'number') return Number.isFinite(v) ? String(v) : 'null';\n if (typeof v === 'boolean') return v ? 'true' : 'false';\n if (typeof v === 'string') return JSON.stringify(v);\n if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']';\n if (typeof v === 'object') {\n const entries = Object.entries(v as Record<string, unknown>)\n .filter(([k]) => k !== 'hostInitiated')\n .filter(([, val]) => val !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return (\n '{' +\n entries.map(([k, val]) => JSON.stringify(k) + ':' + canonicalJson(val)).join(',') +\n '}'\n );\n }\n return 'null';\n}\n\nexport class HostInitiatedTokens {\n private readonly store = new Map<string, TokenRecord>();\n\n /**\n * Mint a fresh one-time token scoped to (boxId, method, paramsHash).\n * `paramsHash` MUST be supplied for any call surface where the box can\n * influence the eventual RPC params. Pass `null` only when there are no\n * params (no current call sites use this).\n */\n mint(\n boxId: string,\n method: string,\n paramsHash: string | null,\n ttlMs: number = DEFAULT_TTL_MS,\n ): string {\n const token = randomBytes(32).toString('hex');\n this.store.set(token, { boxId, method, paramsHash, expiresAt: Date.now() + ttlMs });\n return token;\n }\n\n /**\n * Returns true exactly once if `token` is a valid, unexpired token for the\n * given `(boxId, method)` AND the supplied `incomingParamsHash` matches\n * the hash bound at mint time. The token is removed on a successful match\n * (one-shot semantics). All failure modes return false — callers fall back\n * to the normal prompt path.\n */\n consume(\n token: string | undefined,\n boxId: string,\n method: string,\n incomingParamsHash: string,\n ): boolean {\n if (!token || typeof token !== 'string') return false;\n const record = this.store.get(token);\n if (!record) return false;\n if (record.expiresAt < Date.now()) {\n this.store.delete(token);\n return false;\n }\n if (record.boxId !== boxId || record.method !== method) return false;\n // paramsHash null = \"no binding\"; otherwise enforce exact match.\n if (record.paramsHash !== null && record.paramsHash !== incomingParamsHash) {\n return false;\n }\n this.store.delete(token);\n return true;\n }\n\n /** Drop expired entries. Cheap; safe to call periodically. */\n gc(): void {\n const now = Date.now();\n for (const [token, record] of this.store) {\n if (record.expiresAt < now) this.store.delete(token);\n }\n }\n\n /** Test-only: number of live tokens. */\n size(): number {\n return this.store.size;\n }\n}\n","/**\n * Shared `cp.toHost` / `cp.fromHost` wire handling for both the docker `/rpc`\n * route (`server.ts`) and the cloud host-action queue (`host-actions.ts`).\n *\n * Both paths converge on the same move: normalize the wire params into\n * sources + destination, then re-shell the installed `agentbox cp` host CLI\n * (which owns the tar pipe, excludes, the size guard, and provider routing).\n * Keeping the argv builder here means the docker and cloud paths can't drift.\n */\n\nimport type { CpRpcParams } from './types.js';\n\nexport type CpMethod = 'cp.toHost' | 'cp.fromHost';\n\n/**\n * Normalize the wire params into `{ sources, dest }`, tolerating the legacy\n * single-source `{ boxPath, hostPath }` shape sent by an older in-box\n * `agentbox-ctl` baked into a box image before multi-source support. Throws a\n * plain `Error` (message is safe to surface) on a malformed payload.\n */\nexport function normalizeCpParams(\n method: CpMethod,\n params: CpRpcParams | undefined,\n): { sources: string[]; dest: string } {\n if (!params) throw new Error('cp.* requires params');\n let sources = params.sources;\n let dest = params.dest;\n // Legacy fallback: derive sources/dest from boxPath/hostPath by direction.\n if (!Array.isArray(sources) || sources.length === 0 || typeof dest !== 'string') {\n if (typeof params.boxPath === 'string' && typeof params.hostPath === 'string') {\n if (method === 'cp.toHost') {\n sources = [params.boxPath];\n dest = params.hostPath;\n } else {\n sources = [params.hostPath];\n dest = params.boxPath;\n }\n }\n }\n if (!Array.isArray(sources) || sources.length === 0 || sources.some((s) => typeof s !== 'string')) {\n throw new Error('cp.* requires a non-empty {sources} string array (or legacy {boxPath, hostPath})');\n }\n if (typeof dest !== 'string') {\n throw new Error('cp.* requires a {dest} string (or legacy {boxPath, hostPath})');\n }\n return { sources, dest };\n}\n\n/** Translate the optional cp flags back into `agentbox cp` argv flags. */\nexport function cpFlags(params: CpRpcParams): string[] {\n const flags: string[] = [];\n for (const pat of params.exclude ?? []) flags.push('--exclude', pat);\n if (params.defaultExcludes === false) flags.push('--no-default-excludes');\n if (params.yes) flags.push('--yes');\n return flags;\n}\n\n/**\n * Build the `agentbox cp <src...> <dst>` argv (leading `cp`, no node/entry) plus\n * a human-facing detail line for the consent prompt. The box side carries the\n * `<boxName>:` prefix; host paths are resolved to absolute via `resolveHost`\n * (against the box workspace) so the prompt shows the real destination and the\n * argv doesn't depend on the re-shelled process's cwd.\n */\nexport function buildCpArgv(opts: {\n method: CpMethod;\n boxName: string;\n sources: string[];\n dest: string;\n resolveHost: (p: string) => string;\n flags: string[];\n}): { argv: string[]; detail: string; contextArgv: string[] } {\n const { method, boxName, sources, dest, resolveHost, flags } = opts;\n if (method === 'cp.toHost') {\n const hostAbs = resolveHost(dest);\n const boxArgs = sources.map((s) => `${boxName}:${s}`);\n return {\n argv: ['cp', ...boxArgs, hostAbs, ...flags],\n detail: `${sources.join(', ')} -> ${hostAbs}`,\n contextArgv: [...sources, hostAbs],\n };\n }\n const hostAbsSrcs = sources.map(resolveHost);\n return {\n argv: ['cp', ...hostAbsSrcs, `${boxName}:${dest}`, ...flags],\n detail: `${hostAbsSrcs.join(', ')} -> ${dest}`,\n contextArgv: [...hostAbsSrcs, dest],\n };\n}\n","/**\n * Generic host-side machinery for the `integration.<service>.<op>` RPCs —\n * the relay-side spine that turns a descriptor in `@agentbox/integrations`\n * into a host-CLI invocation with read/write classification and write\n * gating. Companion to `gh.ts`: same spawn/probe/cache shape, but driven\n * by a descriptor (so each service is one small file in\n * `@agentbox/integrations/connectors/`, not a new pair of files here).\n *\n * Lives in its own file so both `server.ts` (docker `POST /rpc`) and\n * `host-actions.ts` (cloud path) share the same helpers — same cycle-\n * avoidance reasoning as `gh.ts`.\n */\n\nimport { spawn } from 'node:child_process';\nimport type { IntegrationConnector, IntegrationOp } from '@agentbox/integrations';\nimport { loadEffectiveConfig } from '@agentbox/config';\nimport type { GitRpcResult } from './types.js';\n\n/** Wire params for every `integration.<service>.<op>` method. Mirrors GhPrRpcParams. */\nexport interface IntegrationRpcParams {\n /** Container path the ctl ran in; used to pick the registered worktree. */\n path?: string;\n /** Pass-through argv forwarded to the host CLI (after `op.buildArgv`). */\n args?: string[];\n /**\n * One-time token minted by the host CLI via `/admin/host-initiated/mint`\n * before invoking `agentbox-ctl integration <svc> <op>`. Validated against\n * the relay's in-memory store, scoped to `(boxId, method=integration.<svc>.<op>)`\n * and the params-hash; consumed on match and the confirm prompt is\n * skipped. Boxes cannot mint tokens (admin endpoint is loopback-only).\n * Reserved for T1's host-CLI surface (T3+) — agent-initiated ctl calls\n * never pass it; the `askPrompt` gate applies.\n */\n hostInitiated?: string;\n}\n\nconst INTEGRATION_RPC_TIMEOUT_MS = 120_000;\nconst INTEGRATION_READY_CACHE_TTL_MS = 60_000;\n\n/**\n * `integration.<service>.<op>` wire shape:\n * - service: lowercase ASCII, matches IntegrationConnector.service.\n * - op: lowercase ASCII + digits + dots; first char a letter\n * (excludes leading `.` shapes like `integration.notion..api`).\n *\n * Dots are allowed in the op portion so descriptor ops can use a\n * dotted-namespace form (e.g. `page.create`) without colliding with the\n * `integration.<svc>.<op>` delimiter — the parser splits on the FIRST two\n * dots and keeps everything after as the op (so e.g.\n * `integration.notion.page.create` parses to `{service:'notion', op:'page.create'}`).\n */\nconst INTEGRATION_METHOD_RE = /^integration\\.([a-z][a-z0-9]*)\\.([a-z][a-z0-9.]*)$/;\n\nexport interface ParsedIntegrationMethod {\n service: string;\n op: string;\n}\n\n/** Parse `integration.<service>.<op>`; returns null on shape miss. */\nexport function parseIntegrationMethod(method: string): ParsedIntegrationMethod | null {\n const m = INTEGRATION_METHOD_RE.exec(method);\n if (!m) return null;\n const service = m[1]!;\n const op = m[2]!;\n // Disallow a trailing dot (`integration.notion.api.`) or consecutive dots\n // (`integration.notion.page..create`) — the regex's `[a-z0-9.]*` is\n // permissive on purpose; we reject the degenerate shapes here.\n if (op.endsWith('.') || op.includes('..')) return null;\n return { service, op };\n}\n\ninterface IntegrationReadyCacheEntry {\n /** null on success; ready-to-send error envelope when the binary isn't usable. */\n result: GitRpcResult | null;\n expiresAt: number;\n}\nconst integrationReadyCache = new Map<string, IntegrationReadyCacheEntry>();\n\n/**\n * Returns `null` when the host has the connector's binary on PATH;\n * otherwise a ready-to-send `{ exitCode, stdout, stderr }` envelope\n * describing what's missing. Cached per `connector.hostBin` for ~60s so a\n * burst of integration ops doesn't reprobe on every call (same TTL as\n * `assertGhReady`).\n *\n * - binary missing → exit 127 (matches Bash's \"command not found\").\n * - binary present but `--version` non-zero → propagate that exit.\n *\n * Auth-status is intentionally NOT probed here — `ntn` exits non-zero with\n * a clear \"not logged in\" message on every call when unauthed, which\n * surfaces directly through the relay's stdout/stderr passthrough. A\n * dedicated `auth` probe is the `agentbox doctor` flow (T3), not the\n * per-call hot path.\n */\nexport async function assertIntegrationReady(\n connector: IntegrationConnector,\n): Promise<GitRpcResult | null> {\n const now = Date.now();\n const cached = integrationReadyCache.get(connector.hostBin);\n if (cached && cached.expiresAt > now) return cached.result;\n const result = await probeIntegration(connector);\n integrationReadyCache.set(connector.hostBin, {\n result,\n expiresAt: now + INTEGRATION_READY_CACHE_TTL_MS,\n });\n return result;\n}\n\n/** Test-only: clear the readiness cache between cases. */\nexport function _resetIntegrationReadyCacheForTests(): void {\n integrationReadyCache.clear();\n}\n\nasync function probeIntegration(\n connector: IntegrationConnector,\n): Promise<GitRpcResult | null> {\n const version = await runHostBinary(\n connector,\n [...connector.detect.versionArgs],\n process.cwd(),\n 10_000,\n );\n if (version.exitCode === 127 || /ENOENT/.test(version.stderr)) {\n return {\n exitCode: 127,\n stdout: '',\n stderr: `${connector.hostBin} not installed on host (install the ${connector.service} CLI on the host)\\n`,\n };\n }\n if (version.exitCode !== 0) {\n return {\n exitCode: version.exitCode,\n stdout: '',\n stderr:\n `${connector.hostBin} ${connector.detect.versionArgs.join(' ')} failed: ` +\n (version.stderr || version.stdout).trimEnd() +\n '\\n',\n };\n }\n return null;\n}\n\n/**\n * Spawn the connector's host binary with the given op + user args inside\n * `cwd`. Returns the standard `{ exitCode, stdout, stderr }` envelope.\n * `op.buildArgv` (when supplied) shapes the host CLI's subcommand path;\n * absent, the user args are forwarded verbatim. A connector-declared\n * `<SERVICE>_*` env override (when present — none set today) is merged onto\n * `process.env` via `mergeConnectorEnv`; a descriptor that tries to set an\n * env var outside its `<SERVICE>_*` namespace yields a typed exit-78 envelope\n * (sysexits EX_CONFIG) rather than throwing, so the docker /rpc and\n * cloud paths both surface the misconfiguration as a normal envelope.\n *\n * Self-contained (no import dependency on the rest of the relay), same\n * cycle-avoidance reasoning as `runHostGh` in `gh.ts`.\n */\nexport function runHostIntegration(\n connector: IntegrationConnector,\n op: IntegrationOp,\n args: readonly string[],\n cwd: string,\n timeoutMs: number = INTEGRATION_RPC_TIMEOUT_MS,\n): Promise<GitRpcResult> {\n const argv = op.buildArgv ? op.buildArgv(args) : [...args];\n return runHostBinary(connector, argv, cwd, timeoutMs);\n}\n\n/**\n * Merge the relay's `process.env` with the connector's declared overrides,\n * but only let the connector set env vars whose names are in its\n * `<SERVICE>_…` namespace (or other deliberately-shared names) — never\n * relay-controlled prefixes like `AGENTBOX_*`, `PATH`, `HOME`, etc. A\n * careless future descriptor cannot disable the relay's prompt gate or\n * rewrite PATH by setting `env: { AGENTBOX_PROMPT: 'off' }`.\n */\nfunction mergeConnectorEnv(connector: IntegrationConnector): NodeJS.ProcessEnv {\n if (!connector.env) return process.env;\n const allowedPrefix = `${connector.service.toUpperCase()}_`;\n const env: NodeJS.ProcessEnv = { ...process.env };\n for (const [key, value] of Object.entries(connector.env)) {\n if (!key.startsWith(allowedPrefix)) {\n throw new Error(\n `integration ${connector.service}: env key '${key}' not in '${allowedPrefix}*' namespace; descriptor cannot set it`,\n );\n }\n env[key] = value;\n }\n return env;\n}\n\nfunction runHostBinary(\n connector: IntegrationConnector,\n argv: readonly string[],\n cwd: string,\n timeoutMs: number,\n): Promise<GitRpcResult> {\n let env: NodeJS.ProcessEnv;\n try {\n env = mergeConnectorEnv(connector);\n } catch (err) {\n // Bad descriptor — return a typed envelope so the in-box ctl prints\n // the actual cause instead of an opaque relay \"internal error\" 500.\n return Promise.resolve({\n exitCode: 78,\n stdout: '',\n stderr: `${connector.hostBin}: ${err instanceof Error ? err.message : String(err)}\\n`,\n });\n }\n return new Promise<GitRpcResult>((resolve) => {\n const child = spawn(connector.hostBin, [...argv], {\n cwd,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: ${connector.hostBin} command timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout += chunk.toString('utf8');\n });\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr += chunk.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n // ENOENT (binary missing) lands here too; surface as exit 127.\n const code = (err as NodeJS.ErrnoException).code;\n stderr += String(err.message ?? err);\n finish(code === 'ENOENT' ? 127 : 1);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/** Ready-to-send refusal for an op not on the connector's allowlist. */\nexport function makeIntegrationOpRefusal(\n service: string,\n op: string,\n hostBin: string,\n knownOps: readonly string[],\n): GitRpcResult {\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n `integration ${service}: op '${op}' not on allowlist for ${hostBin}. ` +\n `Available: ${knownOps.join(', ')}\\n`,\n };\n}\n\n/**\n * Run the op's `refuseCall` pre-flight (e.g. `notion.api`'s GET-only check)\n * and lift its `{exitCode, stderr}` shape into the relay's full\n * `GitRpcResult`. Returns null when the call may proceed.\n */\nexport function refuseIntegrationCall(\n op: IntegrationOp,\n args: readonly string[],\n): GitRpcResult | null {\n const refusal = op.refuseCall?.(args);\n if (!refusal) return null;\n return { exitCode: refusal.exitCode, stdout: '', stderr: refusal.stderr };\n}\n\n/**\n * Returns null when the integration is enabled for the box's project (so the\n * dispatch may proceed), else a ready-to-send refusal envelope. Re-reads the\n * layered config fresh on every call so toggling\n * `integrations.<svc>.enabled` takes effect without bouncing the relay —\n * same approach `loadAutopauseConfig` uses for the autopause loop.\n *\n * Layered (cli/workspace/project/global/default) so a single project can opt\n * in without globally enabling Notion. Defaults to disabled — every\n * integration ships in the image but is inert until flipped on.\n *\n * Injectable `loader` keeps unit tests off-disk.\n */\nexport async function refuseIfIntegrationDisabled(\n service: string,\n cwd: string,\n loader: (cwd: string) => Promise<{\n effective: { integrations?: Record<string, { enabled?: boolean } | undefined> };\n }> = loadEffectiveConfig,\n): Promise<GitRpcResult | null> {\n let enabled = false;\n try {\n const cfg = await loader(cwd);\n enabled = cfg.effective.integrations?.[service]?.enabled === true;\n } catch {\n // A malformed config file should fail closed — the box can't do anything\n // useful with a half-loaded config, and the agent gets a clear message\n // either way.\n }\n if (enabled) return null;\n return {\n exitCode: 65,\n stdout: '',\n stderr:\n `${service} integration is disabled — enable with ` +\n `\\`agentbox config set --project integrations.${service}.enabled true\\`\\n`,\n };\n}\n","/**\n * Shared decision for auto-approving file transfers between a box and the host\n * under `box.autoApproveSafeHostActions`. Used by both the docker (`server.ts`)\n * and cloud (`host-actions.ts`) cp/download handlers so the containment + secret\n * policy can't drift between the two transports.\n *\n * The rule: a transfer auto-approves only when every host-side path it touches\n * resolves *inside the box's project folder* (`workspacePath`), following\n * symlinks. For a host->box copy, a secret-looking source additionally keeps the\n * prompt unless that exact file was already approved via the `carry:` block.\n * Anything else falls back to the interactive confirm — the prompt is never\n * removed, only skipped when provably safe.\n */\n\nimport { isContainedInWorkspace, looksLikeSecret, realpathSafe } from '@agentbox/core';\n\nexport interface TransferApproveInput {\n /** `box.autoApproveSafeHostActions` (false → always prompt). */\n enabled: boolean;\n /** The box's host project folder; relative paths already resolved against it. */\n workspacePath: string | undefined;\n /**\n * Resolved host-side paths the transfer touches: the *destination* for\n * box->host (cp.toHost / download), the *sources* for host->box (cp.fromHost).\n */\n hostPaths: string[];\n /** Apply the secret-file guard (host->box only). */\n checkSecret: boolean;\n /** realpath'd host sources already approved via `carry:` (secret exemption). */\n carried?: Set<string>;\n}\n\n/**\n * True when the transfer may skip the approval prompt. Conservative: any\n * uncontained path, any not-yet-carried secret source, an unknown workspace, or\n * the feature being disabled all return false (→ the caller prompts).\n */\nexport async function canAutoApproveTransfer(input: TransferApproveInput): Promise<boolean> {\n if (!input.enabled) return false;\n if (!input.workspacePath || input.hostPaths.length === 0) return false;\n for (const p of input.hostPaths) {\n if (!(await isContainedInWorkspace(p, input.workspacePath))) return false;\n if (input.checkSecret && looksLikeSecret(p)) {\n const real = await realpathSafe(p);\n if (!input.carried?.has(real)) return false;\n }\n }\n return true;\n}\n","/**\n * `HostActionQueue` — the box-mode relay's parking lot for host-only RPCs.\n * When the in-sandbox `/rpc` route receives `git.push` / `cp.*` / etc., it\n * cannot execute them locally (no host SSH keys, no host filesystem), so it\n * `enqueue`s and `await`s. The host's `CloudBoxPoller` drains via\n * `/bridge/poll`, executes on the host, and `resolve`s here via\n * `/bridge/action-result` — that resolves the awaited Promise and the\n * in-sandbox `/rpc` finally answers the in-box agent.\n *\n * Lifetime: per in-sandbox relay process; in-memory only. Actions outlive\n * individual polls (the queue is the source of truth, not the wire).\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { HostAction, HostActionResult } from './types.js';\n\ninterface Pending {\n action: HostAction;\n resolve: (r: HostActionResult) => void;\n /** True once a `/bridge/poll` has handed this action out. */\n delivered: boolean;\n}\n\n/**\n * Default max age for a parked action before it expires (15 minutes).\n * Picked to be longer than any reasonable interactive prompt + a host\n * restart window, but short enough that a forgotten queue doesn't replay\n * stale `git.push` attempts when the host relay rehydrates. Override per\n * queue instance for tests.\n */\nexport const DEFAULT_HOST_ACTION_MAX_AGE_MS = 15 * 60 * 1000;\n\nexport interface HostActionQueueOptions {\n /** Override the per-action expiry. Default {@link DEFAULT_HOST_ACTION_MAX_AGE_MS}. */\n maxAgeMs?: number;\n /** Clock injector (tests). */\n now?: () => number;\n}\n\nexport class HostActionQueue {\n private readonly map = new Map<string, Pending>();\n private readonly maxAgeMs: number;\n private readonly now: () => number;\n\n constructor(opts: HostActionQueueOptions = {}) {\n this.maxAgeMs = opts.maxAgeMs ?? DEFAULT_HOST_ACTION_MAX_AGE_MS;\n this.now = opts.now ?? ((): number => Date.now());\n }\n\n /**\n * Park a host-only RPC and return a Promise that resolves when the host\n * poller posts the result back. Caller should `await` and forward the\n * result to the in-box client; there's intentionally no client-side\n * timeout (matches the existing in-box `postRpc`'s \"block while a prompt\n * is open\" semantics).\n */\n enqueue(boxId: string, method: string, params: unknown): Promise<HostActionResult> {\n const id = randomUUID();\n const action: HostAction = {\n id,\n boxId,\n method,\n params,\n createdAt: new Date(this.now()).toISOString(),\n };\n return new Promise<HostActionResult>((resolve) => {\n this.map.set(id, { action, resolve, delivered: false });\n });\n }\n\n /**\n * Return every action the host hasn't been handed yet, marking them\n * delivered. The poller is expected to execute them and POST back to\n * `/bridge/action-result`. Re-delivery on poller retry isn't needed —\n * the queue holds the Promise until `resolve` is called.\n *\n * Actions older than `maxAgeMs` expire here: their `resolve` is called\n * with an `exitCode: 124, stderr: 'expired'` result so the in-box RPC\n * unblocks, and they don't appear in the drained list. Keeps a host\n * relay restart from replaying a long-forgotten `git.push`.\n */\n drain(): HostAction[] {\n const now = this.now();\n const out: HostAction[] = [];\n for (const [id, p] of this.map) {\n const createdAt = Date.parse(p.action.createdAt);\n if (Number.isFinite(createdAt) && now - createdAt > this.maxAgeMs) {\n this.map.delete(id);\n p.resolve({\n exitCode: 124,\n stdout: '',\n stderr: `host action '${p.action.method}' expired before the host could execute it\\n`,\n });\n continue;\n }\n if (!p.delivered) {\n out.push(p.action);\n p.delivered = true;\n }\n }\n return out;\n }\n\n /**\n * Settle a parked action with the host's result. Idempotent: a duplicate\n * resolve on the same id is a no-op. Returns whether the id matched.\n */\n resolve(id: string, result: HostActionResult): boolean {\n const p = this.map.get(id);\n if (!p) return false;\n this.map.delete(id);\n p.resolve(result);\n return true;\n }\n\n size(): number {\n return this.map.size;\n }\n\n /** Test/diagnostic: get the action with this id (returns undefined when settled). */\n peek(id: string): HostAction | undefined {\n return this.map.get(id)?.action;\n }\n}\n","/**\n * A minimal in-process fan-out for the embedded hub UI. The hub's SSE route\n * (`/api/events`) subscribes; the relay calls `notify()` whenever the pending\n * approvals set changes (via `PendingPrompts.setOnChange`), so connected\n * browsers refresh without polling. No `EventEmitter` dependency — the surface\n * is just subscribe/notify.\n */\nexport class HubNotifier {\n private readonly listeners = new Set<() => void>();\n\n /** Register a listener; returns an unsubscribe fn. */\n subscribe(fn: () => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n /** Fire every listener. A throwing listener never blocks the others. */\n notify(): void {\n for (const fn of this.listeners) {\n try {\n fn();\n } catch {\n /* a dead listener must not break the fan-out */\n }\n }\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type { PromptSubscribers } from './prompts.js';\nimport type { BoxNoticeEvent, NoticeKind } from './types.js';\n\n/**\n * Default lifespan of a notice when its owner never clears it explicitly.\n * Longer than the relay's checkpoint RPC timeout (600s) so a notice still\n * self-expires even if the host CLI is SIGKILLed before its `finally` runs.\n */\nconst DEFAULT_NOTICE_TTL_MS = 660_000;\n\ninterface NoticeEntry {\n ev: BoxNoticeEvent;\n boxId: string;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * In-memory per-box informational notices, broadcast over the same SSE\n * channel as confirmation prompts. Unlike {@link import('./prompts.js').PendingPrompts}\n * these are fire-and-forget: there is no awaited promise and no answer. A\n * notice marks a box as transiently busy (a checkpoint freezes it via\n * `docker commit`); the host wrapper renders a spinner so the user can\n * tell the box from stuck.\n *\n * Deliberately NOT gated by `AGENTBOX_PROMPT=off` (which `askPrompt`\n * honours): a notice is informational, not a consent gate, so suppressing\n * it would only hide useful feedback.\n */\nexport class BoxNotices {\n /** keyed by notice id. */\n private readonly entries = new Map<string, NoticeEntry>();\n\n constructor(private readonly subscribers: PromptSubscribers) {}\n\n /**\n * Register a notice for `boxId` and broadcast `notice-set`. At most one\n * notice per (box, kind) is kept — a fresh `set` for the same kind\n * replaces the previous one (and cancels its TTL timer so a stale timer\n * can't later fire a `notice-clear` racing the replacement). Returns the\n * generated notice id.\n */\n set(boxId: string, kind: NoticeKind, message: string, ttlMs?: number): string {\n for (const [id, entry] of this.entries) {\n if (entry.boxId === boxId && entry.ev.kind === kind) {\n clearTimeout(entry.timer);\n this.entries.delete(id);\n }\n }\n const ev: BoxNoticeEvent = { id: randomUUID(), kind, message };\n const ttl = typeof ttlMs === 'number' && ttlMs > 0 ? ttlMs : DEFAULT_NOTICE_TTL_MS;\n const timer = setTimeout(() => {\n // Safety net: a notice whose owner died without clearing it self-expires.\n if (this.entries.delete(ev.id)) {\n this.subscribers.broadcast(boxId, 'notice-clear', { id: ev.id });\n }\n }, ttl);\n if (typeof timer.unref === 'function') timer.unref();\n this.entries.set(ev.id, { ev, boxId, timer });\n this.subscribers.broadcast(boxId, 'notice-set', ev);\n return ev.id;\n }\n\n /**\n * Clear a notice by id. Idempotent: returns false when no such notice\n * exists (already cleared / expired). Broadcasts `notice-clear` on a hit.\n */\n clear(id: string): boolean {\n const entry = this.entries.get(id);\n if (!entry) return false;\n clearTimeout(entry.timer);\n this.entries.delete(id);\n this.subscribers.broadcast(entry.boxId, 'notice-clear', { id });\n return true;\n }\n\n /** Snapshot of active notices for a box; replayed to a new SSE subscriber. */\n forBox(boxId: string): BoxNoticeEvent[] {\n const out: BoxNoticeEvent[] = [];\n for (const entry of this.entries.values()) {\n if (entry.boxId === boxId) out.push(entry.ev);\n }\n return out;\n }\n\n size(): number {\n return this.entries.size;\n }\n}\n","import { timingSafeEqual } from 'node:crypto';\n\n/** Constant-time string compare (length leak only, like the HTTP handlers accept). */\nexport function timingSafeEqualStr(a: string, b: string): boolean {\n const ab = Buffer.from(a, 'utf8');\n const bb = Buffer.from(b, 'utf8');\n if (ab.length !== bb.length) return false;\n return timingSafeEqual(ab, bb);\n}\n\n/**\n * Whether an `/admin/*` request may proceed on the full relay/hub.\n *\n * Loopback callers are the host CLI/tray — always allowed (unchanged laptop\n * behavior). A non-loopback caller is allowed only when it presents the\n * configured admin bearer: the control box is network-reachable behind Caddy,\n * and its own resident worker + the PC (phase 4) reach `/admin/*` through the\n * public URL. Fail-closed: with no admin token configured the gate stays\n * loopback-only, so a laptop relay (which never sets one) exposes nothing new.\n */\nexport function adminGateAllows(\n isLoopback: boolean,\n bearer: string | undefined,\n adminToken: string,\n): boolean {\n if (isLoopback) return true;\n if (adminToken.length === 0) return false;\n return Boolean(bearer) && timingSafeEqualStr(bearer ?? '', adminToken);\n}\n","/**\n * Byte-offset tail of a create job's progress log\n * (`~/.agentbox/logs/queue-<jobId>.log`, written by the hub worker's job logger).\n *\n * This is what lets a PC watching a hub-routed create see the same lines a local\n * create prints: the `/remote/boxes/:id/logs` route hands this back, and the\n * CLI's poll loop drains it between status checks. Deliberately fs-only — the\n * `/remote/boxes` dispatcher stays framework-agnostic and injects this, so the\n * serverless plane (which has no such file) simply doesn't wire it.\n */\n\nimport { open, stat } from 'node:fs/promises';\nimport { queueLogPath } from './queue.js';\nimport { isSafeJobId } from './remote-boxes.js';\n\n/** Per-response ceiling. A busy job just gets drained over several polls. */\nconst MAX_BYTES_PER_READ = 64 * 1024;\n\nexport interface JobLogTail {\n /** Whole lines appended since the requested offset. */\n lines: string[];\n /** Byte offset to pass to the next call — never mid-line. */\n offset: number;\n}\n\n/**\n * Read whole lines appended to job `id`'s log after `offset`.\n *\n * A missing file is normal, not an error: the job can be claimed a tick before\n * the worker writes its first line, and a job that never ran has no log at all.\n * The id is re-checked here so this is safe to call from anywhere, not only\n * from behind the route's own {@link isSafeJobId} gate.\n * The returned offset only ever advances past complete lines, so a read that\n * lands mid-line re-reads that line's bytes next time rather than emitting a\n * truncated line or dropping it.\n */\nexport async function readCreateJobLog(id: string, offset: number): Promise<JobLogTail> {\n const from = Number.isFinite(offset) && offset > 0 ? Math.floor(offset) : 0;\n if (!isSafeJobId(id)) return { lines: [], offset: from };\n const path = queueLogPath(id);\n\n let size: number;\n try {\n size = (await stat(path)).size;\n } catch {\n return { lines: [], offset: from };\n }\n // A truncated/rotated file (size < offset) restarts the tail from the top\n // rather than reading past EOF forever.\n const start = size < from ? 0 : from;\n if (size <= start) return { lines: [], offset: start };\n\n const len = Math.min(size - start, MAX_BYTES_PER_READ);\n const buf = Buffer.alloc(len);\n const fh = await open(path, 'r');\n try {\n await fh.read(buf, 0, len, start);\n } finally {\n await fh.close();\n }\n\n const chunk = buf.toString('utf8');\n const lastNewline = chunk.lastIndexOf('\\n');\n if (lastNewline < 0) {\n // No complete line in this window. Only possible for a single line longer\n // than the cap — hand it over and move on, or the tail would wedge here.\n return len >= MAX_BYTES_PER_READ\n ? { lines: [chunk], offset: start + len }\n : { lines: [], offset: start };\n }\n const complete = chunk.slice(0, lastNewline);\n const consumed = Buffer.byteLength(complete, 'utf8') + 1;\n return {\n lines: complete.split('\\n').filter((l) => l.length > 0),\n offset: start + consumed,\n };\n}\n","/**\n * Host-side handler for the ctl credential watcher's `credentials-updated`\n * events (see `packages/ctl/src/credentials-watcher.ts`). Claude's OAuth\n * refresh rotates the refresh token, so the moment one box refreshes, every\n * other copy (host backup, other boxes) is dead — this accepts the freshest\n * blob into `~/.agentbox/<agent>-credentials.json` (newest-wins) and fans it\n * out to all other boxes by spawning the host CLI\n * (`agentbox credentials propagate`), the same decoupling as the relay's\n * checkpoint/cp handlers.\n *\n * The payload carries a secret: callers must never append these events to the\n * event ring buffer (mirrors how `box-status` skips the ring).\n *\n * Concurrency: per-agent debounce (bursts collapse to one fan-out) + a\n * per-agent promise chain (fan-outs never overlap; a fresh accept during an\n * in-flight run schedules one more). The spawned CLI always reads the\n * *current* backup, so collapsed runs lose nothing.\n */\n\nimport { execa } from 'execa';\nimport {\n parseCredentialsUpdate,\n readCredentialBackup,\n resolveAgentSpec,\n shouldAcceptCredentialUpdate,\n writeCredentialBackup,\n type CredentialAgentKind,\n} from '@agentbox/sandbox-core';\n\n/** Mirrors `CREDENTIALS_UPDATED_EVENT` in @agentbox/ctl (like `box-status`). */\nexport const CREDENTIALS_UPDATED_EVENT = 'credentials-updated';\n\nexport interface CredentialsFanoutDeps {\n log: (msg: string) => void;\n /** Debounce before spawning the propagate CLI. Default 3000ms. */\n debounceMs?: number;\n /** Override the fan-out spawn (tests). Default: spawn the host CLI. */\n runPropagate?: (agent: CredentialAgentKind, sourceBoxId: string) => Promise<void>;\n /** Override the per-agent backup path (tests; default: the registry's). */\n backupPathFor?: (agent: CredentialAgentKind) => string;\n /**\n * The control box's custody store, when this relay owns one. Present ⇒ an\n * accepted credential is mirrored into `agents/<id>/…` so the next hub create\n * seeds from a current copy rather than the last one a PC pushed.\n */\n custody?: CredentialCustodyWriter | null;\n}\n\n/** The single write this needs from a custody store (structural: no import cycle). */\nexport interface CredentialCustodyWriter {\n put(path: string, data: Buffer): Promise<unknown>;\n}\n\nexport interface CredentialsHandleResult {\n accepted: boolean;\n reason: string;\n}\n\nexport class CredentialsFanout {\n private readonly log: (msg: string) => void;\n private readonly debounceMs: number;\n private readonly runPropagate: (agent: CredentialAgentKind, sourceBoxId: string) => Promise<void>;\n private readonly backupPathFor?: (agent: CredentialAgentKind) => string;\n private readonly custody: CredentialCustodyWriter | null;\n private readonly pending = new Map<CredentialAgentKind, NodeJS.Timeout>();\n private readonly chains = new Map<CredentialAgentKind, Promise<void>>();\n\n constructor(deps: CredentialsFanoutDeps) {\n this.log = deps.log;\n this.debounceMs = deps.debounceMs ?? 3_000;\n this.runPropagate = deps.runPropagate ?? defaultRunPropagate;\n this.backupPathFor = deps.backupPathFor;\n this.custody = deps.custody ?? null;\n }\n\n /**\n * Validate, newest-wins-gate, persist the host backup, and schedule the\n * fan-out. Fast (no box I/O); the propagate CLI does the slow work detached.\n */\n async handle(sourceBoxId: string, payload: unknown): Promise<CredentialsHandleResult> {\n const update = parseCredentialsUpdate(payload);\n if (!update) return { accepted: false, reason: 'invalid payload' };\n const backupPath = this.backupPathFor?.(update.agent);\n const existing = await readCredentialBackup(update.agent, { backupPath });\n const verdict = shouldAcceptCredentialUpdate(update.agent, update.content, existing);\n if (!verdict.accept) {\n return { accepted: false, reason: verdict.reason };\n }\n await writeCredentialBackup(update.agent, update.content, { backupPath });\n await this.recordInCustody(update.agent, update.content);\n this.log(\n `credentials: accepted ${update.agent} update from box ${sourceBoxId} (${verdict.reason}); fan-out in ${String(this.debounceMs)}ms`,\n );\n this.schedule(update.agent, sourceBoxId);\n return { accepted: true, reason: verdict.reason };\n }\n\n /**\n * Mirror the accepted blob into custody, on a control box.\n *\n * Without this the freshest token lives ONLY in the host backup, and the next\n * hub create re-seeds that backup from custody — a copy that is only as new as\n * the last PC push. Since a refresh rotates the token, every box built after\n * that came up with a dead credential. Writing here is what makes custody\n * self-healing: the boxes refreshing their own tokens keep it current with no\n * PC involvement.\n *\n * Best-effort by design — a custody failure must not cost us the fan-out,\n * which is the part that fixes the boxes that are already running.\n */\n private async recordInCustody(agent: CredentialAgentKind, content: string): Promise<void> {\n if (!this.custody) return;\n try {\n const spec = resolveAgentSpec(agent);\n await this.custody.put(\n `agents/${agent}/${spec.credential.boxRelPath}`,\n Buffer.from(content, 'utf8'),\n );\n } catch (err) {\n this.log(\n `credentials: could not record ${agent} in custody: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n private schedule(agent: CredentialAgentKind, sourceBoxId: string): void {\n const existing = this.pending.get(agent);\n if (existing) clearTimeout(existing);\n const timer = setTimeout(() => {\n this.pending.delete(agent);\n const prev = this.chains.get(agent) ?? Promise.resolve();\n const next = prev\n .then(() => this.runPropagate(agent, sourceBoxId))\n .catch((err: unknown) => {\n this.log(\n `credentials: ${agent} fan-out failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n this.chains.set(agent, next);\n }, this.debounceMs);\n timer.unref();\n this.pending.set(agent, timer);\n }\n\n /** Pending debounce timers + in-flight chain, for tests/shutdown. */\n async flush(): Promise<void> {\n for (const [agent, timer] of this.pending) {\n clearTimeout(timer);\n this.pending.delete(agent);\n void agent;\n }\n await Promise.all([...this.chains.values()]);\n }\n}\n\n/**\n * Spawn `agentbox credentials propagate` via the CLI entry the daemon was\n * started with — the CLI owns provider resolution and per-box transports\n * (same pattern as the checkpoint/cp host actions).\n */\nasync function defaultRunPropagate(\n agent: CredentialAgentKind,\n sourceBoxId: string,\n): Promise<void> {\n const entry = process.env['AGENTBOX_CLI_ENTRY'];\n if (!entry) {\n throw new Error('AGENTBOX_CLI_ENTRY not set; cannot run credential propagate host-side');\n }\n const result = await execa(\n process.execPath,\n [entry, 'credentials', 'propagate', '--agent', agent, '--source-box', sourceBoxId],\n { reject: false, timeout: 300_000 },\n );\n if (result.exitCode !== 0) {\n throw new Error(\n `credentials propagate exited ${String(result.exitCode)}: ${String(result.stderr).slice(-300)}`,\n );\n }\n}\n","import { spawn } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type UserConfig,\n} from '@agentbox/config';\nimport { readActiveAgent, type WorkingAgentState } from './queue.js';\nimport type { BoxRegistry, EventBuffer } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\nexport interface AutopauseConfig {\n enabled: boolean;\n maxRunningBoxes: number;\n idleMinutes: number;\n}\n\nexport type ContainerState = 'running' | 'paused' | 'stopped' | 'missing';\nexport type ClaudeState = 'working' | 'idle' | 'waiting' | 'unknown';\n\n/** One box's runtime facts the pure selector reasons about. No I/O, no clock. */\nexport interface BoxScanEntry {\n boxId: string;\n containerName: string;\n /** docker inspect status === 'running'. */\n running: boolean;\n /** Latest reported claude activity, or null when no snapshot exists. */\n claudeState: ClaudeState | null;\n /** ms the box has been idle (now - claude.updatedAt) when idle; else null. */\n idleMs: number | null;\n /** Box creation time as epoch ms; 0 when unknown/unparseable. */\n createdAt: number;\n}\n\n/**\n * Pure selection: given each running box's idle facts and the config, return\n * the boxIds to pause, in pause order. Pauses only enough to bring the running\n * count back to `maxRunningBoxes`, picking provably-idle boxes longest-idle\n * first (tie-break: oldest box, then boxId for determinism).\n */\nexport function selectBoxesToPause(entries: BoxScanEntry[], cfg: AutopauseConfig): string[] {\n if (!cfg.enabled) return [];\n const runningCount = entries.reduce((n, e) => (e.running ? n + 1 : n), 0);\n const excess = runningCount - cfg.maxRunningBoxes;\n if (excess <= 0) return [];\n\n const idleThresholdMs = cfg.idleMinutes * 60_000;\n const candidates = entries.filter(\n (e) => e.running && e.claudeState === 'idle' && e.idleMs != null && e.idleMs >= idleThresholdMs,\n );\n candidates.sort(\n (a, b) =>\n (b.idleMs as number) - (a.idleMs as number) ||\n a.createdAt - b.createdAt ||\n (a.boxId < b.boxId ? -1 : a.boxId > b.boxId ? 1 : 0),\n );\n return candidates.slice(0, excess).map((e) => e.boxId);\n}\n\n/**\n * Global+built-in autopause config. The relay is host-wide (not project\n * scoped), so it deliberately ignores the project/workspace layers that\n * `loadEffectiveConfig` would apply. Re-read every tick so\n * `agentbox config set --global autopause.*` takes effect without a relay\n * restart. A missing or malformed global file falls back to built-in defaults.\n */\nexport async function loadAutopauseConfig(): Promise<AutopauseConfig> {\n const d = BUILT_IN_DEFAULTS.autopause;\n let global: Partial<UserConfig> = {};\n try {\n global = parseUserConfig(await readFile(GLOBAL_CONFIG_FILE, 'utf8'), GLOBAL_CONFIG_FILE);\n } catch {\n // ENOENT (no global config yet) or a parse error -> built-in defaults.\n }\n const a = global.autopause ?? {};\n return {\n enabled: a.enabled ?? d.enabled,\n maxRunningBoxes: a.maxRunningBoxes ?? d.maxRunningBoxes,\n idleMinutes: a.idleMinutes ?? d.idleMinutes,\n };\n}\n\nexport interface AutopauseLoopDeps {\n registry: BoxRegistry;\n statusStore: BoxStatusStore;\n events: EventBuffer;\n log: (line: string) => void;\n /** Injectable for tests; defaults to the global-config loader. */\n loadConfig?: () => Promise<AutopauseConfig>;\n /** Injectable for tests; defaults to `docker inspect`. */\n inspectStatus?: (containerName: string) => Promise<ContainerState>;\n /** Injectable for tests; defaults to `docker pause`. */\n pause?: (containerName: string) => Promise<void>;\n intervalMs?: number;\n}\n\nexport interface AutopauseLoopHandle {\n /** Stop scheduling and await any in-flight tick. */\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000;\n\nexport function startAutopauseLoop(deps: AutopauseLoopDeps): AutopauseLoopHandle {\n const loadConfig = deps.loadConfig ?? loadAutopauseConfig;\n const inspectStatus = deps.inspectStatus ?? inspectContainerState;\n const pause = deps.pause ?? pauseContainer;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { registry, statusStore, events, log } = deps;\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function tick(): Promise<void> {\n // A slow tick (many `docker inspect`s) must not overlap the next interval.\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n if (!cfg.enabled) return;\n\n const entries: BoxScanEntry[] = [];\n for (const reg of registry.list()) {\n if (!reg.containerName) continue; // pre-feature box; can't pause it\n const state = await inspectStatus(reg.containerName);\n const active = readPauseState(statusStore.get(reg.boxId));\n const idleMs =\n active.state === 'idle' && active.updatedAt ? msSince(active.updatedAt) : null;\n entries.push({\n boxId: reg.boxId,\n containerName: reg.containerName,\n running: state === 'running',\n claudeState: active.state,\n idleMs,\n createdAt: reg.createdAt ? toEpoch(reg.createdAt) : 0,\n });\n }\n\n const toPause = selectBoxesToPause(entries, cfg);\n if (toPause.length === 0) return;\n\n const byId = new Map(entries.map((e) => [e.boxId, e]));\n const runningBefore = entries.reduce((n, e) => (e.running ? n + 1 : n), 0);\n for (const boxId of toPause) {\n const e = byId.get(boxId);\n if (!e) continue;\n try {\n await pause(e.containerName);\n const mins = e.idleMs != null ? Math.round(e.idleMs / 60_000) : null;\n events.append({\n boxId,\n type: 'autopause',\n payload: {\n containerName: e.containerName,\n action: 'paused',\n idleMs: e.idleMs,\n runningBefore,\n max: cfg.maxRunningBoxes,\n },\n });\n log(\n `autopause: paused box ${boxId} (${e.containerName})` +\n (mins != null ? ` after ~${String(mins)}m idle` : '') +\n `; running ${String(runningBefore)} -> target ${String(cfg.maxRunningBoxes)}`,\n );\n } catch (err) {\n // docker failure is non-fatal: log, record, keep going.\n const msg = err instanceof Error ? err.message : String(err);\n log(`autopause: docker pause ${e.containerName} failed: ${msg}`);\n events.append({\n boxId,\n type: 'autopause',\n payload: { containerName: e.containerName, action: 'pause-failed', error: msg },\n });\n }\n }\n } catch (err) {\n // The loop must never crash the relay or stop scheduling.\n const msg = err instanceof Error ? err.message : String(err);\n log(`autopause: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n // The HTTP server keeps the process alive; the timer shouldn't on its own.\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n\ninterface ClaudeSnap {\n state: ClaudeState | null;\n updatedAt: string | null;\n}\n\n/**\n * Coarse activity state for the pause decision, across ALL agents\n * (claude/codex/opencode) — not just claude. Reuses the queue loop's\n * multi-agent reader so a box where codex/opencode is working isn't paused\n * because claude happens to be idle or absent. Any active state (working,\n * compacting, waiting, end-plan, question, error) maps to a non-`idle` value,\n * so only a box whose live agent has settled to `idle` becomes a candidate.\n */\nfunction readPauseState(snap: Record<string, unknown> | undefined): ClaudeSnap {\n const active = readActiveAgent(snap);\n return { state: coarsePauseState(active.state), updatedAt: active.updatedAt };\n}\n\nfunction coarsePauseState(s: WorkingAgentState | null): ClaudeState | null {\n switch (s) {\n case 'idle':\n return 'idle';\n case 'waiting':\n return 'waiting';\n case 'working':\n case 'compacting':\n return 'working';\n case null:\n return null;\n // end-plan / question / error / unknown: a live session expecting attention\n // — never auto-pause it (maps to a non-idle, non-candidate state).\n default:\n return 'unknown';\n }\n}\n\nfunction msSince(iso: string): number | null {\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : Date.now() - t;\n}\n\nfunction toEpoch(iso: string): number {\n const t = Date.parse(iso);\n return Number.isNaN(t) ? 0 : t;\n}\n\nconst INSPECT_TIMEOUT_MS = 15_000;\nconst PAUSE_TIMEOUT_MS = 30_000;\n\ninterface DockerResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runDocker(args: string[], timeoutMs: number): Promise<DockerResult> {\n return new Promise<DockerResult>((resolve) => {\n const child = spawn('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (exitCode: number): void => {\n if (settled) return;\n settled = true;\n resolve({ exitCode, stdout, stderr });\n };\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n stderr += `\\nrelay: docker ${args.join(' ')} timed out after ${String(timeoutMs)}ms\\n`;\n finish(124);\n }, timeoutMs);\n child.stdout?.on('data', (c: Buffer) => {\n stdout += c.toString('utf8');\n });\n child.stderr?.on('data', (c: Buffer) => {\n stderr += c.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(timer);\n stderr += String(err.message ?? err);\n finish(127);\n });\n child.on('close', (code) => {\n clearTimeout(timer);\n finish(code ?? -1);\n });\n });\n}\n\n/** Mirrors `inspectContainerStatus` in @agentbox/sandbox-docker (no dep on it — cycle). */\nasync function inspectContainerState(name: string): Promise<ContainerState> {\n const r = await runDocker(['inspect', '--format', '{{.State.Status}}', name], INSPECT_TIMEOUT_MS);\n if (r.exitCode !== 0) return 'missing';\n switch (r.stdout.trim()) {\n case 'running':\n return 'running';\n case 'paused':\n return 'paused';\n case 'created':\n case 'exited':\n case 'dead':\n case 'restarting':\n case 'removing':\n return 'stopped';\n default:\n return 'missing';\n }\n}\n\nasync function pauseContainer(name: string): Promise<void> {\n const r = await runDocker(['pause', name], PAUSE_TIMEOUT_MS);\n if (r.exitCode !== 0) {\n throw new Error(r.stderr.trim() || `docker pause ${name} exited ${String(r.exitCode)}`);\n }\n}\n","/**\n * `startCloudKeepaliveLoop` — host-resident loop that renews a cloud box's\n * session-timeout while its in-box agent is active, so a long-running\n * Claude/Codex session isn't killed when the create-time timeout elapses.\n *\n * Sibling to `startAutopauseLoop` (and modeled on it): a host-wide sweep on a\n * timer that reads each box's live agent state from the `BoxStatusStore` and\n * acts. Where autopause *pauses* idle docker boxes, this *keeps alive* active\n * cloud boxes by pushing their death-time out. The window REUSES the autopause\n * idle threshold (`autopause.idleMinutes`) — per the design, there is no\n * separate keepalive knob.\n *\n * - active agent -> hold the death-time a full window ahead of NOW.\n * - idle agent -> let it lapse a window after it went idle, then stop.\n *\n * \"Let it lapse\" only works when the provider's timeout is an absolute deadline\n * (vercel, e2b). Daytona's is an INACTIVITY window that any request resets —\n * and this host polls every cloud box's preview URL continuously, so its clock\n * never runs out and an idle box would bill forever. For those backends\n * (`CloudBackend.timeoutModel === 'inactivity'`) the loop performs the stop\n * itself: see `selectBoxesToIdlePause`.\n *\n * The additive-vs-absolute SDK split (vercel `extendTimeout` adds to the\n * current deadline and can't read remaining; e2b `setTimeout` sets TTL from\n * now) is resolved by tracking each box's intended deadline in memory and\n * handing the backend BOTH the absolute target and our tracked current\n * deadline. See `CloudBackend.renewTimeout`. The tracked deadline is seeded\n * from the box's RECORDED effective create timeout (`cloud.sessionTimeoutMs`)\n * so a project/workspace override doesn't desync the seed.\n *\n * Plan caps (vercel Hobby ~45m, Pro+ ~5h; e2b team plan) bound how far a box\n * can be extended — a renew past the cap throws and is swallowed here, after\n * which the box is briefly backed off (so we don't hammer the API / log) and\n * lapses normally. The feature mainly benefits Pro+ plans, where the\n * conservative 45-min create default otherwise kills long sessions early.\n */\n\nimport { readFile } from 'node:fs/promises';\nimport {\n BUILT_IN_DEFAULTS,\n GLOBAL_CONFIG_FILE,\n parseUserConfig,\n type UserConfig,\n} from '@agentbox/config';\nimport type { CloudBackend } from '@agentbox/core';\nimport { findBox, readState, recordBox } from '@agentbox/sandbox-core';\nimport { loadAutopauseConfig, type AutopauseConfig } from './autopause.js';\nimport { resolveCloudBackend } from './host-actions.js';\nimport { readActiveAgent, type WorkingAgentState } from './queue.js';\nimport type { BoxRegistry } from './registry.js';\nimport type { BoxStatusStore } from './status-store.js';\n\n/** Coarse activity for the renewal decision. `active` = keep the box alive. */\nexport type KeepaliveAgentState = 'active' | 'idle' | null;\n\n/** One box's facts the pure selector reasons about. No I/O, no clock. */\nexport interface KeepaliveScanEntry {\n boxId: string;\n /** Cloud backend name, e.g. 'vercel'. */\n backend: string;\n /** Coarse activity across claude/codex/opencode, or null when no snapshot. */\n agentState: KeepaliveAgentState;\n /** epoch ms of the active agent's `updatedAt`, or null when no snapshot. */\n lastActivityMs: number | null;\n}\n\nexport interface RenewDecision {\n boxId: string;\n backend: string;\n /** Absolute death-time we want this box held at. */\n targetDeadlineEpochMs: number;\n}\n\n/**\n * Pure selection: given each cloud box's activity facts, the window, and the\n * clock, return the boxes to renew with their target death-time.\n *\n * - active agent -> keep alive a full window from NOW (`now + windowMs`).\n * - idle, < window since it went idle -> lapse `window` after it went idle\n * (`lastActivityMs + windowMs`, where `lastActivityMs` is the fresh\n * working->idle transition time).\n * - idle >= window, no agent state, or a wedged agent (error/unknown) -> skip.\n *\n * The active case anchors on `now`, NOT on `lastActivityMs`, and does NOT\n * require `lastActivityMs`: the in-box status reporter bumps `updatedAt` on\n * state changes (per-tool-call), not during a long single `working` op (a\n * 30-min test run), so a stale/absent `updatedAt` must not freeze the target\n * below the tracked deadline — that would kill the box mid-work, the exact\n * failure this feature prevents. The idle case stays `now`-independent so an\n * idle box still lapses.\n */\nexport function selectBoxesToRenew(\n entries: KeepaliveScanEntry[],\n windowMs: number,\n now: number,\n): RenewDecision[] {\n const out: RenewDecision[] = [];\n for (const e of entries) {\n if (e.agentState == null) continue;\n let target: number | null = null;\n if (e.agentState === 'active') {\n target = now + windowMs;\n } else if (\n e.agentState === 'idle' &&\n e.lastActivityMs != null &&\n now - e.lastActivityMs < windowMs\n ) {\n target = e.lastActivityMs + windowMs;\n }\n if (target != null) {\n out.push({ boxId: e.boxId, backend: e.backend, targetDeadlineEpochMs: target });\n }\n }\n return out;\n}\n\n/**\n * Would an `inactivity`-model backend have stopped this box by now, had our own\n * polling not kept resetting its idle clock (see `CloudBackend.timeoutModel`)?\n * If so the host pauses it, standing in for the provider's dead timer.\n *\n * `idleWindowMs` is the BOX'S OWN idle timeout — the one it was created with\n * (`cloud.sessionTimeoutMs`, i.e. `box.daytonaTimeoutMs`, 25 min by default) —\n * NOT the keepalive/autopause renewal window (5 min). We are emulating the\n * provider's timer, so we must honour the interval the user configured for it;\n * using the renewal window would pause boxes five times sooner than\n * `box.daytonaTimeoutMs` advertises. A window of `0` means the user disabled\n * the idle timeout, and the caller skips the box entirely.\n *\n * Only a box with a definite `idle` agent is a candidate. A box with no agent\n * state at all (`null` — a plain `agentbox shell` box, or one whose reporter\n * hasn't spoken yet) is left alone: we have no evidence it's unused, and an\n * attached human is exactly the case we must not pull the floor out from under.\n * An `active` agent (incl. waiting/question) is never a candidate.\n */\nexport function shouldIdlePause(\n e: KeepaliveScanEntry,\n idleWindowMs: number,\n now: number,\n): boolean {\n if (e.agentState !== 'idle' || e.lastActivityMs == null) return false;\n return now - e.lastActivityMs >= idleWindowMs;\n}\n\n/**\n * Collapse the multi-agent `WorkingAgentState` into the coarse keepalive state.\n * Mirrors autopause's `coarsePauseState`, but here any live session expecting\n * attention (waiting/question/end-plan) counts as `active` so we never let it\n * be killed mid-interaction; only a settled `idle` is the lapse candidate.\n * error/unknown/null → null (don't keep a wedged or unknown box alive forever).\n */\nfunction coarseKeepaliveState(s: WorkingAgentState | null): KeepaliveAgentState {\n switch (s) {\n case 'working':\n case 'compacting':\n case 'waiting':\n case 'question':\n case 'end-plan':\n return 'active';\n case 'idle':\n return 'idle';\n default:\n return null;\n }\n}\n\n/** What the box-record lookup yields for seeding + the renew call. */\nexport interface CloudBoxLookup {\n sandboxId: string;\n /** Box creation time as epoch ms, or null when unparseable. */\n createdAtMs: number | null;\n /** Recorded effective create timeout (ms), or null when not recorded. */\n createTimeoutMs: number | null;\n /**\n * Provider-specific sandbox class, when the record carries one. Daytona needs\n * it to pause: a `linux-vm` freezes, a `container` archives, and each call is\n * rejected for the other class. Without it the backend has to guess.\n */\n sandboxClass?: string;\n}\n\nexport interface CloudKeepaliveLoopDeps {\n registry: BoxRegistry;\n statusStore: BoxStatusStore;\n log: (line: string) => void;\n /** Injectable for tests; defaults to the global autopause config loader. */\n loadConfig?: () => Promise<AutopauseConfig>;\n /** Injectable for tests; defaults to `resolveCloudBackend`. */\n resolveBackend?: (name: string) => Promise<CloudBackend>;\n /** Injectable for tests; defaults to the state.json box lookup. */\n lookupBox?: (boxId: string) => Promise<CloudBoxLookup | null>;\n /** Injectable for tests; defaults to writing `cloud.lastState: 'paused'`. */\n persistPaused?: (boxId: string) => Promise<void>;\n /** Injectable for tests; fallback create timeout when a record lacks one. */\n fallbackCreateTimeoutMs?: (backend: string) => Promise<number>;\n /** Injectable for tests; defaults to `Date.now`. */\n now?: () => number;\n intervalMs?: number;\n}\n\nexport interface CloudKeepaliveLoopHandle {\n /** Stop scheduling and await any in-flight tick. */\n stop: () => Promise<void>;\n}\n\nconst DEFAULT_INTERVAL_MS = 60_000;\n/** After a failed renew, skip the box for this long (avoid cap hammering / log spam). */\nconst FAILURE_BACKOFF_MS = 5 * 60_000;\n\nexport function startCloudKeepaliveLoop(\n deps: CloudKeepaliveLoopDeps,\n): CloudKeepaliveLoopHandle {\n const loadConfig = deps.loadConfig ?? loadAutopauseConfig;\n const resolveBackend = deps.resolveBackend ?? resolveCloudBackend;\n const lookupBox = deps.lookupBox ?? defaultLookupBox;\n const persistPaused = deps.persistPaused ?? defaultPersistPaused;\n const fallbackCreateTimeoutMs = deps.fallbackCreateTimeoutMs ?? defaultFallbackCreateTimeoutMs;\n const nowFn = deps.now ?? Date.now;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const { registry, statusStore, log } = deps;\n\n // Per-box intended death-time we've pushed the session to. Seeded lazily from\n // the recorded `createdAt + create-timeout`; in-memory only — a relay restart\n // re-seeds (at worst one corrective over-extend, bounded by the plan cap).\n const tracked = new Map<string, number>();\n // Per-box \"don't attempt before\" time, set after a failed renew.\n const backoffUntil = new Map<string, number>();\n // Boxes we idle-paused, keyed by the `lastActivityMs` they had when we did.\n // A paused box keeps reporting that same idle snapshot, so without this it\n // would re-qualify for pausing on every tick.\n const idlePaused = new Map<string, number | null>();\n // Resolved backends cached across ticks (one dynamic import per provider).\n const backendCache = new Map<string, CloudBackend | null>();\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function resolveCached(name: string): Promise<CloudBackend | null> {\n if (backendCache.has(name)) return backendCache.get(name) ?? null;\n let backend: CloudBackend | null = null;\n try {\n backend = await resolveBackend(name);\n } catch {\n backend = null; // no executor for this backend — skip its boxes\n }\n backendCache.set(name, backend);\n return backend;\n }\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const cfg = await loadConfig();\n if (!cfg.enabled) return;\n const windowMs = cfg.idleMinutes * 60_000;\n const now = nowFn();\n\n const live = new Set<string>();\n const entries: KeepaliveScanEntry[] = [];\n for (const reg of registry.list()) {\n if (reg.kind !== 'cloud' || !reg.backend) continue;\n const backend = await resolveCached(reg.backend);\n if (!backend || typeof backend.renewTimeout !== 'function') continue;\n live.add(reg.boxId);\n const active = readActiveAgent(statusStore.get(reg.boxId));\n entries.push({\n boxId: reg.boxId,\n backend: reg.backend,\n agentState: coarseKeepaliveState(active.state),\n lastActivityMs: active.updatedAt ? toEpoch(active.updatedAt) : null,\n });\n }\n\n // Drop per-box state for boxes that are gone (destroyed / forgotten).\n for (const id of [...tracked.keys()]) if (!live.has(id)) tracked.delete(id);\n for (const id of [...backoffUntil.keys()]) if (!live.has(id)) backoffUntil.delete(id);\n for (const id of [...idlePaused.keys()]) if (!live.has(id)) idlePaused.delete(id);\n\n const decisions = selectBoxesToRenew(entries, windowMs, now);\n for (const d of decisions) {\n const until = backoffUntil.get(d.boxId);\n if (until != null && now < until) continue; // recently failed — wait\n\n const lookup = await lookupBox(d.boxId);\n if (!lookup) continue;\n\n // Seed the tracked deadline from the recorded effective create timeout\n // (falls back to a provider default for pre-feature records).\n let current = tracked.get(d.boxId);\n if (current == null) {\n const createMs = lookup.createdAtMs ?? now;\n const createTimeoutMs =\n lookup.createTimeoutMs ?? (await fallbackCreateTimeoutMs(d.backend));\n current = createMs + createTimeoutMs;\n tracked.set(d.boxId, current);\n }\n // Only renew when the target meaningfully exceeds the tracked deadline,\n // so we don't churn the SDK for sub-tick gains or extend a box still\n // riding its create timeout.\n if (d.targetDeadlineEpochMs <= current + intervalMs) continue;\n\n try {\n const backend = await resolveCached(d.backend);\n if (!backend?.renewTimeout) continue;\n await backend.renewTimeout({ sandboxId: lookup.sandboxId }, d.targetDeadlineEpochMs, current);\n // Only advance the tracked deadline on SUCCESS — a failed extend did\n // not actually move the real deadline, so we must not record it.\n tracked.set(d.boxId, d.targetDeadlineEpochMs);\n backoffUntil.delete(d.boxId);\n log(\n `cloud-keepalive: renewed box ${d.boxId} (${d.backend}) ` +\n `+${String(Math.round((d.targetDeadlineEpochMs - now) / 60_000))}m`,\n );\n } catch (err) {\n // Plan-cap rejection or a transient SDK error. Leave `tracked`\n // unchanged (so we retry once the backoff lapses) and back the box\n // off briefly to avoid hammering the cap / spamming the log.\n backoffUntil.set(d.boxId, now + FAILURE_BACKOFF_MS);\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: renew box ${d.boxId} (${d.backend}) failed: ${msg}`);\n }\n }\n\n // Stop the idle boxes an `inactivity`-model backend can't stop by itself,\n // because our own preview polling keeps resetting its clock.\n for (const e of entries) {\n const boxId = e.boxId;\n if (e.agentState !== 'idle') continue; // cheap reject before any I/O\n const backend = await resolveCached(e.backend);\n if (backend?.timeoutModel !== 'inactivity') continue; // absolute TTL: it lapses on its own\n if (typeof backend.pause !== 'function') continue;\n\n // Don't re-pause a box we already paused: it stays `idle` with the same\n // `updatedAt` while paused, so it would otherwise re-qualify every tick.\n // Any fresh agent activity (a resume that does real work) moves\n // `lastActivityMs` and re-arms it.\n if (idlePaused.get(boxId) === e.lastActivityMs) continue;\n const until = backoffUntil.get(boxId);\n if (until != null && now < until) continue;\n\n const lookup = await lookupBox(boxId);\n if (!lookup) continue;\n // The box's OWN idle timeout (box.daytonaTimeoutMs), not the renewal\n // window — we're standing in for the provider's timer, so we wait as\n // long as the user told the provider to wait. `0` disables it.\n const idleWindowMs =\n lookup.createTimeoutMs ?? (await fallbackCreateTimeoutMs(e.backend));\n if (idleWindowMs <= 0) continue;\n if (!shouldIdlePause(e, idleWindowMs, now)) continue;\n try {\n // Pass the recorded class: daytona freezes a linux-vm but archives a\n // container, and each call is rejected for the other class.\n await backend.pause({\n sandboxId: lookup.sandboxId,\n ...(lookup.sandboxClass ? { sandboxClass: lookup.sandboxClass } : {}),\n });\n idlePaused.set(boxId, e.lastActivityMs);\n backoffUntil.delete(boxId);\n // Best-effort, and deliberately after the pause is already a fact: a\n // failed record write must not look like a failed pause and re-arm.\n await persistPaused(boxId).catch(() => {});\n const mins = e.lastActivityMs != null ? Math.round((now - e.lastActivityMs) / 60_000) : null;\n log(\n `cloud-keepalive: paused idle box ${boxId} (${e.backend})` +\n (mins != null ? ` after ~${String(mins)}m idle` : '') +\n ` — ${e.backend}'s own idle timer never fires while we poll it`,\n );\n } catch (err) {\n // Already stopped, mid-transition, or a transient SDK error. Back off\n // rather than retry every tick; `probeState` stays authoritative.\n backoffUntil.set(boxId, now + FAILURE_BACKOFF_MS);\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: pause idle box ${boxId} (${e.backend}) failed: ${msg}`);\n }\n }\n } catch (err) {\n // The loop must never crash the relay or stop scheduling.\n const msg = err instanceof Error ? err.message : String(err);\n log(`cloud-keepalive: tick error: ${msg}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n\nfunction toEpoch(iso: string | undefined): number | null {\n if (!iso) return null;\n const t = Date.parse(iso);\n return Number.isNaN(t) ? null : t;\n}\n\n/** Resolve a box's cloud sandboxId + create facts from `~/.agentbox/state.json`. */\nasync function defaultLookupBox(boxId: string): Promise<CloudBoxLookup | null> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok') return null;\n const sandboxId = hit.box.cloud?.sandboxId;\n if (!sandboxId) return null;\n const sandboxClass = hit.box.cloud?.sandboxClass;\n return {\n sandboxId,\n createdAtMs: toEpoch(hit.box.createdAt),\n createTimeoutMs: hit.box.cloud?.sessionTimeoutMs ?? null,\n ...(sandboxClass ? { sandboxClass } : {}),\n };\n}\n\n/**\n * Mark an auto-paused box `paused` on its record. `agentbox list` / `top` / the\n * hub read `cloud.lastState` rather than probing the SDK on every render, so\n * without this the box we just paused keeps showing as `running` until someone\n * runs a live probe. Mirrors cloud-provider's `persistLastState` (which covers\n * the CLI-driven `pause`/`stop`); best-effort, since the pause itself already\n * happened and a state-write failure must not turn into a retry loop.\n */\nasync function defaultPersistPaused(boxId: string): Promise<void> {\n const state = await readState();\n const hit = findBox(boxId, state);\n if (hit.kind !== 'ok' || !hit.box.cloud) return;\n await recordBox({ ...hit.box, cloud: { ...hit.box.cloud, lastState: 'paused' } });\n}\n\n/**\n * Fallback create timeout for a box record that predates `sessionTimeoutMs`.\n * Vercel reads the global `box.vercelTimeoutMs`; other backends use the shared\n * 45-min default (matches the backends' `DEFAULT_TIMEOUT_MS`). A close estimate\n * is enough — the renew gate tolerates seed drift and self-corrects.\n */\nasync function defaultFallbackCreateTimeoutMs(backend: string): Promise<number> {\n const generic = 45 * 60_000;\n if (backend !== 'vercel') return generic;\n const fallback = BUILT_IN_DEFAULTS.box.vercelTimeoutMs;\n try {\n const global: Partial<UserConfig> = parseUserConfig(\n await readFile(GLOBAL_CONFIG_FILE, 'utf8'),\n GLOBAL_CONFIG_FILE,\n );\n const v = global.box?.vercelTimeoutMs;\n return typeof v === 'number' && v > 0 ? v : fallback;\n } catch {\n return fallback;\n }\n}\n","import type { Store } from './store/store.js';\n\n/**\n * Periodic housekeeping for a resident control box: sweep answered prompts and\n * finished create jobs so the durable tables don't grow without bound. Events\n * are already ring-trimmed on append; prompts + jobs are not.\n *\n * A no-op unless the store implements the prune methods (durable stores only —\n * the laptop's MemoryStore is process-lifetime, nothing to sweep). Modeled on\n * the other daemon loops (timer, `unref`, never crashes the process).\n */\n\n/** Rows are kept this long after they finish before a sweep removes them. */\nconst DEFAULT_RETENTION_MS = 24 * 60 * 60_000;\nconst DEFAULT_INTERVAL_MS = 60 * 60_000;\n\nexport interface RetentionLoopDeps {\n store: Store;\n log: (line: string) => void;\n /** How long a finished row survives before it's swept. Default 24h. */\n retentionMs?: number;\n /** Sweep cadence. Default hourly. */\n intervalMs?: number;\n /** Injectable for tests; defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport interface RetentionLoopHandle {\n stop: () => Promise<void>;\n}\n\nexport function startRetentionLoop(deps: RetentionLoopDeps): RetentionLoopHandle {\n const { store, log } = deps;\n const retentionMs = deps.retentionMs ?? DEFAULT_RETENTION_MS;\n const intervalMs = deps.intervalMs ?? DEFAULT_INTERVAL_MS;\n const nowFn = deps.now ?? Date.now;\n\n // Nothing to sweep on a store without the prune methods (localhost/tests).\n if (!store.prunePrompts && !store.pruneCreateJobs) {\n return { stop: () => Promise.resolve() };\n }\n\n let ticking = false;\n let stopped = false;\n let inFlight: Promise<void> = Promise.resolve();\n\n async function tick(): Promise<void> {\n if (ticking) return;\n ticking = true;\n try {\n const before = new Date(nowFn() - retentionMs).toISOString();\n const prompts = (await store.prunePrompts?.(before)) ?? 0;\n const jobs = (await store.pruneCreateJobs?.(before)) ?? 0;\n if (prompts > 0 || jobs > 0) {\n log(`retention: pruned ${String(prompts)} prompt(s), ${String(jobs)} create job(s)`);\n }\n } catch (err) {\n log(`retention: tick error: ${err instanceof Error ? err.message : String(err)}`);\n } finally {\n ticking = false;\n }\n }\n\n const timer = setInterval(() => {\n if (stopped) return;\n inFlight = tick();\n }, intervalMs);\n timer.unref();\n\n return {\n stop: async () => {\n stopped = true;\n clearInterval(timer);\n await inFlight.catch(() => {});\n },\n };\n}\n","import { startRelayServer, type RelayServerHandle, type RelayServerOptions } from './server.js';\nimport { startAutopauseLoop } from './autopause.js';\nimport { startCloudKeepaliveLoop } from './cloud-keepalive.js';\nimport { startQueueLoop } from './queue.js';\nimport { startRetentionLoop } from './retention.js';\n\n// Re-exported here (not just from index.ts) so the two processes that own a\n// relay — the CLI's `agentbox-relay serve` bin and the hub server — can register\n// their built-in cloud backends from the same module they already import\n// `startRelayDaemon` from, without pulling the full package barrel.\nexport {\n setCloudBackendLoader,\n type CloudBackendLoader,\n type CloudCpModule,\n} from './host-actions.js';\n\nexport interface RelayDaemonHandle {\n /** The underlying relay server (url, store, close, …). */\n handle: RelayServerHandle;\n /** Stop the background loops, then close the server. */\n stop: () => Promise<void>;\n}\n\n/**\n * Boot the relay HTTP server plus its background loops (autopause / cloud\n * keepalive / queue) — the daemon that `agentbox-relay serve` runs. Extracted\n * so the hub server can import it, prepare Next, and pass Next's request\n * handler in as `opts.uiHandler` to serve the UI on the relay's own port.\n *\n * Process-owner concerns (the \"listening\" log line, SIGTERM/SIGINT handling)\n * stay with the caller so the same daemon works under both the relay bin and\n * the hub server.\n */\nexport async function startRelayDaemon(opts: RelayServerOptions): Promise<RelayDaemonHandle> {\n const handle = await startRelayServer(opts);\n const log = opts.logger ?? (() => {});\n const autopause = startAutopauseLoop({\n registry: handle.registry,\n statusStore: handle.statusStore,\n events: handle.events,\n log,\n });\n const cloudKeepalive = startCloudKeepaliveLoop({\n registry: handle.registry,\n statusStore: handle.statusStore,\n log,\n });\n const queue = startQueueLoop({\n log,\n registry: handle.registry,\n statusStore: handle.statusStore,\n // Refresh the embedded hub UI whenever a background job flips state\n // (queued → running → done/failed), so a create job's box shows up and\n // then transitions creating → running without waiting for the 15s SSE ping.\n onStatusChange: () => handle.hubNotifier.notify(),\n });\n // Sweep answered prompts + finished create jobs on a resident control box\n // (durable store). A no-op when the store lacks the prune methods (localhost).\n const retention = startRetentionLoop({ store: handle.store, log });\n // `poke` isn't on the declared QueueLoopHandle (only `stop` is); same cast bin.ts used.\n handle.setQueuePoke(() => {\n (queue as { poke?: () => void }).poke?.();\n });\n\n return {\n handle,\n stop: async () => {\n await Promise.allSettled([\n autopause.stop(),\n cloudKeepalive.stop(),\n queue.stop(),\n retention.stop(),\n ]);\n await handle.close();\n },\n };\n}\n","import type { IntegrationConnector, IntegrationOpRefusal } from '../types.js';\n\n/**\n * Linear connector — wraps `@schpet/linear-cli` (the `linear` binary, v2).\n *\n * The op allowlist is intentionally minimal (start conservative, widen as\n * real agent flows surface needs). Reads cover identity/listing/lookup\n * (`whoami`, `issue list/view/query`, `team list`) plus a GraphQL\n * passthrough (`api`), and writes are limited to issue create/update and a\n * gated comment. The `api` passthrough is query-only —\n * `refuseGraphqlNonQuery` rejects any operation whose first non-whitespace\n * keyword is `mutation` or `subscription`, so the GraphQL endpoint can't\n * be used to slip a write past the read classification (the GraphQL\n * analogue of `notion.api`'s `refuseApiNonGet`).\n *\n * Three subcommands are deliberately absent from the allowlist for\n * security reasons:\n * - `auth token` — PRINTS the raw API token to stdout; proxying it\n * through the relay would expose the host credential to the box.\n * The only `auth` op we expose is `auth whoami` (identity only), via\n * the `whoami` op.\n * - `auth login` / `auth logout` / `auth migrate` / `auth default` —\n * the host owns auth; relaying these would mutate host state.\n * - `issue delete` / `team delete` / `team create` — destructive and\n * unnecessary for the documented agent flows. Add deliberately, as\n * gated writes, only when a real flow needs them.\n *\n * No `env` override is needed (neither connector sets one). Linear stores\n * plaintext credentials at `~/.config/linear/credentials.toml` and keychain\n * mode is opt-in, not the default, so `linear` reads file-based auth on every\n * host without any env shaping. The carry block in `agentbox.yaml` ships that\n * file into nested boxes that run their own relay.\n */\nexport const linearConnector: IntegrationConnector = {\n service: 'linear',\n hostBin: 'linear',\n detect: {\n versionArgs: ['--version'],\n authArgs: ['auth', 'whoami'],\n installHint: 'install @schpet/linear-cli: npm i -g @schpet/linear-cli',\n loginHint: 'linear auth login',\n },\n ops: {\n whoami: {\n write: false,\n buildArgv: (args) => ['auth', 'whoami', ...args],\n },\n 'issue.list': {\n write: false,\n buildArgv: (args) => ['issue', 'list', ...args],\n },\n 'issue.mine': {\n // The v2-native read for \"issues assigned to me\" — the README directs\n // users here in place of the older `issue list --me`. Listed as a\n // separate op so the shim doesn't reject the canonical form.\n write: false,\n buildArgv: (args) => ['issue', 'mine', ...args],\n },\n 'issue.view': {\n write: false,\n buildArgv: (args) => ['issue', 'view', ...args],\n },\n 'issue.query': {\n write: false,\n buildArgv: (args) => ['issue', 'query', ...args],\n },\n 'team.list': {\n write: false,\n buildArgv: (args) => ['team', 'list', ...args],\n },\n api: {\n write: false,\n buildArgv: (args) => ['api', ...args],\n refuseCall: refuseGraphqlNonQuery,\n },\n 'issue.create': {\n write: true,\n buildArgv: (args) => ['issue', 'create', ...args],\n },\n 'issue.update': {\n write: true,\n buildArgv: (args) => ['issue', 'update', ...args],\n },\n 'issue.comment': {\n // Maps to `linear issue comment add` — `@schpet/linear-cli` v2 uses\n // `add` (not `create`); `add`'s sibling subcommands are `list`,\n // `update`, `delete`.\n write: true,\n buildArgv: (args) => ['issue', 'comment', 'add', ...args],\n },\n },\n};\n\n/**\n * Reject any `linear api` call whose GraphQL source declares a `mutation`\n * or `subscription` operation. The Linear `api` op is a single POST that\n * serves both reads and writes — without this guard, the \"read\"\n * classification would be a hole the agent could slip writes through.\n *\n * `linear-cli`'s `api` subcommand takes the GraphQL query as a positional\n * argument and accepts `--variable key=value` (repeatable; the value may\n * be `@/path` to load from a host file — see below), `--variables-json\n * <json>`, `--paginate`, and `--silent`. We:\n *\n * 1. Refuse `--variable key=@<path>` (and the `=` and `--variable=`\n * glued forms) because they would let the box trigger arbitrary\n * host-file reads — the file contents become GraphQL variables and\n * can be echoed back through the response, an exfiltration channel.\n * 2. Refuse `--input` for parity with `refuseApiNonGet`, even though\n * `linear api` doesn't currently accept it — if a future version\n * adds it, the guard pre-empts the stdin/file-body shape.\n * 3. Walk argv consuming value-bearing flags (`--variable`,\n * `--variables-json`) so their JSON/key=value payload isn't\n * misread as an operation keyword.\n * 4. For every remaining positional (non-flag) token, strip leading\n * whitespace + `# …` line comments and reject the call if the\n * first identifier is `mutation` or `subscription`.\n *\n * `query …` and the anonymous `{ … }` shorthand pass. Empty/flag-only\n * argv passes (the host CLI emits its own usage error).\n */\nfunction refuseGraphqlNonQuery(args: readonly string[]): IntegrationOpRefusal | null {\n const refuse = (reason: string): IntegrationOpRefusal => ({\n exitCode: 65,\n stderr: `linear api: ${reason}\\n`,\n });\n // `--variable` and `--variables-json` each take the next argv token as\n // their value — the loop consumes them explicitly below so a JSON\n // payload starting with `mutation`/`subscription` isn't misread as the\n // GraphQL operation. The consume-next branches refuse to swallow the\n // next token if it LOOKS like a flag (`--…`) — otherwise a malformed\n // `--variable --input=/etc/passwd` would silently skip the `--input`\n // refusal one iteration later.\n for (let i = 0; i < args.length; i++) {\n const arg = args[i] ?? '';\n if (arg === '--input' || arg.startsWith('--input=')) {\n return refuse(\"'--input' (stdin/file body) isn't supported through the relay\");\n }\n // `--variable key=@/host/path` reads from a host file — refuse the\n // `@`-prefixed value form regardless of split/glued/equals shape.\n if (arg === '--variable') {\n const next = args[i + 1] ?? '';\n if (variableValueIsFileLoad(next)) {\n return refuse(\n \"'--variable key=@<path>' (host-file load) isn't supported through the relay\",\n );\n }\n // Don't consume a token that's itself a flag — it needs to run\n // through its own per-flag checks (e.g. `--variable --input=/x`).\n if (!next.startsWith('--')) i++;\n continue;\n }\n if (arg.startsWith('--variable=')) {\n if (variableValueIsFileLoad(arg.slice('--variable='.length))) {\n return refuse(\n \"'--variable=key=@<path>' (host-file load) isn't supported through the relay\",\n );\n }\n continue;\n }\n if (arg === '--variables-json') {\n const next = args[i + 1] ?? '';\n if (!next.startsWith('--')) i++;\n continue;\n }\n if (arg.startsWith('--variables-json=')) {\n continue;\n }\n // Only LONG flags (`--…`) skip the keyword check. A bare `-` or a\n // single-dash token like `-mutation` is treated as a positional so\n // it goes through `firstGraphqlOperationKeyword` and the\n // unparseable/mutation cases fail closed.\n if (arg.startsWith('--')) continue;\n const op = firstGraphqlOperationKeyword(arg);\n if (op === 'mutation' || op === 'subscription') {\n return refuse(\n `only GraphQL queries are proxied (use issue.create / issue.update / issue.comment for writes); detected operation '${op}'`,\n );\n }\n // `unparseable` (a positional whose first significant char isn't `{`\n // or an ASCII letter) is refused too. Real queries start with `query`,\n // `mutation`, `subscription`, or `{`. Anything else is a garbage\n // shape that we'd rather not forward — the agent gets a clear refusal\n // instead of an opaque host CLI error.\n if (op === 'unparseable') {\n return refuse(\n `couldn't classify positional argv ${JSON.stringify(arg)} as a GraphQL operation (expected 'query', 'mutation', 'subscription', or '{')`,\n );\n }\n }\n return null;\n}\n\n/**\n * True when a `--variable` value uses linear-cli's `@<path>` host-file load\n * syntax. The standard shape is `key=@<path>`, but we refuse any value\n * that CONTAINS `=@` or a bare leading `@` — guards against:\n * - `key=@<path>` (canonical).\n * - `@<path>` (bare, no `key=` prefix).\n * - `key=name=@<path>` where a `=` appears in the key/name portion.\n * linear-cli's `--variable` parser may split on the FIRST `=` (so the\n * value is `name=@<path>`) or on the LAST `=` (so the value is\n * `@<path>`); we refuse both interpretations by treating any `=@`\n * anywhere in the string as a file-load signal.\n * - Future shape changes: if linear-cli adds escaping or new prefixes,\n * refusing on the literal `=@` substring stays conservative.\n */\nfunction variableValueIsFileLoad(value: string): boolean {\n if (value.startsWith('@')) return true;\n return value.includes('=@');\n}\n\n/**\n * Extract the first GraphQL operation keyword from a source string after\n * stripping leading whitespace and `# …` line comments. Returns the\n * keyword (`query` | `mutation` | `subscription`) when one is found,\n * `'anonymous'` for the `{ … }` shorthand, or `null` for an empty source.\n * Only the prefix matters — the rest of the source is not validated;\n * we're not a GraphQL parser, just a write-shape detector.\n *\n * Returns `'unparseable'` (not null) for sources whose first non-whitespace\n * non-comment character isn't `{` or an ASCII letter — that way an outer\n * gate can decide to fail-CLOSED on shapes it doesn't recognize (BOM,\n * NBSP, stray punctuator, etc.) instead of silently passing them. The\n * caller in `refuseGraphqlNonQuery` is unchanged: it only refuses on\n * `mutation` / `subscription`, so `'unparseable'` still passes — but the\n * sentinel is available for a future stricter mode.\n *\n * The whitespace test uses the JS `\\s` class so Unicode whitespace\n * (U+00A0 NBSP, U+2028, the BOM U+FEFF, etc.) is stripped before the\n * keyword check — otherwise a `'mutation {…}'` source would\n * bypass the gate because `` is not in `[ \\t\\n\\r,]` and not an\n * ASCII letter, so `j === i` and the function returned null.\n */\nfunction firstGraphqlOperationKeyword(source: string): string | null {\n let i = 0;\n const n = source.length;\n while (i < n) {\n const c = source[i]!;\n if (/\\s/.test(c) || c === ',' || c === '') {\n i++;\n continue;\n }\n if (c === '#') {\n while (i < n && source[i] !== '\\n') i++;\n continue;\n }\n break;\n }\n if (i >= n) return null;\n if (source[i] === '{') return 'anonymous';\n let j = i;\n while (j < n) {\n const c = source[j]!;\n if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {\n j++;\n } else {\n break;\n }\n }\n // No leading ASCII letter and not `{` — the source's first significant\n // character is something we can't classify (stray punctuator, smart\n // quote, control char). Return a sentinel rather than null so the gate\n // can choose to be paranoid in the future.\n if (j === i) return 'unparseable';\n return source.slice(i, j).toLowerCase();\n}\n","import type { IntegrationConnector, IntegrationOpRefusal } from '../types.js';\n\n/**\n * Notion connector — wraps the official `ntn` CLI (beta, first-party).\n *\n * The op allowlist is intentionally minimal (start conservative, widen as\n * real agent flows surface needs). Two read passthroughs (`ntn whoami` and\n * `ntn api …` against the v1 REST surface) plus two gated writes. The `api`\n * passthrough is read-only — `refuseUnsafeApiCall` allows GET to any endpoint\n * and POST only to Notion's read-by-POST endpoints (`v1/search`, database /\n * data-source `/query`), and refuses everything else, so an agent can't slip a\n * write past the \"read\" classification.\n *\n * Comment creation is intentionally absent: `ntn` exposes no top-level\n * `comment` subcommand (the official surface is `api datasources files\n * pages login logout whoami workers`), and Notion's REST POST `/v1/comments`\n * takes a structured JSON body that doesn't trivially map from CLI flags.\n * Adding it is a focused follow-up, not built yet.\n *\n * No `env` override: the relay runs the host's `ntn` with its own default\n * auth (the macOS keychain after `ntn login`), matching what `agentbox\n * doctor` probes and what the public docs tell users to do. The carry-based\n * nested-box dev path (a Linux box hosting a relay) needs file-based auth\n * instead; that's an internal-dev concern documented in\n * `docs/development.md`, not something the connector forces on every host.\n */\nexport const notionConnector: IntegrationConnector = {\n service: 'notion',\n hostBin: 'ntn',\n detect: {\n versionArgs: ['--version'],\n authArgs: ['api', 'v1/users/me'],\n installHint: 'install ntn: https://developers.notion.com/reference/notion-cli',\n loginHint: 'ntn login',\n },\n ops: {\n whoami: {\n write: false,\n buildArgv: (args) => ['whoami', ...args],\n },\n api: {\n write: false,\n buildArgv: (args) => ['api', ...args],\n refuseCall: refuseUnsafeApiCall,\n },\n 'page.create': {\n write: true,\n buildArgv: (args) => ['pages', 'create', ...args],\n },\n 'page.update': {\n write: true,\n buildArgv: (args) => ['pages', 'update', ...args],\n },\n },\n};\n\n/**\n * Notion's read-by-POST endpoints — the only POSTs `ntn api` may proxy.\n * Anchored, leading-slash-tolerant, and `[^/?]+` for the id segment so a\n * query string or extra path component can't smuggle a different endpoint.\n */\nconst READ_POST_ENDPOINTS: readonly RegExp[] = [\n /^\\/?v1\\/search$/,\n /^\\/?v1\\/databases\\/[^/?]+\\/query$/,\n /^\\/?v1\\/data_sources\\/[^/?]+\\/query$/,\n];\n\n/**\n * The only flags `ntn api` accepts that take NO value and are safe for a\n * read-only proxy. The gate is fail-closed: every other flag is refused, so an\n * unrecognized value-consuming flag can't have its value misparsed as the\n * endpoint (see `refuseUnsafeApiCall`). Value-consuming flags (`-X/--method`,\n * `-d/--data`, `--notion-version`, `--file`) are handled explicitly before this.\n */\nconst SAFE_API_BOOLEAN_FLAGS: ReadonlySet<string> = new Set([\n '--spec',\n '--docs',\n '-h',\n '--help',\n '-v',\n '--verbose',\n '-V',\n '--version',\n]);\n\n/**\n * Reject any `ntn api` call that isn't a read. A read is: GET to any endpoint,\n * or POST to one of {@link READ_POST_ENDPOINTS} (search + database/data-source\n * `/query` — POST in the Notion API but semantically reads). Everything else —\n * writes (`v1/pages`, `v1/comments`, …), PATCH/PUT/DELETE, POST to a\n * non-read endpoint — is refused; writes go through `page.create`/`page.update`.\n *\n * `ntn api`'s real surface (verified via `ntn api --help`): method is inferred\n * from endpoint + body; `-X`/`--method` overrides; body sources are `-d`/`--data\n * <JSON>` and inline assignments (`path=value`, `path:=json`) — NOT `gh`-style\n * `-f`/`-F` (which `ntn` doesn't have). We classify any body source as non-GET\n * so a write can't slip through as a body-less \"GET\". `--input` (stdin/file\n * body) and `--file` (host-file upload) read host state and can't traverse the\n * relay, so both are refused outright.\n *\n * Kept here (next to the op declaration) — not exported — because the test\n * surface is \"does notion.api refuse this call\", not the parser shape.\n */\nfunction refuseUnsafeApiCall(args: readonly string[]): IntegrationOpRefusal | null {\n const refuse = (reason: string): IntegrationOpRefusal => ({\n exitCode: 65,\n stderr: `notion api: ${reason}\\n`,\n });\n\n let explicitMethod: string | null = null;\n let hasBody = false;\n let endpoint: string | null = null;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i] ?? '';\n\n // Explicit method (split, glued, or `=`-joined).\n if (arg === '-X' || arg === '--method') {\n explicitMethod = args[i + 1] ?? '';\n i++;\n continue;\n }\n if (arg.startsWith('--method=')) {\n explicitMethod = arg.slice('--method='.length);\n continue;\n }\n if (arg.startsWith('-X') && arg.length > 2) {\n explicitMethod = arg.slice(2).replace(/^=/, '');\n continue;\n }\n\n // Raw JSON body — implies a write-class request unless the endpoint is read.\n if (arg === '-d' || arg === '--data') {\n hasBody = true;\n i++;\n continue;\n }\n if (arg.startsWith('--data=') || (arg.startsWith('-d') && arg.length > 2)) {\n hasBody = true;\n continue;\n }\n\n // Host-file / stdin bodies: can't traverse the relay, and `--file` reads an\n // arbitrary host file. Refuse both regardless of endpoint.\n if (arg === '--file' || arg.startsWith('--file=')) {\n return refuse(\"'--file' (host-file upload) isn't supported through the relay\");\n }\n if (arg === '--input' || arg.startsWith('--input=')) {\n return refuse(\"'--input' (stdin/file body) isn't supported through the relay; use -d <JSON>\");\n }\n\n // `--notion-version <VERSION>` — value-consuming; forwarded unchanged.\n if (arg === '--notion-version') {\n i++;\n continue;\n }\n if (arg.startsWith('--notion-version=')) continue;\n\n // Remaining flags are fail-closed: only a known-safe boolean set passes.\n // Anything else is refused rather than ignored, so an unrecognized\n // value-consuming flag — e.g. ntn's global `--workers-config-file <path>`\n // or the hidden `--env <env>`, both accepted after `api` — can't have its\n // value silently misread as the endpoint and smuggle a write past the gate\n // (`api --workers-config-file v1/search v1/pages` POSTs to v1/pages).\n if (arg.startsWith('-')) {\n if (SAFE_API_BOOLEAN_FLAGS.has(arg)) continue;\n return refuse(\n `unsupported option '${arg}' (read-only api accepts a path, inline inputs, ` +\n `-d <JSON>, -X GET/POST, --notion-version, --spec, --docs)`,\n );\n }\n\n // First bare positional is the API path; the rest are inline inputs.\n if (endpoint === null) {\n endpoint = arg;\n continue;\n }\n if (isBodyAssignment(arg)) hasBody = true;\n }\n\n const method = (\n explicitMethod && explicitMethod.length > 0 ? explicitMethod : hasBody ? 'POST' : 'GET'\n ).toUpperCase();\n\n if (method === 'GET') return null;\n if (method !== 'POST') {\n return refuse(\n `only GET and read-only POST are proxied (use page.create / page.update for writes); detected method '${method}'`,\n );\n }\n if (endpoint === null) {\n return refuse('could not determine the API endpoint for a non-GET call');\n }\n // Defense in depth: ntn resolves `.`/`..` before routing, so reject any\n // traversal segment rather than trusting the anchored regexes alone.\n if (endpoint.split('/').some((seg) => seg === '.' || seg === '..')) {\n return refuse(`path traversal segments ('.' / '..') are not allowed in '${endpoint}'`);\n }\n if (READ_POST_ENDPOINTS.some((re) => re.test(endpoint!))) return null;\n return refuse(\n `POST is only proxied for read endpoints (v1/search, v1/databases/{id}/query, ` +\n `v1/data_sources/{id}/query); '${endpoint}' is not one (use page.create / page.update for writes)`,\n );\n}\n\n/**\n * Whether an inline-input token is a request-BODY assignment (so it implies a\n * write-class request). `ntn` inline syntax: `path:=json` (typed body) and\n * `path=value` (string body) are bodies; `name==value` (query param) and\n * `Header:Value` (header) are not.\n */\nfunction isBodyAssignment(token: string): boolean {\n if (token.includes(':=')) return true;\n if (token.includes('==')) return false;\n return token.includes('=');\n}\n","import { linearConnector } from './connectors/linear.js';\nimport { notionConnector } from './connectors/notion.js';\nimport type { IntegrationConnector } from './types.js';\n\n/**\n * All integration connectors known to AgentBox. The relay's dispatcher\n * walks this list to validate `integration.<service>.<op>` calls — anything\n * not present is denied. Mirrors `packages/core/src/provider.ts`'s\n * registry pattern for the provider abstraction.\n */\nexport const ALL_CONNECTORS: readonly IntegrationConnector[] = [notionConnector, linearConnector];\n\n/** Lookup by `IntegrationConnector.service`. Returns `null` for unknown. */\nexport function getConnector(service: string): IntegrationConnector | null {\n for (const c of ALL_CONNECTORS) {\n if (c.service === service) return c;\n }\n return null;\n}\n","/**\n * Rebuild a drivable `BoxRecord` from a control-box `BoxRegistration`.\n *\n * The single source of truth for \"registration → record\" reconstruction, used by\n * BOTH sides of the control-plane topology:\n * - the PC's `agentbox hub adopt` (materializes the record into the PC's\n * `state.json` so direct PC↔box commands resolve the box), and\n * - the control box's own hub backend (`hydrateRegisteredBox`), which drives a\n * box it knows only from its Store registration — created on a PC / another\n * host — so `/api/v1` lifecycle, git, and REAL destroy work on it, not just a\n * state reap.\n *\n * Everything needed rides on the registration (the adoption material added by the\n * plane-register enrichment): provider, sandbox id, public VM host, image, web\n * port, agent, branch, origin URL, bridge/preview tokens. Host-specific concerns\n * stay with the caller: which LOCAL project the box maps to (PC only — the\n * control box has no local clone), SSH-key material (downloaded from custody over\n * HTTP on the PC, read from the local FS store on the control box), and the token\n * generator used for the relay/bridge fallbacks.\n *\n * Kept pure (no fs, no network) so both callers layer their own IO around it.\n */\nimport type { BoxRecord, GitWorktreeRecord, SshTargetRecord } from '@agentbox/core';\nimport { boxSshDirForProvider } from '@agentbox/sandbox-core';\nimport type { BoxRegistration } from './types.js';\n\n/** Box user on every cloud provider's image (the agent never runs as root). */\nconst BOX_SSH_USER = 'vscode';\n\nexport interface RegistrationToRecordOptions {\n /** The control-plane base URL, persisted on the record's cloud fields. */\n controlPlaneUrl: string;\n /**\n * A local record for the same box, when re-adopting: its id/project linkage\n * and live tokens are preserved so status paths stay stable and a refresh\n * never re-mints tokens already injected in the running box.\n */\n existing?: BoxRecord;\n /**\n * Absolute host path of the LOCAL checkout the box maps to. Set only when a\n * clone is present (the PC path); on the control box there is none, so git\n * worktree bookkeeping is left off (the registration's `hostMainRepo` is the\n * control box's create-time temp clone, deleted after create — carrying it\n * over would point host-side git RPCs at a path that doesn't exist).\n */\n projectRoot?: string;\n /** 1-based per-project box index, when the caller resolved one. */\n projectIndex?: number;\n /** Fallback token generator for the relay/bridge tokens (e.g. `generateRelayToken`). */\n freshToken: () => string;\n}\n\n/** Narrow a registration's free-form agent string to the record's union. */\nexport function normalizeRegistrationAgent(agent: string | undefined): BoxRecord['lastAgent'] {\n return agent === 'claude' || agent === 'codex' || agent === 'opencode' ? agent : undefined;\n}\n\n/**\n * The box's SSH target, or undefined when the registration carries no host.\n *\n * `identityFile` is set only when the provider actually mints a per-box key dir:\n * a provider that reports a `publicHost` but no keypair would otherwise get a\n * bogus absolute `\"/id_ed25519\"` written into the record. Omitting it leaves ssh\n * to its normal key resolution.\n */\nexport function buildSshTarget(\n provider: string,\n sandboxId: string,\n publicHost: string | undefined,\n): SshTargetRecord | undefined {\n if (!publicHost) return undefined;\n const dir = boxSshDirForProvider(provider, sandboxId);\n return {\n host: publicHost,\n user: BOX_SSH_USER,\n ...(dir ? { identityFile: `${dir}/id_ed25519` } : {}),\n };\n}\n\n/**\n * Map a `BoxRegistration` (+ caller-supplied host context) to a `BoxRecord`.\n * Pure: it neither reads SSH keys nor writes state — the caller does that around\n * it. Idempotent-friendly: pass `existing` to preserve local identity on refresh.\n */\nexport function registrationToBoxRecord(\n reg: BoxRegistration,\n opts: RegistrationToRecordOptions,\n): BoxRecord {\n const provider = reg.backend ?? 'docker';\n const sandboxId = reg.sandboxId ?? reg.boxId;\n const { existing, projectRoot, projectIndex, controlPlaneUrl, freshToken } = opts;\n\n const branch = reg.worktrees?.[0]?.branch ?? `agentbox/${reg.name}`;\n const sanctionedBranch = reg.worktrees?.[0]?.sanctionedBranch ?? branch;\n\n // Git worktree bookkeeping points at the LOCAL clone (PC only). On the control\n // box `projectRoot` is undefined → no worktrees, which is correct: cloud\n // lifecycle/destroy need none, and host-side git RPCs would have no repo here.\n const gitWorktrees: GitWorktreeRecord[] | undefined = projectRoot\n ? [\n {\n kind: 'root',\n branch,\n sanctionedBranch,\n containerPath: '/workspace',\n hostMainRepo: projectRoot,\n gitWorktreePath: '',\n relPathFromWorkspace: '',\n },\n ]\n : undefined;\n\n return {\n id: existing?.id ?? reg.boxId,\n name: reg.name,\n displayName: existing?.displayName,\n provider,\n container: `cloud:${sandboxId}`,\n image: reg.image ?? existing?.image ?? '',\n workspacePath: projectRoot ?? existing?.workspacePath ?? '/workspace',\n projectRoot,\n projectIndex,\n // Tokens are regenerated only for a fresh adoption; a re-adopt keeps the\n // box's live tokens (already injected in the running box).\n relayToken: existing?.relayToken ?? reg.token ?? freshToken(),\n lastAgent: normalizeRegistrationAgent(reg.agent) ?? existing?.lastAgent,\n gitWorktrees,\n createdAt: reg.createdAt ?? existing?.createdAt ?? new Date().toISOString(),\n ssh: buildSshTarget(provider, sandboxId, reg.publicHost) ?? existing?.ssh,\n cloud: {\n ...existing?.cloud,\n backend: provider,\n sandboxId,\n image: reg.image ?? existing?.cloud?.image,\n webPort: reg.webPort ?? existing?.cloud?.webPort,\n publicHost: reg.publicHost ?? existing?.cloud?.publicHost,\n bridgeToken: reg.bridgeToken ?? existing?.cloud?.bridgeToken ?? freshToken(),\n relayPreviewUrl: reg.previewUrl ?? existing?.cloud?.relayPreviewUrl,\n relayPreviewToken: reg.previewToken ?? existing?.cloud?.relayPreviewToken,\n workspaceBranch: branch,\n sanctionedBranch,\n lastState: existing?.cloud?.lastState ?? 'running',\n topology: 'control-plane',\n controlPlaneUrl,\n // A hub-created box clones in-box from a leased URL — it shares no fork\n // base with a PC, so the session-start live resync must skip it.\n hostSeeded: undefined,\n },\n };\n}\n","import type { BoxStatusSnapshot } from '../status-store.js';\nimport type { BoxRegistration, GitRpcResult, RelayEvent } from '../types.js';\nimport type { PromptRow, Store } from './store.js';\nimport type { StoreRpcResponse } from './store-rpc.js';\n\n/**\n * A {@link Store} backed by a remote hosted control plane over HTTP. A federated\n * laptop relay uses this so its registry / prompts / events / status live\n * centrally (one cross-machine view) while it still executes host-local actions\n * locally. Each method is one admin-bearer `POST /admin/store {method, args}`.\n *\n * `fetch` (Node 20+) is used directly; inject one for tests.\n */\nexport interface RemoteStoreOptions {\n /** Base URL of the hosted control plane (e.g. https://plane.example.com). */\n baseUrl: string;\n /** Admin bearer for `/admin/store`. */\n adminToken: string;\n fetchImpl?: typeof fetch;\n}\n\nexport class RemoteStore implements Store {\n private readonly url: string;\n private readonly token: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(opts: RemoteStoreOptions) {\n this.url = `${opts.baseUrl.replace(/\\/$/, '')}/admin/store`;\n this.token = opts.adminToken;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n private async call<R>(method: string, args: unknown[]): Promise<R> {\n const res = await this.fetchImpl(this.url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.token}`,\n },\n body: JSON.stringify({ method, args }),\n });\n if (!res.ok) {\n throw new Error(`remote store ${method} → ${String(res.status)}`);\n }\n const body = (await res.json()) as StoreRpcResponse;\n return body.result as R;\n }\n\n registerBox(reg: BoxRegistration): Promise<void> {\n return this.call('registerBox', [reg]);\n }\n getBox(boxId: string): Promise<BoxRegistration | undefined> {\n return this.call<BoxRegistration | null>('getBox', [boxId]).then((r) => r ?? undefined);\n }\n authenticateBox(token: string): Promise<BoxRegistration | null> {\n return this.call('authenticateBox', [token]);\n }\n listBoxes(): Promise<BoxRegistration[]> {\n return this.call('listBoxes', []);\n }\n forgetBox(boxId: string): Promise<boolean> {\n return this.call('forgetBox', [boxId]);\n }\n countBoxes(): Promise<number> {\n return this.call('countBoxes', []);\n }\n\n appendEvent(input: Omit<RelayEvent, 'id' | 'receivedAt'>): Promise<RelayEvent> {\n return this.call('appendEvent', [input]);\n }\n listEvents(since: number, boxId?: string): Promise<RelayEvent[]> {\n return this.call('listEvents', [since, boxId]);\n }\n countEvents(): Promise<number> {\n return this.call('countEvents', []);\n }\n\n setStatus(\n boxId: string,\n name: string,\n projectIndex: number | undefined,\n status: BoxStatusSnapshot,\n ): Promise<void> {\n return this.call('setStatus', [boxId, name, projectIndex, status]);\n }\n getStatus(boxId: string): Promise<BoxStatusSnapshot | undefined> {\n return this.call<BoxStatusSnapshot | null>('getStatus', [boxId]).then((r) => r ?? undefined);\n }\n deleteStatus(boxId: string): Promise<void> {\n return this.call('deleteStatus', [boxId]);\n }\n listStatuses(): Promise<Array<{ boxId: string; status: BoxStatusSnapshot }>> {\n return this.call('listStatuses', []);\n }\n\n createPrompt(row: PromptRow): Promise<void> {\n return this.call('createPrompt', [row]);\n }\n getPrompt(promptId: string): Promise<PromptRow | null> {\n return this.call('getPrompt', [promptId]);\n }\n answerPrompt(promptId: string, answer: 'y' | 'n', cancelled?: boolean): Promise<boolean> {\n return this.call('answerPrompt', [promptId, answer, cancelled]);\n }\n listPendingPrompts(boxId: string): Promise<PromptRow[]> {\n return this.call('listPendingPrompts', [boxId]);\n }\n setPromptResult(promptId: string, result: GitRpcResult): Promise<void> {\n return this.call('setPromptResult', [promptId, result]);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AEAA,SAAS,OAAO,QAAQ,IAAI,iBAAiB;AAC7C,SAAS,eAAe;AACxB,SAAS,YAAY;AEFrB,SAAS,kBAAkB;ACA3B,SAAS,cAAAA,mBAAkB;ACA3B,SAAS,kBAAkB;AIe3B,SAAS,uBAAuB;ACDhC,SAAS,kBAAkB;ACE3B,SAAS,mBAAAC,wBAAuB;ACJhC,SAAS,cAAAD,mBAAkB;AAC3B,SAAS,MAAAE,WAAU;AACnB,SAAS,eAAe;AACxB,SAAS,mBAAAD,wBAAuB;AEfhC,SAAS,kBAAkB;ACA3B,SAAS,aAAa;AACtB,SAAS,mBAAmB;AAC5B,SAAS,SAAAE,QAAO,SAAS,UAAU,UAAAC,SAAQ,QAAQ,aAAAC,kBAAiB;AACpE,SAAS,WAAW,cAAAC,aAAY,gBAAgB;AAChD,SAAS,QAAAC,aAAY;AACrB,SAAS,cAAc,aAAa;AhBA7B,IAAM,qBAAqB;AAS3B,IAAM,yBAAyB;AAC/B,IAAM,uBAAuB;AAC7B,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB;AACxB,IAAM,wBAAwB;ACf9B,IAAM,cAAN,MAAkB;EACN,MAAM,oBAAI,IAA6B;EAExD,SAAS,KAA4B;AACnC,SAAK,IAAI,IAAI,IAAI,OAAO,GAAG;EAC7B;EAEA,OAAO,OAAwB;AAC7B,WAAO,KAAK,IAAI,OAAO,KAAK;EAC9B;;EAGA,aAAa,OAAuC;AAClD,QAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,eAAW,OAAO,KAAK,IA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B,aAAa,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC,MAAM,KAAK,MAAS;EAC7F;EACA,aAAa,OAA8B;AACzC,WAAO,KAAK,KAAK,gBAAgB,CAAC,KAAK,CAAC;EAC1C;EACA,eAA6E;AAC3E,WAAO,KAAK,KAAK,gBAAgB,CAAC,CAAC;EACrC;EAEA,aAAa,KAA+B;AAC1C,WAAO,KAAK,KAAK,gBAAgB,CAAC,GAAG,CAAC;EACxC;EACA,UAAU,UAA6C;AACrD,WAAO,KAAK,KAAK,aAAa,CAAC,QAAQ,CAAC;EAC1C;EACA,aAAa,UAAkB,QAAmB,WAAuC;AACvF,WAAO,KAAK,KAAK,gBAAgB,CAAC,UAAU,QAAQ,SAAS,CAAC;EAChE;EACA,mBAAmB,OAAqC;AACtD,WAAO,KAAK,KAAK,sBAAsB,CAAC,KAAK,CAAC;EAChD;EACA,gBAAgB,UAAkB,QAAqC;AACrE,WAAO,KAAK,KAAK,mBAAmB,CAAC,UAAU,MAAM,CAAC;EACxD;AACF;","names":["randomUUID","timingSafeEqual","rm","mkdir","rename","writeFile","existsSync","join","randomUUID","err","text","timingSafeEqualStr","timingSafeEqual","parseJson","readState","boxSshDirForProvider","rm","join","STATE_DIR","mkdir","writeFile","rename","existsSync","timingSafeEqual","dirname","join","mkdir","readFile","readdir","rename","rm","writeFile","dirname","join","createHash","randomBytes","err","timingSafeEqualStr","timingSafeEqual","parseJson","text","integer","pg","DEFAULT_EVENT_CAP","join","require","ok","dirname","eq","asc","lte","gt","and","inArray","desc","or","lt","isNotNull","STATE_DIR","mkdir","randomBytes","writeFile","rename","rm","createHash","readFile","readdir","spawn","existsSync","rm","tmpdir","join","spawn","existsSync","createHash","randomBytes","randomUUID","timingSafeEqual","stat","execa","spawn","readFile","readFile","existsSync","spawn","err","createHash","randomBytes","verdict","realpathSafe","join","tmpdir","rm","fetch","randomUUID","timingSafeEqualStr","timingSafeEqual","stat","execa","text","ok","result","isScratchBranch","isSanctionedPushBranch","resolveRemote","parseDownloadKind","url","hostOpenCommand","hit","resolveLandDest","landRefspec","sanitizeGitArgs","upstreamRef","getConnector","readFile","DEFAULT_INTERVAL_MS","msSince","toEpoch","readState","findBox","BUILT_IN_DEFAULTS","parseUserConfig","GLOBAL_CONFIG_FILE"]}
|